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