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