]> git.donarmstrong.com Git - lib.git/blob - emacs_el/configuration/don-configuration.org
50fbec086a22ac157e96757f6998f540e5a2af23
[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 ** Python Programming
1394 #+BEGIN_SRC emacs-lisp
1395   (use-package elpy
1396     :ensure t
1397     :init
1398     (elpy-enable)
1399     )
1400 #+END_SRC
1401
1402 ** Go language
1403 #+BEGIN_SRC emacs-lisp
1404 (use-package go-mode
1405              :diminish "go"
1406              :mode "\\.go"
1407              )
1408 #+END_SRC
1409
1410 ** Expand region
1411 #+BEGIN_SRC emacs-lisp
1412 (use-package expand-region
1413   :bind (("C-=" . 'er/expand-region))
1414   )
1415 #+END_SRC
1416
1417 ** Dockerfile
1418 #+BEGIN_SRC emacs-lisp
1419 (use-package dockerfile-mode
1420   :mode "Dockerfile"
1421   )
1422 #+END_SRC
1423
1424 ** Beancount
1425 #+BEGIN_SRC emacs-lisp
1426 (use-package beancount
1427   :load-path "~/lib/emacs_el/beancount-mode/"
1428   :ensure f
1429   :mode "\\.beancount\\'"
1430   
1431   )
1432 #+END_SRC
1433 * Email
1434 ** Mutt
1435 *** Message-mode
1436 #+BEGIN_SRC emacs-lisp
1437 (use-package message
1438   :ensure f
1439   :diminish (message "✉")
1440   :mode ("muttng-[a-z0-9]+-[0-9]+-" . message-mode)
1441   :mode ("mutt-[a-z0-9]+-[0-9]+-" . message-mode)
1442   :hook 'my/message-mode-settings
1443   :hook 'turn-on-flyspell
1444   :bind (:map message-mode-map
1445       ("C-c C-a" . my/post-attach-file))
1446   :delight (message-mode "✉")
1447   :config
1448   (defun my/message-mode-settings ()
1449     (font-lock-add-keywords nil
1450                 '(("^[ \t]*>[ \t]*>[ \t]*>.*$"
1451                (0 'message-multiply-quoted-text-face))
1452               ("^[ \t]*>[ \t]*>.*$"
1453                (0 'message-double-quoted-text-face))))
1454     )
1455
1456   (defun my/post-attach-file ()
1457     "Prompt for an attachment."
1458     (interactive)
1459     (let ((file (read-file-name "Attach file: " nil nil t nil)))
1460       (my/header-attach-file file "")))
1461
1462   (defun my/header-attach-file (file description)
1463     "Attach a FILE to the current message (works with Mutt).
1464   Argument DESCRIPTION MIME description."
1465     (interactive "fAttach file: \nsDescription: ")
1466     (when (> (length file) 0)
1467   (save-excursion
1468     (save-match-data
1469       (save-restriction
1470         (widen)
1471         (goto-char (point-min))
1472         (search-forward-regexp "^$")
1473         (insert (concat "Attach: " (replace-regexp-in-string "\\([[:space:]\\]\\)" "\\\\\\1" (file-truename file)) " "
1474                 description "\n"))
1475         (message (concat "Attached '" file "'."))
1476         (setq post-has-attachment t))))))
1477
1478   (setq mail-yank-prefix "> ")
1479   (setq mail-header-separator "") ; fix broken header detection
1480 )
1481 #+END_SRC
1482 *** Muttrc mode
1483 #+BEGIN_SRC emacs-lisp
1484   (use-package muttrc-mode
1485     :mode "muttngrc"
1486     :mode "muttrc"
1487   )
1488
1489 #+END_SRC
1490 * Base emacs
1491 ** Reverting buffers
1492 #+BEGIN_SRC emacs-lisp
1493   (use-package autorevert
1494     :diminish auto-revert-mode
1495     :config
1496     (setq global-auto-revert-non-file-buffers t
1497           global-auto-revert-ignore-modes '(pdf-view-mode)
1498           auto-revert-verbose nil)
1499     (global-auto-revert-mode 1))
1500 #+END_SRC
1501 * Org Mode
1502 ** Use-package and load things
1503 #+BEGIN_SRC emacs-lisp
1504
1505   (use-package org
1506     :delight (org-mode "ø")
1507     :mode ("\\.\\(org\\|org_archive\\|txt\\)\\'" . org-mode)
1508     :bind (("C-c l"  . org-store-link)
1509            ("C-c a"  . org-agenda)
1510            ("C-c b"  . org-iswitchb))
1511 #+END_SRC
1512 ** Agenda Configuration
1513 #+BEGIN_SRC emacs-lisp
1514   :config
1515   (setq-default org-log-done 'time)
1516   (setq-default org-agenda-ndays 5)
1517
1518   (setq org-agenda-sticky t)
1519   (defun dla/show-org-agenda ()
1520     (interactive)
1521     (let (agendabuffer
1522           '(delq nil 
1523                 (mapcar (lambda (x)
1524                           (and (string-match-p
1525                                 "\*Org Agenda.*\*"
1526                                 (buffer-name x))
1527                                x)
1528                           )
1529                         (buffer-list))))
1530       (if agendabuffer
1531           (switch-to-buffer
1532            (buffer-name agendabuffer))
1533         (org-agenda-list)))
1534       (delete-other-windows))
1535
1536   ;; agenda configuration
1537   ;; Do not dim blocked tasks
1538   (setq org-agenda-dim-blocked-tasks nil)
1539   (setq org-agenda-inhibit-startup t)
1540   (setq org-agenda-use-tag-inheritance nil)
1541
1542   ;; Compact the block agenda view
1543   (setq org-agenda-compact-blocks t)
1544
1545   ;; Custom agenda command definitions
1546   (setq org-agenda-custom-commands
1547         (quote (("N" "Notes" tags "NOTE"
1548                  ((org-agenda-overriding-header "Notes")
1549                   (org-tags-match-list-sublevels t)))
1550                 ("h" "Habits" tags-todo "STYLE=\"habit\""
1551                  ((org-agenda-overriding-header "Habits")
1552                   (org-agenda-sorting-strategy
1553                    '(todo-state-down effort-up category-keep))))
1554                 (" " "Agenda"
1555                  ((agenda "" nil)
1556                   (tags "REFILE"
1557                         ((org-agenda-overriding-header "Tasks to Refile")
1558                          (org-tags-match-list-sublevels nil)))
1559                   (tags-todo "-CANCELLED/!"
1560                              ((org-agenda-overriding-header "Stuck Projects")
1561                               (org-agenda-skip-function 'bh/skip-non-stuck-projects)
1562                               (org-agenda-sorting-strategy
1563                                '(category-keep))))
1564                   (tags-todo "-HOLD-CANCELLED/!"
1565                              ((org-agenda-overriding-header "Projects")
1566                               (org-agenda-skip-function 'bh/skip-non-projects)
1567                               (org-tags-match-list-sublevels 'indented)
1568                               (org-agenda-sorting-strategy
1569                                '(category-keep))))
1570                   (tags-todo "-CANCELLED/!NEXT"
1571                              ((org-agenda-overriding-header (concat "Project Next Tasks"
1572                                                                     (if bh/hide-scheduled-and-waiting-next-tasks
1573                                                                         ""
1574                                                                       " (including WAITING and SCHEDULED tasks)")))
1575                               (org-agenda-skip-function 'bh/skip-projects-and-habits-and-single-tasks)
1576                               (org-tags-match-list-sublevels t)
1577                               (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
1578                               (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
1579                               (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
1580                               (org-agenda-sorting-strategy
1581                                '(todo-state-down effort-up category-keep))))
1582                   (tags-todo "-REFILE-CANCELLED-WAITING-HOLD/!"
1583                              ((org-agenda-overriding-header (concat "Project Subtasks"
1584                                                                     (if bh/hide-scheduled-and-waiting-next-tasks
1585                                                                         ""
1586                                                                       " (including WAITING and SCHEDULED tasks)")))
1587                               (org-agenda-skip-function 'bh/skip-non-project-tasks)
1588                               (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
1589                               (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
1590                               (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
1591                               (org-agenda-sorting-strategy
1592                                '(category-keep))))
1593                   (tags-todo "-REFILE-CANCELLED-WAITING-HOLD/!"
1594                              ((org-agenda-overriding-header (concat "Standalone Tasks"
1595                                                                     (if bh/hide-scheduled-and-waiting-next-tasks
1596                                                                         ""
1597                                                                       " (including WAITING and SCHEDULED tasks)")))
1598                               (org-agenda-skip-function 'bh/skip-project-tasks)
1599                               (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
1600                               (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
1601                               (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
1602                               (org-agenda-sorting-strategy
1603                                '(category-keep))))
1604                   (tags-todo "-CANCELLED+WAITING|HOLD/!"
1605                              ((org-agenda-overriding-header "Waiting and Postponed Tasks")
1606                               (org-agenda-skip-function 'bh/skip-stuck-projects)
1607                               (org-tags-match-list-sublevels nil)
1608                               (org-agenda-todo-ignore-scheduled t)
1609                               (org-agenda-todo-ignore-deadlines t)))
1610                   (tags "-REFILE/"
1611                         ((org-agenda-overriding-header "Tasks to Archive")
1612                          (org-agenda-skip-function 'bh/skip-non-archivable-tasks)
1613                          (org-tags-match-list-sublevels nil))))
1614                  nil))))
1615
1616   ; org mode agenda files
1617   (setq org-agenda-files
1618         (append
1619         (file-expand-wildcards "~/projects/org-notes/*.org")
1620         (file-expand-wildcards "~/org-mode/from-mobile.org")
1621         (file-expand-wildcards "~/org-notes-*/*.org")
1622         )
1623   )
1624   (setq my/org-refile-file
1625         (car (seq-filter
1626               (lambda (file) (string-match-p (regexp-quote "/refile.org") file))
1627               org-agenda-files)))
1628
1629   (set-register ?n (cons 'file "~/projects/org-notes/notes.org"))
1630   (set-register ?r (cons 'file my/org-refile-file))
1631   (set-register ?o (cons 'file "~/projects/org-notes/ool.org"))
1632   (set-register ?s (cons 'file "~/projects/org-notes/sndservers.org"))
1633   (set-register ?c (cons 'file "~/projects/org-notes/chaim.org"))
1634   (set-register ?w (cons 'file "~/projects/org-notes/wildman.org"))
1635   (set-register ?u (cons 'file "~/projects/org-notes/uddin.org"))
1636   (set-register ?R (cons 'file "~/projects/reviews/reviews.org"))
1637   (set-register ?d (cons 'file "~/projects/org-notes/diary.org"))
1638   ; from https://emacs.stackexchange.com/questions/909/how-can-i-have-an-agenda-timeline-view-of-multiple-files
1639   (defun org-agenda-timeline-all (&optional arg)
1640     (interactive "P")
1641     (with-temp-buffer
1642       (dolist (org-agenda-file org-agenda-files)
1643         (insert-file-contents org-agenda-file nil)
1644         (goto-char (point-max))
1645         (newline))
1646       (write-file "/tmp/timeline.org")
1647       (org-agenda arg "L")))
1648   (define-key org-mode-map (kbd "C-c t") 'org-agenda-timeline-all)
1649
1650 #+END_SRC
1651 ** General config
1652 #+BEGIN_SRC emacs-lisp
1653   (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")))
1654   (setq org-columns-default-format "%40ITEM(Task) %6Effort{:} %CLOCKSUM %PRIORITY %TODO %13SCHEDULED %13DEADLINE %TAGS")
1655
1656   (setq org-default-notes-file "~/projects/org-notes/notes.org")
1657   (setq org-id-link-to-org-use-id 'use-existing)
1658 #+END_SRC
1659 ** Capture Templates
1660 #+BEGIN_SRC emacs-lisp
1661   (setq org-capture-templates  ;; mail-specific note template, identified by "m"
1662         `(("m" "Mail" entry (file my/org-refile-file)
1663            "* %?\n\n  Source: %u, [[%:link][%:description]]\n  %:initial")
1664           ("t" "todo" entry (file my/org-refile-file)
1665            "* TODO %?\n  :PROPERTIES:\n  :END:\n  :LOGBOOK:\n  :END:\n%U\n%a\n" :clock-in t :clock-resume t)
1666           ("r" "respond" entry (file my/org-refile-file)
1667            "* NEXT Respond to %:from on %:subject\nSCHEDULED: %t\n%U\n%a\n" :clock-in t :clock-resume t :immediate-finish t)
1668           ("n" "note" entry (file my/org-refile-file)
1669            "* %? :NOTE:\n%U\n%a\n" :clock-in t :clock-resume t)
1670           ("s" "schedule" entry (file my/org-refile-file)
1671            "* %? :cal:\n%^{scheduled:}t\n%U\n%a\n" :clock-in t :clock-resume t)
1672           ("j" "Journal" entry (file+datetree "~/projects/org-notes/diary.org")
1673            "* %?\n%U\n" :clock-in t :clock-resume t)
1674           ("w" "org-protocol" entry (file my/org-refile-file)
1675            "* TODO Review %c\n%U\n" :immediate-finish t)
1676           ("M" "Meeting" entry (file my/org-refile-file)
1677            "* MEETING with %? :MEETING:\n%U" :clock-in t :clock-resume t)
1678           ("S" "Seminar" entry (file my/org-refile-file)
1679            "* SEMINAR notes %? :SEMINAR:\n%U" :clock-in t :clock-resume t)
1680           ("P" "Paper to read" entry (file+headline "~/projects/research/papers_to_read.org" "Refile")
1681            "* TODO Get/Read %? \n%U" :clock-in t :clock-resume t)
1682           ("p" "Phone call" entry (file my/org-refile-file)
1683            "* PHONE %? :PHONE:\n%U" :clock-in t :clock-resume t)
1684            ("J" "job" entry (file+olp "~/projects/org-notes/notes.org"
1685                                        "Jobs"
1686                                        ,(format-time-string "Positions %Y"))
1687            "* TODO Apply for %? :job:\nSCHEDULED: <%<%Y-%m-%d>>\n%U\n%x\n" :clock-in t :clock-resume t)
1688           ("h" "Habit" entry (file my/org-refile-file)
1689            "* 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")
1690           )
1691         )
1692
1693   ;; Remove empty LOGBOOK drawers on clock out
1694   (defun bh/remove-empty-drawer-on-clock-out ()
1695     (interactive)
1696     (save-excursion
1697       (beginning-of-line 0)
1698       (org-remove-empty-drawer-at (point))))
1699
1700   (defun my/org-add-id ()
1701     (interactive)
1702     (save-excursion
1703       (if (org-current-level)
1704           ()
1705         (forward-char 1)
1706         )
1707       (org-id-get-create)
1708       )
1709   )
1710
1711 #+END_SRC
1712 ** Org mode key bindings
1713 #+BEGIN_SRC emacs-lisp
1714   ;; org mode configuration from http://doc.norang.ca/org-mode.html
1715   ;; Custom Key Bindings
1716   :bind* (("<f9> a" . org-agenda)
1717           ("<f9> I" . bh/punch-in)
1718           ("<f9> O" . bh/punch-out)
1719           ("<f9> SPC" . bh/clock-in-last-task)
1720           ("<f12>" . dla/show-org-agenda)
1721           ;; ("<f5>" . bh/org-todo)
1722           ("<S-f5>" . bh/widen)
1723           ("<f7>" . bh/set-truncate-lines)
1724           ("<f8>" . org-cycle-agenda-files)
1725           ("<f9> <f9>" . dla/show-org-agenda)
1726           ("<f9> b" . bbdb)
1727           ("<f9> c" . calendar)
1728           ("<f9> f" . boxquote-insert-file)
1729           ("<f9> h" . bh/hide-other)
1730           ("<f9> n" . bh/toggle-next-task-display)
1731           ("<f9> w" . widen)
1732
1733           ("<f9> r" . boxquote-region)
1734           ("<f9> s" . bh/switch-to-scratch)
1735
1736           ("<f9> t" . bh/insert-inactive-timestamp)
1737           ("<f9> T" . bh/toggle-insert-inactive-timestamp)
1738
1739           ("<f9> v" . visible-mode)
1740           ("<f9> l" . org-toggle-link-display)
1741           ("<f9> SPC" . bh/clock-in-last-task)
1742           ("C-<f9>" . previous-buffer)
1743           ("M-<f9>" . org-toggle-inline-images)
1744           ("C-x n r" . narrow-to-region)
1745           ("C-<f10>" . next-buffer)
1746           ("<f11>" . org-clock-goto)
1747           ("C-<f11>" . org-clock-in)
1748           ("C-s-<f12>" . bh/save-then-publish)
1749           ("C-c c" . org-capture))
1750   :config
1751 #+END_SRC
1752 ** Utility Functions
1753 #+BEGIN_SRC emacs-lisp
1754   (defun bh/hide-other ()
1755     (interactive)
1756     (save-excursion
1757       (org-back-to-heading 'invisible-ok)
1758       (hide-other)
1759       (org-cycle)
1760       (org-cycle)
1761       (org-cycle)))
1762
1763   (defun bh/set-truncate-lines ()
1764     "Toggle value of truncate-lines and refresh window display."
1765     (interactive)
1766     (setq truncate-lines (not truncate-lines))
1767     ;; now refresh window display (an idiom from simple.el):
1768     (save-excursion
1769       (set-window-start (selected-window)
1770                         (window-start (selected-window)))))
1771
1772   (defun bh/switch-to-scratch ()
1773     (interactive)
1774     (switch-to-buffer "*scratch*"))
1775
1776   (setq org-use-fast-todo-selection t)
1777   (setq org-treat-S-cursor-todo-selection-as-state-change nil)
1778
1779   ; create function to create headlines in file. This comes from
1780   ; http://stackoverflow.com/questions/13340616/assign-ids-to-every-entry-in-org-mode
1781   (defun my/org-add-ids-to-headlines-in-file ()
1782     "Add ID properties to all headlines in the current file which
1783   do not already have one."
1784     (interactive)
1785     (org-map-entries 'org-id-get-create))
1786   (defun dla/org-update-ids-to-headlines-in-file ()
1787     "Add or replace ID properties to all headlines in the current file 
1788   (or narrowed region)."
1789     (interactive)
1790     (org-map-entries '(lambda () (org-id-get-create t))))
1791   ; if we wanted to do this to every buffer, do the following:
1792   ; (add-hook 'org-mode-hook
1793   ;           (lambda ()
1794   ;             (add-hook 'before-save-hook 'my/org-add-ids-to-headlines-in-file nil 'local)))
1795 #+END_SRC
1796 ** Org ID locations
1797 #+BEGIN_SRC emacs-lisp
1798 (use-package find-lisp
1799   :ensure t)
1800 (setq org-agenda-text-search-extra-files
1801       (append '(agenda-archives)
1802               (find-lisp-find-files "~/projects/org-notes" "\.org$")
1803               (find-lisp-find-files "~/projects/org-notes" "\.org_archive$")
1804               ))
1805 #+END_SRC
1806 ** Keywords (TODO)
1807 #+BEGIN_SRC emacs-lisp
1808 (setq org-todo-keywords
1809       (quote ((sequence "TODO(t)" "NEXT(n)" "|" "DONE(d)")
1810               (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" "PHONE" "MEETING"))))
1811
1812 (setq org-todo-keyword-faces
1813       (quote (("TODO" :foreground "red" :weight bold)
1814               ("NEXT" :foreground "blue" :weight bold)
1815               ("DONE" :foreground "forest green" :weight bold)
1816               ("WAITING" :foreground "orange" :weight bold)
1817               ("HOLD" :foreground "magenta" :weight bold)
1818               ("CANCELLED" :foreground "forest green" :weight bold)
1819               ("MEETING" :foreground "forest green" :weight bold)
1820               ("PHONE" :foreground "forest green" :weight bold))))
1821
1822 (setq org-todo-state-tags-triggers
1823       (quote (("CANCELLED" ("CANCELLED" . t))
1824               ("WAITING" ("WAITING" . t))
1825               ("HOLD" ("WAITING") ("HOLD" . t))
1826               (done ("WAITING") ("HOLD"))
1827               ("TODO" ("WAITING") ("CANCELLED") ("HOLD"))
1828               ("NEXT" ("WAITING") ("CANCELLED") ("HOLD"))
1829               ("DONE" ("WAITING") ("CANCELLED") ("HOLD")))))
1830
1831
1832
1833 ; (add-hook 'org-clock-out-hook 'bh/remove-empty-drawer-on-clock-out 'append)
1834 ; add ids on creation of nodes
1835 (add-hook 'org-capture-prepare-finalize-hook 'my/org-add-id)
1836
1837
1838 ; resolve clocks after 10 minutes of idle; use xprintidle
1839 ; (setq org-clock-idle-time 10)
1840 ; (setq org-clock-x11idle-program-name "xprintidle")
1841
1842 ; this is from http://doc.norang.ca/org-mode.html#Capture
1843 ; use C-M-r for org mode capture
1844 (global-set-key (kbd "C-M-r") 'org-capture)
1845
1846 ; Targets include this file and any file contributing to the agenda - up to 9 levels deep
1847 (setq org-refile-targets (quote ((nil :maxlevel . 9)
1848                                  (org-agenda-files :maxlevel . 9))))
1849
1850 ; Use full outline paths for refile targets - we file directly with IDO
1851 (setq org-refile-use-outline-path t)
1852
1853 ; Targets complete directly with IDO
1854 (setq org-outline-path-complete-in-steps nil)
1855
1856 ; Allow refile to create parent tasks with confirmation
1857 (setq org-refile-allow-creating-parent-nodes (quote confirm))
1858
1859 ; ; Use IDO for both buffer and file completion and ido-everywhere to t
1860 ; (setq org-completion-use-ido t)
1861 ; (setq ido-everywhere t)
1862 ; (setq ido-max-directory-size 100000)
1863 ; (ido-mode (quote both))
1864 ; ; Use the current window when visiting files and buffers with ido
1865 ; (setq ido-default-file-method 'selected-window)
1866 ; (setq ido-default-buffer-method 'selected-window)
1867 ; ; Use the current window for indirect buffer display
1868 ; (setq org-indirect-buffer-display 'current-window)
1869
1870
1871 ;;;; Refile settings
1872 ; Exclude DONE state tasks from refile targets
1873 (defun bh/verify-refile-target ()
1874   "Exclude todo keywords with a done state from refile targets"
1875   (not (member (nth 2 (org-heading-components)) org-done-keywords)))
1876
1877 (setq org-refile-target-verify-function 'bh/verify-refile-target)
1878
1879 ;; ensure that emacsclient will show just the note to be edited when invoked
1880 ;; from Mutt, and that it will shut down emacsclient once finished;
1881 ;; fallback to legacy behavior when not invoked via org-protocol.
1882 (require 'org-protocol)
1883 ; (add-hook 'org-capture-mode-hook 'delete-other-windows)
1884 (setq my-org-protocol-flag nil)
1885 (defadvice org-capture-finalize (after delete-frame-at-end activate)
1886   "Delete frame at remember finalization"
1887   (progn (if my-org-protocol-flag (delete-frame))
1888          (setq my-org-protocol-flag nil)))
1889 (defadvice org-capture-refile (around delete-frame-after-refile activate)
1890   "Delete frame at remember refile"
1891   (if my-org-protocol-flag
1892       (progn
1893         (setq my-org-protocol-flag nil)
1894         ad-do-it
1895         (delete-frame))
1896     ad-do-it)
1897   )
1898 (defadvice org-capture-kill (after delete-frame-at-end activate)
1899   "Delete frame at remember abort"
1900   (progn (if my-org-protocol-flag (delete-frame))
1901          (setq my-org-protocol-flag nil)))
1902 (defadvice org-protocol-capture (before set-org-protocol-flag activate)
1903   (setq my-org-protocol-flag t))
1904
1905 (defadvice org-insert-todo-heading (after dla/create-id activate)
1906   (unless (org-in-item-p)
1907     (org-id-get-create)
1908     )
1909   )
1910
1911 ;; org modules
1912 (add-to-list 'org-modules 'org-habit)
1913
1914 ; this comes from http://upsilon.cc/~zack/blog/posts/2010/02/integrating_Mutt_with_Org-mode/
1915 (defun open-mail-in-mutt (message)
1916   "Open a mail message in Mutt, using an external terminal.
1917
1918 Message can be specified either by a path pointing inside a
1919 Maildir, or by Message-ID."
1920   (interactive "MPath or Message-ID: ")
1921   (shell-command
1922    (format "faf xterm -e \"%s %s\""
1923        (substitute-in-file-name "$HOME/bin/mutt_open") message)))
1924
1925 ;; add support for "mutt:ID" links
1926 (org-add-link-type "mutt" 'open-mail-in-mutt)
1927
1928 (defun my-org-mode-setup ()
1929   ; (load-library "reftex")
1930   (and (buffer-file-name)
1931        (file-exists-p (buffer-file-name))
1932        (progn
1933          ; (reftex-parse-all)
1934          (reftex-set-cite-format
1935           '((?b . "[[bib:%l][%l-bib]]")
1936             (?n . "[[notes:%l][%l-notes]]")
1937             (?c . "\\cite{%l}")
1938             (?h . "*** %t\n:PROPERTIES:\n:Custom_ID: %l\n:END:\n[[papers:%l][%l xoj]] [[papers-pdf:%l][pdf]]")))
1939          ))
1940   (define-key org-mode-map (kbd "C-c )") 'reftex-citation)
1941   (define-key org-mode-map (kbd "C-c [") 'reftex-citation)
1942   (define-key org-mode-map (kbd "C-c (") 'org-mode-reftex-search)
1943   (define-key org-mode-map (kbd "C-c 0") 'reftex-view-crossref)
1944   )
1945 (add-hook 'org-mode-hook 'my-org-mode-setup)
1946
1947 (defun org-mode-reftex-search ()
1948   (interactive)
1949   (org-open-link-from-string (format "[[notes:%s]]" (first (reftex-citation t)))))
1950
1951 (defun open-research-paper (bibtexkey)
1952   "Open a paper by bibtex key"
1953   (interactive "bibtex key: ")
1954   (shell-command
1955    (format "%s %s"
1956        (substitute-in-file-name "$HOME/bin/bibtex_to_paper") bibtexkey)))
1957 (org-add-link-type "papers" 'open-research-paper)
1958 (defun open-research-paper-pdf (bibtexkey)
1959   "Open a paper pdf by bibtex key"
1960   (interactive "bibtex key: ")
1961   (shell-command
1962    (format "%s -p evince_annot %s"
1963        (substitute-in-file-name "$HOME/bin/bibtex_to_paper") bibtexkey)))
1964 (org-add-link-type "papers-pdf" 'open-research-paper-pdf)
1965
1966 (add-to-list 'org-link-abbrev-alist
1967              '("notes" .
1968                "~/projects/research/paper_notes.org::#%s"))
1969
1970 ; I pretty much always want hiearchical checkboxes
1971 (setq org-hierachical-checkbox-statistics nil)
1972
1973 ;; Add \begin{equation}\end{equation} templates to the org mode easy templates
1974 (add-to-list 'org-structure-template-alist
1975              '("E" "\\begin{equation}\n?\n\\end{equation}"))
1976
1977  ;; stolen from
1978 ;; http://www-public.it-sudparis.eu/~berger_o/weblog/2012/03/23/how-to-manage-and-export-bibliographic-notesrefs-in-org-mode/
1979 (defun my-rtcite-export-handler (path desc format)
1980   (message "my-rtcite-export-handler is called : path = %s, desc = %s, format = %s" path desc format)
1981   (let* ((search (when (string-match "::#?\\(.+\\)\\'" path)
1982                    (match-string 1 path)))
1983          (path (substring path 0 (match-beginning 0))))
1984     (cond ((eq format 'latex)
1985            (if (or (not desc) 
1986                    (equal 0 (search "rtcite:" desc)))
1987                (format "\\cite{%s}" search)
1988              (format "\\cite[%s]{%s}" desc search))))))
1989
1990 (org-add-link-type "rtcite" 
1991                    'org-bibtex-open
1992                    'my-rtcite-export-handler)
1993
1994
1995 #+END_SRC
1996 ** Org Mobile Configuration
1997 #+BEGIN_SRC emacs-lisp
1998   (setq-default org-mobile-directory "/linnode.donarmstrong.com:/sites/dav.donarmstrong.com/root/org/")
1999   (when (string= system-name "linnode")
2000     (setq-default org-mobile-directory "/sites/dav.donarmstrong.com/root/org/"))
2001   (setq-default org-directory "/home/don/org-mode/")
2002   (setq-default org-mobile-inbox-for-pull "/home/don/org-mode/from-mobile.org")
2003
2004 #+END_SRC
2005 ** Org iCal Support
2006 #+BEGIN_SRC emacs-lisp
2007   ;; org mode ical export
2008   (setq org-icalendar-timezone "America/Los_Angeles")
2009   (setq org-icalendar-use-scheduled '(todo-start event-if-todo))
2010   ;; we already add the id manually
2011   (setq org-icalendar-store-UID t)
2012
2013 #+END_SRC
2014 ** General Org Babel Configuration
2015 #+BEGIN_SRC emacs-lisp
2016 ;; org babel support
2017 (org-babel-do-load-languages
2018  'org-babel-load-languages
2019  '((emacs-lisp . t )
2020    (R . t)
2021    (latex . t)
2022    (ditaa . t)
2023    (dot . t)
2024    ))
2025 ;; set the right path to ditaa.jar
2026 (setq org-ditaa-jar-path "/usr/share/ditaa/ditaa.jar")
2027 ;; use graphviz-dot for dot things
2028 (add-to-list 'org-src-lang-modes '("dot" . graphviz-dot))
2029 ;; do not indent begin_src blocks
2030 (setq org-edit-src-content-indentation 0)
2031 ;; org-babel-by-backend
2032 (defmacro org-babel-by-backend (&rest body)
2033    `(case (if (boundp 'backend) 
2034               (org-export-backend-name backend)
2035             nil) ,@body))
2036
2037 (defun my/fix-inline-images ()
2038   (when org-inline-image-overlays
2039     (org-redisplay-inline-images)))
2040
2041 (add-hook 'org-babel-after-execute-hook
2042            'my/fix-inline-images)
2043
2044 #+END_SRC
2045 ** LaTeX configuration
2046    :PROPERTIES:
2047    :ID:       7135ba17-6a50-4eed-84ca-b90afa5b12f8
2048    :END:
2049 #+BEGIN_SRC emacs-lisp
2050 (use-package ox-extra
2051   :config
2052   (ox-extras-activate '(ignore-headlines)))
2053 (require 'ox-latex)
2054 (add-to-list 'org-latex-classes
2055          '("memarticle"
2056        "\\documentclass[11pt,oneside,article]{memoir}\n"
2057        ("\\section{%s}" . "\\section*{%s}")
2058        ("\\subsection{%s}" . "\\subsection*{%s}")
2059        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2060        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2061        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2062
2063 (setq org-beamer-outline-frame-options "")
2064 (add-to-list 'org-latex-classes
2065          '("beamer"
2066        "\\documentclass[ignorenonframetext]{beamer}
2067 [NO-DEFAULT-PACKAGES]
2068 [PACKAGES]
2069 [EXTRA]"
2070        ("\\section{%s}" . "\\section*{%s}")
2071        ("\\subsection{%s}" . "\\subsection*{%s}")
2072        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2073        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2074        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2075
2076 (add-to-list 'org-latex-classes
2077          '("membook"
2078        "\\documentclass[11pt,oneside]{memoir}\n"
2079        ("\\chapter{%s}" . "\\chapter*{%s}")
2080        ("\\section{%s}" . "\\section*{%s}")
2081        ("\\subsection{%s}" . "\\subsection*{%s}")
2082        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
2083
2084 (add-to-list 'org-latex-classes
2085          '("letter"
2086        "\\documentclass[11pt]{letter}
2087 [NO-DEFAULT-PACKAGES]
2088 [PACKAGES]
2089 [EXTRA]"
2090    ("\\section{%s}" . "\\section*{%s}")
2091        ("\\subsection{%s}" . "\\subsection*{%s}")
2092        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2093        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2094        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2095
2096 (add-to-list 'org-latex-classes
2097          '("dlacv"
2098        "\\documentclass{dlacv}
2099 [NO-DEFAULT-PACKAGES]
2100 [NO-PACKAGES]
2101 [NO-EXTRA]"
2102        ("\\section{%s}" . "\\section*{%s}")
2103        ("\\subsection{%s}" . "\\subsection*{%s}")
2104        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2105        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2106        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2107
2108
2109 (add-to-list 'org-latex-classes
2110          '("dlaresume"
2111        "\\documentclass{dlaresume}
2112 [NO-DEFAULT-PACKAGES]
2113 [NO-PACKAGES]
2114 [NO-EXTRA]"
2115        ("\\section{%s}" . "\\section*{%s}")
2116        ("\\subsection{%s}" . "\\subsection*{%s}")
2117        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
2118        ("\\paragraph{%s}" . "\\paragraph*{%s}")
2119        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2120
2121
2122 ;; Originally taken from Bruno Tavernier: http://thread.gmane.org/gmane.emacs.orgmode/31150/focus=31432
2123 ;; but adapted to use latexmk 4.22 or higher.  
2124 (setq org-latex-pdf-process '("latexmk -f -pdflatex=xelatex -bibtex -use-make -pdf %f"))
2125
2126 ;; Default packages included in /every/ tex file, latex, pdflatex or xelatex
2127 (setq org-latex-default-packages-alist
2128   '(("" "amsmath" t)
2129     ("" "unicode-math" t)
2130     ))
2131 (setq org-latex-packages-alist
2132   '(("" "graphicx" t)
2133     ("" "fontspec" t)
2134     ("" "xunicode" t)
2135     ("" "hyperref" t)
2136     ("" "url" t)
2137     ("" "rotating" t)
2138     ("" "longtable" nil)
2139     ("" "float" )))
2140
2141 ;; make equations larger
2142 (setq org-format-latex-options (plist-put org-format-latex-options :scale 2.0))
2143
2144 (defun org-create-formula--latex-header ()
2145   "Return LaTeX header appropriate for previewing a LaTeX snippet."
2146   (let ((info (org-combine-plists (org-export--get-global-options
2147            (org-export-get-backend 'latex))
2148           (org-export--get-inbuffer-options
2149            (org-export-get-backend 'latex)))))
2150     (org-latex-guess-babel-language
2151      (org-latex-guess-inputenc
2152   (org-splice-latex-header
2153    org-format-latex-header
2154    org-latex-default-packages-alist
2155    nil t
2156    (plist-get info :latex-header)))
2157      info)))
2158
2159
2160 ; support ignoring headers in org mode export to latex
2161 ; from http://article.gmane.org/gmane.emacs.orgmode/67692
2162 (defadvice org-latex-headline (around my-latex-skip-headlines
2163                   (headline contents info) activate)
2164   (if (member "ignoreheading" (org-element-property :tags headline))
2165   (setq ad-return-value contents)
2166     ad-do-it))
2167
2168 ;; keep latex logfiles
2169
2170 (setq org-latex-remove-logfiles nil)
2171
2172 ;; Resume clocking task when emacs is restarted
2173 (org-clock-persistence-insinuate)
2174 ;;
2175 ;; Show lot of clocking history so it's easy to pick items off the C-F11 list
2176 (setq org-clock-history-length 23)
2177 ;; Resume clocking task on clock-in if the clock is open
2178 (setq org-clock-in-resume t)
2179 ;; Change tasks to NEXT when clocking in; this avoids clocking in when
2180 ;; there are things like PHONE calls
2181 (setq org-clock-in-switch-to-state 'bh/clock-in-to-next)
2182 ;; Separate drawers for clocking and logs
2183 (setq org-drawers (quote ("PROPERTIES" "LOGBOOK")))
2184 ;; Save clock data and state changes and notes in the LOGBOOK drawer
2185 (setq org-clock-into-drawer t)
2186 (setq org-log-into-drawer t)
2187 ;; Sometimes I change tasks I'm clocking quickly - this removes clocked tasks with 0:00 duration
2188 (setq org-clock-out-remove-zero-time-clocks t)
2189 ;; Clock out when moving task to a done state
2190 (setq org-clock-out-when-done t)
2191 ;; Save the running clock and all clock history when exiting Emacs, load it on startup
2192 (setq org-clock-persist t)
2193 ;; Do not prompt to resume an active clock
2194 (setq org-clock-persist-query-resume nil)
2195 ;; Enable auto clock resolution for finding open clocks
2196 (setq org-clock-auto-clock-resolution (quote when-no-clock-is-running))
2197 ;; Include current clocking task in clock reports
2198 (setq org-clock-report-include-clocking-task t)
2199
2200 ;; the cache seems to be broken
2201 (setq org-element-use-cache nil)
2202
2203 (defvar bh/keep-clock-running nil)
2204
2205 (defun bh/is-task-p ()
2206   "Any task with a todo keyword and no subtask"
2207   (save-restriction
2208     (widen)
2209     (let ((has-subtask)
2210           (subtree-end (save-excursion (org-end-of-subtree t)))
2211           (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
2212       (save-excursion
2213         (forward-line 1)
2214         (while (and (not has-subtask)
2215                     (< (point) subtree-end)
2216                     (re-search-forward "^\*+ " subtree-end t))
2217           (when (member (org-get-todo-state) org-todo-keywords-1)
2218             (setq has-subtask t))))
2219       (and is-a-task (not has-subtask)))))
2220 (defun bh/is-project-p ()
2221   "Any task with a todo keyword subtask"
2222   (save-restriction
2223     (widen)
2224     (let ((has-subtask)
2225           (subtree-end (save-excursion (org-end-of-subtree t)))
2226           (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
2227       (save-excursion
2228         (forward-line 1)
2229         (while (and (not has-subtask)
2230                     (< (point) subtree-end)
2231                     (re-search-forward "^\*+ " subtree-end t))
2232           (when (member (org-get-todo-state) org-todo-keywords-1)
2233             (setq has-subtask t))))
2234       (and is-a-task has-subtask))))
2235
2236 (defun bh/is-subproject-p ()
2237   "Any task which is a subtask of another project"
2238   (let ((is-subproject)
2239         (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
2240     (save-excursion
2241       (while (and (not is-subproject) (org-up-heading-safe))
2242         (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
2243           (setq is-subproject t))))
2244     (and is-a-task is-subproject)))
2245
2246
2247 (defun bh/clock-in-to-next (kw)
2248   "Switch a task from TODO to NEXT when clocking in.
2249 Skips capture tasks, projects, and subprojects.
2250 Switch projects and subprojects from NEXT back to TODO"
2251   (when (not (and (boundp 'org-capture-mode) org-capture-mode))
2252     (cond
2253      ((and (member (org-get-todo-state) (list "TODO"))
2254        (bh/is-task-p))
2255   "NEXT")
2256      ((and (member (org-get-todo-state) (list "NEXT"))
2257        (bh/is-project-p))
2258   "TODO"))))
2259
2260 (defun bh/punch-in (arg)
2261   "Start continuous clocking and set the default task to the
2262 selected task.  If no task is selected set the Organization task
2263 as the default task."
2264   (interactive "p")
2265   (setq bh/keep-clock-running t)
2266   (if (equal major-mode 'org-agenda-mode)
2267   ;;
2268   ;; We're in the agenda
2269   ;;
2270   (let* ((marker (org-get-at-bol 'org-hd-marker))
2271          (tags (org-with-point-at marker (org-get-tags-at))))
2272     (if (and (eq arg 4) tags)
2273         (org-agenda-clock-in '(16))
2274       (bh/clock-in-organization-task-as-default)))
2275     ;;
2276     ;; We are not in the agenda
2277     ;;
2278     (save-restriction
2279   (widen)
2280   ; Find the tags on the current task
2281   (if (and (equal major-mode 'org-mode) (not (org-before-first-heading-p)) (eq arg 4))
2282       (org-clock-in '(16))
2283     (bh/clock-in-organization-task-as-default)))))
2284
2285 (defun bh/punch-out ()
2286   (interactive)
2287   (setq bh/keep-clock-running nil)
2288   (when (org-clock-is-active)
2289     (org-clock-out))
2290   (org-agenda-remove-restriction-lock))
2291
2292 (defun bh/clock-in-default-task ()
2293   (save-excursion
2294     (org-with-point-at org-clock-default-task
2295   (org-clock-in))))
2296
2297 (defun bh/clock-in-parent-task ()
2298   "Move point to the parent (project) task if any and clock in"
2299   (let ((parent-task))
2300     (save-excursion
2301   (save-restriction
2302     (widen)
2303     (while (and (not parent-task) (org-up-heading-safe))
2304       (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
2305         (setq parent-task (point))))
2306     (if parent-task
2307         (org-with-point-at parent-task
2308       (org-clock-in))
2309       (when bh/keep-clock-running
2310         (bh/clock-in-default-task)))))))
2311
2312 (defvar bh/organization-task-id "e22cb8bf-07c7-408b-8f60-ff3aadac95e4")
2313
2314 (defun bh/clock-in-organization-task-as-default ()
2315   (interactive)
2316   (org-with-point-at (org-id-find bh/organization-task-id 'marker)
2317     (org-clock-in '(16))))
2318
2319 (defun bh/clock-out-maybe ()
2320   (when (and bh/keep-clock-running
2321          (not org-clock-clocking-in)
2322          (marker-buffer org-clock-default-task)
2323          (not org-clock-resolving-clocks-due-to-idleness))
2324     (bh/clock-in-parent-task)))
2325
2326 ; (add-hook 'org-clock-out-hook 'bh/clock-out-maybe 'append)
2327
2328 (require 'org-id)
2329 (defun bh/clock-in-task-by-id (id)
2330   "Clock in a task by id"
2331   (org-with-point-at (org-id-find id 'marker)
2332     (org-clock-in nil)))
2333
2334 (defun bh/clock-in-last-task (arg)
2335   "Clock in the interrupted task if there is one
2336 Skip the default task and get the next one.
2337 A prefix arg forces clock in of the default task."
2338   (interactive "p")
2339   (let ((clock-in-to-task
2340      (cond
2341       ((eq arg 4) org-clock-default-task)
2342       ((and (org-clock-is-active)
2343         (equal org-clock-default-task (cadr org-clock-history)))
2344        (caddr org-clock-history))
2345       ((org-clock-is-active) (cadr org-clock-history))
2346       ((equal org-clock-default-task (car org-clock-history)) (cadr org-clock-history))
2347       (t (car org-clock-history)))))
2348     (widen)
2349     (org-with-point-at clock-in-to-task
2350   (org-clock-in nil))))
2351
2352
2353 (defun org-export-to-ods ()
2354   (interactive)
2355   (let ((csv-file "data.csv"))
2356     (org-table-export csv-file "orgtbl-to-csv")
2357     (org-odt-convert csv-file "ods" 'open)))
2358
2359 ; allow for zero-width-space to be a break in regexp too
2360 ; (setcar org-emphasis-regexp-components "​ [:space:] \t('\"{")
2361 ; (setcar (nthcdr 1 org-emphasis-regexp-components) "​ [:space:]- \t.,:!?;'\")}\\")
2362 ; (org-set-emph-re 'org-emphasis-regexp-components org-emphasis-regexp-components)
2363
2364 ;; support inserting screen shots
2365 (defun my/org-insert-screenshot ()
2366   "Take a screenshot into a time stamped unique-named file in the
2367 same directory as the org-buffer and insert a link to this file."
2368   (interactive)
2369   (defvar my/org-insert-screenshot/filename)
2370   (setq my/org-insert-screenshot/filename
2371     (read-file-name
2372      "Screenshot to insert: "
2373      nil
2374      (concat (buffer-file-name) "_" (format-time-string "%Y%m%d_%H%M%S") ".png")
2375      )
2376     )
2377   (call-process "import" nil nil nil my/org-insert-screenshot/filename)
2378   (insert (concat "[[" my/org-insert-screenshot/filename "]]"))
2379   (org-display-inline-images))
2380
2381 (defun my/fix-inline-images ()
2382   (when org-inline-image-overlays
2383     (org-redisplay-inline-images)))
2384
2385 (add-hook 'org-babel-after-execute-hook 'my/fix-inline-images)
2386
2387 ;; use xelatex to preview with imagemagick
2388 (add-to-list 'org-preview-latex-process-alist
2389          '(xelateximagemagick
2390       :programs ("xelatex" "convert")
2391       :description "pdf > png"
2392       :message "you need to install xelatex and imagemagick"
2393       :use-xcolor t
2394       :image-input-type "pdf"
2395       :image-output-type "png"
2396       :image-size-adjust (1.0 . 1.0)
2397       :latex-compiler ("xelatex -interaction nonstopmode -output-directory %o %f")
2398       :image-converter ("convert -density %D -trim -antialias %f -quality 100 %O"))
2399          )
2400 ;; use xelatex by default
2401 (setq org-preview-latex-default-process 'xelateximagemagick)
2402
2403 ; from http://orgmode.org/Changes.html
2404 (defun my/org-repair-property-drawers ()
2405   "Fix properties drawers in current buffer.
2406  Ignore non Org buffers."
2407   (interactive)
2408   (when (eq major-mode 'org-mode)
2409     (org-with-wide-buffer
2410      (goto-char (point-min))
2411      (let ((case-fold-search t)
2412        (inline-re (and (featurep 'org-inlinetask)
2413                (concat (org-inlinetask-outline-regexp)
2414                    "END[ \t]*$"))))
2415    (org-map-entries
2416     (lambda ()
2417       (unless (and inline-re (org-looking-at-p inline-re))
2418         (save-excursion
2419       (let ((end (save-excursion (outline-next-heading) (point))))
2420         (forward-line)
2421         (when (org-looking-at-p org-planning-line-re) (forward-line))
2422         (when (and (< (point) end)
2423                (not (org-looking-at-p org-property-drawer-re))
2424                (save-excursion
2425                  (and (re-search-forward org-property-drawer-re end t)
2426                   (eq (org-element-type
2427                    (save-match-data (org-element-at-point)))
2428                   'drawer))))
2429           (insert (delete-and-extract-region
2430                (match-beginning 0)
2431                (min (1+ (match-end 0)) end)))
2432           (unless (bolp) (insert "\n"))))))))))))
2433
2434 #+END_SRC
2435 ** Org-Gcal
2436 #+BEGIN_SRC emacs-lisp
2437 (use-package calfw
2438   :ensure f
2439   )
2440 (use-package calfw-org
2441   :ensure f
2442   )
2443 (use-package org-gcal
2444   :if (file-readable-p "~/.hide/org_gcal.el")
2445   :ensure f
2446   :config '((if (file-readable-p "~/.hide/org_gcal.el")
2447                 (load-file "~/.hide/org_gcal.el"))
2448             )
2449   )
2450 #+END_SRC
2451 ** appt integration
2452 #+BEGIN_SRC emacs-lisp
2453   (use-package appt
2454     :ensure f
2455     :config
2456     ;; Show notification 10 minutes before event
2457     (setq appt-message-warning-time 10)
2458     ;; Disable multiple reminders
2459     (setq appt-display-interval appt-message-warning-time)
2460     (setq appt-display-mode-line nil)
2461
2462     ;; add automatic reminders for appointments
2463     (defun my/org-agenda-to-appt ()
2464       (interactive)
2465       (setq appt-time-msg-list nil)
2466       (org-agenda-to-appt))
2467     ;; add reminders when starting emacs
2468     (my/org-agenda-to-appt)
2469     ;; when rebuilding the agenda
2470     (defadvice  org-agenda-redo (after org-agenda-redo-add-appts)
2471       "Pressing `r' on the agenda will also add appointments."
2472       (my/org-agenda-to-appt)
2473       )
2474     ;; when saving all org buffers
2475     (defadvice org-save-all-org-buffers (after org-save-all-org-buffers-add-appts)
2476       "Re-add appts after saving all org buffers"
2477       (my/org-agenda-to-appt))
2478     ;; Display appointments as a window manager notification
2479     (setq appt-disp-window-function 'my/appt-display)
2480     (setq appt-delete-window-function (lambda () t))
2481
2482     (setq my/appt-notification-app (concat (getenv "HOME") "/bin/appt_notification"))
2483
2484     (defun my/appt-display (min-to-app new-time msg)
2485       (if (atom min-to-app)
2486       (start-process "my/appt-notification-app" nil my/appt-notification-app min-to-app msg)
2487     (dolist (i (number-sequence 0 (1- (length min-to-app))))
2488       (start-process "my/appt-notification-app" nil my/appt-notification-app
2489                      (nth i min-to-app) (nth i msg))))
2490       )
2491     )
2492
2493
2494 #+END_SRC
2495 ** outshine (outlining) integration
2496 #+BEGIN_SRC emacs-lisp
2497 (use-package outshine
2498   :ensure t
2499   :hook (outline-minor-mode . outshine-hook-function)
2500 )
2501 #+END_SRC
2502 ** End use-package
2503 #+BEGIN_SRC emacs-lisp
2504   )
2505 #+END_SRC
2506 * Keybindings
2507 ** Home/End Begining/End of line
2508 #+BEGIN_SRC emacs-lisp
2509   (global-set-key [home] 'move-beginning-of-line)
2510   (global-set-key [end] 'move-end-of-line)
2511 #+END_SRC
2512 ** Goto line
2513 #+BEGIN_SRC emacs-lisp
2514   (global-unset-key "\M-g")
2515   (global-set-key (kbd "M-g l") 'goto-line)
2516 #+END_SRC
2517 * Debian
2518 ** debian-changelog
2519 #+BEGIN_SRC emacs-lisp
2520   (use-package debian-changelog-mode
2521     :mode "debian/changelog"
2522     :config
2523     (setq debian-changelog-mailing-address "don@debian.org")
2524     (setq debian-changelog-full-name "Don Armstrong"))
2525 #+END_SRC
2526 * Misc (uncharacterized)
2527 #+BEGIN_SRC emacs-lisp
2528   (setq calendar-latitude 38.6)
2529   (setq calendar-longitude -121.5)
2530   (setq case-fold-search t)
2531   (setq confirm-kill-emacs (quote y-or-n-p))
2532   (setq cperl-lazy-help-time nil)
2533 #+END_SRC
2534 ** Turn on fontlock and icomplete
2535 #+BEGIN_SRC emacs-lisp
2536   (global-font-lock-mode 1)
2537   (icomplete-mode 1)
2538   (setq log-edit-keep-buffer t)
2539 #+END_SRC
2540 ** Set mail User agent
2541 #+BEGIN_SRC emacs-lisp
2542   (setq mail-user-agent (quote sendmail-user-agent))
2543   (setq mutt-alias-file-list (quote ("~/.mutt/aliases" "~/.mail_aliases")))
2544 #+END_SRC
2545 ** PS Printing
2546 #+BEGIN_SRC emacs-lisp
2547   (setq ps-footer-font-size (quote (8 . 10)))
2548   (setq ps-header-font-size (quote (8 . 10)))
2549   (setq ps-header-title-font-size (quote (10 . 10)))
2550   (setq ps-line-number-color "blue")
2551   (setq ps-print-footer t)
2552   (setq ps-print-footer-frame nil)
2553   (setq ps-print-only-one-header t)
2554 #+END_SRC
2555 ** Only single spacing on sentences
2556 #+BEGIN_SRC emacs-lisp
2557   (setq sentence-end "[.?!][]\"')]*\\($\\|   \\| \\)[    
2558   ]*")
2559   (setq sentence-end-double-space nil)
2560   ; enable matching parenthesis
2561 #+END_SRC
2562 ** Display paren mode
2563 #+BEGIN_SRC emacs-lisp
2564   (show-paren-mode 1)
2565   (setq show-paren-delay 0.2)
2566
2567   (setq user-mail-address "don@donarmstrong.com")
2568
2569   ;; switch back to the old primary selection method
2570   (setq x-select-enable-clipboard nil)
2571   (setq x-select-enable-primary t)
2572   ; (setq mouse-drag-copy-region t)
2573
2574   (fset 'perl-mode 'cperl-mode)
2575   ;;(load-file "cperl-mode.el")
2576
2577   ;; tramp configuration
2578   (setq tramp-use-ssh-controlmaster-options nil)
2579
2580   (setq-default c-indent-level 4)
2581   (setq-default c-brace-imaginary-offset 0)
2582   (setq-default c-brace-offset -4)
2583   (setq-default c-argdecl-indent 4)
2584   (setq-default c-label-offset -4)
2585   (setq-default c-continued-statement-offset 4)
2586   ; tabs are annoying
2587   (setq-default indent-tabs-mode nil)
2588   (setq-default tab-width 4)
2589
2590
2591   ;; (autoload 'php-mode "php-mode" "PHP editing mode" t)
2592   ;; (add-to-list 'auto-mode-alist '("\\.php3?\\'" . php-mode))
2593   ;; (add-to-list 'auto-mode-alist '("\\.phtml?\\'" . php-mode))
2594   ;; (add-to-list 'auto-mode-alist '("\\.php?\\'" . php-mode))
2595   ;; (add-to-list 'auto-mode-alist '("\\.php4?\\'" . php-mode))
2596
2597
2598   (defun insert-date ()
2599     "Insert date at point."
2600     (interactive)
2601     (insert (format-time-string "%A, %B %e, %Y %k:%M:%S %Z")))
2602   (global-set-key "\C-[d" 'insert-date)
2603
2604   (defun unfill-paragraph (arg)
2605     "Pull this whole paragraph up onto one line."
2606     (interactive "*p")
2607     (let ((fill-column 10000))
2608       (fill-paragraph arg))
2609     )
2610
2611   (column-number-mode t)
2612  
2613 #+END_SRC
2614 ** Desktop-save-mode
2615 If the envvar EMACS_SERVER_NAME is set, consider this a separate
2616 emacs, and use a different desktop file to restore history
2617 #+BEGIN_SRC emacs-lisp
2618   (use-package desktop
2619     :demand
2620     :config
2621     (setq desktop-base-file-name
2622           (convert-standard-filename
2623            (concat ".emacs"
2624                    (or (getenv "EMACS_SERVER_NAME")
2625                        "")
2626                    ".desktop")
2627            ))
2628     (setq desktop-base-lock-name
2629           (convert-standard-filename
2630            (concat desktop-base-file-name
2631                    ".lock")))
2632     (setq desktop-auto-save-timeout 60)
2633     (setq desktop-restore-eager 5)
2634     (setq desktop-lazy-verbose nil)
2635     (desktop-save-mode 1)
2636     ; (desktop-read)
2637   )
2638 #+END_SRC
2639 ** Misc (Uncharacterized)
2640 #+BEGIN_SRC emacs-lisp
2641   '(icomplete-mode on)
2642   (custom-set-faces
2643    ;; custom-set-faces was added by Custom.
2644    ;; If you edit it by hand, you could mess it up, so be careful.
2645    ;; Your init file should contain only one such instance.
2646    ;; If there is more than one, they won't work right.
2647    '(menu ((((type x-toolkit)) (:background "black" :foreground "grey90")))))
2648
2649
2650   (put 'upcase-region 'disabled nil)
2651   (put 'downcase-region 'disabled nil)
2652   (put 'narrow-to-region 'disabled nil)
2653
2654   ; (defun turn-on-flyspell ()
2655   ;    "Force flyspell-mode on using a positive arg.  For use in hooks."
2656   ;    (interactive)
2657   ;    (flyspell-mode 1))
2658
2659
2660    ; Outline-minor-mode key map
2661    (define-prefix-command 'cm-map nil "Outline-")
2662    ; HIDE
2663    (define-key cm-map "q" 'outline-hide-sublevels)    ; Hide everything but the top-level headings
2664    (define-key cm-map "t" 'outline-hide-body)         ; Hide everything but headings (all body lines)
2665    (define-key cm-map "o" 'outline-hide-other)        ; Hide other branches
2666    (define-key cm-map "c" 'outline-hide-entry)        ; Hide this entry's body
2667    (define-key cm-map "l" 'outline-hide-leaves)       ; Hide body lines in this entry and sub-entries
2668    (define-key cm-map "d" 'outline-hide-subtree)      ; Hide everything in this entry and sub-entries
2669    ; SHOW
2670    (define-key cm-map "a" 'outline-show-all)          ; Show (expand) everything
2671    (define-key cm-map "e" 'outline-show-entry)        ; Show this heading's body
2672    (define-key cm-map "i" 'outline-show-children)     ; Show this heading's immediate child sub-headings
2673    (define-key cm-map "k" 'outline-show-branches)     ; Show all sub-headings under this heading
2674    (define-key cm-map "s" 'outline-show-subtree)      ; Show (expand) everything in this heading & below
2675    ; MOVE
2676    (define-key cm-map "u" 'outline-up-heading)                ; Up
2677    (define-key cm-map "n" 'outline-next-visible-heading)      ; Next
2678    (define-key cm-map "p" 'outline-previous-visible-heading)  ; Previous
2679    (define-key cm-map "f" 'outline-forward-same-level)        ; Forward - same level
2680    (define-key cm-map "b" 'outline-backward-same-level)       ; Backward - same level
2681    (global-set-key "\M-o" cm-map)
2682   ; fix up tmux xterm keys
2683   ; stolen from http://unix.stackexchange.com/questions/24414/shift-arrow-not-working-in-emacs-within-tmux
2684   (defun fix-up-tmux-keys ()
2685       "Fix up tmux xterm keys"
2686       (if (getenv "TMUX")
2687           (progn
2688             (let ((x 2) (tkey ""))
2689               (while (<= x 8)
2690                 ;; shift
2691                 (if (= x 2)
2692                     (setq tkey "S-"))
2693                 ;; alt
2694                 (if (= x 3)
2695                     (setq tkey "M-"))
2696                 ;; alt + shift
2697                 (if (= x 4)
2698                     (setq tkey "M-S-"))
2699                 ;; ctrl
2700                 (if (= x 5)
2701                     (setq tkey "C-"))
2702                 ;; ctrl + shift
2703                 (if (= x 6)
2704                     (setq tkey "C-S-"))
2705                 ;; ctrl + alt
2706                 (if (= x 7)
2707                     (setq tkey "C-M-"))
2708                 ;; ctrl + alt + shift
2709                 (if (= x 8)
2710                     (setq tkey "C-M-S-"))
2711
2712                 ;; arrows
2713                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d A" x)) (kbd (format "%s<up>" tkey)))
2714                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d B" x)) (kbd (format "%s<down>" tkey)))
2715                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d C" x)) (kbd (format "%s<right>" tkey)))
2716                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d D" x)) (kbd (format "%s<left>" tkey)))
2717                 ;; home
2718                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d H" x)) (kbd (format "%s<home>" tkey)))
2719                 ;; end
2720                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d F" x)) (kbd (format "%s<end>" tkey)))
2721                 ;; page up
2722                 (define-key key-translation-map (kbd (format "M-[ 5 ; %d ~" x)) (kbd (format "%s<prior>" tkey)))
2723                 ;; page down
2724                 (define-key key-translation-map (kbd (format "M-[ 6 ; %d ~" x)) (kbd (format "%s<next>" tkey)))
2725                 ;; insert
2726                 (define-key key-translation-map (kbd (format "M-[ 2 ; %d ~" x)) (kbd (format "%s<delete>" tkey)))
2727                 ;; delete
2728                 (define-key key-translation-map (kbd (format "M-[ 3 ; %d ~" x)) (kbd (format "%s<delete>" tkey)))
2729                 ;; f1
2730                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d P" x)) (kbd (format "%s<f1>" tkey)))
2731                 ;; f2
2732                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d Q" x)) (kbd (format "%s<f2>" tkey)))
2733                 ;; f3
2734                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d R" x)) (kbd (format "%s<f3>" tkey)))
2735                 ;; f4
2736                 (define-key key-translation-map (kbd (format "M-[ 1 ; %d S" x)) (kbd (format "%s<f4>" tkey)))
2737                 ;; f5
2738                 (define-key key-translation-map (kbd (format "M-[ 15 ; %d ~" x)) (kbd (format "%s<f5>" tkey)))
2739                 ;; f6
2740                 (define-key key-translation-map (kbd (format "M-[ 17 ; %d ~" x)) (kbd (format "%s<f6>" tkey)))
2741                 ;; f7
2742                 (define-key key-translation-map (kbd (format "M-[ 18 ; %d ~" x)) (kbd (format "%s<f7>" tkey)))
2743                 ;; f8
2744                 (define-key key-translation-map (kbd (format "M-[ 19 ; %d ~" x)) (kbd (format "%s<f8>" tkey)))
2745                 ;; f9
2746                 (define-key key-translation-map (kbd (format "M-[ 20 ; %d ~" x)) (kbd (format "%s<f9>" tkey)))
2747                 ;; f10
2748                 (define-key key-translation-map (kbd (format "M-[ 21 ; %d ~" x)) (kbd (format "%s<f10>" tkey)))
2749                 ;; f11
2750                 (define-key key-translation-map (kbd (format "M-[ 23 ; %d ~" x)) (kbd (format "%s<f11>" tkey)))
2751                 ;; f12
2752                 (define-key key-translation-map (kbd (format "M-[ 24 ; %d ~" x)) (kbd (format "%s<f12>" tkey)))
2753                 ;; f13
2754                 (define-key key-translation-map (kbd (format "M-[ 25 ; %d ~" x)) (kbd (format "%s<f13>" tkey)))
2755                 ;; f14
2756                 (define-key key-translation-map (kbd (format "M-[ 26 ; %d ~" x)) (kbd (format "%s<f14>" tkey)))
2757                 ;; f15
2758                 (define-key key-translation-map (kbd (format "M-[ 28 ; %d ~" x)) (kbd (format "%s<f15>" tkey)))
2759                 ;; f16
2760                 (define-key key-translation-map (kbd (format "M-[ 29 ; %d ~" x)) (kbd (format "%s<f16>" tkey)))
2761                 ;; f17
2762                 (define-key key-translation-map (kbd (format "M-[ 31 ; %d ~" x)) (kbd (format "%s<f17>" tkey)))
2763                 ;; f18
2764                 (define-key key-translation-map (kbd (format "M-[ 32 ; %d ~" x)) (kbd (format "%s<f18>" tkey)))
2765                 ;; f19
2766                 (define-key key-translation-map (kbd (format "M-[ 33 ; %d ~" x)) (kbd (format "%s<f19>" tkey)))
2767                 ;; f20
2768                 (define-key key-translation-map (kbd (format "M-[ 34 ; %d ~" x)) (kbd (format "%s<f20>" tkey)))
2769
2770                 (setq x (+ x 1))
2771                 ))
2772             )
2773         )
2774       )
2775   ; (add-hook 'tty-setup-hook 'fix-up-tmux-keys)
2776
2777   (defadvice ask-user-about-supersession-threat (around ask-user-about-supersession-threat-if-necessary)
2778     "Call ask-user-about-supersession-threat only if the buffer is actually obsolete."
2779     (if (or (buffer-modified-p)
2780             (verify-visited-file-modtime)
2781             (< (* 8 1024 1024) (buffer-size))
2782             (/= 0 (call-process-region 1 (+ 1 (buffer-size)) "diff" nil nil nil "-q" (buffer-file-name) "-")))
2783         ad-do-it
2784       (clear-visited-file-modtime)
2785       (not-modified)))
2786   (ad-activate 'ask-user-about-supersession-threat)
2787 #+END_SRC
2788
2789 * Start Server
2790 #+BEGIN_SRC emacs-lisp
2791   (use-package server
2792     :config
2793     (setq server-name
2794           (or (getenv "EMACS_SERVER_NAME")
2795               "server"))
2796     (unless (server-running-p)
2797       (global-set-key "\C-xp" 'server-edit)
2798       (server-start)))
2799 #+END_SRC
2800
2801
2802
2803 * END
2804 #+BEGIN_SRC emacs-lisp
2805   (provide 'don-configuration)
2806 #+END_SRC