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