]> git.donarmstrong.com Git - lib.git/blob - emacs_el/configuration/org-mode-configuration.el
Merge branch 'master' of git+ssh://git.donarmstrong.com/srv/git/lib
[lib.git] / emacs_el / configuration / org-mode-configuration.el
1 (require 'org-id)
2 (require 'reftex)
3 (require 'gnus)
4
5 ;; The following lines are always needed. Choose your own keys.
6 (add-to-list 'auto-mode-alist '("\\.\\(org\\|org_archive\\|txt\\)$" . org-mode))
7 (require 'org)
8 (global-set-key "\C-cl" 'org-store-link)
9 (global-set-key "\C-ca" 'org-agenda)
10 (global-set-key "\C-cb" 'org-iswitchb)
11 (setq-default org-log-done 'time)
12 (setq-default org-agenda-ndays 5)
13
14 ;; agenda configuration
15 ;; Do not dim blocked tasks
16 (setq org-agenda-dim-blocked-tasks nil)
17
18 ;; Compact the block agenda view
19 (setq org-agenda-compact-blocks t)
20
21 ;; Custom agenda command definitions
22 (setq org-agenda-custom-commands
23       (quote (("N" "Notes" tags "NOTE"
24                ((org-agenda-overriding-header "Notes")
25                 (org-tags-match-list-sublevels t)))
26               ("h" "Habits" tags-todo "STYLE=\"habit\""
27                ((org-agenda-overriding-header "Habits")
28                 (org-agenda-sorting-strategy
29                  '(todo-state-down effort-up category-keep))))
30               (" " "Agenda"
31                ((agenda "" nil)
32                 (tags "REFILE"
33                       ((org-agenda-overriding-header "Tasks to Refile")
34                        (org-tags-match-list-sublevels nil)))
35                 (tags-todo "-CANCELLED/!"
36                            ((org-agenda-overriding-header "Stuck Projects")
37                             (org-agenda-skip-function 'bh/skip-non-stuck-projects)
38                             (org-agenda-sorting-strategy
39                              '(category-keep))))
40                 (tags-todo "-HOLD-CANCELLED/!"
41                            ((org-agenda-overriding-header "Projects")
42                             (org-agenda-skip-function 'bh/skip-non-projects)
43                             (org-tags-match-list-sublevels 'indented)
44                             (org-agenda-sorting-strategy
45                              '(category-keep))))
46                 (tags-todo "-CANCELLED/!NEXT"
47                            ((org-agenda-overriding-header (concat "Project Next Tasks"
48                                                                   (if bh/hide-scheduled-and-waiting-next-tasks
49                                                                       ""
50                                                                     " (including WAITING and SCHEDULED tasks)")))
51                             (org-agenda-skip-function 'bh/skip-projects-and-habits-and-single-tasks)
52                             (org-tags-match-list-sublevels t)
53                             (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
54                             (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
55                             (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
56                             (org-agenda-sorting-strategy
57                              '(todo-state-down effort-up category-keep))))
58                 (tags-todo "-REFILE-CANCELLED-WAITING-HOLD/!"
59                            ((org-agenda-overriding-header (concat "Project Subtasks"
60                                                                   (if bh/hide-scheduled-and-waiting-next-tasks
61                                                                       ""
62                                                                     " (including WAITING and SCHEDULED tasks)")))
63                             (org-agenda-skip-function 'bh/skip-non-project-tasks)
64                             (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
65                             (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
66                             (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
67                             (org-agenda-sorting-strategy
68                              '(category-keep))))
69                 (tags-todo "-REFILE-CANCELLED-WAITING-HOLD/!"
70                            ((org-agenda-overriding-header (concat "Standalone Tasks"
71                                                                   (if bh/hide-scheduled-and-waiting-next-tasks
72                                                                       ""
73                                                                     " (including WAITING and SCHEDULED tasks)")))
74                             (org-agenda-skip-function 'bh/skip-project-tasks)
75                             (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
76                             (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
77                             (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
78                             (org-agenda-sorting-strategy
79                              '(category-keep))))
80                 (tags-todo "-CANCELLED+WAITING|HOLD/!"
81                            ((org-agenda-overriding-header "Waiting and Postponed Tasks")
82                             (org-agenda-skip-function 'bh/skip-stuck-projects)
83                             (org-tags-match-list-sublevels nil)
84                             (org-agenda-todo-ignore-scheduled t)
85                             (org-agenda-todo-ignore-deadlines t)))
86                 (tags "-REFILE/"
87                       ((org-agenda-overriding-header "Tasks to Archive")
88                        (org-agenda-skip-function 'bh/skip-non-archivable-tasks)
89                        (org-tags-match-list-sublevels nil))))
90                nil))))
91
92 ; org mode agenda files
93 (setq org-agenda-files
94       (quote ("~/projects/debbugs/debbugs.org"
95               "~/projects/notes/notes.org"
96               "~/projects/notes/refile.org"
97               "~/projects/notes/diary.org"
98               "~/projects/origins_of_life/ool.org"
99               "~/projects/sysadmin/sndservers/sndservers.org"
100               "~/projects/chaim/chaim.org"
101               "~/projects/chaim/papers/gwas_paper_2012/gwas_paper.org"
102           "~/projects/reviews/reviews.org"
103               "~/projects/fh/fh.org")))
104
105 (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")))
106 (setq org-columns-default-format "%40ITEM(Task) %6Effort{:} %CLOCKSUM %PRIORITY %TODO %13SCHEDULED %13DEADLINE %TAGS")
107
108 (setq org-default-notes-file "~/projects/notes/notes.org")
109 (setq org-capture-templates  ;; mail-specific note template, identified by "m"
110       '(("m" "Mail" entry (file+headline "~/projects/notes/refile.org" "Mail")
111          "* %?\n\n  Source: %u, %c\n  %i")
112         ("t" "todo" entry (file "~/projects/notes/refile.org")
113          "* TODO %?\n%U\n%a\n" :clock-in t :clock-resume t)
114         ("r" "respond" entry (file "~/projects/notes/refile.org")
115          "* NEXT Respond to %:from on %:subject\nSCHEDULED: %t\n%U\n%a\n" :clock-in t :clock-resume t :immediate-finish t)
116         ("n" "note" entry (file "~/projects/notes/refile.org")
117          "* %? :NOTE:\n%U\n%a\n" :clock-in t :clock-resume t)
118         ("s" "schedule" entry (file "~/projects/notes/refile.org")
119          "* %? \n%^{scheduled:}t\n%U\n%a\n" :clock-in t :clock-resume t)
120         ("j" "Journal" entry (file+datetree "~/projects/notes/diary.org")
121          "* %?\n%U\n" :clock-in t :clock-resume t)
122         ("w" "org-protocol" entry (file "~/projects/notes/refile.org")
123          "* TODO Review %c\n%U\n" :immediate-finish t)
124         ("m" "Meeting" entry (file "~/projects/notes/refile.org")
125          "* MEETING with %? :MEETING:\n%U" :clock-in t :clock-resume t)
126         ("p" "Phone call" entry (file "~/projects/notes/refile.org")
127          "* PHONE %? :PHONE:\n%U" :clock-in t :clock-resume t)
128         ("J" "job" entry (file "~/projects/notes/refile.org")
129          "* TODO Apply for %a%? :job:\n%U\n" :clock-in t :clock-resume t)
130         ("h" "Habit" entry (file "~/projects/notes/refile.org")
131          "* NEXT %?\n%U\n%a\nSCHEDULED: %(format-time-string \"<%Y-%m-%d %a .+1d/3d>\")\n:PROPERTIES:\n:STYLE: habit\n:REPEAT_TO_STATE: NEXT\n:END:\n")
132         )
133       )
134
135 ;; Remove empty LOGBOOK drawers on clock out
136 (defun bh/remove-empty-drawer-on-clock-out ()
137   (interactive)
138   (save-excursion
139     (beginning-of-line 0)
140     (org-remove-empty-drawer-at "LOGBOOK" (point))))
141
142 (defun my/org-add-id ()
143   (interactive)
144   (save-excursion
145     (if (org-current-level)
146         ()
147       (forward-char 1)
148       )
149     (org-id-get-create)
150     )
151 )
152
153 ; org mode configuration from http://doc.norang.ca/org-mode.html
154 ;; Custom Key Bindings
155 (global-set-key (kbd "<f12>") 'org-agenda)
156 (global-set-key (kbd "<f5>") 'bh/org-todo)
157 (global-set-key (kbd "<S-f5>") 'bh/widen)
158 (global-set-key (kbd "<f7>") 'bh/set-truncate-lines)
159 (global-set-key (kbd "<f8>") 'org-cycle-agenda-files)
160 (global-set-key (kbd "<f9> <f9>") 'bh/show-org-agenda)
161 (global-set-key (kbd "<f9> b") 'bbdb)
162 (global-set-key (kbd "<f9> c") 'calendar)
163 (global-set-key (kbd "<f9> f") 'boxquote-insert-file)
164 (global-set-key (kbd "<f9> h") 'bh/hide-other)
165 (global-set-key (kbd "<f9> n") 'bh/toggle-next-task-display)
166 (global-set-key (kbd "<f9> w") 'widen)
167
168 ; change the outline mode prefix from C-c @ to C-c C-2
169 (setq outline-minor-mode-prefix "C-c C-2")
170 (add-hook 'outline-minor-mode-hook
171           (lambda () (local-set-key (kbd "C-c C-2")
172                                     outline-mode-prefix-map)))
173
174 (global-set-key (kbd "<f9> I") 'bh/punch-in)
175 (global-set-key (kbd "<f9> O") 'bh/punch-out)
176
177 (global-set-key (kbd "<f9> o") 'bh/make-org-scratch)
178
179 (global-set-key (kbd "<f9> r") 'boxquote-region)
180 (global-set-key (kbd "<f9> s") 'bh/switch-to-scratch)
181
182 (global-set-key (kbd "<f9> t") 'bh/insert-inactive-timestamp)
183 (global-set-key (kbd "<f9> T") 'bh/toggle-insert-inactive-timestamp)
184
185 (global-set-key (kbd "<f9> v") 'visible-mode)
186 (global-set-key (kbd "<f9> l") 'org-toggle-link-display)
187 (global-set-key (kbd "<f9> SPC") 'bh/clock-in-last-task)
188 (global-set-key (kbd "C-<f9>") 'previous-buffer)
189 (global-set-key (kbd "M-<f9>") 'org-toggle-inline-images)
190 (global-set-key (kbd "C-x n r") 'narrow-to-region)
191 (global-set-key (kbd "C-<f10>") 'next-buffer)
192 (global-set-key (kbd "<f11>") 'org-clock-goto)
193 (global-set-key (kbd "C-<f11>") 'org-clock-in)
194 (global-set-key (kbd "C-s-<f12>") 'bh/save-then-publish)
195 (global-set-key (kbd "C-c c") 'org-capture)
196
197 (defun bh/hide-other ()
198   (interactive)
199   (save-excursion
200     (org-back-to-heading 'invisible-ok)
201     (hide-other)
202     (org-cycle)
203     (org-cycle)
204     (org-cycle)))
205
206 (defun bh/set-truncate-lines ()
207   "Toggle value of truncate-lines and refresh window display."
208   (interactive)
209   (setq truncate-lines (not truncate-lines))
210   ;; now refresh window display (an idiom from simple.el):
211   (save-excursion
212     (set-window-start (selected-window)
213                       (window-start (selected-window)))))
214
215 (defun bh/make-org-scratch ()
216   (interactive)
217   (find-file "/tmp/publish/scratch.org")
218   (gnus-make-directory "/tmp/publish"))
219
220 (defun bh/switch-to-scratch ()
221   (interactive)
222   (switch-to-buffer "*scratch*"))
223
224 (setq org-use-fast-todo-selection t)
225 (setq org-treat-S-cursor-todo-selection-as-state-change nil)
226
227 (setq org-todo-keywords
228       (quote ((sequence "TODO(t)" "NEXT(n)" "|" "DONE(d)")
229               (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" "PHONE" "MEETING"))))
230
231 (setq org-todo-keyword-faces
232       (quote (("TODO" :foreground "red" :weight bold)
233               ("NEXT" :foreground "blue" :weight bold)
234               ("DONE" :foreground "forest green" :weight bold)
235               ("WAITING" :foreground "orange" :weight bold)
236               ("HOLD" :foreground "magenta" :weight bold)
237               ("CANCELLED" :foreground "forest green" :weight bold)
238               ("MEETING" :foreground "forest green" :weight bold)
239               ("PHONE" :foreground "forest green" :weight bold))))
240
241 (setq org-todo-state-tags-triggers
242       (quote (("CANCELLED" ("CANCELLED" . t))
243               ("WAITING" ("WAITING" . t))
244               ("HOLD" ("WAITING") ("HOLD" . t))
245               (done ("WAITING") ("HOLD"))
246               ("TODO" ("WAITING") ("CANCELLED") ("HOLD"))
247               ("NEXT" ("WAITING") ("CANCELLED") ("HOLD"))
248               ("DONE" ("WAITING") ("CANCELLED") ("HOLD")))))
249
250
251
252 (add-hook 'org-clock-out-hook 'bh/remove-empty-drawer-on-clock-out 'append)
253 ; add ids on creation of nodes
254 (add-hook 'org-capture-prepare-finalize-hook 'my/org-add-id)
255 ; create function to create headlines in file. This comes from
256 ; http://stackoverflow.com/questions/13340616/assign-ids-to-every-entry-in-org-mode
257 (defun my/org-add-ids-to-headlines-in-file ()
258   "Add ID properties to all headlines in the current file which
259 do not already have one."
260   (interactive)
261   (org-map-entries 'org-id-get-create))
262 ; if we wanted to do this to every buffer, do the following:
263 ; (add-hook 'org-mode-hook
264 ;           (lambda ()
265 ;             (add-hook 'before-save-hook 'my/org-add-ids-to-headlines-in-file nil 'local)))
266
267
268 ; resolve clocks after 10 minutes of idle; use xprintidle
269 ; (setq org-clock-idle-time 10)
270 ; (setq org-clock-x11idle-program-name "xprintidle")
271
272 ; this is from http://doc.norang.ca/org-mode.html#Capture
273 ; use C-M-r for org mode capture
274 (global-set-key (kbd "C-M-r") 'org-capture)
275
276 ; Targets include this file and any file contributing to the agenda - up to 9 levels deep
277 (setq org-refile-targets (quote ((nil :maxlevel . 9)
278                                  (org-agenda-files :maxlevel . 9))))
279
280 ; Use full outline paths for refile targets - we file directly with IDO
281 (setq org-refile-use-outline-path t)
282
283 ; Targets complete directly with IDO
284 (setq org-outline-path-complete-in-steps nil)
285
286 ; Allow refile to create parent tasks with confirmation
287 (setq org-refile-allow-creating-parent-nodes (quote confirm))
288
289 ; Use IDO for both buffer and file completion and ido-everywhere to t
290 (setq org-completion-use-ido t)
291 (setq ido-everywhere t)
292 (setq ido-max-directory-size 100000)
293 (ido-mode (quote both))
294 ; Use the current window when visiting files and buffers with ido
295 (setq ido-default-file-method 'selected-window)
296 (setq ido-default-buffer-method 'selected-window)
297 ; Use the current window for indirect buffer display
298 (setq org-indirect-buffer-display 'current-window)
299
300
301 ;;;; Refile settings
302 ; Exclude DONE state tasks from refile targets
303 (defun bh/verify-refile-target ()
304   "Exclude todo keywords with a done state from refile targets"
305   (not (member (nth 2 (org-heading-components)) org-done-keywords)))
306
307 (setq org-refile-target-verify-function 'bh/verify-refile-target)
308
309 ;; ensure that emacsclient will show just the note to be edited when invoked
310 ;; from Mutt, and that it will shut down emacsclient once finished;
311 ;; fallback to legacy behavior when not invoked via org-protocol.
312 (require 'org-protocol)
313 (add-hook 'org-capture-mode-hook 'delete-other-windows)
314 (setq my-org-protocol-flag nil)
315 (defadvice org-capture-finalize (after delete-frame-at-end activate)
316   "Delete frame at remember finalization"
317   (progn (if my-org-protocol-flag (delete-frame))
318          (setq my-org-protocol-flag nil)))
319 (defadvice org-capture-refile (around delete-frame-after-refile activate)
320   "Delete frame at remember refile"
321   (if my-org-protocol-flag
322       (progn
323         (setq my-org-protocol-flag nil)
324         ad-do-it
325         (delete-frame))
326     ad-do-it)
327   )
328 (defadvice org-capture-kill (after delete-frame-at-end activate)
329   "Delete frame at remember abort"
330   (progn (if my-org-protocol-flag (delete-frame))
331          (setq my-org-protocol-flag nil)))
332 (defadvice org-protocol-capture (before set-org-protocol-flag activate)
333   (setq my-org-protocol-flag t))
334
335 (defadvice org-insert-todo-heading (after dla/create-id activate)
336   (org-id-get-create)
337   )
338
339 ;; org modules
340 (add-to-list 'org-modules 'org-habit)
341
342 ; this comes from http://upsilon.cc/~zack/blog/posts/2010/02/integrating_Mutt_with_Org-mode/
343 (defun open-mail-in-mutt (message)
344   "Open a mail message in Mutt, using an external terminal.
345
346 Message can be specified either by a path pointing inside a
347 Maildir, or by Message-ID."
348   (interactive "MPath or Message-ID: ")
349   (shell-command
350    (format "faf xterm -e \"%s %s\""
351        (substitute-in-file-name "$HOME/bin/mutt_open") message)))
352
353 ;; add support for "mutt:ID" links
354 (org-add-link-type "mutt" 'open-mail-in-mutt)
355
356 (defun my-org-mode-setup ()
357   (load-library "reftex")
358   (and (buffer-file-name)
359        (file-exists-p (buffer-file-name))
360        (progn
361          (reftex-parse-all)
362          (reftex-set-cite-format
363           '((?b . "[[bib:%l][%l-bib]]")
364             (?n . "[[notes:%l][%l-notes]]")
365             (?c . "\\cite{%l}")
366             (?h . "*** %t\n:PROPERTIES:\n:Custom_ID: %l\n:END:\n[[papers:%l][%l paper]]")))
367          ))
368   (define-key org-mode-map (kbd "C-c )") 'reftex-citation)
369   (define-key org-mode-map (kbd "C-c [") 'reftex-citation)
370   (define-key org-mode-map (kbd "C-c (") 'org-mode-reftex-search)
371   (define-key org-mode-map (kbd "C-c 0") 'reftex-view-crossref)
372   )
373 (add-hook 'org-mode-hook 'my-org-mode-setup)
374
375 (defun org-mode-reftex-search ()
376   (interactive)
377   (org-open-link-from-string (format "[[notes:%s]]" (first (reftex-citation t)))))
378
379 (defun open-research-paper (bibtexkey)
380   "Open a paper by bibtex key"
381   (interactive "bibtex key: ")
382   (shell-command
383    (format "%s %s"
384        (substitute-in-file-name "$HOME/bin/bibtex_to_paper") bibtexkey)))
385 (org-add-link-type "papers" 'open-research-paper)
386
387 (add-to-list 'org-link-abbrev-alist
388              '("notes" .
389                "~/projects/research/paper_notes.org::#%s"))
390
391 ; I pretty much always want hiearchical checkboxes
392 (setq org-hierachical-checkbox-statistics nil)
393  
394 ;; stolen from
395 ;; http://www-public.it-sudparis.eu/~berger_o/weblog/2012/03/23/how-to-manage-and-export-bibliographic-notesrefs-in-org-mode/
396 (defun my-rtcite-export-handler (path desc format)
397   (message "my-rtcite-export-handler is called : path = %s, desc = %s, format = %s" path desc format)
398   (let* ((search (when (string-match "::#?\\(.+\\)\\'" path)
399                    (match-string 1 path)))
400          (path (substring path 0 (match-beginning 0))))
401     (cond ((eq format 'latex)
402            (if (or (not desc) 
403                    (equal 0 (search "rtcite:" desc)))
404                (format "\\cite{%s}" search)
405              (format "\\cite[%s]{%s}" desc search))))))
406
407 (org-add-link-type "rtcite" 
408                    'org-bibtex-open
409                    'my-rtcite-export-handler)
410
411
412 (setq-default org-mobile-directory "/rzlab.ucr.edu:/sites/dav.donarmstrong.com/root/org/")
413 (setq-default org-directory "/home/don/org-mode/")
414 (setq-default org-mobile-inbox-for-pull "/home/don/org-mode/from-mobile.org")
415
416 ;; org mode ical export
417 (setq org-icalendar-timezone "America/Los_Angeles")
418 (setq org-icalendar-use-scheduled '(todo-start event-if-todo))
419 ;; we already add the id manually
420 ;; (setq org-icalendar-store-UID t)
421
422 ;; org babel support
423 (org-babel-do-load-languages
424  'org-babel-load-languages
425  '((emacs-lisp . t )
426    (R . t)
427    (latex . t)
428    (ditaa . t)
429    ))
430 ;; org-babel-by-backend
431 (defmacro org-babel-by-backend (&rest body)
432    `(case (if (boundp 'backend) 
433               (org-export-backend-name backend)
434             nil) ,@body))
435
436
437
438 ;; org latex
439 ;; stolen from http://kieranhealy.org/esk/kjhealy.html
440 (require 'org-latex)   
441 ;; Choose either listings or minted for exporting source code blocks.
442 ;; Using minted (as here) requires pygments be installed. To use the
443 ;; default listings package instead, use
444 ;; (setq org-latex-listings t)
445 ;; and change references to "minted" below to "listings"
446 ; (setq org-latex-listings 'minted)
447
448 ;; default settings for minted code blocks
449 (setq org-latex-minted-options
450       '(;("frame" "single")
451         ("bgcolor" "bg") ; bg will need to be defined in the preamble of your document. It's defined in org-preamble-pdflatex.sty and org-preamble-xelatex.sty below.
452         ("fontsize" "\\small")
453         ))
454 ;; turn off the default toc behavior; deal with it properly in headers to files.
455 (defun org-latex-no-toc (depth)  
456   (when depth
457     (format "%% Org-mode is exporting headings to %s levels.\n"
458             depth)))
459 (setq org-latex-format-toc-function 'org-latex-no-toc)
460
461 (require 'ox-latex)
462 (add-to-list 'org-latex-classes
463              '("memarticle"
464                "\\documentclass[11pt,oneside,article]{memoir}\n"
465                ("\\section{%s}" . "\\section*{%s}")
466                ("\\subsection{%s}" . "\\subsection*{%s}")
467                ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
468                ("\\paragraph{%s}" . "\\paragraph*{%s}")
469                ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
470
471 (add-to-list 'org-latex-classes
472              '("beamer"
473                "\\documentclass[ignorenonframetext]{beamer}
474 [NO-DEFAULT-PACKAGES]
475 [PACKAGES]
476 [EXTRA]"
477                ("\\section{%s}" . "\\section*{%s}")
478                ("\\subsection{%s}" . "\\subsection*{%s}")
479                ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
480                ("\\paragraph{%s}" . "\\paragraph*{%s}")
481                ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
482
483 (add-to-list 'org-latex-classes
484              '("membook"
485                "\\documentclass[11pt,oneside]{memoir}\n"
486                ("\\chapter{%s}" . "\\chapter*{%s}")
487                ("\\section{%s}" . "\\section*{%s}")
488                ("\\subsection{%s}" . "\\subsection*{%s}")
489                ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
490
491 (add-to-list 'org-latex-classes
492              '("letter"
493                "\\documentclass[11pt]{letter}
494 [NO-DEFAULT-PACKAGES]
495 [PACKAGES]
496 [EXTRA]"
497        ("\\section{%s}" . "\\section*{%s}")
498                ("\\subsection{%s}" . "\\subsection*{%s}")
499                ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
500                ("\\paragraph{%s}" . "\\paragraph*{%s}")
501                ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
502
503 ;; Originally taken from Bruno Tavernier: http://thread.gmane.org/gmane.emacs.orgmode/31150/focus=31432
504 ;; but adapted to use latexmk 4.22 or higher.  
505 (setq org-latex-pdf-process '("latexmk -pdflatex=xelatex -bibtex -use-make -pdf %f"))
506
507 ;; Default packages included in /every/ tex file, latex, pdflatex or xelatex
508 (setq org-latex-default-packages-alist
509       '())
510 (setq org-latex-packages-alist
511       '(("" "graphicx" t)
512         ("" "fontspec" t)
513         ("" "xunicode" t)
514         ("" "hyperref" t)
515         ("" "url" t)
516         ("" "rotating" t)
517         ("" "longtable" nil)
518         ("" "float" )))
519
520 (defun org-create-formula--latex-header ()
521   "Return LaTeX header appropriate for previewing a LaTeX snippet."
522   (let ((info (org-combine-plists (org-export--get-global-options
523                                    (org-export-get-backend 'latex))
524                                   (org-export--get-inbuffer-options
525                                    (org-export-get-backend 'latex)))))
526     (org-latex-guess-babel-language
527      (org-latex-guess-inputenc
528       (org-splice-latex-header
529        org-format-latex-header
530        org-latex-default-packages-alist
531        nil t
532        (plist-get info :latex-header)))
533      info)))
534
535
536 ; support ignoring headers in org mode export to latex
537 ; from http://article.gmane.org/gmane.emacs.orgmode/67692
538 (defadvice org-latex-headline (around my-latex-skip-headlines
539                                       (headline contents info) activate)
540   (if (member "ignoreheading" (org-element-property :tags headline))
541       (setq ad-return-value contents)
542     ad-do-it))
543
544 ;; keep latex logfiles
545
546 (setq org-latex-remove-logfiles nil)
547
548 ;; helper functions
549 (defun bh/is-project-p ()
550   "Any task with a todo keyword subtask"
551   (save-restriction
552     (widen)
553     (let ((has-subtask)
554           (subtree-end (save-excursion (org-end-of-subtree t)))
555           (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
556       (save-excursion
557         (forward-line 1)
558         (while (and (not has-subtask)
559                     (< (point) subtree-end)
560                     (re-search-forward "^\*+ " subtree-end t))
561           (when (member (org-get-todo-state) org-todo-keywords-1)
562             (setq has-subtask t))))
563       (and is-a-task has-subtask))))
564
565 (defun bh/is-project-subtree-p ()
566   "Any task with a todo keyword that is in a project subtree.
567 Callers of this function already widen the buffer view."
568   (let ((task (save-excursion (org-back-to-heading 'invisible-ok)
569                               (point))))
570     (save-excursion
571       (bh/find-project-task)
572       (if (equal (point) task)
573           nil
574         t))))
575
576 (defun bh/is-task-p ()
577   "Any task with a todo keyword and no subtask"
578   (save-restriction
579     (widen)
580     (let ((has-subtask)
581           (subtree-end (save-excursion (org-end-of-subtree t)))
582           (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
583       (save-excursion
584         (forward-line 1)
585         (while (and (not has-subtask)
586                     (< (point) subtree-end)
587                     (re-search-forward "^\*+ " subtree-end t))
588           (when (member (org-get-todo-state) org-todo-keywords-1)
589             (setq has-subtask t))))
590       (and is-a-task (not has-subtask)))))
591
592 (defun bh/is-subproject-p ()
593   "Any task which is a subtask of another project"
594   (let ((is-subproject)
595         (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
596     (save-excursion
597       (while (and (not is-subproject) (org-up-heading-safe))
598         (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
599           (setq is-subproject t))))
600     (and is-a-task is-subproject)))
601
602 (defun bh/list-sublevels-for-projects-indented ()
603   "Set org-tags-match-list-sublevels so when restricted to a subtree we list all subtasks.
604   This is normally used by skipping functions where this variable is already local to the agenda."
605   (if (marker-buffer org-agenda-restrict-begin)
606       (setq org-tags-match-list-sublevels 'indented)
607     (setq org-tags-match-list-sublevels nil))
608   nil)
609
610 (defun bh/list-sublevels-for-projects ()
611   "Set org-tags-match-list-sublevels so when restricted to a subtree we list all subtasks.
612   This is normally used by skipping functions where this variable is already local to the agenda."
613   (if (marker-buffer org-agenda-restrict-begin)
614       (setq org-tags-match-list-sublevels t)
615     (setq org-tags-match-list-sublevels nil))
616   nil)
617
618 (defvar bh/hide-scheduled-and-waiting-next-tasks t)
619
620 (defun bh/toggle-next-task-display ()
621   (interactive)
622   (setq bh/hide-scheduled-and-waiting-next-tasks (not bh/hide-scheduled-and-waiting-next-tasks))
623   (when  (equal major-mode 'org-agenda-mode)
624     (org-agenda-redo))
625   (message "%s WAITING and SCHEDULED NEXT Tasks" (if bh/hide-scheduled-and-waiting-next-tasks "Hide" "Show")))
626
627 (defun bh/skip-stuck-projects ()
628   "Skip trees that are not stuck projects"
629   (save-restriction
630     (widen)
631     (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
632       (if (bh/is-project-p)
633           (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
634                  (has-next ))
635             (save-excursion
636               (forward-line 1)
637               (while (and (not has-next) (< (point) subtree-end) (re-search-forward "^\\*+ NEXT " subtree-end t))
638                 (unless (member "WAITING" (org-get-tags-at))
639                   (setq has-next t))))
640             (if has-next
641                 nil
642               next-headline)) ; a stuck project, has subtasks but no next task
643         nil))))
644
645 (defun bh/skip-non-stuck-projects ()
646   "Skip trees that are not stuck projects"
647   ;; (bh/list-sublevels-for-projects-indented)
648   (save-restriction
649     (widen)
650     (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
651       (if (bh/is-project-p)
652           (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
653                  (has-next ))
654             (save-excursion
655               (forward-line 1)
656               (while (and (not has-next) (< (point) subtree-end) (re-search-forward "^\\*+ NEXT " subtree-end t))
657                 (unless (member "WAITING" (org-get-tags-at))
658                   (setq has-next t))))
659             (if has-next
660                 next-headline
661               nil)) ; a stuck project, has subtasks but no next task
662         next-headline))))
663
664 (defun bh/skip-non-projects ()
665   "Skip trees that are not projects"
666   ;; (bh/list-sublevels-for-projects-indented)
667   (if (save-excursion (bh/skip-non-stuck-projects))
668       (save-restriction
669         (widen)
670         (let ((subtree-end (save-excursion (org-end-of-subtree t))))
671           (cond
672            ((bh/is-project-p)
673             nil)
674            ((and (bh/is-project-subtree-p) (not (bh/is-task-p)))
675             nil)
676            (t
677             subtree-end))))
678     (save-excursion (org-end-of-subtree t))))
679
680 (defun bh/skip-project-trees-and-habits ()
681   "Skip trees that are projects"
682   (save-restriction
683     (widen)
684     (let ((subtree-end (save-excursion (org-end-of-subtree t))))
685       (cond
686        ((bh/is-project-p)
687         subtree-end)
688        ((org-is-habit-p)
689         subtree-end)
690        (t
691         nil)))))
692
693 (defun bh/skip-projects-and-habits-and-single-tasks ()
694   "Skip trees that are projects, tasks that are habits, single non-project tasks"
695   (save-restriction
696     (widen)
697     (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
698       (cond
699        ((org-is-habit-p)
700         next-headline)
701        ((and bh/hide-scheduled-and-waiting-next-tasks
702              (member "WAITING" (org-get-tags-at)))
703         next-headline)
704        ((bh/is-project-p)
705         next-headline)
706        ((and (bh/is-task-p) (not (bh/is-project-subtree-p)))
707         next-headline)
708        (t
709         nil)))))
710
711 (defun bh/skip-project-tasks-maybe ()
712   "Show tasks related to the current restriction.
713 When restricted to a project, skip project and sub project tasks, habits, NEXT tasks, and loose tasks.
714 When not restricted, skip project and sub-project tasks, habits, and project related tasks."
715   (save-restriction
716     (widen)
717     (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
718            (next-headline (save-excursion (or (outline-next-heading) (point-max))))
719            (limit-to-project (marker-buffer org-agenda-restrict-begin)))
720       (cond
721        ((bh/is-project-p)
722         next-headline)
723        ((org-is-habit-p)
724         subtree-end)
725        ((and (not limit-to-project)
726              (bh/is-project-subtree-p))
727         subtree-end)
728        ((and limit-to-project
729              (bh/is-project-subtree-p)
730              (member (org-get-todo-state) (list "NEXT")))
731         subtree-end)
732        (t
733         nil)))))
734
735 (defun bh/skip-project-tasks ()
736   "Show non-project tasks.
737 Skip project and sub-project tasks, habits, and project related tasks."
738   (save-restriction
739     (widen)
740     (let* ((subtree-end (save-excursion (org-end-of-subtree t))))
741       (cond
742        ((bh/is-project-p)
743         subtree-end)
744        ((org-is-habit-p)
745         subtree-end)
746        ((bh/is-project-subtree-p)
747         subtree-end)
748        (t
749         nil)))))
750
751 (defun bh/skip-non-project-tasks ()
752   "Show project tasks.
753 Skip project and sub-project tasks, habits, and loose non-project tasks."
754   (save-restriction
755     (widen)
756     (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
757            (next-headline (save-excursion (or (outline-next-heading) (point-max)))))
758       (cond
759        ((bh/is-project-p)
760         next-headline)
761        ((org-is-habit-p)
762         subtree-end)
763        ((and (bh/is-project-subtree-p)
764              (member (org-get-todo-state) (list "NEXT")))
765         subtree-end)
766        ((not (bh/is-project-subtree-p))
767         subtree-end)
768        (t
769         nil)))))
770
771 (defun bh/skip-projects-and-habits ()
772   "Skip trees that are projects and tasks that are habits"
773   (save-restriction
774     (widen)
775     (let ((subtree-end (save-excursion (org-end-of-subtree t))))
776       (cond
777        ((bh/is-project-p)
778         subtree-end)
779        ((org-is-habit-p)
780         subtree-end)
781        (t
782         nil)))))
783
784 (defun bh/skip-non-subprojects ()
785   "Skip trees that are not projects"
786   (let ((next-headline (save-excursion (outline-next-heading))))
787     (if (bh/is-subproject-p)
788         nil
789       next-headline)))
790 ;
791 ;; Resume clocking task when emacs is restarted
792 (org-clock-persistence-insinuate)
793 ;;
794 ;; Show lot of clocking history so it's easy to pick items off the C-F11 list
795 (setq org-clock-history-length 23)
796 ;; Resume clocking task on clock-in if the clock is open
797 (setq org-clock-in-resume t)
798 ;; Change tasks to NEXT when clocking in
799 (setq org-clock-in-switch-to-state 'bh/clock-in-to-next)
800 ;; Separate drawers for clocking and logs
801 (setq org-drawers (quote ("PROPERTIES" "LOGBOOK")))
802 ;; Save clock data and state changes and notes in the LOGBOOK drawer
803 (setq org-clock-into-drawer t)
804 (setq org-log-into-drawer t)
805 ;; Sometimes I change tasks I'm clocking quickly - this removes clocked tasks with 0:00 duration
806 (setq org-clock-out-remove-zero-time-clocks t)
807 ;; Clock out when moving task to a done state
808 (setq org-clock-out-when-done t)
809 ;; Save the running clock and all clock history when exiting Emacs, load it on startup
810 (setq org-clock-persist t)
811 ;; Do not prompt to resume an active clock
812 (setq org-clock-persist-query-resume nil)
813 ;; Enable auto clock resolution for finding open clocks
814 (setq org-clock-auto-clock-resolution (quote when-no-clock-is-running))
815 ;; Include current clocking task in clock reports
816 (setq org-clock-report-include-clocking-task t)
817
818
819 (defvar bh/keep-clock-running nil)
820
821 (defun bh/clock-in-to-next (kw)
822   "Switch a task from TODO to NEXT when clocking in.
823 Skips capture tasks, projects, and subprojects.
824 Switch projects and subprojects from NEXT back to TODO"
825   (when (not (and (boundp 'org-capture-mode) org-capture-mode))
826     (cond
827      ((and (member (org-get-todo-state) (list "TODO"))
828            (bh/is-task-p))
829       "NEXT")
830      ((and (member (org-get-todo-state) (list "NEXT"))
831            (bh/is-project-p))
832       "TODO"))))
833
834 (defun bh/find-project-task ()
835   "Move point to the parent (project) task if any"
836   (save-restriction
837     (widen)
838     (let ((parent-task (save-excursion (org-back-to-heading 'invisible-ok) (point))))
839       (while (org-up-heading-safe)
840         (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
841           (setq parent-task (point))))
842       (goto-char parent-task)
843       parent-task)))
844
845 (defun bh/punch-in (arg)
846   "Start continuous clocking and set the default task to the
847 selected task.  If no task is selected set the Organization task
848 as the default task."
849   (interactive "p")
850   (setq bh/keep-clock-running t)
851   (if (equal major-mode 'org-agenda-mode)
852       ;;
853       ;; We're in the agenda
854       ;;
855       (let* ((marker (org-get-at-bol 'org-hd-marker))
856              (tags (org-with-point-at marker (org-get-tags-at))))
857         (if (and (eq arg 4) tags)
858             (org-agenda-clock-in '(16))
859           (bh/clock-in-organization-task-as-default)))
860     ;;
861     ;; We are not in the agenda
862     ;;
863     (save-restriction
864       (widen)
865       ; Find the tags on the current task
866       (if (and (equal major-mode 'org-mode) (not (org-before-first-heading-p)) (eq arg 4))
867           (org-clock-in '(16))
868         (bh/clock-in-organization-task-as-default)))))
869
870 (defun bh/punch-out ()
871   (interactive)
872   (setq bh/keep-clock-running nil)
873   (when (org-clock-is-active)
874     (org-clock-out))
875   (org-agenda-remove-restriction-lock))
876
877 (defun bh/clock-in-default-task ()
878   (save-excursion
879     (org-with-point-at org-clock-default-task
880       (org-clock-in))))
881
882 (defun bh/clock-in-parent-task ()
883   "Move point to the parent (project) task if any and clock in"
884   (let ((parent-task))
885     (save-excursion
886       (save-restriction
887         (widen)
888         (while (and (not parent-task) (org-up-heading-safe))
889           (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
890             (setq parent-task (point))))
891         (if parent-task
892             (org-with-point-at parent-task
893               (org-clock-in))
894           (when bh/keep-clock-running
895             (bh/clock-in-default-task)))))))
896
897 (defvar bh/organization-task-id "e22cb8bf-07c7-408b-8f60-ff3aadac95e4")
898
899 (defun bh/clock-in-organization-task-as-default ()
900   (interactive)
901   (org-with-point-at (org-id-find bh/organization-task-id 'marker)
902     (org-clock-in '(16))))
903
904 (defun bh/clock-out-maybe ()
905   (when (and bh/keep-clock-running
906              (not org-clock-clocking-in)
907              (marker-buffer org-clock-default-task)
908              (not org-clock-resolving-clocks-due-to-idleness))
909     (bh/clock-in-parent-task)))
910
911 (add-hook 'org-clock-out-hook 'bh/clock-out-maybe 'append)
912
913 (require 'org-id)
914 (defun bh/clock-in-task-by-id (id)
915   "Clock in a task by id"
916   (org-with-point-at (org-id-find id 'marker)
917     (org-clock-in nil)))
918
919 (defun bh/clock-in-last-task (arg)
920   "Clock in the interrupted task if there is one
921 Skip the default task and get the next one.
922 A prefix arg forces clock in of the default task."
923   (interactive "p")
924   (let ((clock-in-to-task
925          (cond
926           ((eq arg 4) org-clock-default-task)
927           ((and (org-clock-is-active)
928                 (equal org-clock-default-task (cadr org-clock-history)))
929            (caddr org-clock-history))
930           ((org-clock-is-active) (cadr org-clock-history))
931           ((equal org-clock-default-task (car org-clock-history)) (cadr org-clock-history))
932           (t (car org-clock-history)))))
933     (widen)
934     (org-with-point-at clock-in-to-task
935       (org-clock-in nil))))
936