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