]> git.donarmstrong.com Git - lib.git/blob - emacs_el/configuration/don-configuration.org
we use straight; don't ensure markdown mode
[lib.git] / emacs_el / configuration / don-configuration.org
1 #+PROPERTY: header-args:emacs-lisp :tangle don-configuration.el
2 #+OPTIONS: auto-id:f
3
4 * General Notes
5
6 ** Delight
7 To look up options for symbols for delight, check out https://en.wikipedia.org/wiki/Emoji#Unicode_blocks
8
9 * Load debugger
10
11 # if for some reason, things get pear-shaped, we want to be able to
12 # enter the debugger by sending -USR2 to emacs
13
14 #+BEGIN_SRC emacs-lisp
15 (setq debug-on-event 'siguser2)
16 #+END_SRC
17 * Paths
18 ** Update PATH
19 #+BEGIN_SRC emacs-lisp
20 (add-to-list 'exec-path '"/usr/local/bin")
21 (add-to-list 'exec-path '"~/bin/")
22 #+END_SRC
23 ** Add library paths
24 #+BEGIN_SRC emacs-lisp
25 (let ((default-directory "~/lib/emacs_el/"))
26   (normal-top-level-add-subdirs-to-load-path))
27 ;; (eval-and-compile
28 ;;   (let ((default-directory "~/var/emacs/elpa"))
29 ;;     (normal-top-level-add-subdirs-to-load-path))
30 ;; )
31 (add-to-list 'load-path '"~/lib/emacs_el")
32 (setq package-user-dir "~/var/emacs/elpa")
33
34 #+END_SRC
35 * Initial startup stuff
36 ** Disable startup screen
37 #+BEGIN_SRC emacs-lisp
38 (setq inhibit-startup-screen t)
39 #+END_SRC
40 ** Disable cluter
41 #+BEGIN_SRC emacs-lisp
42 ; (if (fboundp 'menu-bar-mode) (menu-bar-mode -1))
43 (if (fboundp 'tool-bar-mode) (tool-bar-mode -1))
44 (if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))
45 #+END_SRC
46 ** Fullscreen
47 #+BEGIN_SRC emacs-lisp
48 (setq frame-resize-pixelwise t)
49 (add-to-list 'default-frame-alist '(fullscreen . maximixed))
50 #+END_SRC
51 * Package management
52 ** Bootstrap straight.el
53 #+BEGIN_SRC emacs-lisp
54 (defvar bootstrap-version)
55 (setq straight-base-dir '"~/var/emacs/")
56 (let ((bootstrap-file
57        (expand-file-name "straight/repos/straight.el/bootstrap.el" straight-base-dir))
58       (bootstrap-version 6))
59   (unless (file-exists-p bootstrap-file)
60     (with-current-buffer
61         (url-retrieve-synchronously
62          "https://raw.githubusercontent.com/radian-software/straight.el/develop/install.el"
63          'silent 'inhibit-cookies)
64       (goto-char (point-max))
65       (eval-print-last-sexp)))
66   (load bootstrap-file nil 'nomessage))
67 #+END_SRC
68 ** package repositories and package manager
69 #+BEGIN_SRC emacs-lisp
70 (straight-use-package 'use-package)
71 (setq straight-use-package-by-default t)
72 (setq use-package-verbose (not (bound-and-true-p byte-compile-current-file)))
73 (require 'gnutls)
74 (add-to-list 'gnutls-trustfiles "/etc/ssl/ca-global/ca-certificates.crt")
75 #+END_SRC
76 ** Paradox
77 #+BEGIN_SRC emacs-lisp
78 (use-package paradox
79   ;:ensure paradox
80   :commands (paradox-upgrade-packages paradox-list-packages)
81   :config
82   (setq paradox-execute-asynchronously t)
83   (setq paradox-github-token t) ; I don't want to be prompted about this integration
84   )
85 #+END_SRC
86 * Disable custom-vars
87 #+BEGIN_SRC emacs-lisp
88 ;; Set the custom file to /dev/null and don't bother to load it
89 (setq custom-file "/dev/null")
90 #+END_SRC
91 * Misc functions
92 ** with-library
93 #+BEGIN_SRC emacs-lisp
94 ;; From http://www.emacswiki.org/emacs/LoadingLispFiles
95 ;; execute conditional code when loading libraries
96 ; (defmacro with-library (symbol &rest body)
97 ;   `(when (require ,symbol nil t)
98 ;     ,@body))
99 ; (put 'with-library 'lisp-indent-function 1)
100 #+END_SRC
101
102 * Variables
103 ** Safe Local Variables
104 #+BEGIN_SRC emacs-lisp
105 (setq safe-local-variable-values
106       (quote ((auto-save-default)
107               (make-backup-files)
108               (cperl-indent-level . 4)
109               (indent-level . 4)
110               (indent-tabs-mode . f)
111               (vcl-indent-level . 4)
112               )))
113 #+END_SRC
114 * Memory
115 #+BEGIN_SRC emacs-lisp
116 (setq global-mark-ring-max 128
117       mark-ring-max 128
118       kill-ring-max 128)
119
120 (defun don/minibuffer-setup-hook ()
121   (setq gc-cons-threshold most-positive-fixnum))
122
123 (defun don/minibuffer-exit-hook ()
124   (setq gc-cons-threshold 1048576))
125
126 (add-hook 'minibuffer-setup-hook #'don/minibuffer-setup-hook)
127 (add-hook 'minibuffer-exit-hook #'don/minibuffer-exit-hook)
128 #+END_SRC
129 * Modules
130 ** Tree sitter
131 #+BEGIN_SRC emacs-lisp
132 (use-package tree-sitter
133   :defer t
134   :config
135   (global-tree-sitter-mode)
136   )
137 (use-package tree-sitter-langs
138   :ensure t
139   :defer 1
140   :after tree-sitter
141 ;   :config
142 ;   (defun dla/python-function-at-point ()
143 ;     "Return a list of function arguments
144
145 ; Borrowed from https://xenodium.com/emacs-generate-a-swift-initializer/
146 ; "
147 ;   (interactive)
148 ;   (cl-assert (seq-contains-p local-minor-modes 'tree-sitter-mode) "tree-sitter-mode not enabled")
149 ;   (let* ((node (tree-sitter-node-at-point 'function_definition)
150 ;                )
151 ;          (args)
152 ;          (arg)
153 ;          (ret))
154 ;     (unless node
155 ;       (error "Not in function"))
156 ;     (mapc
157 ;      (lambda (item)
158 ;        (cond ((eq 'func_name
159 ;                   (car item))
160 ;               ; (when arg
161 ;               ;   (setq args (append args (list arg)))
162 ;               ;   )
163 ;               (setq arg (list (cons 'function (tsc-node-text
164 ;                                            (cdr item))))))
165 ;              ((eq 'ident
166 ;                   (car item))
167 ;               (setq arg (map-insert arg 'ident (tsc-node-text
168 ;                                                (cdr item)))))
169 ;              ((eq 'ident_type
170 ;                   (car item))
171 ;               (setq arg (map-insert arg 'ident_type (tsc-node-text
172 ;                                                (cdr item)))))
173 ;              ((eq 'ret_type
174 ;                   (car item))
175 ;               (setq arg (map-insert arg 'ret_type (tsc-node-text
176 ;                                                (cdr item)))))
177 ;              ))
178 ;      (tsc-query-captures
179 ;       (tsc-make-query tree-sitter-language
180 ;                       "(function_definition (identifier) @func_name (parameters [(identifier) @ident (typed_parameter (identifier) @ident (type) @ident_type)]) (type)? @ret_type)")
181 ;       (tree-sitter-node-at-point 'function_definition) nil))
182 ;     (when arg
183 ;       (setq args (append args (list arg))))
184 ;     args))
185
186 )
187 #+END_SRC
188 ** Spacemacs theme
189 #+BEGIN_SRC emacs-lisp
190 (use-package spacemacs-theme
191   :config
192   (load-theme 'spacemacs-dark t)
193   )
194 #+END_SRC
195 ** Hippie Expand
196 #+BEGIN_SRC emacs-lisp
197 (use-package hippie-exp
198   :bind* (("M-<SPC>" . hippie-expand))
199   )
200 #+END_SRC
201 ** Flyspell 🐝 
202 #+BEGIN_SRC emacs-lisp
203 (use-package flyspell
204   ; :delight flyspell-mode 🐝
205   :config
206   (setq flyspell-mode-line-string " 🐝")
207   (add-hook 'text-mode-hook 'turn-on-flyspell)
208   (add-hook 'c-mode-common-hook 'flyspell-prog-mode)
209   (add-hook 'cperl-mode-hook 'flyspell-prog-mode)
210   (add-hook 'tcl-mode-hook 'flyspell-prog-mode)
211   :init
212   (setq ispell-program-name "ispell")
213   )
214 #+END_SRC
215
216 ** Flycheck
217 #+begin_src emacs-lisp :tangle yes
218 (use-package flycheck
219   :delight 🦋
220   :if (version<= "24.4" emacs-version)
221   :commands flycheck-mode
222   :hook ((prog-mode . flycheck-mode)
223          )
224 )
225 ;; Other pkgs
226 (use-package flycheck-tip
227   :commands 'flycheck-tip-cycle
228   :after flycheck
229   :bind (:map flycheck-mode-map
230               ("C-c C-n" . flycheck-tip-cycle)))
231
232 (use-package flycheck-package)
233
234 (use-package flycheck-checkpatch
235   :config (flycheck-checkpatch-setup)
236   :config (setq flycheck-checkers (delete 'checkpatch
237   flycheck-checkers))
238   :config (add-to-list 'flycheck-checkers 'checkpatch t))
239 #+end_src  
240
241 ** Flymake
242 #+BEGIN_SRC emacs-lisp
243   (use-package flymake
244     :delight "Φ")
245 #+END_SRC
246
247 ** Winnermode
248 #+BEGIN_SRC emacs-lisp
249   (winner-mode 1)
250 #+END_SRC
251 ** Eyebrowse
252
253 #+BEGIN_SRC emacs-lisp
254   (use-package eyebrowse
255     :ensure t
256     :delight eyebrowse-mode
257     :init (setq eyebrowse-keymap-prefix (kbd "C-c e"))
258     :config (progn
259               (setq eyebrowse-wrap-around t)
260               (eyebrowse-mode t)
261
262               (defun my/eyebrowse-new-window-config ()
263                 (interactive)
264                 (let ((done nil))
265                   (dotimes (i 10)
266                     ;; start at 1 run till 0
267                     (let ((j (mod (+ i 1) 10)))
268                       (when (and (not done)
269                                  (not (eyebrowse--window-config-present-p j)))
270                         (eyebrowse-switch-to-window-config j)
271                         (call-interactively 'eyebrowse-rename-window-config2 j)
272                         (setq done t)
273                         ))
274                     )))
275
276               ;; I don't use latex-preview-pane
277               ;; (require 'latex-preview-pane)
278               ;; (defun my/close-latex-preview-pane-before-eyebrowse-switch ()
279               ;;   ;; latex-preview-pane uses window-parameters which are
280               ;;   ;; not preserved by eyebrowse, so we close the preview
281               ;;   ;; pane before switching, it will be regenerated when we
282               ;;   ;; edit the TeX file.
283               ;;   (when (lpp/window-containing-preview)
284               ;;     (delete-window (lpp/window-containing-preview))))
285
286               ;; (add-to-list 'eyebrowse-pre-window-switch-hook
287               ;;              #'my/close-latex-preview-pane-before-eyebrowse-switch)
288
289               ;; (my/set-menu-key "["  #'my/eyebrowse-new-window-config)
290               ;; (my/set-menu-key ";"  #'eyebrowse-prev-window-config)
291               ;; (my/set-menu-key "'"  #'eyebrowse-next-window-config)
292               ;; (my/set-menu-key "]"  #'eyebrowse-close-window-config)
293               ;; (my/set-menu-key "\\" #'eyebrowse-rename-window-config)
294               )
295     )
296 #+END_SRC
297
298 ** Window handling
299
300 *** Splitting
301 #+BEGIN_SRC emacs-lisp
302   (defun my/vsplit-last-buffer ()
303     "Split the window vertically and display the previous buffer."
304     (interactive)
305     (split-window-vertically)
306     (other-window 1 nil)
307     (switch-to-next-buffer))
308
309   (defun my/hsplit-last-buffer ()
310     "Split the window horizontally and display the previous buffer."
311     (interactive)
312     (split-window-horizontally)
313     (other-window 1 nil)
314     (switch-to-next-buffer))
315
316   (bind-key "C-x 2" 'my/vsplit-last-buffer)
317   (bind-key "C-x 3" 'my/hsplit-last-buffer)
318
319   (setq split-width-threshold  100)
320   (setq split-height-threshold 60)
321
322   (defun my/split-window-prefer-vertically (window)
323     "If there's only one window (excluding any possibly active
324            minibuffer), then split the current window horizontally."
325     (if (and (one-window-p t)
326              (not (active-minibuffer-window))
327              ( < (frame-width) (frame-height))
328              )
329         (let ((split-width-threshold nil))
330           (split-window-sensibly window))
331       (split-window-sensibly window)))
332
333   (setq split-window-preferred-function #'my/split-window-prefer-vertically)
334   (setq window-combination-resize t)
335 #+END_SRC
336
337 *** Compilation window
338
339 If there is no compilation window, open one at the bottom, spanning
340 the complete width of the frame. Otherwise, reuse existing window. In
341 the former case, if there was no error the window closes
342 automatically.
343
344 #+BEGIN_SRC emacs-lisp
345   (add-to-list 'display-buffer-alist
346                `(,(rx bos "*compilation*" eos)
347                  (display-buffer-reuse-window
348                   display-buffer-in-side-window)
349                  (reusable-frames . visible)
350                  (side            . bottom)
351                  (window-height   . 0.4)))
352 #+END_SRC
353
354 #+BEGIN_SRC emacs-lisp
355   (defun my/compilation-exit-autoclose (status code msg)
356     ;; If M-x compile exists with a 0
357     (when (and (eq status 'exit) (zerop code))
358       ;; and delete the *compilation* window
359       (let ((compilation-window (get-buffer-window (get-buffer "*compilation*"))))
360         (when (and (not (window-at-side-p compilation-window 'top))
361                    (window-at-side-p compilation-window 'left)
362                    (window-at-side-p compilation-window 'right))
363           (delete-window compilation-window))))
364     ;; Always return the anticipated result of compilation-exit-message-function
365     (cons msg code))
366
367   ;; Specify my function (maybe I should have done a lambda function)
368   (setq compilation-exit-message-function #'my/compilation-exit-autoclose)
369 #+END_SRC
370
371 If you change the variable ~compilation-scroll-output~ to a ~non-nil~
372 value, the compilation buffer scrolls automatically to follow the
373 output. If the value is ~first-error~, scrolling stops when the first
374 error appears, leaving point at that error. For any other non-nil
375 value, scrolling continues until there is no more output.
376
377 #+BEGIN_SRC emacs-lisp
378   (setq compilation-scroll-output 'first-error)
379 #+END_SRC
380
381 ** Mode line cleaning
382 *** Delight 
383 #+BEGIN_SRC emacs-lisp
384 (use-package delight
385   :demand t)
386 #+END_SRC
387
388 ** Jumping
389 *** Avy
390 #+BEGIN_SRC emacs-lisp
391   (use-package avy
392     :if (>= emacs-major-version 25)
393     :ensure t
394     :bind (("C-c C-<SPC>" . avy-goto-word-or-subword-1)
395            ("C-c j j" . avy-goto-word-or-subword-1)
396            ("M-g g" . avy-goto-line))
397     :config (progn (setq avy-background t))
398     )
399 #+END_SRC
400 *** Ace-link (jumping to links)
401 #+BEGIN_SRC emacs-lisp
402   (use-package ace-link
403     :ensure t
404     ; bind o in most modes
405     :config (ace-link-setup-default))
406 #+END_SRC
407 *** Jumping through edit points (goto-chg)
408 #+BEGIN_SRC emacs-lisp
409   (use-package goto-chg
410     :ensure t
411     :bind (("C-c j ," . goto-last-change)
412            ("C-c j ." . goto-last-change-reverse))
413     )
414 #+END_SRC
415 *** Jumping to bookmarks (visible bookmarks, bm)
416 #+BEGIN_SRC emacs-lisp
417   (use-package bm
418     :ensure t
419     :bind (("C-c j b ." . bm-next)
420            ("C-c j b ," . bm-previous)
421            ("C-c j b SPC" . bm-toggle)))
422 #+END_SRC
423
424 ** Snippets
425 *** Yasnippet
426 #+BEGIN_SRC emacs-lisp
427 (use-package yasnippet
428   :ensure t
429   :delight yas-minor-mode
430   :config (progn
431             (yas-global-mode)
432             (setq yas-verbosity 1)
433             (define-key yas-minor-mode-map (kbd "<tab>") nil)
434             (define-key yas-minor-mode-map (kbd "TAB") nil)
435             (define-key yas-minor-mode-map (kbd "<backtab>") nil)
436             (setq yas-snippet-dirs '("~/lib/emacs_el/snippets/"
437                                      "~/lib/emacs_el/yasnippet-snippets/snippets/"))
438             (add-to-list 'hippie-expand-try-functions-list
439                              'yas-hippie-try-expand)
440             (yas-reload-all)
441             )
442   )
443 #+END_SRC
444 *** Auto-YASnippet
445 #+BEGIN_SRC emacs-lisp
446 (use-package auto-yasnippet
447   :ensure t
448   :bind (("H-w" . aya-create)
449          ("H-y" . aya-expand)
450          )
451   )
452 #+END_SRC
453 ** Treemacs: Tree file viewer
454 #+BEGIN_SRC emacs-lisp
455 ;; Provides workspaces with file browsing (tree file viewer)
456 ;; and project management when coupled with `projectile`.
457
458 ; (use-package treemacs
459 ;   :ensure t
460 ;   :defer t
461 ;   :config
462 ;   (setq treemacs-no-png-images t
463 ;         treemacs-width 24)
464 ;   :bind ("C-c t" . treemacs))
465 #+END_SRC
466 ** LSP mode
467 #+BEGIN_SRC emacs-lisp
468 (use-package lsp-mode
469   :defer t
470   :commands (lsp lsp-deferred)
471   :init (setq lsp-keymap-prefix "C-c l")
472   (defun my/orderless-dispatch-flex-first (_pattern index _total)
473     (and (eq index 0) 'orderless-flex))
474
475   (defun my/lsp-mode-setup-completion ()
476     (setf (alist-get 'styles (alist-get 'lsp-capf completion-category-defaults))
477           '(orderless)))
478
479   ;; Optionally configure the first word as flex filtered.
480   (add-hook 'orderless-style-dispatchers #'my/orderless-dispatch-flex-first nil 'local)
481
482   ;; Optionally configure the cape-capf-buster.
483   ; (setq-local completion-at-point-functions (list (cape-capf-buster #'lsp-completion-at-point)))
484
485   :hook (python-mode . lsp-deferred)
486         (cperl-mode . lsp-deferred)
487   (lsp-completion-mode . my/lsp-mode-setup-completion)
488   :custom
489   (lsp-completion-provider :none) ;; we use Corfu!
490   :config
491    (add-to-list 'lsp-file-watch-ignored-directories "[/\\\\]venv\\'")
492 )
493 #+END_SRC
494 ** LSP mode
495 #+BEGIN_SRC emacs-lisp
496 ;; provides visual help in the buffer 
497 ;; for example definitions on hover. 
498 ;; the `imenu` lets me browse definitions quickly.
499 (use-package lsp-ui
500   :defer t
501   :after lsp-mode
502   :config
503   (setq lsp-ui-sideline-enable t
504             lsp-ui-doc-delay 2)
505   :hook (lsp-mode . lsp-ui-mode)
506   :bind (:map lsp-ui-mode-map
507               ("c-c i" . lsp-ui-imenu)))
508 #+END_SRC
509 *** LSP Pyright -- Python language server
510 #+BEGIN_SRC emacs-lisp
511 ;; language server for python 
512 ;; read the docs for the different variables set in the config.
513 (use-package lsp-pyright
514   :defer t
515   :config
516   (setq lsp-clients-python-library-directories '("/usr/"))
517   (setq lsp-pyright-disable-language-service nil
518         lsp-pyright-disable-organize-imports nil
519         lsp-pyright-auto-import-completions t
520         lsp-pyright-use-library-code-for-types t
521         lsp-pyright-venv-path "venv")
522   :hook ((python-mode . (lambda () 
523                           (require 'lsp-pyright) (lsp-deferred)))))
524 #+END_SRC
525 ** Corfu
526 #+BEGIN_SRC emacs-lisp
527 (use-package corfu
528   ;; Optional customizations
529   :custom
530   (corfu-cycle t)                ;; Enable cycling for `corfu-next/previous'
531   (corfu-auto t)                 ;; Enable auto completion
532   (corfu-separator ?\s)          ;; Orderless field separator
533   (corfu-quit-at-boundary t)
534   (corfu-quit-no-match 'separator)
535   (corfu-preview-current nil)    ;; Disable current candidate preview
536   (corfu-preselect 'prompt)      ;; Preselect the prompt
537   (corfu-on-exact-match nil)     ;; Configure handling of exact matches
538   (corfu-scroll-margin 5)        ;; Use scroll margin
539
540   :bind (
541          :map corfu-map
542               ("M-m" , corfu-move-to-minibuffer)
543               )
544   :init
545   (global-corfu-mode)
546   (setq completion-cycle-threshold 3)
547   (setq tab-always-indent 'complete)
548   :config
549   (defun corfu-move-to-minibuffer ()
550     (interactive)
551     (when completion-in-region--data
552       (let ((completion-extra-properties corfu--extra)
553             completion-cycle-threshold completion-cycling)
554         (apply #'consult-completion-in-region completion-in-region--data))))
555   (add-to-list 'corfu-continue-commands #'corfu-move-to-minibuffer)
556   )
557 #+END_SRC
558 ** Dabbrv
559 #+BEGIN_SRC emacs-lisp
560 (use-package dabbrev
561   :ensure t
562   ;; Swap M-/ and C-M-/
563   :bind (("M-/" . dabbrev-completion)
564          ("C-M-/" . dabbrev-expand))
565   ;; Other useful Dabbrev configurations.
566   :custom
567   (dabbrev-ignored-buffer-regexps '("\\.\\(?:pdf\\|jpe?g\\|png\\)\\'")))
568 #+END_SRC
569 ** Tinyprocmail
570
571 #+BEGIN_SRC emacs-lisp
572 ;; load tinyprocmail
573 (use-package tinyprocmail
574   :straight (tinytools :type git :type git :host github :repo "jaalto/project--emacs-tiny-tools")
575   ; :load-path "~/lib/emacs_el/tiny-tools/lisp/tiny"
576   :mode (".procmailrc" . turn-on-tinyprocmail-mode)
577   )
578 #+END_SRC
579
580 ** Magit
581 #+BEGIN_SRC emacs-lisp
582 (use-package magit
583   :defer t
584   :bind (("C-x g" . magit-status)
585          ("C-x C-g" . magit-status))
586   :config
587   ;; refine diffs always (hilight words)
588   (setq magit-diff-refine-hunk nil)
589   )
590 (use-package magit-annex
591   :defer t
592   :after magit
593   )
594 (use-package magit-vcsh
595   :defer t
596   :after magit
597   )
598 #+END_SRC
599
600 *** Forge (github/gitlab)
601 #+BEGIN_SRC emacs-lisp
602 (use-package forge
603   :defer t
604   :after magit
605   )
606 #+END_SRC
607
608 ** Perl
609 #+BEGIN_SRC emacs-lisp
610 (use-package cperl-mode
611   :mode ("\\.pl'" . cperl-mode)
612   ("\\.perl5\\'" . cperl-mode)
613   ("\\.perl\\'" . cperl-mode)
614   ("\\.miniperl\\'" . cperl-mode)
615   ("\\.\\([Pp][Llm]\\|al\\)\\'" . cperl-mode)
616     ;; use c-mode for perl .xs files
617   ("\\.xs\\'" . c-mode)
618   :config
619        (setq cperl-hairy t
620           cperl-indent-level 4
621           cperl-auto-newline nil
622           cperl-auto-newline-after-colon nil
623           cperl-continued-statement-offset 4
624           cperl-brace-offset -1
625           cperl-continued-brace-offset 0
626           cperl-label-offset -4
627           cperl-highlight-variables-indiscriminately t
628           cperl-electric-lbrace-space nil
629           cperl-indent-parens-as-block nil
630           cperl-close-paren-offset -1
631           cperl-tab-always-indent t)
632     (setq cperl-lazy-help-time nil)
633     ;;(add-hook 'cperl-mode-hook (lambda () (cperl-set-style "PerlStyle")))
634 ))
635 #+END_SRC
636
637 ** Markdown mode
638 #+BEGIN_SRC emacs-lisp
639 (use-package markdown-mode
640   :defer t
641   :mode (("\\.md\\'" . markdown-mode)
642          ("\\.mdwn\\'" . markdown-mode)
643          ("README\\.md\\'" . gfm-mode)
644          )
645   :config
646   (setq markdown-enable-math t)
647   (setq markdown-follow-wiki-link-on-enter nil)
648   (bind-key "M-." #'markdown-jump markdown-mode-map)
649   (add-hook 'markdown-mode-hook #'flyspell-mode)
650   (add-hook 'markdown-mode-hook #'outline-minor-mode)
651   (bind-key "C-<tab>" #'outline-cycle markdown-mode-map)
652 )
653
654 #+END_SRC
655 ** SQL mode
656 #+BEGIN_SRC emacs-lisp
657 ; load sql-indent when sql is loaded
658 (use-package sql-indent
659   :hook sql-mode
660   )
661 (use-package sql
662   :mode (("\\.sql\\'" . sql-mode))
663   )
664 #+END_SRC
665 ** Ediff
666 #+BEGIN_SRC emacs-lisp
667 (use-package ediff
668   :commands ediff ediff3
669   :config
670   ;; ediff configuration
671   ;; don't use the multi-window configuration
672   (setq ediff-window-setup-function 'ediff-setup-windows-plain)
673 )
674 #+END_SRC
675 ** Do the Right Thing Indenting
676 Attempts to automatically identify the right indentation for a file
677 #+BEGIN_SRC emacs-lisp
678 (use-package dtrt-indent
679 )  
680 #+END_SRC
681 ** VCL --editing varnish configuration files
682 #+BEGIN_SRC emacs-lisp
683 (use-package vcl-mode
684   :mode "\\.vcl\\'"
685   )
686 #+END_SRC
687 ** Vertico
688 #+BEGIN_SRC emacs-lisp
689 (use-package vertico
690   :demand t
691   :config
692   (vertico-mode)
693   ; (define-key vertico-map "\r" #'vertico-directory-enter)
694   ; (define-key vertico-map "\d" #'vertico-directory-delete-char)
695   ; (define-key vertico-map "\M-\d" #'vertico-directory-delete-word)
696   ; (add-hook 'rfn-eshadow-update-overlay-hook #'vertico-directory-tidy)
697
698   ;; Different scroll margin
699   ;; (setq vertico-scroll-margin 0)
700
701   ;; Show more candidates
702   ;; (setq vertico-count 20)
703
704   ;; Grow and shrink the Vertico minibuffer
705   ;; (setq vertico-resize t)
706
707   ;; Optionally enable cycling for `vertico-next' and `vertico-previous'.
708   ;; (setq vertico-cycle t)
709   :custom
710   (vertico-grid-separator "       ")
711   (vertico-grid-lookahead 50)
712 )
713 (use-package vertico-multiform
714   :straight nil
715   :load-path "~/var/emacs/straight/build/vertico/extensions/"
716   :after vertico
717   :config
718   (setq vertico-multiform-categories
719      '((file reverse)
720        (consult-grep buffer)
721        (consult-location)
722        (imenu buffer)
723        (library reverse indexed)
724        (org-roam-node reverse indexed)
725        ; (t reverse)
726        )
727      )
728   (setq vertico-multiform-commands
729         '(("flyspell-correct-*" grid reverse)
730           (org-refile grid reverse indexed)
731           (consult-yank-pop indexed)
732           (consult-flycheck)
733           (consult-lsp-diagnostics)
734           )
735         )
736   (vertico-multiform-mode)
737   )
738
739 (use-package vertico-grid
740   :straight nil
741   :after vertico
742   )
743 (use-package vertico-reverse
744   :straight nil
745   :after vertico
746   )
747 (use-package vertico-indexed
748   :straight nil
749   :after vertico
750   )
751 (use-package vertico-buffer
752   :straight nil
753   :after vertico
754   )
755
756
757 ;; Persist history over Emacs restarts. Vertico sorts by history position.
758 (use-package savehist
759   :demand t
760   :config
761   (savehist-mode))
762
763 #+END_SRC
764 ** Orderless: advanced completion style
765 #+begin_src emacs-lisp
766 (use-package orderless
767   :demand t
768   :config
769   ;; Configure a custom style dispatcher (see the Consult wiki)
770   ;; (setq orderless-style-dispatchers '(+orderless-dispatch)
771   ;;       orderless-component-separator #'orderless-escapable-split-on-space)
772   (setq completion-styles '(orderless basic)
773         completion-category-defaults nil
774         completion-category-overrides '((file (styles partial-completion)))))
775 #+end_src
776 ** Marginalia: Rich annotations in the minibuffer
777 #+begin_src emacs-lisp
778 (use-package marginalia
779   :demand t
780   :bind (:map minibuffer-local-map
781          ("M-A" . marginalia-cycle))
782   :config
783   (marginalia-mode)
784   )
785 #+end_src
786 ** Embark: Minibuffer actions and context menu
787 #+begin_src emacs-lisp
788 (use-package embark
789   :bind
790   (("C-." . embark-act)         ;; pick some comfortable binding
791    ("C-;" . embark-dwim)        ;; good alternative: M-.
792    ("C-h B" . embark-bindings)) ;; alternative for `describe-bindings'
793
794   :init
795
796   ;; Optionally replace the key help with a completing-read interface
797   (setq prefix-help-command #'embark-prefix-help-command)
798
799   :config
800
801   ;; Hide the mode line of the Embark live/completions buffers
802   (add-to-list 'display-buffer-alist
803                '("\\`\\*Embark Collect \\(Live\\|Completions\\)\\*"
804                  nil
805                  (window-parameters (mode-line-format . none)))))
806
807 (use-package embark-consult
808   :hook
809   (embark-collect-mode . consult-preview-at-point-mode))
810 #+end_src
811 ** Consult
812 #+begin_src emacs-lisp
813 (use-package consult
814   ;; Replace bindings. Lazily loaded due by `use-package'.
815   :bind (;; C-c bindings in `mode-specific-map'
816          ("C-c M-x" . consult-mode-command)
817          ("C-c h" . consult-history)
818          ("C-c k" . consult-kmacro)
819          ("C-c m" . consult-man)
820          ("C-c i" . consult-info)
821          ([remap Info-search] . consult-info)
822          ;; C-x bindings in `ctl-x-map'
823          ("C-x M-:" . consult-complex-command)     ;; orig. repeat-complex-command
824          ("C-x b" . consult-buffer)                ;; orig. switch-to-buffer
825          ("C-x 4 b" . consult-buffer-other-window) ;; orig. switch-to-buffer-other-window
826          ("C-x 5 b" . consult-buffer-other-frame)  ;; orig. switch-to-buffer-other-frame
827          ("C-x r b" . consult-bookmark)            ;; orig. bookmark-jump
828          ("C-x p b" . consult-project-buffer)      ;; orig. project-switch-to-buffer
829          ;; Custom M-# bindings for fast register access
830          ("M-#" . consult-register-load)
831          ("M-'" . consult-register-store)          ;; orig. abbrev-prefix-mark (unrelated)
832          ("C-M-#" . consult-register)
833          ;; Other custom bindings
834          ("M-y" . consult-yank-pop)                ;; orig. yank-pop
835          ;; M-g bindings in `goto-map'
836          ("M-g e" . consult-compile-error)
837          ("M-g f" . consult-flymake)               ;; Alternative: consult-flycheck
838          ("M-g g" . consult-goto-line)             ;; orig. goto-line
839          ("M-g M-g" . consult-goto-line)           ;; orig. goto-line
840          ("M-g o" . consult-outline)               ;; Alternative: consult-org-heading
841          ("M-g m" . consult-mark)
842          ("M-g k" . consult-global-mark)
843          ("M-g i" . consult-imenu)
844          ("M-g I" . consult-imenu-multi)
845          ;; M-s bindings in `search-map'
846          ("M-s d" . consult-find)
847          ("M-s D" . consult-locate)
848          ("M-s g" . consult-grep)
849          ("M-s G" . consult-git-grep)
850          ("M-s r" . consult-ripgrep)
851          ("M-s l" . consult-line)
852          ("M-s L" . consult-line-multi)
853          ("M-s k" . consult-keep-lines)
854          ("M-s u" . consult-focus-lines)
855          ;; Isearch integration
856          ("M-s e" . consult-isearch-history)
857          :map isearch-mode-map
858          ("M-e" . consult-isearch-history)         ;; orig. isearch-edit-string
859          ("M-s e" . consult-isearch-history)       ;; orig. isearch-edit-string
860          ("M-s l" . consult-line)                  ;; needed by consult-line to detect isearch
861          ("M-s L" . consult-line-multi)            ;; needed by consult-line to detect isearch
862          ;; Minibuffer history
863          :map minibuffer-local-map
864          ("M-s" . consult-history)                 ;; orig. next-matching-history-element
865          ("M-r" . consult-history))                ;; orig. previous-matching-history-element
866
867   ;; Enable automatic preview at point in the *Completions* buffer. This is
868   ;; relevant when you use the default completion UI.
869   :hook (completion-list-mode . consult-preview-at-point-mode)
870
871   :commands (consult-xref)
872
873   ;; The :init configuration is always executed (Not lazy)
874   :init
875
876   ;; Optionally configure the register formatting. This improves the register
877   ;; preview for `consult-register', `consult-register-load',
878   ;; `consult-register-store' and the Emacs built-ins.
879   (setq register-preview-delay 0.5
880         register-preview-function #'consult-register-format)
881
882   ;; Optionally tweak the register preview window.
883   ;; This adds thin lines, sorting and hides the mode line of the window.
884   (advice-add #'register-preview :override #'consult-register-window)
885
886   ;; Use Consult to select xref locations with preview
887   (setq xref-show-xrefs-function #'consult-xref
888         xref-show-definitions-function #'consult-xref)
889
890   ;; Configure other variables and modes in the :config section,
891   ;; after lazily loading the package.
892   :config
893   ;; Optionally configure preview. The default value
894   ;; is 'any, such that any key triggers the preview.
895   ;; (setq consult-preview-key 'any)
896   ;; (setq consult-preview-key "M-.")
897   ;; (setq consult-preview-key '("S-<down>" "S-<up>"))
898   ;; For some commands and buffer sources it is useful to configure the
899   ;; :preview-key on a per-command basis using the `consult-customize' macro.
900   (consult-customize
901    consult-theme :preview-key '(:debounce 0.2 any)
902    consult-ripgrep consult-git-grep consult-grep
903    consult-bookmark consult-recent-file consult-xref
904    consult--source-bookmark consult--source-file-register
905    consult--source-recent-file consult--source-project-recent-file
906    ;; :preview-key "M-."
907    :preview-key '(:debounce 0.4 any))
908
909   ;; Optionally configure the narrowing key.
910   ;; Both < and C-+ work reasonably well.
911   (setq consult-narrow-key "<") ;; "C-+"
912
913   ;; Optionally make narrowing help available in the minibuffer.
914   ;; You may want to use `embark-prefix-help-command' or which-key instead.
915   ;; (define-key consult-narrow-map (vconcat consult-narrow-key "?") #'consult-narrow-help)
916
917   ;; By default `consult-project-function' uses `project-root' from project.el.
918   ;; Optionally configure a different project root function.
919   ;;;; 1. project.el (the default)
920   ;; (setq consult-project-function #'consult--default-project--function)
921   ;;;; 2. vc.el (vc-root-dir)
922   ;; (setq consult-project-function (lambda (_) (vc-root-dir)))
923   ;;;; 3. locate-dominating-file
924   ;; (setq consult-project-function (lambda (_) (locate-dominating-file "." ".git")))
925   ;;;; 4. projectile.el (projectile-project-root)
926   ;; (autoload 'projectile-project-root "projectile")
927   ;; (setq consult-project-function (lambda (_) (projectile-project-root)))
928   ;;;; 5. No project support
929   ;; (setq consult-project-function nil)
930 )
931 #+end_src
932 ** Projectile -- Project management
933 #+begin_src emacs-lisp
934 (use-package projectile
935   :bind (("<f5>" . projectile-compile-project)
936          ("<f6>" . next-error))
937   :config (projectile-global-mode))
938 #+end_src
939
940 ** Zap to char
941 #+BEGIN_SRC emacs-lisp
942 (use-package avy-zap
943   :bind ("M-z" . avy-zap-up-to-char-dwim))
944 #+END_SRC
945 ** Hydra
946 #+BEGIN_SRC emacs-lisp
947 (use-package hydra
948   :bind (("C-c 2" . my/hydra-orgmodes/body)
949          ("C-c @" . my/hydra-orgmodes/body)
950          ("C-c #" . my/hydra-outline/body)
951          ("C-c 3" . my/hydra-outline/body)
952          )
953   :config
954   (defhydra my/hydra-orgmodes (:color blue :hint nil)
955   "
956 _n_: notes _c_: chaim _w_: wildman _o_: ool
957 _u_: uddin _s_: steve _r_: refile  _f_: fh    
958 _p_: read papers      _R_: paper notes
959 _h_: hpcbio
960 _q_: quit
961 _z_: quit
962 "
963   ("n" (find-file "~/projects/org-notes/notes.org"))
964   ("c" (find-file "~/projects/org-notes/chaim.org"))
965   ("w" (find-file "~/projects/org-notes/wildman.org"))
966   ("u" (find-file "~/projects/org-notes/uddin.org"))
967   ("o" (find-file "~/projects/org-notes/ool.org"))
968   ("f" (find-file "~/projects/org-notes/fh.org"))
969   ("s" (find-file "~/projects/org-notes/sndservers.org"))
970   ("r" (find-file my/org-refile-file))
971   ("p" (find-file "~/projects/research/papers_to_read.org"))
972   ("R" (find-file "~/projects/research/paper_notes.org"))
973   ("h" (find-file "~/projects/org-notes/hpcbio.org"))
974   ("q" nil "quit")
975   ("z" nil "quit")
976   )
977
978   ;; from https://github.com/abo-abo/hydra/wiki/Emacs
979   (defhydra my/hydra-outline (:color pink :hint nil)
980   "
981 ^Hide^             ^Show^           ^Move
982 ^^^^^^------------------------------------------------------
983 _q_: sublevels     _a_: all         _u_: up
984 _t_: body          _e_: entry       _n_: next visible
985 _o_: other         _i_: children    _p_: previous visible
986 _c_: entry         _k_: branches    _f_: forward same level
987 _l_: leaves        _s_: subtree     _b_: backward same level
988 _d_: subtree
989
990 "
991   ;; Hide
992   ("q" outline-hide-sublevels)    ; Hide everything but the top-level headings
993   ("t" outline-hide-body)         ; Hide everything but headings (all body lines)
994   ("o" outline-hide-other)        ; Hide other branches
995   ("c" outline-hide-entry)        ; Hide this entry's body
996   ("l" outline-hide-leaves)       ; Hide body lines in this entry and sub-entries
997   ("d" outline-hide-subtree)      ; Hide everything in this entry and sub-entries
998   ;; Show
999   ("a" outline-show-all)          ; Show (expand) everything
1000   ("e" outline-show-entry)        ; Show this heading's body
1001   ("i" outline-show-children)     ; Show this heading's immediate child sub-headings
1002   ("k" outline-show-branches)     ; Show all sub-headings under this heading
1003   ("s" outline-show-subtree)      ; Show (expand) everything in this heading & below
1004   ;; Move
1005   ("u" outline-up-heading)                ; Up
1006   ("n" outline-next-visible-heading)      ; Next
1007   ("p" outline-previous-visible-heading)  ; Previous
1008   ("f" outline-forward-same-level)        ; Forward - same level
1009   ("b" outline-backward-same-level)       ; Backward - same level
1010   ("z" nil "leave"))
1011 )
1012 #+END_SRC
1013
1014 ** Tramp
1015 #+BEGIN_SRC emacs-lisp
1016 (use-package tramp
1017   :demand t
1018   ; use the built in tramp
1019   :straight nil
1020   :config
1021   (setq tramp-use-ssh-controlmaster-options nil)
1022   (add-to-list 'tramp-methods '("vcsh"
1023                                 (tramp-login-program "vcsh")
1024                                 (tramp-login-args
1025                                  (("enter")
1026                                   ("%h")))
1027                                 (tramp-remote-shell "/bin/sh")
1028                                 (tramp-remote-shell-args
1029                                  ("-c")))))
1030 #+END_SRC
1031 ** Reftex
1032 #+BEGIN_SRC emacs-lisp
1033 (use-package reftex
1034   :config
1035   (setq-default reftex-default-bibliography
1036                   '("~/projects/research/references.bib")))
1037 #+END_SRC
1038 ** BibTex
1039 #+BEGIN_SRC emacs-lisp
1040 (use-package bibtex
1041   :config (setq bibtex-user-optional-fields
1042                 (quote (("annote" "Personal annotation (ignored)")
1043                         ("abstract" "")
1044                 ("pmid" "")
1045                 ("doi" ""))))
1046   )
1047
1048 #+END_SRC
1049 ** LaTeX
1050 #+BEGIN_SRC emacs-lisp
1051 (use-package tex-site
1052   :straight auctex
1053   :mode ("\\.tex\\'" . LaTeX-mode)
1054   :mode ("\\.bib\\'" . bibtex-mode)
1055   :config
1056   ; (add-to-list 'TeX-style-path '"/home/don/lib/emacs_el/auctex/style")
1057   ;; REFTEX (much enhanced management of cross-ref, labels, etc)
1058   ;; http://www.strw.leidenuniv.nl/~dominik/Tools/reftex/
1059   ; (autoload 'reftex-mode     "reftex" "RefTeX Minor Mode" t)
1060   ; (autoload 'turn-on-reftex  "reftex" "RefTeX Minor Mode" nil)
1061   ; (autoload 'reftex-citation "reftex-cite" "Make citation" nil)
1062   ; (autoload 'reftex-index-phrase-mode "reftex-index" "Phrase mode" t)
1063   (add-hook 'LaTeX-mode-hook 'turn-on-reftex)   ; with AUCTeX LaTeX mode
1064   (add-hook 'latex-mode-hook 'turn-on-reftex)   ; with Emacs latex mode
1065   (add-hook 'LaTeX-mode-hook 'outline-minor-mode)   ; with AUCTeX LaTeX mode
1066   (add-hook 'latex-mode-hook 'outline-minor-mode)   ; with Emacs latex mode
1067
1068   (setq-default reftex-plug-into-AUCTeX t)
1069   ;; support fake section headers
1070   (setq TeX-outline-extra
1071         '(("%chapter" 1)
1072           ("%section" 2)
1073           ("%subsection" 3)
1074           ("%subsubsection" 4)
1075           ("%paragraph" 5)))
1076   ;; add font locking to the headers
1077   (font-lock-add-keywords
1078    'latex-mode
1079    '(("^%\\(chapter\\|\\(sub\\|subsub\\)?section\\|paragraph\\)"
1080       0 'font-lock-keyword-face t)
1081      ("^%chapter{\\(.*\\)}"       1 'font-latex-sectioning-1-face t)
1082      ("^%section{\\(.*\\)}"       1 'font-latex-sectioning-2-face t)
1083      ("^%subsection{\\(.*\\)}"    1 'font-latex-sectioning-3-face t)
1084      ("^%subsubsection{\\(.*\\)}" 1 'font-latex-sectioning-4-face t)
1085      ("^%paragraph{\\(.*\\)}"     1 'font-latex-sectioning-5-face t)))
1086
1087   ;; use smart quotes by default instead of `` and ''
1088   ;; taken from http://kieranhealy.org/esk/kjhealy.html
1089   (setq TeX-open-quote "“")
1090   (setq TeX-close-quote "”")
1091
1092   ;; (TeX-add-style-hook
1093   ;;  "latex"
1094   ;;  (lambda ()
1095   ;;    (TeX-add-symbols
1096   ;;     '("DLA" 1))))
1097   ;; (custom-set-variables
1098   ;;  '(font-latex-user-keyword-classes 
1099   ;;    '(("fixme" 
1100   ;;       ("DLA" "RZ")
1101   ;;       font-lock-function-name-face 2 (command 1 t))))
1102   ;; ) 
1103   (setq-default TeX-parse-self t)
1104   (setq-default TeX-auto-save t)
1105   (setq-default TeX-master nil)
1106   (add-to-list 'LaTeX-font-list
1107                '(?\C-a "\\alert{","}"))
1108   (eval-after-load
1109       "latex"
1110     '(TeX-add-style-hook
1111       "cleveref"
1112       (lambda ()
1113         (if (boundp 'reftex-ref-style-alist)
1114             (add-to-list
1115              'reftex-ref-style-alist
1116              '("Cleveref" "cleveref"
1117                (("\\cref" ?c) ("\\Cref" ?C) ("\\cpageref" ?d) ("\\Cpageref" ?D)))))
1118         (reftex-ref-style-activate "Cleveref")
1119         (TeX-add-symbols
1120          '("cref" TeX-arg-ref)
1121          '("Cref" TeX-arg-ref)
1122          '("cpageref" TeX-arg-ref)
1123          '("Cpageref" TeX-arg-ref)))))
1124   (eval-after-load
1125       "latex"
1126     '(add-to-list 'LaTeX-fill-excluded-macros
1127                   '("Sexpr")))
1128   
1129   (setq font-latex-match-reference-keywords
1130         '(
1131           ("fref" "{")
1132           ("Fref" "{")
1133           ("citep" "{")
1134           ("citet" "{")
1135           ("acs" "{")
1136           ("acsp" "{")
1137           ("ac" "{")
1138           ("acp" "{")
1139           ("acl" "{")
1140           ("aclp" "{")
1141           ("acsu" "{")
1142           ("aclu" "{")
1143           ("acused" "{")
1144           ("DLA" "{")
1145           ("RZ" "{")
1146           ("OM" "{")
1147           ("DL" "{")
1148           ("fixme" "{"))
1149         )
1150   (setq font-latex-fontify-script nil)
1151   (setq font-latex-fontify-sectioning (quote color))
1152   (setq font-latex-script-display (quote (nil)))
1153 )
1154
1155 #+END_SRC
1156 ** ESS
1157 #+BEGIN_SRC emacs-lisp
1158 (use-package ess
1159   :commands R
1160   :mode ("\\.R\\'" . ess-r-mode)
1161   :bind (:map ess-mode-map
1162               ("C-c C-R" . dla/ess-region-remote-eval))
1163   :init
1164   (autoload 'ess-r-mode "ess-site" nil t)
1165   (autoload 'R "ess-site" nil t)
1166   :config
1167   ; actually load the rest of ess
1168   (require 'ess-site)
1169   (defun ess-change-directory (path)
1170     "Set the current working directory to PATH for both *R* and Emacs."
1171     (interactive "Directory to change to: ")
1172
1173     (when (file-exists-p path)
1174       (ess-command (concat "setwd(\"" path "\")\n"))
1175       ;; use file-name-as-directory to ensure it has trailing /
1176       (setq default-directory (file-name-as-directory path))))
1177   (add-hook 'ess-mode-hook 'flyspell-prog-mode)
1178   ;; outlining support for ess modes
1179   (add-hook
1180    'ess-mode-hook
1181    '(lambda ()
1182       (outline-minor-mode)
1183       (setq outline-regexp "\\(^#\\{4,5\\} \\)\\|\\(^[a-zA-Z0-9_\.]+ ?<- ?function\\)")
1184       (defun outline-level ()
1185         (cond ((looking-at "^##### ") 1)
1186               ((looking-at "^#### ") 2)
1187               ((looking-at "^[a-zA-Z0-9_\.]+ ?<- ?function(.*{") 3)
1188               (t 1000)))
1189       ))
1190   (defun dla/ess-region-remote-eval (start end)
1191     "Evaluate region in a remote ESS instance"
1192     (interactive "r")
1193     (shell-command-on-region start end "eval_r" (get-buffer-create "***essregionremoteeval***") nil nil nil)
1194     (kill-buffer "***essregionremoteeval***"))
1195   ;; Don't restore history or save workspace image
1196   '(inferior-R-args "--no-restore-history --no-save")
1197   )
1198 #+END_SRC
1199
1200 ** Rainbowmode
1201 From http://julien.danjou.info/projects/emacs-packages#rainbow-mode, this colorizes color strings
1202
1203 #+BEGIN_SRC emacs-lisp
1204 (use-package rainbow-mode
1205   ;; add ess to the x major mode
1206   :config (add-to-list 'rainbow-x-colors-major-mode-list 'ESS[S])
1207   (add-to-list 'rainbow-x-colors-major-mode-list 'ESS[R])
1208 )
1209 #+END_SRC
1210
1211 ** YAML Mode
1212 #+BEGIN_SRC emacs-lisp
1213 (use-package yaml-mode
1214   ;; add ess to the x major mode
1215   :mode ("\\.\\(yaml|yml\\)\\'" . yaml-mode)
1216 )
1217 #+END_SRC
1218
1219 ** Polymode
1220 #+BEGIN_SRC emacs-lisp
1221 (use-package poly-noweb
1222   :after polymode
1223
1224   )
1225 (use-package poly-markdown
1226   :after polymode
1227   )
1228 (use-package poly-R
1229   :after (:all polymode poly-markdown poly-noweb)
1230   :mode ("\\.Snw" . poly-noweb+r-mode)
1231   :mode ("\\.Rnw" . poly-noweb+r-mode)
1232   :mode ("\\.Rmd" . poly-markdown+r-mode)
1233   )
1234 (use-package polymode
1235   )
1236
1237 #+END_SRC
1238
1239 ** Outlining
1240 *** outline minor mode
1241 #+BEGIN_SRC emacs-lisp
1242 (use-package outline
1243    :straight nil
1244    :delight
1245    :init
1246    (setq outline-minor-mode-prefix "C-c C-2")
1247 )
1248 #+END_SRC
1249 *** outshine (outlining) integration
1250 #+BEGIN_SRC emacs-lisp
1251 (use-package outshine
1252   :after outline
1253   :hook (outline-minor-mode . outshine-mode)
1254 )
1255 #+END_SRC
1256 ** Writeroom Mode
1257 #+BEGIN_SRC emacs-lisp
1258 (use-package writeroom-mode
1259   :config
1260   (defun my/writing-mode ()
1261     "Start my writing mode; enable visual-line-mode and auto-fill-mode"
1262     (interactive)
1263     (if writeroom-mode
1264         (progn
1265           (writeroom-mode -1)
1266           (visual-line-mode -1)
1267           (auto-fill-mode -1)
1268           (visual-fill-column-mode -1)
1269           )
1270       (visual-line-mode 1)
1271       (auto-fill-mode 1)
1272       (visual-fill-column-mode 1)
1273       (writeroom-mode 1))
1274     )
1275   )
1276 #+END_SRC
1277 ** GhostText/Atomic Chrome
1278 #+BEGIN_SRC emacs-lisp
1279 (use-package atomic-chrome
1280   :config
1281   (ignore-errors (atomic-chrome-start-server))
1282   (setq atomic-chrome-buffer-open-style 'full)
1283   )
1284 #+END_SRC
1285 ** Edit Server
1286 #+BEGIN_SRC emacs-lisp
1287 (use-package edit-server
1288   :commands edit-server-start
1289   :init (if after-init-time
1290             (edit-server-start)
1291           (add-hook 'after-init-hook
1292                     #'(lambda() (edit-server-start))))
1293   :config (setq edit-server-new-frame-alist
1294                 '((name . "Edit with Emacs FRAME")
1295                   (top . 200)
1296                   (left . 200)
1297                   (width . 80)
1298                   (height . 25)
1299                   (minibuffer . t)
1300                   (menu-bar-lines . t)
1301                   (window-system . x)))
1302   )
1303 #+END_SRC
1304 ** Multiple Cursors
1305 [[https://github.com/magnars/multiple-cursors.el][Multiple Cursors]]
1306 #+BEGIN_SRC emacs-lisp
1307 (use-package multiple-cursors
1308   :bind* (("C-;" . mc/mark-all-dwim)
1309           ("C-<" . mc/mark-previous-like-this)
1310           ("C->" . mc/mark-next-like-this)
1311           ("C-S-c C-S-c" . mc/edit-lines))
1312   )
1313 #+END_SRC
1314 ** Web Mode
1315 #+BEGIN_SRC emacs-lisp
1316 (use-package web-mode
1317   :mode ("\\.\\(tx|tmpl\\)\\'" . web-mode)
1318   :config
1319   (add-to-list 'auto-mode-alist '("\\.tmpl\\'" . web-mode))
1320   (setq web-mode-enable-engine-detection t)
1321   (setq web-mode-engines-alist
1322         '(("template-toolkit" . "\\.tmpl\\'")))
1323   )
1324 #+END_SRC
1325 ** Spamassassin Mode
1326 #+BEGIN_SRC emacs-lisp
1327 (use-package spamassassin-mode
1328   :straight nil
1329   :load-path "~/lib/emacs_el"
1330   :commands spamassassin-mode
1331   )
1332 #+END_SRC
1333 ** Password Store
1334 #+BEGIN_SRC emacs-lisp
1335 (use-package password-store
1336   :commands password-store-edit password-store-generate
1337   :config
1338   (defun dla/password-store-edit (entry)
1339     "Edit password for ENTRY which doesn't require it to already exist"
1340     (interactive (list (password-store--completing-read nil)))
1341     (password-store--run-edit entry))
1342   (advice-add 'password-store-edit :override #'dla/password-store-edit)
1343   )
1344 #+END_SRC
1345 ** CSS mode
1346 #+BEGIN_SRC emacs-lisp
1347 (use-package css
1348   :straight css-mode
1349   :mode "\\.css'"
1350   :config
1351   ;; fix up css mode to not be silly
1352   ;; from http://www.stokebloke.com/wordpress/2008/03/21/css-mode-indent-buffer-fix/
1353   (setq cssm-indent-level 4)
1354   (setq cssm-newline-before-closing-bracket t)
1355   (setq cssm-indent-function #'cssm-c-style-indenter)
1356   (setq cssm-mirror-mode nil))
1357 #+END_SRC
1358 ** Abbrev Mode
1359 #+BEGIN_SRC emacs-lisp
1360 (use-package abbrev
1361   :straight nil
1362   :delight abbrev-mode
1363   :config
1364   ;; load abbreviations from 
1365   (setq abbrev-file-name       
1366         "~/.emacs_abbrev_def")
1367
1368   ;; read the abbrev file if it exists
1369   (if (file-exists-p abbrev-file-name)
1370       (quietly-read-abbrev-file))
1371
1372   ;; for now, use abbrev mode everywhere
1373   :init 
1374   (setq default-abbrev-mode t))
1375 #+END_SRC
1376
1377 ** Debugging (realgud)
1378 #+BEGIN_SRC emacs-lisp
1379 (use-package realgud
1380   :commands (realgud:pdb realgud:gdb)
1381   )
1382 #+END_SRC
1383 ** Python Programming
1384 #+BEGIN_SRC emacs-lisp
1385 (use-package python-mode
1386   :delight Py 🐍
1387   :hook
1388   (python-mode . pyvenv-mode)
1389   (python-mode . flycheck-mode)
1390   (python-mode . blacken-mode)
1391   (python-mode . yas-minor-mode)
1392   (python-mode . anaconda-mode)
1393   )
1394 (use-package pyvenv
1395   :delight
1396   :after python-mode
1397   )
1398 (use-package blacken
1399   :delight
1400   :after python-mode
1401   :commands (blacken-buffer)
1402   :config
1403   (setq-default blacken-fast-unsafe t)
1404 )
1405 #+END_SRC
1406 *** Black
1407 #+begin_src emacs-lisp :tangle yes
1408 (use-package python-black
1409   :delight
1410   :commands (python-black-buffer python-black-statement)
1411   :after python)
1412 #+end_src
1413 *** Sphinx Documentation
1414 #+begin_src emacs-lisp :tangle yes
1415 (use-package numpydoc
1416   :after python
1417   :bind (:map python-mode-map
1418               ("C-c C-n" . numpydoc-generate)))
1419 (use-package sphinx-doc
1420   :delight 🐈
1421   :config
1422   (setq sphinx-doc-include-types t)
1423   :after python
1424   :hook (python-mode . sphinx-doc-mode)
1425   )
1426 (use-package python-docstring
1427   :delight 
1428   :after python
1429   :hook (python-mode . python-docstring-mode)
1430   )
1431 #+end_src
1432 *** Anaconda Mode (Documentation lookup and completion)
1433 #+BEGIN_SRC emacs-lisp
1434 (use-package anaconda-mode
1435   :delight
1436   :after python
1437 )
1438 #+END_SRC
1439 ** Go language
1440 #+BEGIN_SRC emacs-lisp
1441 (use-package go-mode
1442              :delight "go"
1443              :mode "\\.go"
1444              )
1445 #+END_SRC
1446
1447 ** Expand region
1448 #+BEGIN_SRC emacs-lisp
1449 (use-package expand-region
1450   :bind (("C-=" . 'er/expand-region))
1451   )
1452 #+END_SRC
1453
1454 ** Dockerfile
1455 #+BEGIN_SRC emacs-lisp
1456 (use-package dockerfile-mode
1457   :mode "Dockerfile"
1458   )
1459 #+END_SRC
1460
1461 ** Beancount
1462 #+BEGIN_SRC emacs-lisp
1463 (use-package beancount
1464   :straight nil
1465   :load-path "~/lib/emacs_el/beancount-mode/"
1466   :mode "\\.beancount\\'"
1467   
1468   )
1469 #+END_SRC
1470 ** Apache
1471 #+BEGIN_SRC emacs-lisp
1472 (use-package apache-mode
1473   :delight 🪶
1474   :mode "apache\\.conf\\'"
1475   )
1476 #+END_SRC
1477 ** ELDoc
1478 #+BEGIN_SRC emacs-lisp
1479 (use-package eldoc
1480   :delight
1481   :commands eldoc-mode
1482   :straight nil
1483   )
1484 #+END_SRC
1485
1486 * Email
1487 ** Mutt
1488 *** Message-mode
1489 #+BEGIN_SRC emacs-lisp
1490 (use-package message
1491   :straight nil
1492   :delight (message "✉")
1493   :delight (message-mode "✉")
1494   :mode ("muttng-[a-z0-9]+-[0-9]+-" . message-mode)
1495   :mode ("mutt-[a-z0-9]+-[0-9]+-" . message-mode)
1496   :hook 'my/message-mode-settings
1497   :hook 'turn-on-flyspell
1498   :bind (:map message-mode-map
1499       ("C-c C-a" . my/post-attach-file)
1500       ("C-x p" . my/message-kill-buffer)
1501       )
1502   :config
1503   (defun my/message-mode-settings ()
1504     (font-lock-add-keywords nil
1505                 '(("^[ \t]*>[ \t]*>[ \t]*>.*$"
1506                (0 'message-multiply-quoted-text-face))
1507               ("^[ \t]*>[ \t]*>.*$"
1508                (0 'message-double-quoted-text-face))))
1509     )
1510   (defun my/message-kill-buffer ()
1511     (interactive)
1512     (kill-buffer nil)
1513     )
1514   (defun my/post-attach-file ()
1515     "Prompt for an attachment."
1516     (interactive)
1517     (let ((file (read-file-name "Attach file: " nil nil t nil)))
1518       (my/header-attach-file file "")))
1519
1520   (defun my/header-attach-file (file description)
1521     "Attach a FILE to the current message (works with Mutt).
1522   Argument DESCRIPTION MIME description."
1523     (interactive "fAttach file: \nsDescription: ")
1524     (when (> (length file) 0)
1525   (save-excursion
1526     (save-match-data
1527       (save-restriction
1528         (widen)
1529         (goto-char (point-min))
1530         (search-forward-regexp "^$")
1531         (insert (concat "Attach: " (replace-regexp-in-string "\\([[:space:]\\]\\)" "\\\\\\1" (file-truename file)) " "
1532                 description "\n"))
1533         (message (concat "Attached '" file "'."))
1534         (setq post-has-attachment t))))))
1535
1536   (setq mail-yank-prefix "> ")
1537   (setq mail-header-separator "") ; fix broken header detection
1538 )
1539 #+END_SRC
1540 *** Muttrc mode
1541 #+BEGIN_SRC emacs-lisp
1542 (use-package mutt-mode
1543   :mode "muttngrc"
1544   :mode "muttrc"
1545 )
1546 #+END_SRC
1547 *** Set mail User agent
1548 #+BEGIN_SRC emacs-lisp
1549 (setq mail-user-agent (quote sendmail-user-agent))
1550 #+END_SRC
1551 *** Mail aliases
1552 #+BEGIN_SRC emacs-lisp
1553 ; (use-package
1554 ;   :straight t
1555 ;   :hook message
1556 ;   :config
1557 ;   (setq mutt-alias-file-list (quote ("~/.mutt/aliases" "~/.mail_aliases")))
1558 ; )
1559 #+END_SRC
1560 * Base emacs
1561 ** Reverting buffers
1562 #+BEGIN_SRC emacs-lisp
1563 (use-package autorevert
1564   :delight auto-revert-mode
1565   :config
1566   (setq global-auto-revert-non-file-buffers t
1567         global-auto-revert-ignore-modes '(pdf-view-mode)
1568         auto-revert-verbose nil)
1569   (global-auto-revert-mode 1))
1570 #+END_SRC
1571 * Org Mode
1572 ** Use-package and load things
1573 #+BEGIN_SRC emacs-lisp
1574
1575 (use-package org
1576   :delight (org-mode "ø")
1577   :mode ("\\.\\(org\\|org_archive\\|txt\\)\\'" . org-mode)
1578   :bind (("C-c l l" . org-store-link)
1579          ("C-c a"  . org-agenda)
1580          ("C-c b"  . org-iswitchb))
1581 #+END_SRC
1582 ** Agenda Configuration
1583 #+BEGIN_SRC emacs-lisp
1584   :config
1585   (setq-default org-log-done 'time)
1586   (setq-default org-agenda-ndays 5)
1587
1588   (setq org-agenda-sticky t)
1589   (defun dla/show-org-agenda ()
1590     (interactive)
1591     (let (agendabuffer
1592           '(delq nil 
1593                 (mapcar (lambda (x)
1594                           (and (string-match-p
1595                                 "\*Org Agenda.*\*"
1596                                 (buffer-name x))
1597                                x)
1598                           )
1599                         (buffer-list))))
1600       (if agendabuffer
1601           (switch-to-buffer
1602            (buffer-name agendabuffer))
1603         (org-agenda-list)))
1604       (delete-other-windows))
1605
1606   ;; agenda configuration
1607   ;; Do not dim blocked tasks
1608   (setq org-agenda-dim-blocked-tasks nil)
1609   (setq org-agenda-inhibit-startup t)
1610   (setq org-agenda-use-tag-inheritance nil)
1611
1612   ;; Compact the block agenda view
1613   (setq org-agenda-compact-blocks t)
1614
1615   ;; Custom agenda command definitions
1616   (setq org-agenda-custom-commands
1617         (quote (("N" "Notes" tags "NOTE"
1618                  ((org-agenda-overriding-header "Notes")
1619                   (org-tags-match-list-sublevels t)))
1620                 ("h" "Habits" tags-todo "STYLE=\"habit\""
1621                  ((org-agenda-overriding-header "Habits")
1622                   (org-agenda-sorting-strategy
1623                    '(todo-state-down effort-up category-keep))))
1624                 (" " "Agenda"
1625                  ((agenda "" nil)
1626                   (tags "REFILE"
1627                         ((org-agenda-overriding-header "Tasks to Refile")
1628                          (org-tags-match-list-sublevels nil)))
1629                   (tags-todo "-CANCELLED/!"
1630                              ((org-agenda-overriding-header "Stuck Projects")
1631                               (org-agenda-skip-function 'bh/skip-non-stuck-projects)
1632                               (org-agenda-sorting-strategy
1633                                '(category-keep))))
1634                   (tags-todo "-HOLD-CANCELLED/!"
1635                              ((org-agenda-overriding-header "Projects")
1636                               (org-agenda-skip-function 'bh/skip-non-projects)
1637                               (org-tags-match-list-sublevels 'indented)
1638                               (org-agenda-sorting-strategy
1639                                '(category-keep))))
1640                   (tags-todo "-CANCELLED/!NEXT"
1641                              ((org-agenda-overriding-header (concat "Project Next Tasks"
1642                                                                     (if bh/hide-scheduled-and-waiting-next-tasks
1643                                                                         ""
1644                                                                       " (including WAITING and SCHEDULED tasks)")))
1645                               (org-agenda-skip-function 'bh/skip-projects-and-habits-and-single-tasks)
1646                               (org-tags-match-list-sublevels t)
1647                               (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
1648                               (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
1649                               (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
1650                               (org-agenda-sorting-strategy
1651                                '(todo-state-down effort-up category-keep))))
1652                   (tags-todo "-REFILE-CANCELLED-WAITING-HOLD/!"
1653                              ((org-agenda-overriding-header (concat "Project Subtasks"
1654                                                                     (if bh/hide-scheduled-and-waiting-next-tasks
1655                                                                         ""
1656                                                                       " (including WAITING and SCHEDULED tasks)")))
1657                               (org-agenda-skip-function 'bh/skip-non-project-tasks)
1658                               (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
1659                               (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
1660                               (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
1661                               (org-agenda-sorting-strategy
1662                                '(category-keep))))
1663                   (tags-todo "-REFILE-CANCELLED-WAITING-HOLD/!"
1664                              ((org-agenda-overriding-header (concat "Standalone Tasks"
1665                                                                     (if bh/hide-scheduled-and-waiting-next-tasks
1666                                                                         ""
1667                                                                       " (including WAITING and SCHEDULED tasks)")))
1668                               (org-agenda-skip-function 'bh/skip-project-tasks)
1669                               (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
1670                               (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
1671                               (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
1672                               (org-agenda-sorting-strategy
1673                                '(category-keep))))
1674                   (tags-todo "-CANCELLED+WAITING|HOLD/!"
1675                              ((org-agenda-overriding-header "Waiting and Postponed Tasks")
1676                               (org-agenda-skip-function 'bh/skip-stuck-projects)
1677                               (org-tags-match-list-sublevels nil)
1678                               (org-agenda-todo-ignore-scheduled t)
1679                               (org-agenda-todo-ignore-deadlines t)))
1680                   (tags "-REFILE/"
1681                         ((org-agenda-overriding-header "Tasks to Archive")
1682                          (org-agenda-skip-function 'bh/skip-non-archivable-tasks)
1683                          (org-tags-match-list-sublevels nil))))
1684                  nil))))
1685
1686   ; org mode agenda files
1687   (setq org-agenda-files
1688         (append
1689         (file-expand-wildcards "~/projects/org-notes/*.org")
1690         (file-expand-wildcards "~/org-mode/from-mobile.org")
1691         (file-expand-wildcards "~/org-notes-*/*.org")
1692         )
1693   )
1694   (setq my/org-refile-file
1695         (car (seq-filter
1696               (lambda (file) (string-match-p (regexp-quote "/refile.org") file))
1697               org-agenda-files)))
1698
1699   (set-register ?n (cons 'file "~/projects/org-notes/notes.org"))
1700   (set-register ?r (cons 'file my/org-refile-file))
1701   (set-register ?o (cons 'file "~/projects/org-notes/ool.org"))
1702   (set-register ?s (cons 'file "~/projects/org-notes/sndservers.org"))
1703   (set-register ?c (cons 'file "~/projects/org-notes/chaim.org"))
1704   (set-register ?w (cons 'file "~/projects/org-notes/wildman.org"))
1705   (set-register ?u (cons 'file "~/projects/org-notes/uddin.org"))
1706   (set-register ?R (cons 'file "~/projects/reviews/reviews.org"))
1707   (set-register ?d (cons 'file "~/projects/org-notes/diary.org"))
1708   ; from https://emacs.stackexchange.com/questions/909/how-can-i-have-an-agenda-timeline-view-of-multiple-files
1709   ; (defun org-agenda-timeline-all (&optional arg)
1710   ;   (interactive "P")
1711   ;   (with-temp-buffer
1712   ;     (dolist (org-agenda-file org-agenda-files)
1713   ;       (insert-file-contents org-agenda-file nil)
1714   ;       (goto-char (point-max))
1715   ;       (newline))
1716   ;     (write-file "/tmp/timeline.org")
1717   ;     (org-agenda arg "L")))
1718   ; (define-key org-mode-map (kbd "C-c t") 'org-agenda-timeline-all)
1719
1720 #+END_SRC
1721 ** General config
1722 #+BEGIN_SRC emacs-lisp
1723   (setq org-global-properties '(("Effort_ALL 0 0:10 0:30 1:00 2:00 3:00 4:00 5:00 6:00 7:00")))
1724   (setq org-columns-default-format "%40ITEM(Task) %6Effort{:} %CLOCKSUM %PRIORITY %TODO %13SCHEDULED %13DEADLINE %TAGS")
1725
1726   (setq org-default-notes-file "~/projects/org-notes/notes.org")
1727   (setq org-id-link-to-org-use-id 'use-existing)
1728 #+END_SRC
1729 ** Capture Templates
1730 #+BEGIN_SRC emacs-lisp
1731   (setq org-capture-templates  ;; mail-specific note template, identified by "m"
1732         `(("m" "Mail" entry (file my/org-refile-file)
1733            "* %?\n\n  Source: %u, [[%:link][%:description]]\n  %:initial")
1734           ("t" "todo" entry (file my/org-refile-file)
1735            "* TODO %?\n  :PROPERTIES:\n  :END:\n  :LOGBOOK:\n  :END:\n%U\n%a\n" :clock-in t :clock-resume t)
1736           ("r" "respond" entry (file my/org-refile-file)
1737            "* NEXT Respond to %:from on %:subject\nSCHEDULED: %t\n%U\n%a\n" :clock-in t :clock-resume t :immediate-finish t)
1738           ("n" "note" entry (file my/org-refile-file)
1739            "* %? :NOTE:\n%U\n%a\n" :clock-in t :clock-resume t)
1740           ("s" "schedule" entry (file my/org-refile-file)
1741            "* %? :cal:\n%^{scheduled:}t\n%U\n%a\n" :clock-in t :clock-resume t)
1742           ("j" "Journal" entry (file+datetree "~/projects/org-notes/diary.org")
1743            "* %?\n%U\n" :clock-in t :clock-resume t)
1744           ("w" "org-protocol" entry (file my/org-refile-file)
1745            "* TODO Review %c\n%U\n" :immediate-finish t)
1746           ("M" "Meeting" entry (file my/org-refile-file)
1747            "* MEETING with %? :MEETING:\n%U" :clock-in t :clock-resume t)
1748           ("S" "Seminar" entry (file my/org-refile-file)
1749            "* SEMINAR notes %? :SEMINAR:\n%U" :clock-in t :clock-resume t)
1750           ("P" "Paper to read" entry (file+headline "~/projects/research/papers_to_read.org" "Refile")
1751            "* TODO Get/Read %? \n%U" :clock-in t :clock-resume t)
1752           ("p" "Phone call" entry (file my/org-refile-file)
1753            "* PHONE %? :PHONE:\n%U" :clock-in t :clock-resume t)
1754            ("J" "job" entry (file+olp "~/projects/org-notes/notes.org"
1755                                        "Jobs"
1756                                        ,(format-time-string "Positions %Y"))
1757            "* TODO Apply for %? :job:\nSCHEDULED: <%<%Y-%m-%d>>\n%U\n%x\n" :clock-in t :clock-resume t)
1758           ("h" "Habit" entry (file my/org-refile-file)
1759            "* NEXT %?\n%U\n%a\nSCHEDULED: %(format-time-string \"<%Y-%m-%d .+1d/3d>\")\n:PROPERTIES:\n:STYLE: habit\n:REPEAT_TO_STATE: NEXT\n:END:\n%a\n")
1760           )
1761         )
1762
1763   ;; Remove empty LOGBOOK drawers on clock out
1764   (defun bh/remove-empty-drawer-on-clock-out ()
1765     (interactive)
1766     (save-excursion
1767       (beginning-of-line 0)
1768       (org-remove-empty-drawer-at (point))))
1769
1770   (defun my/org-add-id ()
1771     (interactive)
1772     (save-excursion
1773       (if (org-current-level)
1774           ()
1775         (forward-char 1)
1776         )
1777       (org-id-get-create)
1778       )
1779   )
1780
1781 #+END_SRC
1782 ** Org mode key bindings
1783 #+BEGIN_SRC emacs-lisp
1784   ;; org mode configuration from http://doc.norang.ca/org-mode.html
1785   ;; Custom Key Bindings
1786   :bind* (("<f9> a" . org-agenda)
1787           ("<f9> I" . bh/punch-in)
1788           ("<f9> O" . bh/punch-out)
1789           ("<f9> SPC" . bh/clock-in-last-task)
1790           ("<f12>" . dla/show-org-agenda)
1791           ;; ("<f5>" . bh/org-todo)
1792           ("<S-f5>" . bh/widen)
1793           ("<f7>" . bh/set-truncate-lines)
1794           ("<f8>" . org-cycle-agenda-files)
1795           ("<f9> <f9>" . dla/show-org-agenda)
1796           ("<f9> b" . bbdb)
1797           ("<f9> c" . calendar)
1798           ("<f9> f" . boxquote-insert-file)
1799           ("<f9> h" . bh/hide-other)
1800           ("<f9> n" . bh/toggle-next-task-display)
1801           ("<f9> w" . widen)
1802
1803           ("<f9> r" . boxquote-region)
1804           ("<f9> s" . bh/switch-to-scratch)
1805
1806           ("<f9> t" . bh/insert-inactive-timestamp)
1807           ("<f9> T" . bh/toggle-insert-inactive-timestamp)
1808
1809           ("<f9> v" . visible-mode)
1810           ("<f9> l" . org-toggle-link-display)
1811           ("<f9> SPC" . bh/clock-in-last-task)
1812           ("C-<f9>" . previous-buffer)
1813           ("M-<f9>" . org-toggle-inline-images)
1814           ("C-x n r" . narrow-to-region)
1815           ("C-<f10>" . next-buffer)
1816           ("<f11>" . org-clock-goto)
1817           ("C-<f11>" . org-clock-in)
1818           ("C-s-<f12>" . bh/save-then-publish)
1819           ("C-c c" . org-capture))
1820   :config
1821 #+END_SRC
1822 ** Utility Functions
1823 #+BEGIN_SRC emacs-lisp
1824 (defun bh/hide-other ()
1825   (interactive)
1826   (save-excursion
1827     (org-back-to-heading 'invisible-ok)
1828     (outline-hide-other)
1829     (org-cycle)
1830     (org-cycle)
1831     (org-cycle)))
1832
1833 (defun bh/set-truncate-lines ()
1834   "Toggle value of truncate-lines and refresh window display."
1835   (interactive)
1836   (setq truncate-lines (not truncate-lines))
1837   ;; now refresh window display (an idiom from simple.el):
1838   (save-excursion
1839     (set-window-start (selected-window)
1840                       (window-start (selected-window)))))
1841
1842 (defun bh/switch-to-scratch ()
1843   (interactive)
1844   (switch-to-buffer "*scratch*"))
1845
1846 (setq org-use-fast-todo-selection t)
1847 (setq org-treat-S-cursor-todo-selection-as-state-change nil)
1848
1849 ; create function to create headlines in file. This comes from
1850 ; http://stackoverflow.com/questions/13340616/assign-ids-to-every-entry-in-org-mode
1851 (defun my/org-add-ids-to-headlines-in-file ()
1852   "Add ID properties to all headlines in the current file which
1853 do not already have one."
1854   (interactive)
1855   (save-excursion
1856     (widen)
1857     (goto-char (point-min))
1858     (when (not (re-search-forward "^#\\+OPTIONS:.*auto-id:f" (point-max) t))
1859       (org-map-entries 'org-id-get-create))))
1860 (defun dla/org-update-ids-to-headlines-in-file ()
1861   "Add or replace ID properties to all headlines in the current file 
1862 (or narrowed region)."
1863   (interactive)
1864
1865   (org-map-entries '(lambda () (org-id-get-create t))))
1866 ; if we wanted to do this to every buffer, do the following:
1867 (add-hook 'org-mode-hook
1868           (lambda ()
1869             (add-hook 'before-save-hook 'my/org-add-ids-to-headlines-in-file nil 'local)))
1870 #+END_SRC
1871 ** Org ID locations
1872 #+BEGIN_SRC emacs-lisp
1873 (use-package find-lisp
1874   :demand t)
1875 (setq org-agenda-text-search-extra-files
1876       (append '(agenda-archives)
1877               (find-lisp-find-files "~/projects/org-notes" "\.org$")
1878               (find-lisp-find-files "~/projects/org-notes" "\.org_archive$")
1879               ))
1880 #+END_SRC
1881 ** Keywords (TODO)
1882 #+BEGIN_SRC emacs-lisp
1883 (setq org-todo-keywords
1884       (quote ((sequence "TODO(t)" "NEXT(n)" "|" "DONE(d)")
1885               (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" "PHONE" "MEETING"))))
1886
1887 (setq org-todo-keyword-faces
1888       (quote (("TODO" :foreground "red" :weight bold)
1889               ("NEXT" :foreground "blue" :weight bold)
1890               ("DONE" :foreground "forest green" :weight bold)
1891               ("WAITING" :foreground "orange" :weight bold)
1892               ("HOLD" :foreground "magenta" :weight bold)
1893               ("CANCELLED" :foreground "forest green" :weight bold)
1894               ("MEETING" :foreground "forest green" :weight bold)
1895               ("PHONE" :foreground "forest green" :weight bold))))
1896
1897 (setq org-todo-state-tags-triggers
1898       (quote (("CANCELLED" ("CANCELLED" . t))
1899               ("WAITING" ("WAITING" . t))
1900               ("HOLD" ("WAITING") ("HOLD" . t))
1901               (done ("WAITING") ("HOLD"))
1902               ("TODO" ("WAITING") ("CANCELLED") ("HOLD"))
1903               ("NEXT" ("WAITING") ("CANCELLED") ("HOLD"))
1904               ("DONE" ("WAITING") ("CANCELLED") ("HOLD")))))
1905
1906
1907
1908 ; (add-hook 'org-clock-out-hook 'bh/remove-empty-drawer-on-clock-out 'append)
1909 ; add ids on creation of nodes
1910 (add-hook 'org-capture-prepare-finalize-hook 'my/org-add-id)
1911
1912
1913 ; resolve clocks after 10 minutes of idle; use xprintidle
1914 ; (setq org-clock-idle-time 10)
1915 ; (setq org-clock-x11idle-program-name "xprintidle")
1916
1917 ; this is from http://doc.norang.ca/org-mode.html#Capture
1918 ; use C-M-r for org mode capture
1919 (global-set-key (kbd "C-M-r") 'org-capture)
1920
1921 ; Targets include this file and any file contributing to the agenda - up to 9 levels deep
1922 (setq org-refile-targets (quote ((nil :maxlevel . 9)
1923                                  (org-agenda-files :maxlevel . 9))))
1924
1925 ; Use full outline paths for refile targets - we file directly with IDO
1926 (setq org-refile-use-outline-path t)
1927
1928 ; Targets complete directly with IDO
1929 (setq org-outline-path-complete-in-steps nil)
1930
1931 ; Allow refile to create parent tasks with confirmation
1932 (setq org-refile-allow-creating-parent-nodes (quote confirm))
1933
1934 ; ; Use IDO for both buffer and file completion and ido-everywhere to t
1935 ; (setq org-completion-use-ido t)
1936 ; (setq ido-everywhere t)
1937 ; (setq ido-max-directory-size 100000)
1938 ; (ido-mode (quote both))
1939 ; ; Use the current window when visiting files and buffers with ido
1940 ; (setq ido-default-file-method 'selected-window)
1941 ; (setq ido-default-buffer-method 'selected-window)
1942 ; ; Use the current window for indirect buffer display
1943 ; (setq org-indirect-buffer-display 'current-window)
1944
1945
1946 ;;;; Refile settings
1947 ; Exclude DONE state tasks from refile targets
1948 (defun bh/verify-refile-target ()
1949   "Exclude todo keywords with a done state from refile targets"
1950   (not (member (nth 2 (org-heading-components)) org-done-keywords)))
1951
1952 (setq org-refile-target-verify-function 'bh/verify-refile-target)
1953
1954 ;; ensure that emacsclient will show just the note to be edited when invoked
1955 ;; from Mutt, and that it will shut down emacsclient once finished;
1956 ;; fallback to legacy behavior when not invoked via org-protocol.
1957 (require 'org-protocol)
1958 ; (add-hook 'org-capture-mode-hook 'delete-other-windows)
1959 (setq my-org-protocol-flag nil)
1960 (defadvice org-capture-finalize (after delete-frame-at-end activate)
1961   "Delete frame at remember finalization"
1962   (progn (if my-org-protocol-flag (delete-frame))
1963          (setq my-org-protocol-flag nil)))
1964 (defadvice org-capture-refile (around delete-frame-after-refile activate)
1965   "Delete frame at remember refile"
1966   (if my-org-protocol-flag
1967       (progn
1968         (setq my-org-protocol-flag nil)
1969         ad-do-it
1970         (delete-frame))
1971     ad-do-it)
1972   )
1973 (defadvice org-capture-kill (after delete-frame-at-end activate)
1974   "Delete frame at remember abort"
1975   (progn (if my-org-protocol-flag (delete-frame))
1976          (setq my-org-protocol-flag nil)))
1977 (defadvice org-protocol-capture (before set-org-protocol-flag activate)
1978   (setq my-org-protocol-flag t))
1979
1980 (defadvice org-insert-todo-heading (after dla/create-id activate)
1981   (unless (org-in-item-p)
1982     (org-id-get-create)
1983     )
1984   )
1985
1986 ;; org modules
1987 (add-to-list 'org-modules 'org-habit)
1988
1989 ; this comes from http://upsilon.cc/~zack/blog/posts/2010/02/integrating_Mutt_with_Org-mode/
1990 (defun open-mail-in-mutt (message)
1991   "Open a mail message in Mutt, using an external terminal.
1992
1993 Message can be specified either by a path pointing inside a
1994 Maildir, or by Message-ID."
1995   (interactive "MPath or Message-ID: ")
1996   (shell-command
1997    (format "faf xterm -e \"%s %s\""
1998        (substitute-in-file-name "$HOME/bin/mutt_open") message)))
1999
2000 ;; add support for "mutt:ID" links
2001 (org-add-link-type "mutt" 'open-mail-in-mutt)
2002
2003 (defun my-org-mode-setup ()
2004   ; (load-library "reftex")
2005   (and (buffer-file-name)
2006        (file-exists-p (buffer-file-name))
2007        (progn
2008          ; (reftex-parse-all)
2009          (reftex-set-cite-format
2010           '((?b . "[[bib:%l][%l-bib]]")
2011             (?n . "[[notes:%l][%l-notes]]")
2012             (?c . "\\cite{%l}")
2013             (?h . "*** %t\n:PROPERTIES:\n:Custom_ID: %l\n:END:\n[[papers:%l][%l xoj]] [[papers-pdf:%l][pdf]]")))
2014          ))
2015   (define-key org-mode-map (kbd "C-c )") 'reftex-citation)
2016   (define-key org-mode-map (kbd "C-c [") 'reftex-citation)
2017   (define-key org-mode-map (kbd "C-c (") 'org-mode-reftex-search)
2018   (define-key org-mode-map (kbd "C-c 0") 'reftex-view-crossref)
2019   )
2020 (add-hook 'org-mode-hook 'my-org-mode-setup)
2021
2022 (defun org-mode-reftex-search ()
2023   (interactive)
2024   (org-open-link-from-string (format "[[notes:%s]]" (first (reftex-citation t)))))
2025
2026 (defun open-research-paper (bibtexkey)
2027   "Open a paper by bibtex key"
2028   (interactive "bibtex key: ")
2029   (shell-command
2030    (format "%s %s"
2031        (substitute-in-file-name "$HOME/bin/bibtex_to_paper") bibtexkey)))
2032 (org-add-link-type "papers" 'open-research-paper)
2033 (defun open-research-paper-pdf (bibtexkey)
2034   "Open a paper pdf by bibtex key"
2035   (interactive "bibtex key: ")
2036   (shell-command
2037    (format "%s -p evince_annot %s"
2038        (substitute-in-file-name "$HOME/bin/bibtex_to_paper") bibtexkey)))
2039 (org-add-link-type "papers-pdf" 'open-research-paper-pdf)
2040
2041 (add-to-list 'org-link-abbrev-alist
2042              '("notes" .
2043                "~/projects/research/paper_notes.org::#%s"))
2044
2045 ; I pretty much always want hiearchical checkboxes
2046 (setq org-hierachical-checkbox-statistics nil)
2047
2048 ;; Add \begin{equation}\end{equation} templates to the org mode easy templates
2049 (add-to-list 'org-structure-template-alist
2050              '("E" "\\begin{equation}\n?\n\\end{equation}"))
2051
2052  ;; stolen from
2053 ;; http://www-public.it-sudparis.eu/~berger_o/weblog/2012/03/23/how-to-manage-and-export-bibliographic-notesrefs-in-org-mode/
2054 (defun my-rtcite-export-handler (path desc format)
2055   (message "my-rtcite-export-handler is called : path = %s, desc = %s, format = %s" path desc format)
2056   (let* ((search (when (string-match "::#?\\(.+\\)\\'" path)
2057                    (match-string 1 path)))
2058          (path (substring path 0 (match-beginning 0))))
2059     (cond ((eq format 'latex)
2060            (if (or (not desc) 
2061                    (equal 0 (search "rtcite:" desc)))
2062                (format "\\cite{%s}" search)
2063              (format "\\cite[%s]{%s}" desc search))))))
2064
2065 (org-add-link-type "rtcite" 
2066                    'org-bibtex-open
2067                    'my-rtcite-export-handler)
2068
2069
2070 #+END_SRC
2071 ** Org Mobile Configuration
2072 #+BEGIN_SRC emacs-lisp
2073   (setq-default org-mobile-directory "/linnode.donarmstrong.com:/sites/dav.donarmstrong.com/root/org/")
2074   (when (string= system-name "linnode")
2075     (setq-default org-mobile-directory "/sites/dav.donarmstrong.com/root/org/"))
2076   (setq-default org-directory "/home/don/org-mode/")
2077   (setq-default org-mobile-inbox-for-pull "/home/don/org-mode/from-mobile.org")
2078
2079 #+END_SRC
2080 ** Org iCal Support
2081 #+BEGIN_SRC emacs-lisp
2082   ;; org mode ical export
2083   (setq org-icalendar-timezone "America/Los_Angeles")
2084   (setq org-icalendar-use-scheduled '(todo-start event-if-todo))
2085   ;; we already add the id manually
2086   (setq org-icalendar-store-UID t)
2087
2088 #+END_SRC
2089 ** General Org Babel Configuration
2090 #+BEGIN_SRC emacs-lisp
2091 ;; org babel support
2092 (org-babel-do-load-languages
2093  'org-babel-load-languages
2094  '((emacs-lisp . t )
2095    (R . t)
2096    (latex . t)
2097    (ditaa . t)
2098    (dot . t)
2099    ))
2100 ;; set the right path to ditaa.jar
2101 (setq org-ditaa-jar-path "/usr/share/ditaa/ditaa.jar")
2102 ;; use graphviz-dot for dot things
2103 (add-to-list 'org-src-lang-modes '("dot" . graphviz-dot))
2104 ;; do not indent begin_src blocks
2105 (setq org-edit-src-content-indentation 0)
2106 ;; org-babel-by-backend
2107 (defmacro org-babel-by-backend (&rest body)
2108    `(case (if (boundp 'backend) 
2109               (org-export-backend-name backend)
2110             nil) ,@body))
2111
2112 (defun my/fix-inline-images ()
2113   (when org-inline-image-overlays
2114     (org-redisplay-inline-images)))
2115
2116 (add-hook 'org-babel-after-execute-hook
2117            'my/fix-inline-images)
2118
2119 #+END_SRC
2120 ** LaTeX configuration
2121 #+BEGIN_SRC emacs-lisp
2122 (use-package org-contrib
2123   :no-require t
2124   :after org
2125   :config
2126   (require 'ox-extra)
2127   (ox-extras-activate '(latex-header-blocks ignore-headlines))
2128   (require 'ox-latex)
2129 (add-to-list 'org-latex-classes
2130          '("memarticle"
2131        "\\documentclass[11pt,oneside,article]{memoir}\n"
2132        ("\\section{%s}" . "\\section*{%s}")
2133        ("\\subsection{%s}" . "\\subsection*{%s}")
2134        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2135        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2136        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2137
2138 (setq org-beamer-outline-frame-options "")
2139 (add-to-list 'org-latex-classes
2140          '("beamer"
2141        "\\documentclass[ignorenonframetext]{beamer}
2142 [NO-DEFAULT-PACKAGES]
2143 [PACKAGES]
2144 [EXTRA]"
2145        ("\\section{%s}" . "\\section*{%s}")
2146        ("\\subsection{%s}" . "\\subsection*{%s}")
2147        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2148        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2149        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2150
2151 (add-to-list 'org-latex-classes
2152          '("membook"
2153        "\\documentclass[11pt,oneside]{memoir}\n"
2154        ("\\chapter{%s}" . "\\chapter*{%s}")
2155        ("\\section{%s}" . "\\section*{%s}")
2156        ("\\subsection{%s}" . "\\subsection*{%s}")
2157        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
2158
2159 (add-to-list 'org-latex-classes
2160          '("letter"
2161        "\\documentclass[11pt]{letter}
2162 [NO-DEFAULT-PACKAGES]
2163 [PACKAGES]
2164 [EXTRA]"
2165    ("\\section{%s}" . "\\section*{%s}")
2166        ("\\subsection{%s}" . "\\subsection*{%s}")
2167        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2168        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2169        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2170
2171 (add-to-list 'org-latex-classes
2172          '("dlacv"
2173        "\\documentclass{dlacv}
2174 [NO-DEFAULT-PACKAGES]
2175 [NO-PACKAGES]
2176 [NO-EXTRA]"
2177        ("\\section{%s}" . "\\section*{%s}")
2178        ("\\subsection{%s}" . "\\subsection*{%s}")
2179        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2180        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2181        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2182
2183
2184 (add-to-list 'org-latex-classes
2185          '("dlaresume"
2186        "\\documentclass{dlaresume}
2187 [NO-DEFAULT-PACKAGES]
2188 [NO-PACKAGES]
2189 [NO-EXTRA]"
2190        ("\\section{%s}" . "\\section*{%s}")
2191        ("\\subsection{%s}" . "\\subsection*{%s}")
2192        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2193        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2194        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2195
2196
2197 ;; Originally taken from Bruno Tavernier: http://thread.gmane.org/gmane.emacs.orgmode/31150/focus=31432
2198 ;; but adapted to use latexmk 4.22 or higher.  
2199 (setq org-latex-pdf-process '("latexmk -f -pdflatex=xelatex -bibtex -use-make -pdf %f"))
2200
2201 ;; Default packages included in /every/ tex file, latex, pdflatex or xelatex
2202 (setq org-latex-default-packages-alist
2203   '(("" "amsmath" t)
2204     ("" "unicode-math" t)
2205     ))
2206 (setq org-latex-packages-alist
2207   '(("" "graphicx" t)
2208     ("" "fontspec" t)
2209     ("" "xunicode" t)
2210     ("" "hyperref" t)
2211     ("" "url" t)
2212     ("" "rotating" t)
2213     ("" "longtable" nil)
2214     ("" "float" )))
2215
2216 ;; make equations larger
2217 (setq org-format-latex-options (plist-put org-format-latex-options :scale 2.0))
2218
2219 (defun org-create-formula--latex-header ()
2220   "Return LaTeX header appropriate for previewing a LaTeX snippet."
2221   (let ((info (org-combine-plists (org-export--get-global-options
2222            (org-export-get-backend 'latex))
2223           (org-export--get-inbuffer-options
2224            (org-export-get-backend 'latex)))))
2225     (org-latex-guess-babel-language
2226      (org-latex-guess-inputenc
2227   (org-splice-latex-header
2228    org-format-latex-header
2229    org-latex-default-packages-alist
2230    nil t
2231    (plist-get info :latex-header)))
2232      info)))
2233
2234
2235 ; support ignoring headers in org mode export to latex
2236 ; from http://article.gmane.org/gmane.emacs.orgmode/67692
2237 (defadvice org-latex-headline (around my-latex-skip-headlines
2238                   (headline contents info) activate)
2239   (if (member "ignoreheading" (org-element-property :tags headline))
2240   (setq ad-return-value contents)
2241     ad-do-it))
2242
2243 ;; keep latex logfiles
2244
2245 (setq org-latex-remove-logfiles nil)
2246 )
2247
2248 ;; Resume clocking task when emacs is restarted
2249 (org-clock-persistence-insinuate)
2250 ;;
2251 ;; Show lot of clocking history so it's easy to pick items off the C-F11 list
2252 (setq org-clock-history-length 23)
2253 ;; Resume clocking task on clock-in if the clock is open
2254 (setq org-clock-in-resume t)
2255 ;; Change tasks to NEXT when clocking in; this avoids clocking in when
2256 ;; there are things like PHONE calls
2257 (setq org-clock-in-switch-to-state 'bh/clock-in-to-next)
2258 ;; Separate drawers for clocking and logs
2259 (setq org-drawers (quote ("PROPERTIES" "LOGBOOK")))
2260 ;; Save clock data and state changes and notes in the LOGBOOK drawer
2261 (setq org-clock-into-drawer t)
2262 (setq org-log-into-drawer t)
2263 ;; Sometimes I change tasks I'm clocking quickly - this removes clocked tasks with 0:00 duration
2264 (setq org-clock-out-remove-zero-time-clocks t)
2265 ;; Clock out when moving task to a done state
2266 (setq org-clock-out-when-done t)
2267 ;; Save the running clock and all clock history when exiting Emacs, load it on startup
2268 (setq org-clock-persist t)
2269 ;; Do not prompt to resume an active clock
2270 (setq org-clock-persist-query-resume nil)
2271 ;; Enable auto clock resolution for finding open clocks
2272 (setq org-clock-auto-clock-resolution (quote when-no-clock-is-running))
2273 ;; Include current clocking task in clock reports
2274 (setq org-clock-report-include-clocking-task t)
2275
2276 ;; the cache seems to be broken
2277 (setq org-element-use-cache nil)
2278
2279 (defvar bh/keep-clock-running nil)
2280
2281 (defun bh/is-task-p ()
2282   "Any task with a todo keyword and no subtask"
2283   (save-restriction
2284     (widen)
2285     (let ((has-subtask)
2286           (subtree-end (save-excursion (org-end-of-subtree t)))
2287           (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
2288       (save-excursion
2289         (forward-line 1)
2290         (while (and (not has-subtask)
2291                     (< (point) subtree-end)
2292                     (re-search-forward "^\*+ " subtree-end t))
2293           (when (member (org-get-todo-state) org-todo-keywords-1)
2294             (setq has-subtask t))))
2295       (and is-a-task (not has-subtask)))))
2296 (defun bh/is-project-p ()
2297   "Any task with a todo keyword subtask"
2298   (save-restriction
2299     (widen)
2300     (let ((has-subtask)
2301           (subtree-end (save-excursion (org-end-of-subtree t)))
2302           (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
2303       (save-excursion
2304         (forward-line 1)
2305         (while (and (not has-subtask)
2306                     (< (point) subtree-end)
2307                     (re-search-forward "^\*+ " subtree-end t))
2308           (when (member (org-get-todo-state) org-todo-keywords-1)
2309             (setq has-subtask t))))
2310       (and is-a-task has-subtask))))
2311
2312 (defun bh/is-subproject-p ()
2313   "Any task which is a subtask of another project"
2314   (let ((is-subproject)
2315         (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
2316     (save-excursion
2317       (while (and (not is-subproject) (org-up-heading-safe))
2318         (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
2319           (setq is-subproject t))))
2320     (and is-a-task is-subproject)))
2321
2322
2323 (defun bh/clock-in-to-next (kw)
2324   "Switch a task from TODO to NEXT when clocking in.
2325 Skips capture tasks, projects, and subprojects.
2326 Switch projects and subprojects from NEXT back to TODO"
2327   (when (not (and (boundp 'org-capture-mode) org-capture-mode))
2328     (cond
2329      ((and (member (org-get-todo-state) (list "TODO"))
2330        (bh/is-task-p))
2331   "NEXT")
2332      ((and (member (org-get-todo-state) (list "NEXT"))
2333        (bh/is-project-p))
2334   "TODO"))))
2335
2336 (defun bh/punch-in (arg)
2337   "Start continuous clocking and set the default task to the
2338 selected task.  If no task is selected set the Organization task
2339 as the default task."
2340   (interactive "p")
2341   (setq bh/keep-clock-running t)
2342   (if (equal major-mode 'org-agenda-mode)
2343   ;;
2344   ;; We're in the agenda
2345   ;;
2346   (let* ((marker (org-get-at-bol 'org-hd-marker))
2347          (tags (org-with-point-at marker (org-get-tags))))
2348     (if (and (eq arg 4) tags)
2349         (org-agenda-clock-in '(16))
2350       (bh/clock-in-organization-task-as-default)))
2351     ;;
2352     ;; We are not in the agenda
2353     ;;
2354     (save-restriction
2355   (widen)
2356   ; Find the tags on the current task
2357   (if (and (equal major-mode 'org-mode) (not (org-before-first-heading-p)) (eq arg 4))
2358       (org-clock-in '(16))
2359     (bh/clock-in-organization-task-as-default)))))
2360
2361 (defun bh/punch-out ()
2362   (interactive)
2363   (setq bh/keep-clock-running nil)
2364   (when (org-clock-is-active)
2365     (org-clock-out))
2366   (org-agenda-remove-restriction-lock))
2367
2368 (defun bh/clock-in-default-task ()
2369   (save-excursion
2370     (org-with-point-at org-clock-default-task
2371   (org-clock-in))))
2372
2373 (defun bh/clock-in-parent-task ()
2374   "Move point to the parent (project) task if any and clock in"
2375   (let ((parent-task))
2376     (save-excursion
2377   (save-restriction
2378     (widen)
2379     (while (and (not parent-task) (org-up-heading-safe))
2380       (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
2381         (setq parent-task (point))))
2382     (if parent-task
2383         (org-with-point-at parent-task
2384       (org-clock-in))
2385       (when bh/keep-clock-running
2386         (bh/clock-in-default-task)))))))
2387
2388 (defvar bh/organization-task-id "e22cb8bf-07c7-408b-8f60-ff3aadac95e4")
2389
2390 (defun bh/clock-in-organization-task-as-default ()
2391   (interactive)
2392   (org-with-point-at (org-id-find bh/organization-task-id 'marker)
2393     (org-clock-in '(16))))
2394
2395 (defun bh/clock-out-maybe ()
2396   (when (and bh/keep-clock-running
2397          (not org-clock-clocking-in)
2398          (marker-buffer org-clock-default-task)
2399          (not org-clock-resolving-clocks-due-to-idleness))
2400     (bh/clock-in-parent-task)))
2401
2402 ; (add-hook 'org-clock-out-hook 'bh/clock-out-maybe 'append)
2403
2404 (require 'org-id)
2405 (defun bh/clock-in-task-by-id (id)
2406   "Clock in a task by id"
2407   (org-with-point-at (org-id-find id 'marker)
2408     (org-clock-in nil)))
2409
2410 (defun bh/clock-in-last-task (arg)
2411   "Clock in the interrupted task if there is one
2412 Skip the default task and get the next one.
2413 A prefix arg forces clock in of the default task."
2414   (interactive "p")
2415   (let ((clock-in-to-task
2416      (cond
2417       ((eq arg 4) org-clock-default-task)
2418       ((and (org-clock-is-active)
2419         (equal org-clock-default-task (cadr org-clock-history)))
2420        (caddr org-clock-history))
2421       ((org-clock-is-active) (cadr org-clock-history))
2422       ((equal org-clock-default-task (car org-clock-history)) (cadr org-clock-history))
2423       (t (car org-clock-history)))))
2424     (widen)
2425     (org-with-point-at clock-in-to-task
2426   (org-clock-in nil))))
2427
2428
2429 (defun org-export-to-ods ()
2430   (interactive)
2431   (let ((csv-file "data.csv"))
2432     (org-table-export csv-file "orgtbl-to-csv")
2433     (org-odt-convert csv-file "ods" 'open)))
2434
2435 ; allow for zero-width-space to be a break in regexp too
2436 ; (setcar org-emphasis-regexp-components "​ [:space:] \t('\"{")
2437 ; (setcar (nthcdr 1 org-emphasis-regexp-components) "​ [:space:]- \t.,:!?;'\")}\\")
2438 ; (org-set-emph-re 'org-emphasis-regexp-components org-emphasis-regexp-components)
2439
2440 ;; support inserting screen shots
2441 (defun my/org-insert-screenshot ()
2442   "Take a screenshot into a time stamped unique-named file in the
2443 same directory as the org-buffer and insert a link to this file."
2444   (interactive)
2445   (defvar my/org-insert-screenshot/filename)
2446   (setq my/org-insert-screenshot/filename
2447     (read-file-name
2448      "Screenshot to insert: "
2449      nil
2450      (concat (buffer-file-name) "_" (format-time-string "%Y%m%d_%H%M%S") ".png")
2451      )
2452     )
2453   (call-process "import" nil nil nil my/org-insert-screenshot/filename)
2454   (insert (concat "[[" my/org-insert-screenshot/filename "]]"))
2455   (org-display-inline-images))
2456
2457 (defun my/fix-inline-images ()
2458   (when org-inline-image-overlays
2459     (org-redisplay-inline-images)))
2460
2461 (add-hook 'org-babel-after-execute-hook 'my/fix-inline-images)
2462
2463 ;; use xelatex to preview with imagemagick
2464 (add-to-list 'org-preview-latex-process-alist
2465          '(xelateximagemagick
2466       :programs ("xelatex" "convert")
2467       :description "pdf > png"
2468       :message "you need to install xelatex and imagemagick"
2469       :use-xcolor t
2470       :image-input-type "pdf"
2471       :image-output-type "png"
2472       :image-size-adjust (1.0 . 1.0)
2473       :latex-compiler ("xelatex -interaction nonstopmode -output-directory %o %f")
2474       :image-converter ("convert -density %D -trim -antialias %f -quality 100 %O"))
2475          )
2476 ;; use xelatex by default
2477 (setq org-preview-latex-default-process 'xelateximagemagick)
2478
2479 ; from http://orgmode.org/Changes.html
2480 (defun my/org-repair-property-drawers ()
2481   "Fix properties drawers in current buffer.
2482  Ignore non Org buffers."
2483   (interactive)
2484   (when (eq major-mode 'org-mode)
2485     (org-with-wide-buffer
2486      (goto-char (point-min))
2487      (let ((case-fold-search t)
2488        (inline-re (and (featurep 'org-inlinetask)
2489                (concat (org-inlinetask-outline-regexp)
2490                    "END[ \t]*$"))))
2491    (org-map-entries
2492     (lambda ()
2493       (unless (and inline-re (org-looking-at-p inline-re))
2494         (save-excursion
2495       (let ((end (save-excursion (outline-next-heading) (point))))
2496         (forward-line)
2497         (when (org-looking-at-p org-planning-line-re) (forward-line))
2498         (when (and (< (point) end)
2499                (not (org-looking-at-p org-property-drawer-re))
2500                (save-excursion
2501                  (and (re-search-forward org-property-drawer-re end t)
2502                   (eq (org-element-type
2503                    (save-match-data (org-element-at-point)))
2504                   'drawer))))
2505           (insert (delete-and-extract-region
2506                (match-beginning 0)
2507                (min (1+ (match-end 0)) end)))
2508           (unless (bolp) (insert "\n"))))))))))))
2509
2510 #+END_SRC
2511 ** Org-Gcal
2512 #+BEGIN_SRC emacs-lisp
2513 (use-package calfw
2514   :ensure f
2515   )
2516 (use-package calfw-org
2517   :ensure f
2518   )
2519 (use-package org-gcal
2520   :if (file-readable-p "~/.hide/org_gcal.el")
2521   :ensure f
2522   :config '((if (file-readable-p "~/.hide/org_gcal.el")
2523                 (load-file "~/.hide/org_gcal.el"))
2524             )
2525   )
2526 #+END_SRC
2527 ** appt integration
2528 #+BEGIN_SRC emacs-lisp
2529 (use-package appt
2530   :straight nil
2531   :config
2532   ;; Show notification 10 minutes before event
2533   (setq appt-message-warning-time 10)
2534   ;; Disable multiple reminders
2535   (setq appt-display-interval appt-message-warning-time)
2536   (setq appt-display-mode-line nil)
2537
2538   ;; add automatic reminders for appointments
2539   (defun my/org-agenda-to-appt ()
2540     (interactive)
2541     (setq appt-time-msg-list nil)
2542     (org-agenda-to-appt))
2543   ;; add reminders when starting emacs
2544   (my/org-agenda-to-appt)
2545   ;; when rebuilding the agenda
2546   (defadvice  org-agenda-redo (after org-agenda-redo-add-appts)
2547     "Pressing `r' on the agenda will also add appointments."
2548     (my/org-agenda-to-appt)
2549     )
2550   ;; when saving all org buffers
2551   (defadvice org-save-all-org-buffers (after org-save-all-org-buffers-add-appts)
2552     "Re-add appts after saving all org buffers"
2553     (my/org-agenda-to-appt))
2554   ;; Display appointments as a window manager notification
2555   (setq appt-disp-window-function 'my/appt-display)
2556   (setq appt-delete-window-function (lambda () t))
2557
2558   (setq my/appt-notification-app (concat (getenv "HOME") "/bin/appt_notification"))
2559
2560   (defun my/appt-display (min-to-app new-time msg)
2561     (if (atom min-to-app)
2562     (start-process "my/appt-notification-app" nil my/appt-notification-app min-to-app msg)
2563   (dolist (i (number-sequence 0 (1- (length min-to-app))))
2564     (start-process "my/appt-notification-app" nil my/appt-notification-app
2565              (nth i min-to-app) (nth i msg))))
2566     )
2567   )
2568
2569
2570 #+END_SRC
2571 ** End use-package
2572 #+BEGIN_SRC emacs-lisp
2573   )
2574 #+END_SRC
2575 * Keybindings
2576 ** Home/End Begining/End of line
2577 #+BEGIN_SRC emacs-lisp
2578   (global-set-key [home] 'move-beginning-of-line)
2579   (global-set-key [end] 'move-end-of-line)
2580 #+END_SRC
2581 ** Goto line
2582 #+BEGIN_SRC emacs-lisp
2583   ; (global-unset-key "\M-g")
2584   ; (global-set-key (kbd "M-g l") 'goto-line)
2585 #+END_SRC
2586 * Debian
2587 ** debian-changelog
2588 #+BEGIN_SRC emacs-lisp
2589 (use-package debian-changelog-mode
2590   :mode "debian/changelog"
2591   :ensure debian-el
2592   :config
2593   (setq debian-changelog-mailing-address "don@debian.org")
2594   (setq debian-changelog-full-name "Don Armstrong"))
2595 #+END_SRC
2596 * Misc (uncharacterized)
2597 #+BEGIN_SRC emacs-lisp
2598   (setq calendar-latitude 38.6)
2599   (setq calendar-longitude -121.5)
2600   (setq case-fold-search t)
2601   (setq confirm-kill-emacs (quote y-or-n-p))
2602
2603 #+END_SRC
2604 ** Turn on fontlock
2605 #+BEGIN_SRC emacs-lisp
2606   (global-font-lock-mode 1)
2607 #+END_SRC
2608 ** PS Printing
2609 #+BEGIN_SRC emacs-lisp
2610   (setq ps-footer-font-size (quote (8 . 10)))
2611   (setq ps-header-font-size (quote (8 . 10)))
2612   (setq ps-header-title-font-size (quote (10 . 10)))
2613   (setq ps-line-number-color "blue")
2614   (setq ps-print-footer t)
2615   (setq ps-print-footer-frame nil)
2616   (setq ps-print-only-one-header t)
2617 #+END_SRC
2618 ** Only single spacing on sentences
2619 #+BEGIN_SRC emacs-lisp
2620   (setq sentence-end "[.?!][]\"')]*\\($\\|   \\| \\)[    
2621   ]*")
2622   (setq sentence-end-double-space nil)
2623   ; enable matching parenthesis
2624 #+END_SRC
2625 ** Display paren mode
2626 #+BEGIN_SRC emacs-lisp
2627   (show-paren-mode 1)
2628   (setq show-paren-delay 0.2)
2629
2630 #+END_SRC
2631 ** My Username
2632 #+BEGIN_SRC emacs-lisp
2633   (setq user-mail-address "don@donarmstrong.com")
2634
2635 #+END_SRC
2636 ** Use primary selection on unix machines
2637 #+BEGIN_SRC emacs-lisp
2638 ;; switch back to the old primary selection method
2639 (if (or (string-equal system-type "darwin")
2640         (string-equal system-type "windows")
2641         )
2642     (progn
2643       (setq select-enable-clipboard t)
2644       (setq select-enable-primary nil)
2645       )
2646   (progn
2647     (setq select-enable-clipboard nil)
2648     (setq select-enable-primary t)
2649     ))
2650 ; (setq mouse-drag-copy-region t)
2651
2652 (setq-default c-indent-level 4)
2653 (setq-default c-brace-imaginary-offset 0)
2654 (setq-default c-brace-offset -4)
2655 (setq-default c-argdecl-indent 4)
2656 (setq-default c-label-offset -4)
2657 (setq-default c-continued-statement-offset 4)
2658 ; tabs are annoying
2659 (setq-default indent-tabs-mode nil)
2660 (setq-default tab-width 4)
2661
2662 (defun insert-date ()
2663   "Insert date at point."
2664   (interactive)
2665   (insert (format-time-string "%A, %B %e, %Y %k:%M:%S %Z")))
2666 (global-set-key "\C-[d" 'insert-date)
2667
2668 (defun unfill-paragraph (arg)
2669   "Pull this whole paragraph up onto one line."
2670   (interactive "*p")
2671   (let ((fill-column 10000))
2672     (fill-paragraph arg))
2673   )
2674
2675 (column-number-mode t)
2676
2677 #+END_SRC
2678 ** Desktop-save-mode
2679 If the envvar EMACS_SERVER_NAME is set, consider this a separate
2680 emacs, and use a different desktop file to restore history
2681 #+BEGIN_SRC emacs-lisp
2682 (use-package desktop
2683   :demand
2684   :config
2685   (setq desktop-base-file-name
2686         (convert-standard-filename
2687          (concat ".emacs"
2688                  (or (getenv "EMACS_SERVER_NAME")
2689                      "")
2690                  ".desktop")
2691          ))
2692   (setq desktop-base-lock-name
2693         (convert-standard-filename
2694          (concat desktop-base-file-name
2695                  ".lock")))
2696   (setq desktop-auto-save-timeout 60)
2697   (setq desktop-restore-eager 5)
2698   (setq desktop-lazy-verbose nil)
2699   (desktop-save-mode 1)
2700   ; (desktop-read)
2701 )
2702 #+END_SRC
2703 ** Misc (Uncharacterized)
2704 #+BEGIN_SRC emacs-lisp
2705
2706 (put 'upcase-region 'disabled nil)
2707 (put 'downcase-region 'disabled nil)
2708 (put 'narrow-to-region 'disabled nil)
2709
2710 ; Outline-minor-mode key map
2711 (define-prefix-command 'cm-map nil "Outline-")
2712 ; HIDE
2713 (define-key cm-map "q" 'outline-hide-sublevels)    ; Hide everything but the top-level headings
2714 (define-key cm-map "t" 'outline-hide-body)         ; Hide everything but headings (all body lines)
2715 (define-key cm-map "o" 'outline-hide-other)        ; Hide other branches
2716 (define-key cm-map "c" 'outline-hide-entry)        ; Hide this entry's body
2717 (define-key cm-map "l" 'outline-hide-leaves)       ; Hide body lines in this entry and sub-entries
2718 (define-key cm-map "d" 'outline-hide-subtree)      ; Hide everything in this entry and sub-entries
2719 ; SHOW
2720 (define-key cm-map "a" 'outline-show-all)          ; Show (expand) everything
2721 (define-key cm-map "e" 'outline-show-entry)        ; Show this heading's body
2722 (define-key cm-map "i" 'outline-show-children)     ; Show this heading's immediate child sub-headings
2723 (define-key cm-map "k" 'outline-show-branches)     ; Show all sub-headings under this heading
2724 (define-key cm-map "s" 'outline-show-subtree)      ; Show (expand) everything in this heading & below
2725 ; MOVE
2726 (define-key cm-map "u" 'outline-up-heading)                ; Up
2727 (define-key cm-map "n" 'outline-next-visible-heading)      ; Next
2728 (define-key cm-map "p" 'outline-previous-visible-heading)  ; Previous
2729 (define-key cm-map "f" 'outline-forward-same-level)        ; Forward - same level
2730 (define-key cm-map "b" 'outline-backward-same-level)       ; Backward - same level
2731 (global-set-key "\M-o" cm-map)
2732 ; fix up tmux xterm keys
2733 ; stolen from http://unix.stackexchange.com/questions/24414/shift-arrow-not-working-in-emacs-within-tmux
2734 (defun fix-up-tmux-keys ()
2735     "Fix up tmux xterm keys"
2736     (if (getenv "TMUX")
2737         (progn
2738           (let ((x 2) (tkey ""))
2739             (while (<= x 8)
2740               ;; shift
2741               (if (= x 2)
2742                   (setq tkey "S-"))
2743               ;; alt
2744               (if (= x 3)
2745                   (setq tkey "M-"))
2746               ;; alt + shift
2747               (if (= x 4)
2748                   (setq tkey "M-S-"))
2749               ;; ctrl
2750               (if (= x 5)
2751                   (setq tkey "C-"))
2752               ;; ctrl + shift
2753               (if (= x 6)
2754                   (setq tkey "C-S-"))
2755               ;; ctrl + alt
2756               (if (= x 7)
2757                   (setq tkey "C-M-"))
2758               ;; ctrl + alt + shift
2759               (if (= x 8)
2760                   (setq tkey "C-M-S-"))
2761
2762               ;; arrows
2763               (define-key key-translation-map (kbd (format "M-[ 1 ; %d A" x)) (kbd (format "%s<up>" tkey)))
2764               (define-key key-translation-map (kbd (format "M-[ 1 ; %d B" x)) (kbd (format "%s<down>" tkey)))
2765               (define-key key-translation-map (kbd (format "M-[ 1 ; %d C" x)) (kbd (format "%s<right>" tkey)))
2766               (define-key key-translation-map (kbd (format "M-[ 1 ; %d D" x)) (kbd (format "%s<left>" tkey)))
2767               ;; home
2768               (define-key key-translation-map (kbd (format "M-[ 1 ; %d H" x)) (kbd (format "%s<home>" tkey)))
2769               ;; end
2770               (define-key key-translation-map (kbd (format "M-[ 1 ; %d F" x)) (kbd (format "%s<end>" tkey)))
2771               ;; page up
2772               (define-key key-translation-map (kbd (format "M-[ 5 ; %d ~" x)) (kbd (format "%s<prior>" tkey)))
2773               ;; page down
2774               (define-key key-translation-map (kbd (format "M-[ 6 ; %d ~" x)) (kbd (format "%s<next>" tkey)))
2775               ;; insert
2776               (define-key key-translation-map (kbd (format "M-[ 2 ; %d ~" x)) (kbd (format "%s<delete>" tkey)))
2777               ;; delete
2778               (define-key key-translation-map (kbd (format "M-[ 3 ; %d ~" x)) (kbd (format "%s<delete>" tkey)))
2779               ;; f1
2780               (define-key key-translation-map (kbd (format "M-[ 1 ; %d P" x)) (kbd (format "%s<f1>" tkey)))
2781               ;; f2
2782               (define-key key-translation-map (kbd (format "M-[ 1 ; %d Q" x)) (kbd (format "%s<f2>" tkey)))
2783               ;; f3
2784               (define-key key-translation-map (kbd (format "M-[ 1 ; %d R" x)) (kbd (format "%s<f3>" tkey)))
2785               ;; f4
2786               (define-key key-translation-map (kbd (format "M-[ 1 ; %d S" x)) (kbd (format "%s<f4>" tkey)))
2787               ;; f5
2788               (define-key key-translation-map (kbd (format "M-[ 15 ; %d ~" x)) (kbd (format "%s<f5>" tkey)))
2789               ;; f6
2790               (define-key key-translation-map (kbd (format "M-[ 17 ; %d ~" x)) (kbd (format "%s<f6>" tkey)))
2791               ;; f7
2792               (define-key key-translation-map (kbd (format "M-[ 18 ; %d ~" x)) (kbd (format "%s<f7>" tkey)))
2793               ;; f8
2794               (define-key key-translation-map (kbd (format "M-[ 19 ; %d ~" x)) (kbd (format "%s<f8>" tkey)))
2795               ;; f9
2796               (define-key key-translation-map (kbd (format "M-[ 20 ; %d ~" x)) (kbd (format "%s<f9>" tkey)))
2797               ;; f10
2798               (define-key key-translation-map (kbd (format "M-[ 21 ; %d ~" x)) (kbd (format "%s<f10>" tkey)))
2799               ;; f11
2800               (define-key key-translation-map (kbd (format "M-[ 23 ; %d ~" x)) (kbd (format "%s<f11>" tkey)))
2801               ;; f12
2802               (define-key key-translation-map (kbd (format "M-[ 24 ; %d ~" x)) (kbd (format "%s<f12>" tkey)))
2803               ;; f13
2804               (define-key key-translation-map (kbd (format "M-[ 25 ; %d ~" x)) (kbd (format "%s<f13>" tkey)))
2805               ;; f14
2806               (define-key key-translation-map (kbd (format "M-[ 26 ; %d ~" x)) (kbd (format "%s<f14>" tkey)))
2807               ;; f15
2808               (define-key key-translation-map (kbd (format "M-[ 28 ; %d ~" x)) (kbd (format "%s<f15>" tkey)))
2809               ;; f16
2810               (define-key key-translation-map (kbd (format "M-[ 29 ; %d ~" x)) (kbd (format "%s<f16>" tkey)))
2811               ;; f17
2812               (define-key key-translation-map (kbd (format "M-[ 31 ; %d ~" x)) (kbd (format "%s<f17>" tkey)))
2813               ;; f18
2814               (define-key key-translation-map (kbd (format "M-[ 32 ; %d ~" x)) (kbd (format "%s<f18>" tkey)))
2815               ;; f19
2816               (define-key key-translation-map (kbd (format "M-[ 33 ; %d ~" x)) (kbd (format "%s<f19>" tkey)))
2817               ;; f20
2818               (define-key key-translation-map (kbd (format "M-[ 34 ; %d ~" x)) (kbd (format "%s<f20>" tkey)))
2819
2820               (setq x (+ x 1))
2821               ))
2822           )
2823       )
2824     )
2825 ; (add-hook 'tty-setup-hook 'fix-up-tmux-keys)
2826
2827 (defadvice ask-user-about-supersession-threat (around ask-user-about-supersession-threat-if-necessary)
2828   "Call ask-user-about-supersession-threat only if the buffer is actually obsolete."
2829   (if (or (buffer-modified-p)
2830           (verify-visited-file-modtime)
2831           (< (* 8 1024 1024) (buffer-size))
2832           (/= 0 (call-process-region 1 (+ 1 (buffer-size)) "diff" nil nil nil "-q" (buffer-file-name) "-")))
2833       ad-do-it
2834     (clear-visited-file-modtime)
2835     (not-modified)))
2836 (ad-activate 'ask-user-about-supersession-threat)
2837 #+END_SRC
2838
2839 * Start Server
2840 #+BEGIN_SRC emacs-lisp
2841   (use-package server
2842     :config
2843     (setq server-name
2844           (or (getenv "EMACS_SERVER_NAME")
2845               "server"))
2846     (unless (server-running-p)
2847       ; (global-set-key "\C-xp" 'server-edit)
2848       (server-start)))
2849 #+END_SRC
2850
2851 * END
2852 #+BEGIN_SRC emacs-lisp
2853 (provide 'don-configuration)
2854 #+END_SRC