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