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