1 #+OPTIONS: H:3 num:nil toc:t \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate
3 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
4 #+TAGS: Write(w) Update(u) Fix(f) Check(c)
5 #+TITLE: Org ad hoc code, quick hacks and workarounds
7 #+EMAIL: mdl AT imapmail DOT org
12 # This file is the default header for new Org files in Worg. Feel free
13 # to tailor it to your needs.
15 [[file:index.org][{Back to Worg's index}]]
17 This page is for ad hoc bits of code. Feel free to add quick hacks and
20 * Hacking Org: Working within Org-mode.
21 ** Building and Managing Org
22 *** Generating autoloads and Compiling Org without make
24 :CUSTOM_ID: compiling-org-without-make
27 #+index: Compilation!without make
29 Compilation is optional, but you _must_ update the autoloads file
30 each time you update org, even when you run org uncompiled!
32 Starting with Org 7.9 you'll find functions for creating the
33 autoload files and do byte-compilation in =mk/org-fixup.el=. When
34 you execute the commands below, your current directory must be where
35 org has been unpacked into, in other words the file =README= should
36 be found in your current directory and the directories =lisp= and
37 =etc= should be subdirectories of it. The command =emacs= should be
38 found in your =PATH= and start the Emacs version you are using. To
39 make just the autoloads file do:
40 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
41 To make the autoloads file and byte-compile org:
42 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
43 To make the autoloads file and byte-compile all of org again:
44 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
45 If you are not using Git, you'll have to make fake version strings
46 first if =org-version.el= is not already available (if it is, you
47 could also edit the version strings there).
48 : emacs -batch -Q -L lisp -l ../mk/org-fixup \
49 : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
50 : (org-make-autoloads))'
52 POSIX shell for its quoting. Windows =CMD.exe= has quite different
53 quoting rules and this won't work, so your other option is to start
55 : emacs -Q -L lisp -l ../mk/org-fixup
56 then paste the following into the =*scratch*= buffer
57 #+BEGIN_SRC emacs-lisp
58 (let ((org-fake-release "7.9.1")
59 (org-fake-git-version "7.9.1-fake"))
62 position the cursor after the closing paren and press =C-j= or =C-x
63 C-e= to evaluate the form. Of course you can replace
64 =org-make-autoloads= with =org-make-autoloads-compile= or even
65 =org-make-autoloads-compile-force= if you wish with both variants.
67 For *older org versions only* (that do not yet have
68 =mk/org-fixup.el=), you can use the definitions below. To use
69 this function, adjust the variables =my/org-lisp-directory= and
70 =my/org-compile-sources= to suit your needs. If you have
71 byte-compiled org, but want to run org uncompiled again, just remove
72 all =*.elc= files in the =lisp/= directory, set
73 =my/org-compile-sources= to =nil=.
75 #+BEGIN_SRC emacs-lisp
76 (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
77 "Directory where your org-mode files live.")
79 (defvar my/org-compile-sources t
80 "If `nil', never compile org-sources. `my/compile-org' will only create
81 the autoloads file `org-loaddefs.el' then. If `t', compile the sources, too.")
83 ;; Customize: (must end with a slash!)
84 (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")
87 (setq my/org-compile-sources t)
89 (defun my/compile-org(&optional directory)
90 "Generate autoloads file org-loaddefs.el. Optionally compile
91 all *.el files that come with org-mode."
93 (defun my/compile-org()
94 "Generate autoloads file org-loaddefs.el. Optionally compile
95 all *.el files that come with org-mode."
97 (let ((dirlisp (file-name-directory my/org-lisp-directory)))
98 (add-to-list 'load-path dirlisp)
100 (let ((generated-autoload-file (concat dirlisp "org-loaddefs.el")))
101 ;; create the org-loaddefs file
102 (update-directory-autoloads dirlisp)
103 (when my/org-compile-sources
104 ;; optionally byte-compile
105 (byte-recompile-directory dirlisp 0 'force)))))
109 #+index: Initialization!Reload
111 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
112 function to reload org files.
114 Normally you want to use the compiled files since they are faster.
115 If you update your org files you can easily reload them with
119 If you run into a bug and want to generate a useful backtrace you can
120 reload the source files instead of the compiled files with
124 and turn on the "Enter Debugger On Error" option. Redo the action
125 that generates the error and cut and paste the resulting backtrace.
126 To switch back to the compiled version just reload again with
130 *** Check for possibly problematic old link escapes
132 :CUSTOM_ID: check-old-link-escapes
135 Starting with version 7.5 Org uses [[http://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
136 and with a modified algorithm to determine which characters to escape
139 As a side effect this modified behaviour might break existing links if
140 they contain a sequence of characters that look like a percent escape
141 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
143 The function below can be used to perform a preliminary check for such
144 links in an Org mode file. It will run through all links in the file
145 and issue a warning if it finds a percent escape sequence which is not
146 in old Org's list of known percent escapes.
148 #+begin_src emacs-lisp
149 (defun dmaus/org-check-percent-escapes ()
150 "*Check buffer for possibly problematic old link escapes."
152 (when (eq major-mode 'org-mode)
153 (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
154 "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
155 (unless (boundp 'warning-suppress-types)
156 (setq warning-suppress-types nil))
159 (goto-char (point-min))
160 (while (re-search-forward org-any-link-re nil t)
161 (let ((end (match-end 0)))
162 (goto-char (match-beginning 0))
163 (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
164 (let ((escape (match-string-no-properties 0)))
165 (unless (member (upcase escape) old-escapes)
166 (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
173 ** Structure Movement and Editing
174 *** Show next/prev heading tidily
176 #+index: Navigation!Heading
178 These close the current heading and open the next/previous heading.
180 #+begin_src emacs-lisp
181 (defun ded/org-show-next-heading-tidily ()
182 "Show next entry, keeping other entries closed."
183 (if (save-excursion (end-of-line) (outline-invisible-p))
184 (progn (org-show-entry) (show-children))
185 (outline-next-heading)
186 (unless (and (bolp) (org-on-heading-p))
187 (org-up-heading-safe)
189 (error "Boundary reached"))
195 (defun ded/org-show-previous-heading-tidily ()
196 "Show previous entry, keeping other entries closed."
198 (outline-previous-heading)
199 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
202 (error "Boundary reached"))
208 (setq org-use-speed-commands t)
209 (add-to-list 'org-speed-commands-user
210 '("n" ded/org-show-next-heading-tidily))
211 (add-to-list 'org-speed-commands-user
212 '("p" ded/org-show-previous-heading-tidily))
215 *** Promote all items in subtree
216 #+index: Structure Editing!Promote
219 This function will promote all items in a subtree. Since I use
220 subtrees primarily to organize projects, the function is somewhat
221 unimaginatively called my-org-un-project:
223 #+begin_src emacs-lisp
224 (defun my-org-un-project ()
226 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
230 *** Turn a heading into an Org link
232 :CUSTOM_ID: heading-to-link
234 #+index: Structure Editing!Heading
235 #+index: Link!Turn a heading into a
238 #+begin_src emacs-lisp
239 (defun dmj:turn-headline-into-org-mode-link ()
240 "Replace word at point by an Org mode link."
242 (when (org-at-heading-p)
243 (let ((hl-text (nth 4 (org-heading-components))))
244 (unless (or (null hl-text)
245 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
247 (search-forward hl-text (point-at-eol))
250 (format "[[file:%s.org][%s]]"
251 (org-link-escape hl-text)
252 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
253 nil (- (point) (length hl-text)) (point))))))
256 *** Using M-up and M-down to transpose paragraphs
257 #+index: Structure Editing!paragraphs
259 From Paul Sexton: By default, if used within ordinary paragraphs in
260 org mode, =M-up= and =M-down= transpose *lines* (not sentences). The
261 following code makes these keys transpose paragraphs, keeping the
262 point at the start of the moved paragraph. Behavior in tables and
263 headings is unaffected. It would be easy to modify this to transpose
266 #+begin_src emacs-lisp
267 (defun org-transpose-paragraphs (arg)
269 (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
270 (thing-at-point 'sentence))
271 (transpose-paragraphs arg)
273 (re-search-forward "[[:graph:]]")
274 (goto-char (match-beginning 0))
277 (add-to-list 'org-metaup-hook
278 (lambda () (interactive) (org-transpose-paragraphs -1)))
279 (add-to-list 'org-metadown-hook
280 (lambda () (interactive) (org-transpose-paragraphs 1)))
282 *** Changelog support for org headers
283 #+index: Structure Editing!Heading
286 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
287 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
288 headline as the "current function" if you add a changelog entry from an org
291 #+BEGIN_SRC emacs-lisp
292 (defun org-log-current-defun ()
294 (org-back-to-heading)
295 (if (looking-at org-complex-heading-regexp)
298 (add-hook 'org-mode-hook
300 (make-variable-buffer-local 'add-log-current-defun-function)
301 (setq add-log-current-defun-function 'org-log-current-defun)))
304 *** Different org-cycle-level behavior
305 #+index: Cycling!behavior
308 In recent org versions, when your point (cursor) is at the end of an
309 empty header line (like after you first created the header), the TAB
310 key (=org-cycle=) has a special behavior: it cycles the headline through
311 all possible levels. However, I did not like the way it determined
312 "all possible levels," so I rewrote the whole function, along with a
313 couple of supporting functions.
315 The original function's definition of "all possible levels" was "every
316 level from 1 to one more than the initial level of the current
317 headline before you started cycling." My new definition is "every
318 level from 1 to one more than the previous headline's level." So, if
319 you have a headline at level 4 and you use ALT+RET to make a new
320 headline below it, it will cycle between levels 1 and 5, inclusive.
322 The main advantage of my custom =org-cycle-level= function is that it
323 is stateless: the next level in the cycle is determined entirely by
324 the contents of the buffer, and not what command you executed last.
325 This makes it more predictable, I hope.
327 #+BEGIN_SRC emacs-lisp
330 (defun org-point-at-end-of-empty-headline ()
331 "If point is at the end of an empty headline, return t, else nil."
332 (and (looking-at "[ \t]*$")
334 (beginning-of-line 1)
335 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
337 (defun org-level-increment ()
338 "Return the number of stars that will be added or removed at a
339 time to headlines when structure editing, based on the value of
340 `org-odd-levels-only'."
341 (if org-odd-levels-only 2 1))
343 (defvar org-previous-line-level-cached nil)
345 (defun org-recalculate-previous-line-level ()
346 "Same as `org-get-previous-line-level', but does not use cached
347 value. It does *set* the cached value, though."
348 (set 'org-previous-line-level-cached
349 (let ((current-level (org-current-level))
350 (prev-level (when (> (line-number-at-pos) 1)
353 (org-current-level)))))
354 (cond ((null current-level) nil) ; Before first headline
355 ((null prev-level) 0) ; At first headline
358 (defun org-get-previous-line-level ()
359 "Return the outline depth of the last headline before the
360 current line. Returns 0 for the first headline in the buffer, and
361 nil if before the first headline."
362 ;; This calculation is quite expensive, with all the regex searching
363 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
364 ;; the last value of this command.
365 (or (and (eq last-command 'org-cycle-level)
366 org-previous-line-level-cached)
367 (org-recalculate-previous-line-level)))
369 (defun org-cycle-level ()
371 (let ((org-adapt-indentation nil))
372 (when (org-point-at-end-of-empty-headline)
373 (setq this-command 'org-cycle-level) ;Only needed for caching
374 (let ((cur-level (org-current-level))
375 (prev-level (org-get-previous-line-level)))
377 ;; If first headline in file, promote to top-level.
379 (loop repeat (/ (- cur-level 1) (org-level-increment))
380 do (org-do-promote)))
381 ;; If same level as prev, demote one.
382 ((= prev-level cur-level)
384 ;; If parent is top-level, promote to top level if not already.
386 (loop repeat (/ (- cur-level 1) (org-level-increment))
387 do (org-do-promote)))
388 ;; If top-level, return to prev-level.
390 (loop repeat (/ (- prev-level 1) (org-level-increment))
392 ;; If less than prev-level, promote one.
393 ((< cur-level prev-level)
395 ;; If deeper than prev-level, promote until higher than
397 ((> cur-level prev-level)
398 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
399 do (org-do-promote))))
403 *** Count words in an Org buffer
404 #FIXME: Does not fit too well under Structure. Any idea where to put it?
405 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
407 #+begin_src emacs-lisp
408 (defun org-word-count (beg end
409 &optional count-latex-macro-args?
411 "Report the number of words in the Org mode buffer or selected region.
415 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
416 - hyperlinks (but does count words in hyperlink descriptions)
417 - tags, priorities, and TODO keywords in headers
418 - sections tagged as 'not for export'.
420 The text of footnote definitions is ignored, unless the optional argument
421 COUNT-FOOTNOTES? is non-nil.
423 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
424 includes LaTeX macro arguments (the material between {curly braces}).
425 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
429 (setf beg (point-min)
432 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
435 (while (< (point) end)
438 ((or (org-in-commented-line) (org-at-table-p))
440 ;; Ignore hyperlinks. But if link has a description, count
441 ;; the words within the description.
442 ((looking-at org-bracket-link-analytic-regexp)
443 (when (match-string-no-properties 5)
444 (let ((desc (match-string-no-properties 5)))
446 (incf wc (length (remove "" (org-split-string
448 (goto-char (match-end 0)))
449 ((looking-at org-any-link-re)
450 (goto-char (match-end 0)))
451 ;; Ignore source code blocks.
452 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
454 ;; Ignore inline source blocks, counting them as 1 word.
457 (looking-at org-babel-inline-src-block-regexp))
458 (goto-char (match-end 0))
460 ;; Count latex macros as 1 word, ignoring their arguments.
463 (looking-at latex-macro-regexp))
464 (goto-char (if count-latex-macro-args?
469 ((and (not count-footnotes?)
470 (or (org-footnote-at-definition-p)
471 (org-footnote-at-reference-p)))
474 (let ((contexts (org-context)))
476 ;; Ignore tags and TODO keywords, etc.
477 ((or (assoc :todo-keyword contexts)
478 (assoc :priority contexts)
479 (assoc :keyword contexts)
480 (assoc :checkbox contexts))
482 ;; Ignore sections marked with tags that are
483 ;; excluded from export.
484 ((assoc :tags contexts)
485 (if (intersection (org-get-tags-at) org-export-exclude-tags
487 (org-forward-same-level 1)
491 (re-search-forward "\\w+\\W*")))
492 (message (format "%d words in %s." wc
493 (if mark-active "region" "buffer")))))
496 *** Check for misplaced SCHEDULED and DEADLINE cookies
498 The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
499 below* the headline -- like this:
503 , SCHEDULED: <2012-04-09 lun.>
506 This is what =org-scheduled= and =org-deadline= (and other similar
507 commands) do. And the manual explicitely tell people to stick to this
508 format (see the section "8.3.1 Inserting deadlines or schedules").
510 If you think you might have subtrees with misplaced =SCHEDULED= and
511 =DEADLINE= cookies, this command lets you check the current buffer:
513 #+begin_src emacs-lisp
514 (defun org-check-misformatted-subtree ()
515 "Check misformatted entries in the current buffer."
520 (when (and (move-beginning-of-line 2)
521 (not (looking-at org-heading-regexp)))
522 (if (or (and (org-get-scheduled-time (point))
523 (not (looking-at (concat "^.*" org-scheduled-regexp))))
524 (and (org-get-deadline-time (point))
525 (not (looking-at (concat "^.*" org-deadline-regexp)))))
526 (when (y-or-n-p "Fix this subtree? ")
527 (message "Call the function again when you're done fixing this subtree.")
529 (message "All subtrees checked."))))))
533 *** Align all tables in a file
535 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
537 #+begin_src emacs-lisp
538 (defun my-align-all-tables ()
540 (org-table-map-tables 'org-table-align 'quietly))
544 #+index: Table!Calculation
546 :CUSTOM_ID: transpose-table
549 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
550 see.) There are also other solutions:
552 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
553 list, see [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00239.html][gnu]]
555 - with org-babel and R: provided by Dan Davison in the mailing list (old
556 =#+TBLR:= syntax), see [[http://thread.gmane.org/gmane.emacs.orgmode/10159/focus=10159][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2008-12/msg00454.html][gnu]]
558 - with field coordinates in formulas (=@#= and =$#=): see [[file:org-hacks.org::#field-coordinates-in-formulas-transpose-table][Worg]].
560 *** Manipulate hours/minutes/seconds in table formulas
561 #+index: Table!hours-minutes-seconds
562 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
563 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
564 "=d=" is any digit) as time values in Org-mode table formula. These
565 functions have now been wrapped up into a =with-time= macro which can
566 be used in table formula to translate table cell values to and from
567 numerical values for algebraic manipulation.
569 Here is the code implementing this macro.
570 #+begin_src emacs-lisp :results silent
571 (defun org-time-string-to-seconds (s)
572 "Convert a string HH:MM:SS to a number of seconds."
575 (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
576 (let ((hour (string-to-number (match-string 1 s)))
577 (min (string-to-number (match-string 2 s)))
578 (sec (string-to-number (match-string 3 s))))
579 (+ (* hour 3600) (* min 60) sec)))
581 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
582 (let ((min (string-to-number (match-string 1 s)))
583 (sec (string-to-number (match-string 2 s))))
585 ((stringp s) (string-to-number s))
588 (defun org-time-seconds-to-string (secs)
589 "Convert a number of seconds to a time string."
590 (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
591 ((>= secs 60) (format-seconds "%m:%.2s" secs))
592 (t (format-seconds "%s" secs))))
594 (defmacro with-time (time-output-p &rest exprs)
595 "Evaluate an org-table formula, converting all fields that look
596 like time data to integer seconds. If TIME-OUTPUT-P then return
597 the result as a time value."
599 (if time-output-p 'org-time-seconds-to-string 'identity)
607 (list 'with-time nil el)
608 (org-time-string-to-seconds el)))
613 Which allows the following forms of table manipulation such as adding
614 and subtracting time values.
615 : | Date | Start | Lunch | Back | End | Sum |
616 : |------------------+-------+-------+-------+-------+------|
617 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
618 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
620 and dividing time values by integers
621 : | time | miles | minutes/mile |
622 : |-------+-------+--------------|
623 : | 34:43 | 2.9 | 11:58 |
624 : | 32:15 | 2.77 | 11:38 |
625 : | 33:56 | 3.0 | 11:18 |
626 : | 52:22 | 4.62 | 11:20 |
627 : #+TBLFM: $3='(with-time t (/ $1 $2))
629 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
630 Elisp formulas) to compute time durations. For example:
632 : | Task 1 | Task 2 | Total |
633 : |--------+--------+---------|
634 : | 35:00 | 35:00 | 1:10:00 |
635 : #+TBLFM: @2$3=$1+$2;T
637 *** Dates computation
639 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of
640 dates stored in an org table.
642 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
646 | Start Date | End Date | Duration |
647 |------------+------------+----------|
648 | 2004.08.07 | 2005.07.08 | 335 |
649 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
651 See [[http://thread.gmane.org/gmane.emacs.orgmode/7741][this thread]] as well as [[http://article.gmane.org/gmane.emacs.orgmode/7753][this post]] (which is really a followup on the
652 above). The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
653 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
656 #+index: Table!Calculation
657 As with Times computation, the following code allows Computation with
658 Hex values in Org-mode tables using the =with-hex= macro.
660 Here is the code implementing this macro.
661 #+begin_src emacs-lisp
662 (defun org-hex-strip-lead (str)
663 (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
664 (substring str 2) str))
666 (defun org-hex-to-hex (int)
669 (defun org-hex-to-dec (str)
672 (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
676 (setf out (+ (* out 16)
677 (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
678 (coerce (match-string 1 str) 'list))
680 ((stringp str) (string-to-number str))
683 (defmacro with-hex (hex-output-p &rest exprs)
684 "Evaluate an org-table formula, converting all fields that look
685 like hexadecimal to decimal integers. If HEX-OUTPUT-P then
686 return the result as a hex value."
688 (if hex-output-p 'org-hex-to-hex 'identity)
695 (list 'with-hex nil el)
696 (org-hex-to-dec el)))
701 Which allows the following forms of table manipulation such as adding
702 and subtracting hex values.
703 | 0x10 | 0x0 | 0x10 | 16 |
704 | 0x20 | 0x1 | 0x21 | 33 |
705 | 0x30 | 0x2 | 0x32 | 50 |
706 | 0xf0 | 0xf | 0xff | 255 |
707 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
709 *** Field coordinates in formulas (=@#= and =$#=)
711 :CUSTOM_ID: field-coordinates-in-formulas
713 #+index: Table!Field Coordinates
716 Following are some use cases that can be implemented with the “field
717 coordinates in formulas” described in the corresponding chapter in the
718 [[http://orgmode.org/manual/References.html#References][Org manual]].
720 **** Copy a column from a remote table into a column
722 :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
725 current column =$3= = remote column =$2=:
726 : #+TBLFM: $3 = remote(FOO, @@#$2)
728 **** Copy a row from a remote table transposed into a column
730 :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
733 current column =$1= = transposed remote row =@1=:
734 : #+TBLFM: $1 = remote(FOO, @$#$@#)
738 :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
743 This is more like a demonstration of using “field coordinates in formulas”
744 and is bound to be slow for large tables. See the discussion in the mailing
746 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
747 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
748 For more efficient solutions see
749 [[file:org-hacks.org::#transpose-table][Worg]].
751 To transpose this 4x7 table
754 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
755 : |------+------+------+------+------+------+------|
756 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
757 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
758 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
760 start with a 7x4 table without any horizontal line (to have filled
761 also the column header) and yet empty:
771 Then add the =TBLFM= line below. After recalculation this will end up with
774 : | year | min | avg | max |
775 : | 2004 | 401 | 402 | 403 |
776 : | 2005 | 501 | 502 | 503 |
777 : | 2006 | 601 | 602 | 603 |
778 : | 2007 | 701 | 702 | 703 |
779 : | 2008 | 801 | 802 | 803 |
780 : | 2009 | 901 | 902 | 903 |
781 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
783 The formula simply exchanges row and column numbers by taking
784 - the absolute remote row number =@$#= from the current column number =$#=
785 - the absolute remote column number =$@#= from the current row number =@#=
787 Formulas to be taken over from the remote table will have to be transformed
790 **** Dynamic variation of ranges
794 In this example all columns next to =quote= are calculated from the column
795 =quote= and show the average change of the time series =quote[year]=
796 during the period of the preceding =1=, =2=, =3= or =4= years:
798 : | year | quote | 1 a | 2 a | 3 a | 4 a |
799 : |------+-------+-------+-------+-------+-------|
800 : | 2005 | 10 | | | | |
801 : | 2006 | 12 | 0.200 | | | |
802 : | 2007 | 14 | 0.167 | 0.183 | | |
803 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
804 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
805 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
807 The important part of the formula without the field blanking is:
809 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
811 which is the Emacs Calc implementation of the equation
813 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
815 where /i/ is the current time and /a/ is the length of the preceding period.
817 *** Change the column sequence in one row only
818 #+index: Table!Editing
820 :CUSTOM_ID: column-sequence-in-row
825 The functions below can be used to change the column sequence in one row
826 only, without affecting the other rows above and below like with M-<left> or
827 M-<right> (org-table-move-column). Please see the docstring of the functions
828 for more explanations. Below is one example per function, with this original
829 table as the starting point for each example:
831 : | e | 9 | 10 | 11 |
834 **** Move in row left
836 1) place point at "10" in original table
837 2) result of M-x my-org-table-move-column-in-row-left:
839 : | e | 10 | 9 | 11 |
842 **** Move in row right
844 1) place point at "9" in original table
845 2) result of M-x my-org-table-move-column-in-row-right:
847 : | e | 10 | 9 | 11 |
850 **** Rotate in row left
852 1) place point at "9" in original table
853 2) result of M-x my-org-table-rotate-column-in-row-left:
855 : | e | 10 | 11 | 9 |
858 **** Rotate in row right
860 1) place point at "9" in original table
861 2) result of M-x my-org-table-rotate-column-in-row-right:
863 : | e | 11 | 9 | 10 |
868 #+BEGIN_SRC emacs-lisp
869 (defun my-org-table-move-column-in-row-right ()
870 "Move column to the right, limited to the current row."
872 (my-org-table-move-column-in-row nil))
873 (defun my-org-table-move-column-in-row-left ()
874 "Move column to the left, limited to the current row."
876 (my-org-table-move-column-in-row 'left))
878 (defun my-org-table-move-column-in-row (&optional left)
879 "Move the current column to the right, limited to the current row.
880 With arg LEFT, move to the left. For repeated invocation the point follows
881 the value and changes to the target colum. Does not fix formulas."
882 ;; derived from `org-table-move-column'
884 (if (not (org-at-table-p))
885 (error "Not at a table"))
886 (org-table-find-dataline)
887 (org-table-check-inside-data-field)
888 (let* ((col (org-table-current-column))
889 (col1 (if left (1- col) col))
890 ;; Current cursor position
891 (colpos (if left (1- col) (1+ col))))
892 (if (and left (= col 1))
893 (error "Cannot move column further left"))
894 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
895 (error "Cannot move column further right"))
896 (org-table-goto-column col1 t)
897 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
898 (replace-match "|\\2|\\1|"))
899 (org-table-goto-column colpos)
902 (defun my-org-table-rotate-column-in-row-right ()
903 "Rotate column to the right, limited to the current row."
905 (my-org-table-rotate-column-in-row nil))
906 (defun my-org-table-rotate-column-in-row-left ()
907 "Rotate column to the left, limited to the current row."
909 (my-org-table-rotate-column-in-row 'left))
911 (defun my-org-table-rotate-column-in-row (&optional left)
912 "Rotate the current column to the right, limited to the current row.
913 With arg LEFT, rotate to the left. The boundaries of the rotation range are
914 the current and the most right column for both directions. For repeated
915 invocation the point stays on the current column. Does not fix formulas."
916 ;; derived from `org-table-move-column'
918 (if (not (org-at-table-p))
919 (error "Not at a table"))
920 (org-table-find-dataline)
921 (org-table-check-inside-data-field)
922 (let ((col (org-table-current-column)))
923 (org-table-goto-column col t)
924 (and (looking-at (if left
925 "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
926 "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
927 (replace-match "|\\2|\\1|"))
928 (org-table-goto-column col)
934 As hack I have this in an Org buffer to change temporarily to the desired
935 behavior with C-c C-c on one of the three snippets:
937 : #+begin_src emacs-lisp :results silent
938 : (org-defkey org-mode-map [(meta left)]
939 : 'my-org-table-move-column-in-row-left)
940 : (org-defkey org-mode-map [(meta right)]
941 : 'my-org-table-move-column-in-row-right)
942 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
943 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
947 : #+begin_src emacs-lisp :results silent
948 : (org-defkey org-mode-map [(meta left)]
949 : 'my-org-table-rotate-column-in-row-left)
950 : (org-defkey org-mode-map [(meta right)]
951 : 'my-org-table-rotate-column-in-row-right)
952 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
953 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
956 : - back to original:
957 : #+begin_src emacs-lisp :results silent
958 : (org-defkey org-mode-map [(meta left)] 'org-metaleft)
959 : (org-defkey org-mode-map [(meta right)] 'org-metaright)
960 : (org-defkey org-mode-map [(left)] 'backward-char)
961 : (org-defkey org-mode-map [(right)] 'forward-char)
964 **** reasons why this is not put into the Org core
966 I consider this as only a hack for several reasons:
967 - Generalization: The existing org-table-move-column function could be
968 enhanced with additional optional parameters to incorporate these
969 functionalities and could be used as the only function for better
970 maintainability. Now it's only a copy/paste hack of several similar
971 functions with simple modifications.
972 - Bindings: Should be convenient for repetition like M-<right>. What
973 should be bound where, what has to be left unbound?
974 - Does not fix formulas. Could be resolved for field formulas but
975 most probably not for column or range formulas and this can lead
976 to confusion. AFAIK all "official" table manipulations fix formulas.
977 - Completeness: Not all variations and combinations are covered yet
978 - left-right, up-down
979 - move, rotate with range to end, rotate with range to begin
980 - whole column/row, only in-row/in-column
982 ** Capture and Remember
983 *** Customize the size of the frame for remember
984 #+index: Remember!frame
985 #+index: Customization!remember
986 (Note: this hack is likely out of date due to the development of
990 On emacs-orgmode, Ryan C. Thompson suggested this:
993 I am using org-remember set to open a new frame when used,
994 and the default frame size is much too large. To fix this, I have
995 designed some advice and a custom variable to implement custom
996 parameters for the remember frame:
999 #+begin_src emacs-lisp
1000 (defcustom remember-frame-alist nil
1001 "Additional frame parameters for dedicated remember frame."
1005 (defadvice remember (around remember-frame-parameters activate)
1006 "Set some frame parameters for the remember frame."
1007 (let ((default-frame-alist (append remember-frame-alist
1008 default-frame-alist)))
1012 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1013 reasonable size for the frame.
1015 *** [[#heading-to-link][Turn a heading into an org link]]
1016 *** Quickaccess to the link part of hyperlinks
1017 #+index: Link!Referent
1018 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1019 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1020 which is indeed kind of cumbersome.
1022 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1024 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1025 #+begin_src emacs-lisp
1027 (lambda (&optional arg)
1030 (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1034 #+begin_src emacs-lisp
1035 (defun my-org-extract-link ()
1036 "Extract the link location at point and put it on the killring."
1038 (when (org-in-regexp org-bracket-link-regexp 1)
1039 (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1042 They put the link destination on the killring and can be easily bound to a key.
1044 *** Insert link with HTML title as default description
1045 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1046 from HTML <title> tag and use it as a default link description. Here is a way to
1049 #+begin_src emacs-lisp
1050 (require 'mm-url) ; to include mm-url-decode-entities-string
1052 (defun my-org-insert-link ()
1053 "Insert org link where default description is set to html title."
1055 (let* ((url (read-string "URL: "))
1056 (title (get-html-title-from-url url)))
1057 (org-insert-link nil url title)))
1059 (defun get-html-title-from-url (url)
1060 "Return content in <title> tag."
1061 (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1063 (set-buffer download-buffer)
1064 (beginning-of-buffer)
1065 (setq x1 (search-forward "<title>"))
1066 (search-forward "</title>")
1067 (setq x2 (search-backward "<"))
1068 (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1071 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1073 ** Archiving Content in Org-Mode
1074 *** Preserve top level headings when archiving to a file
1075 #+index: Archiving!Preserve top level headings
1078 To preserve (somewhat) the integrity of your archive structure while
1079 archiving lower level items to a file, you can use the following
1082 #+begin_src emacs-lisp
1083 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1084 (let ((org-archive-location
1085 (if (save-excursion (org-back-to-heading)
1086 (> (org-outline-level) 1))
1087 (concat (car (split-string org-archive-location "::"))
1089 (car (org-get-outline-path)))
1090 org-archive-location)))
1094 Thus, if you have an outline structure such as...
1102 ...archiving "Subsubheading" to a new file will set the location in
1103 the new file to the top level heading:
1110 While this hack obviously destroys the outline hierarchy somewhat, it
1111 at least preserves the logic of level one groupings.
1113 A slightly more complex version of this hack will not only keep the
1114 archive organized by top-level headings, but will also preserve the
1115 tags found on those headings:
1117 #+begin_src emacs-lisp
1118 (defun my-org-inherited-no-file-tags ()
1119 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1120 (ltags (org-entry-get nil "TAGS")))
1123 (replace-regexp-in-string (concat tag ":") "" tags)))
1124 (append org-file-tags (when ltags (split-string ltags ":" t))))
1125 (if (string= ":" tags) nil tags)))
1127 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1128 (let ((tags (my-org-inherited-no-file-tags))
1129 (org-archive-location
1130 (if (save-excursion (org-back-to-heading)
1131 (> (org-outline-level) 1))
1132 (concat (car (split-string org-archive-location "::"))
1134 (car (org-get-outline-path)))
1135 org-archive-location)))
1137 (with-current-buffer (find-file-noselect (org-extract-archive-file))
1139 (while (org-up-heading-safe))
1140 (org-set-tags-to tags)))))
1143 *** Archive in a date tree
1144 #+index: Archiving!date tree
1145 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1147 (Make sure org-datetree.el is loaded for this to work.)
1149 #+begin_src emacs-lisp
1150 ;; (setq org-archive-location "%s_archive::date-tree")
1151 (defadvice org-archive-subtree
1152 (around org-archive-subtree-to-data-tree activate)
1153 "org-archive-subtree to date-tree"
1155 (string= "date-tree"
1156 (org-extract-archive-heading
1157 (org-get-local-archive-location)))
1158 (let* ((dct (decode-time (org-current-time)))
1162 (this-buffer (current-buffer))
1163 (location (org-get-local-archive-location))
1164 (afile (org-extract-archive-file location))
1165 (org-archive-location
1166 (format "%s::*** %04d-%02d-%02d %s" afile y m d
1167 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1168 (message "afile=%s" afile)
1170 (error "Invalid `org-archive-location'"))
1172 (switch-to-buffer (find-file-noselect afile))
1173 (org-datetree-find-year-create y)
1174 (org-datetree-find-month-create y m)
1175 (org-datetree-find-day-create y m d)
1177 (switch-to-buffer this-buffer))
1182 *** Add inherited tags to archived entries
1183 #+index: Archiving!Add inherited tags
1184 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1185 advise the function like this:
1188 (defadvice org-archive-subtree
1189 (before add-inherited-tags-before-org-archive-subtree activate)
1190 "add inherited tags before org-archive-subtree"
1191 (org-set-tags-to (org-get-tags-at)))
1194 ** Using and Managing Org-Metadata
1195 *** Remove redundant tags of headlines
1196 #+index: Tag!Remove redundant
1199 A small function that processes all headlines in current buffer and
1200 removes tags that are local to a headline and inherited by a parent
1201 headline or the #+FILETAGS: statement.
1203 #+BEGIN_SRC emacs-lisp
1204 (defun dmj/org-remove-redundant-tags ()
1205 "Remove redundant tags of headlines in current buffer.
1207 A tag is considered redundant if it is local to a headline and
1208 inherited by a parent headline."
1210 (when (eq major-mode 'org-mode)
1214 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1215 local inherited tag)
1216 (dolist (tag alltags)
1217 (if (get-text-property 0 'inherited tag)
1218 (push tag inherited) (push tag local)))
1220 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1224 *** Remove empty property drawers
1225 #+index: Drawer!Empty
1226 David Maus proposed this:
1228 #+begin_src emacs-lisp
1229 (defun dmj:org:remove-empty-propert-drawers ()
1230 "*Remove all empty property drawers in current file."
1232 (unless (eq major-mode 'org-mode)
1233 (error "You need to turn on Org mode for this function."))
1235 (goto-char (point-min))
1236 (while (re-search-forward ":PROPERTIES:" nil t)
1238 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1241 *** Group task list by a property
1242 #+index: Agenda!Group task list
1243 This advice allows you to group a task list in Org-Mode. To use it,
1244 set the variable =org-agenda-group-by-property= to the name of a
1245 property in the option list for a TODO or TAGS search. The resulting
1246 agenda view will group tasks by that property prior to searching.
1248 #+begin_src emacs-lisp
1249 (defvar org-agenda-group-by-property nil
1250 "Set this in org-mode agenda views to group tasks by property")
1252 (defun org-group-bucket-items (prop items)
1254 (dolist (item items)
1255 (let* ((marker (get-text-property 0 'org-marker item))
1256 (pvalue (org-entry-get marker prop t))
1257 (cell (assoc pvalue buckets)))
1259 (setcdr cell (cons item (cdr cell)))
1260 (setq buckets (cons (cons pvalue (list item))
1262 (setq buckets (mapcar (lambda (bucket)
1264 (reverse (cdr bucket))))
1266 (sort buckets (lambda (i1 i2)
1267 (string< (car i1) (car i2))))))
1269 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1270 (list &optional nosort))
1271 "Prepare bucketed agenda entry lists"
1272 (if org-agenda-group-by-property
1273 ;; bucketed, handle appropriately
1275 (dolist (bucket (org-group-bucket-items
1276 org-agenda-group-by-property
1278 (let ((header (concat "Property "
1279 org-agenda-group-by-property
1281 (or (car bucket) "<nil>") ":\n")))
1282 (add-text-properties 0 (1- (length header))
1283 (list 'face 'org-agenda-structure)
1287 ;; recursively process
1288 (let ((org-agenda-group-by-property nil))
1289 (org-finalize-agenda-entries
1290 (cdr bucket) nosort))
1292 (setq ad-return-value text))
1294 (ad-activate 'org-finalize-agenda-entries)
1296 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1299 Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1301 A small hook run when clocking out of a task that prompts for a note
1302 when the tag "=clockout_note=" is found in a headline. It uses the tag
1303 ("=clockout_note=") so inheritance can also be used...
1305 #+begin_src emacs-lisp
1306 (defun rgr/check-for-clock-out-note()
1309 (org-back-to-heading)
1310 (let ((tags (org-get-tags)))
1311 (and tags (message "tags: %s " tags)
1312 (when (member "clocknote" tags)
1315 (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1317 *** Dynamically adjust tag position
1318 #+index: Tag!position
1319 Here is a bit of code that allows you to have the tags always
1320 right-adjusted in the buffer.
1322 This is useful when you have bigger window than default window-size
1323 and you dislike the aesthetics of having the tag in the middle of the
1326 This hack solves the problem of adjusting it whenever you change the
1328 Before saving it will revert the file to having the tag position be
1329 left-adjusted so that if you track your files with version control,
1330 you won't run into artificial diffs just because the window-size
1333 *IMPORTANT*: This is probably slow on very big files.
1335 #+begin_src emacs-lisp
1336 (setq ba/org-adjust-tags-column t)
1338 (defun ba/org-adjust-tags-column-reset-tags ()
1339 "In org-mode buffers it will reset tag position according to
1342 (not (string= (buffer-name) "*Remember*"))
1343 (eql major-mode 'org-mode))
1344 (let ((b-m-p (buffer-modified-p)))
1347 (goto-char (point-min))
1348 (command-execute 'outline-next-visible-heading)
1349 ;; disable (message) that org-set-tags generates
1350 (flet ((message (&rest ignored) nil))
1352 (set-buffer-modified-p b-m-p))
1355 (defun ba/org-adjust-tags-column-now ()
1356 "Right-adjust `org-tags-column' value, then reset tag position."
1357 (set (make-local-variable 'org-tags-column)
1358 (- (- (window-width) (length org-ellipsis))))
1359 (ba/org-adjust-tags-column-reset-tags))
1361 (defun ba/org-adjust-tags-column-maybe ()
1362 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1363 (when ba/org-adjust-tags-column
1364 (ba/org-adjust-tags-column-now)))
1366 (defun ba/org-adjust-tags-column-before-save ()
1367 "Tags need to be left-adjusted when saving."
1368 (when ba/org-adjust-tags-column
1369 (setq org-tags-column 1)
1370 (ba/org-adjust-tags-column-reset-tags)))
1372 (defun ba/org-adjust-tags-column-after-save ()
1373 "Revert left-adjusted tag position done by before-save hook."
1374 (ba/org-adjust-tags-column-maybe)
1375 (set-buffer-modified-p nil))
1377 ; automatically align tags on right-hand side
1378 (add-hook 'window-configuration-change-hook
1379 'ba/org-adjust-tags-column-maybe)
1380 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1381 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1382 (add-hook 'org-agenda-mode-hook '(lambda ()
1383 (setq org-agenda-tags-column (- (window-width)))))
1385 ; between invoking org-refile and displaying the prompt (which
1386 ; triggers window-configuration-change-hook) tags might adjust,
1387 ; which invalidates the org-refile cache
1388 (defadvice org-refile (around org-refile-disable-adjust-tags)
1389 "Disable dynamically adjusting tags"
1390 (let ((ba/org-adjust-tags-column nil))
1392 (ad-activate 'org-refile)
1394 *** Use an "attach" link type to open files without worrying about their location
1395 #+index: Link!Attach
1396 -- Darlan Cavalcante Moreira
1398 In the setup part in my org-files I put:
1401 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1404 Now I can use the "attach" link type, but org will ask me if I want to
1405 allow executing the elisp code. To avoid this you can even set
1406 org-confirm-elisp-link-function to nil (I don't like this because it allows
1407 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1412 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1414 This works very well.
1416 ** Org Agenda and Task Management
1417 *** Make it easier to set org-agenda-files from multiple directories
1418 #+index: Agenda!Files
1421 #+begin_src emacs-lisp
1422 (defun my-org-list-files (dirs ext)
1423 "Function to create list of org files in multiple subdirectories.
1424 This can be called to generate a list of files for
1425 org-agenda-files or org-refile-targets.
1427 DIRS is a list of directories.
1429 EXT is a list of the extensions of files to be included."
1430 (let ((dirs (if (listp dirs)
1433 (ext (if (listp ext)
1443 (file-expand-wildcards
1444 (concat (file-name-as-directory x) "*" y)))))
1449 (when (or (string-match "/.#" x)
1450 (string-match "#$" x))
1451 (setq files (delete x files))))
1455 (defvar my-org-agenda-directories '("~/org/")
1456 "List of directories containing org files.")
1457 (defvar my-org-agenda-extensions '(".org")
1458 "List of extensions of agenda files")
1460 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1461 (setq my-org-agenda-extensions '(".org" ".ref"))
1463 (defun my-org-set-agenda-files ()
1465 (setq org-agenda-files (my-org-list-files
1466 my-org-agenda-directories
1467 my-org-agenda-extensions)))
1469 (my-org-set-agenda-files)
1472 The code above will set your "default" agenda files to all files
1473 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1474 You can change these values by setting the variables
1475 my-org-agenda-extensions and my-org-agenda-directories. The function
1476 my-org-agenda-files-by-filetag uses these two variables to determine
1477 which files to search for filetags (i.e., the larger set from which
1478 the subset will be drawn).
1480 You can also easily use my-org-list-files to "mix and match"
1481 directories and extensions to generate different lists of agenda
1484 *** Restrict org-agenda-files by filetag
1485 #+index: Agenda!Files
1487 :CUSTOM_ID: set-agenda-files-by-filetag
1491 It is often helpful to limit yourself to a subset of your agenda
1492 files. For instance, at work, you might want to see only files related
1493 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1494 information on filtering tasks using [[file:org-faq.org::#limit-agenda-with-tag-filtering][filetags]] and [[file:org-faq.org::#limit-agenda-with-category-match][custom agenda
1495 commands]]. These solutions, however, require reapplying a filter each
1496 time you call the agenda or writing several new custom agenda commands
1497 for each context. Another solution is to use directories for different
1498 types of tasks and to change your agenda files with a function that
1499 sets org-agenda-files to the appropriate directory. But this relies on
1500 hard and static boundaries between files.
1502 The following functions allow for a more dynamic approach to selecting
1503 a subset of files based on filetags:
1505 #+begin_src emacs-lisp
1506 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1507 "Restrict org agenda files only to those containing filetag."
1509 (let* ((tagslist (my-org-get-all-filetags))
1511 (completing-read "Tag: "
1512 (mapcar 'car tagslist)))))
1513 (org-agenda-remove-restriction-lock 'noupdate)
1514 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1515 (setq org-agenda-overriding-restriction 'files)))
1517 (defun my-org-get-all-filetags ()
1518 "Get list of filetags from all default org-files."
1519 (let ((files org-agenda-files)
1521 (save-window-excursion
1522 (while (setq x (pop files))
1523 (set-buffer (find-file-noselect x))
1526 (let ((tagfiles (assoc y tagslist)))
1528 (setcdr tagfiles (cons x (cdr tagfiles)))
1529 (add-to-list 'tagslist (list y x)))))
1530 (my-org-get-filetags)))
1533 (defun my-org-get-filetags ()
1534 "Get list of filetags for current buffer"
1535 (let ((ftags org-file-tags)
1539 (org-substring-no-properties x))
1543 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1544 with all filetags in your "normal" agenda files. When you select a
1545 tag, org-agenda-files will be restricted to only those files
1546 containing the filetag. To release the restriction, type C-c C-x >
1547 (org-agenda-remove-restriction-lock).
1549 *** Highlight the agenda line under cursor
1550 #+index: Agenda!Highlight
1551 This is useful to make sure what task you are operating on.
1553 #+BEGIN_SRC emacs-lisp
1554 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1559 #+BEGIN_SRC emacs-lisp
1560 ;; hl-line seems to be only for emacs
1562 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1564 ;; highline-mode does not work straightaway in tty mode.
1565 ;; I use a black background
1567 '(highline-face ((((type tty) (class color))
1568 (:background "white" :foreground "black")))))
1571 *** Split frame horizontally for agenda
1572 #+index: Agenda!frame
1573 If you would like to split the frame into two side-by-side windows when
1574 displaying the agenda, try this hack from Jan Rehders, which uses the
1575 `toggle-window-split' from
1577 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1579 #+BEGIN_SRC emacs-lisp
1580 ;; Patch org-mode to use vertical splitting
1581 (defadvice org-prepare-agenda (after org-fix-split)
1582 (toggle-window-split))
1583 (ad-activate 'org-prepare-agenda)
1586 *** Automatically add an appointment when clocking in a task
1587 #+index: Clock!Automatically add an appointment when clocking in a task
1588 #+index: Appointment!Automatically add an appointment when clocking in a task
1589 #+BEGIN_SRC emacs-lisp
1590 ;; Make sure you have a sensible value for `appt-message-warning-time'
1591 (defvar bzg-org-clock-in-appt-delay 100
1592 "Number of minutes for setting an appointment by clocking-in")
1595 This function let's you add an appointment for the current entry.
1596 This can be useful when you need a reminder.
1598 #+BEGIN_SRC emacs-lisp
1599 (defun bzg-org-clock-in-add-appt (&optional n)
1600 "Add an appointment for the Org entry at point in N minutes."
1603 (org-back-to-heading t)
1604 (looking-at org-complex-heading-regexp)
1605 (let* ((msg (match-string-no-properties 4))
1606 (ct-time (decode-time))
1607 (appt-min (+ (cadr ct-time)
1608 (or n bzg-org-clock-in-appt-delay)))
1609 (appt-time ; define the time for the appointment
1610 (progn (setf (cadr ct-time) appt-min) ct-time)))
1611 (appt-add (format-time-string
1612 "%H:%M" (apply 'encode-time appt-time)) msg)
1613 (if (interactive-p) (message "New appointment for %s" msg)))))
1616 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1619 #+BEGIN_SRC emacs-lisp
1620 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1621 "Add an appointment when clocking a task in."
1622 (bzg-org-clock-in-add-appt))
1625 You may also want to delete the associated appointment when clocking
1626 out. This function does this:
1628 #+BEGIN_SRC emacs-lisp
1629 (defun bzg-org-clock-out-delete-appt nil
1630 "When clocking out, delete any associated appointment."
1633 (org-back-to-heading t)
1634 (looking-at org-complex-heading-regexp)
1635 (let* ((msg (match-string-no-properties 4)))
1636 (setq appt-time-msg-list
1640 (if (not (string-match (regexp-quote msg)
1641 (cadr appt))) appt))
1642 appt-time-msg-list)))
1646 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1648 #+BEGIN_SRC emacs-lisp
1649 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1650 "Delete an appointment when clocking a task out."
1651 (bzg-org-clock-out-delete-appt))
1654 *IMPORTANT*: You can add appointment by clocking in in both an
1655 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1656 agenda buffer with the advice above will bring an error.
1658 *** Using external programs for appointments reminders
1659 #+index: Appointment!reminders
1660 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1662 *** Remove from agenda time grid lines that are in an appointment
1663 #+index: Agenda!time grid
1664 #+index: Appointment!Remove from agenda time grid lines
1665 The agenda shows lines for the time grid. Some people think that
1666 these lines are a distraction when there are appointments at those
1667 times. You can get rid of the lines which coincide exactly with the
1668 beginning of an appointment. Michael Ekstrand has written a piece of
1669 advice that also removes lines that are somewhere inside an
1672 #+begin_src emacs-lisp
1673 (defun org-time-to-minutes (time)
1674 "Convert an HHMM time to minutes"
1675 (+ (* (/ time 100) 60) (% time 100)))
1677 (defun org-time-from-minutes (minutes)
1678 "Convert a number of minutes to an HHMM time"
1679 (+ (* (/ minutes 60) 100) (% minutes 60)))
1681 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1682 (list ndays todayp))
1683 (if (member 'remove-match (car org-agenda-time-grid))
1684 (flet ((extract-window
1686 (let ((start (get-text-property 1 'time-of-day line))
1687 (dur (get-text-property 1 'duration line)))
1691 (org-time-from-minutes
1692 (+ dur (org-time-to-minutes start)))))
1695 (let* ((windows (delq nil (mapcar 'extract-window list)))
1696 (org-agenda-time-grid
1697 (list (car org-agenda-time-grid)
1698 (cadr org-agenda-time-grid)
1701 (find-if (lambda (w)
1704 (and (>= time (car w))
1707 (caddr org-agenda-time-grid)))))
1710 (ad-activate 'org-agenda-add-time-grid-maybe)
1712 *** Disable version control for Org mode agenda files
1713 #+index: Agenda!Files
1716 Even if you use Git to track your agenda files you might not need
1717 vc-mode to be enabled for these files.
1719 #+begin_src emacs-lisp
1720 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1721 (defun dmj/disable-vc-for-agenda-files-hook ()
1722 "Disable vc-mode for Org agenda files."
1723 (if (and (fboundp 'org-agenda-file-p)
1724 (org-agenda-file-p (buffer-file-name)))
1725 (remove-hook 'find-file-hook 'vc-find-file-hook)
1726 (add-hook 'find-file-hook 'vc-find-file-hook)))
1729 *** Easy customization of TODO colors
1730 #+index: Customization!Todo keywords
1731 #+index: Todo keywords!Customization
1735 Here is some code I came up with some code to make it easier to
1736 customize the colors of various TODO keywords. As long as you just
1737 want a different color and nothing else, you can customize the
1738 variable org-todo-keyword-faces and use just a string color (i.e. a
1739 string of the color name) as the face, and then org-get-todo-face
1740 will convert the color to a face, inheriting everything else from
1741 the standard org-todo face.
1743 To demonstrate, I currently have org-todo-keyword-faces set to
1745 #+BEGIN_SRC emacs-lisp
1746 (("IN PROGRESS" . "dark orange")
1747 ("WAITING" . "red4")
1748 ("CANCELED" . "saddle brown"))
1751 Here's the code, in a form you can put in your =.emacs=
1753 #+BEGIN_SRC emacs-lisp
1754 (eval-after-load 'org-faces
1756 (defcustom org-todo-keyword-faces nil
1757 "Faces for specific TODO keywords.
1758 This is a list of cons cells, with TODO keywords in the car and
1759 faces in the cdr. The face can be a symbol, a color, or a
1760 property list of attributes, like (:foreground \"blue\" :weight
1761 bold :underline t)."
1766 (string :tag "Keyword")
1767 (choice color (sexp :tag "Face")))))))
1769 (eval-after-load 'org
1771 (defun org-get-todo-face-from-color (color)
1772 "Returns a specification for a face that inherits from org-todo
1773 face and has the given color as foreground. Returns nil if
1776 `(:inherit org-warning :foreground ,color)))
1778 (defun org-get-todo-face (kwd)
1779 "Get the right face for a TODO keyword KWD.
1780 If KWD is a number, get the corresponding match group."
1781 (if (numberp kwd) (setq kwd (match-string kwd)))
1782 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1784 (org-get-todo-face-from-color face)
1786 (and (member kwd org-done-keywords) 'org-done)
1790 *** Add an effort estimate on the fly when clocking in
1791 #+index: Effort estimate!Add when clocking in
1792 #+index: Clock!Effort estimate
1793 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1794 This way you can easily have a "tea-timer" for your tasks when they
1795 don't already have an effort estimate.
1797 #+begin_src emacs-lisp
1798 (add-hook 'org-clock-in-prepare-hook
1799 'my-org-mode-ask-effort)
1801 (defun my-org-mode-ask-effort ()
1802 "Ask for an effort estimate when clocking in."
1803 (unless (org-entry-get (point) "Effort")
1807 (org-entry-get-multivalued-property (point) "Effort"))))
1808 (unless (equal effort "")
1809 (org-set-property "Effort" effort)))))
1812 Or you can use a default effort for such a timer:
1814 #+begin_src emacs-lisp
1815 (add-hook 'org-clock-in-prepare-hook
1816 'my-org-mode-add-default-effort)
1818 (defvar org-clock-default-effort "1:00")
1820 (defun my-org-mode-add-default-effort ()
1821 "Add a default effort estimation."
1822 (unless (org-entry-get (point) "Effort")
1823 (org-set-property "Effort" org-clock-default-effort)))
1826 *** Use idle timer for automatic agenda views
1827 #+index: Agenda view!Refresh
1828 From John Wiegley's mailing list post (March 18, 2010):
1831 I have the following snippet in my .emacs file, which I find very
1832 useful. Basically what it does is that if I don't touch my Emacs for 5
1833 minutes, it displays the current agenda. This keeps my tasks "always
1834 in mind" whenever I come back to Emacs after doing something else,
1835 whereas before I had a tendency to forget that it was there.
1838 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1840 #+begin_src emacs-lisp
1841 (defun jump-to-org-agenda ()
1843 (let ((buf (get-buffer "*Org Agenda*"))
1846 (if (setq wind (get-buffer-window buf))
1847 (select-window wind)
1848 (if (called-interactively-p)
1850 (select-window (display-buffer buf t t))
1851 (org-fit-window-to-buffer)
1852 ;; (org-agenda-redo)
1854 (with-selected-window (display-buffer buf)
1855 (org-fit-window-to-buffer)
1856 ;; (org-agenda-redo)
1858 (call-interactively 'org-agenda-list)))
1859 ;;(let ((buf (get-buffer "*Calendar*")))
1860 ;; (unless (get-buffer-window buf)
1861 ;; (org-agenda-goto-calendar)))
1864 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1868 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1870 *** Refresh the agenda view regularly
1871 #+index: Agenda view!Refresh
1872 Hack sent by Kiwon Um:
1874 #+begin_src emacs-lisp
1875 (defun kiwon/org-agenda-redo-in-other-window ()
1876 "Call org-agenda-redo function even in the non-agenda buffer."
1878 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1880 (with-selected-window agenda-window (org-agenda-redo)))))
1881 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1884 *** Reschedule agenda items to today with a single command
1885 #+index: Agenda!Reschedule
1886 This was suggested by Carsten in reply to David Abrahams:
1888 #+begin_example emacs-lisp
1889 (defun org-agenda-reschedule-to-today ()
1891 (flet ((org-read-date (&rest rest) (current-time)))
1892 (call-interactively 'org-agenda-schedule)))
1895 *** Mark subtree DONE along with all subheadings
1896 #+index: Subtree!subheadings
1897 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
1899 #+begin_src emacs-lisp
1900 (defun bh/mark-subtree-done ()
1903 (let ((limit (point)))
1905 (exchange-point-and-mark)
1906 (while (> (point) limit)
1908 (outline-previous-visible-heading 1))
1909 (org-todo "DONE"))))
1912 Then M-x bh/mark-subtree-done.
1914 *** Mark heading done when all checkboxes are checked.
1916 :CUSTOM_ID: mark-done-when-all-checkboxes-checked
1921 An item consists of a list with checkboxes. When all of the
1922 checkboxes are checked, the item should be considered complete and its
1923 TODO state should be automatically changed to DONE. The code below
1924 does that. This version is slightly enhanced over the one in the
1926 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
1927 reset the state back to TODO if a checkbox is unchecked.
1929 Note that the code requires that a checkbox statistics cookie (the [/]
1930 or [%] thingie in the headline - see the [[http://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
1931 manual) be present in order for it to work. Note also that it is too
1932 dumb to figure out whether the item has a TODO state in the first
1933 place: if there is a statistics cookie, a TODO/DONE state will be
1934 added willy-nilly any time that the statistics cookie is changed.
1936 #+begin_src emacs-lisp
1937 ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
1938 (eval-after-load 'org-list
1939 '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
1941 (defun ndk/checkbox-list-complete ()
1943 (org-back-to-heading t)
1944 (let ((beg (point)) end)
1948 (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
1950 (if (equal (match-string 1) "100%")
1951 ;; all done - do the state change
1954 (if (and (> (match-end 2) (match-beginning 2))
1955 (equal (match-string 2) (match-string 3)))
1957 (org-todo 'todo)))))))
1960 *** Links to custom agenda views
1962 :CUSTOM_ID: links-to-agenda-views
1964 #+index: Agenda view!Links to
1965 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
1967 If you have custom agenda commands defined to some key, say w, then
1968 the following will serve as a link to the custom agenda buffer.
1969 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
1971 Clicking on it will prompt if you want to execute the elisp code. If
1972 you would rather not have the prompt or would want to respond with a
1973 single letter, ~y~ or ~n~, take a look at the docstrings of the
1974 variables =org-confirm-elisp-link-function= and
1975 =org-confirm-elisp-link-not-regexp=. Please take special note of the
1976 security risk associated with completely disabling the prompting
1979 ** Exporting org files
1980 *** Export Org to Org and handle includes.
1981 #+index: Export!handle includes
1982 Nick Dokos came up with this useful function:
1984 #+begin_src emacs-lisp
1985 (defun org-to-org-handle-includes ()
1986 "Copy the contents of the current buffer to OUTFILE,
1987 recursively processing #+INCLUDEs."
1988 (let* ((s (buffer-string))
1989 (fname (buffer-file-name))
1990 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
1994 (org-export-handle-include-files-recurse)
1997 (delete-region (point-min) (point-max))
2002 *** Specifying LaTeX commands to floating environments
2004 :CUSTOM_ID: latex-command-for-floats
2007 #+index: Export!LaTeX
2008 The keyword ~placement~ can be used to specify placement options to
2009 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2010 LaTeX export. Org passes along everything passed in options as long as
2011 there are no spaces. One can take advantage of this to pass other
2012 LaTeX commands and have their scope limited to the floating
2015 For example one can set the fontsize of a table different from the
2016 default normal size by putting something like =\footnotesize= right
2017 after the placement options. During LaTeX export using the
2018 ~#+ATTR_LaTeX:~ line below:
2021 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2024 exports the associated floating environment as shown in the following
2028 \begin{table}[<options>]\footnotesize
2033 It should be noted that this hack does not work for beamer export of
2034 tables since the =table= environment is not used. As an ugly
2035 workaround, one can use the following:
2038 ,#+LATEX: {\footnotesize
2039 ,#+ATTR_LaTeX: align=rr
2046 *** Styling code sections with CSS
2048 #+index: HTML!Styling code sections with CSS
2050 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2051 to HTML using =<pre>= tags, and assigned CSS classes by their content
2052 type. For example, Perl content will have an opening tag like
2053 =<pre class="src src-perl">=. You can use those classes to add styling
2054 to the output, such as here where a small language tag is added at the
2055 top of each kind of code box:
2058 (setq org-export-html-style
2059 "<style type=\"text/css\">
2060 <!--/*--><![CDATA[/*><!--*/
2061 .src { background-color: #F5FFF5; position: relative; overflow: visible; }
2062 .src:before { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2063 .src-sh:before { content: 'sh'; }
2064 .src-bash:before { content: 'sh'; }
2065 .src-R:before { content: 'R'; }
2066 .src-perl:before { content: 'Perl'; }
2067 .src-sql:before { content: 'SQL'; }
2068 .example { background-color: #FFF5F5; }
2073 Additionally, we use color to distinguish code output (the =.example=
2074 class) from input (all the =.src-*= classes).
2076 * Hacking Org: Working with Org-mode and other Emacs Packages.
2077 ** org-remember-anything
2079 #+index: Remember!Anything
2081 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2083 #+BEGIN_SRC emacs-lisp
2084 (defvar org-remember-anything
2085 '((name . "Org Remember")
2086 (candidates . (lambda () (mapcar 'car org-remember-templates)))
2087 (action . (lambda (name)
2088 (let* ((orig-template org-remember-templates)
2089 (org-remember-templates
2090 (list (assoc name orig-template))))
2091 (call-interactively 'org-remember))))))
2094 You can add it to your 'anything-sources' variable and open remember directly
2095 from anything. I imagine this would be more interesting for people with many
2096 remember templates, so that you are out of keys to assign those to.
2098 ** Org-mode and saveplace.el
2100 Fix a problem with =saveplace.el= putting you back in a folded position:
2102 #+begin_src emacs-lisp
2103 (add-hook 'org-mode-hook
2105 (when (outline-invisible-p)
2107 (outline-previous-visible-heading 1)
2108 (org-show-subtree)))))
2111 ** Using ido-mode for org-refile (and archiving via refile)
2113 First set up ido-mode, for example using:
2115 #+begin_src emacs-lisp
2116 ; use ido mode for completion
2117 (setq ido-everywhere t)
2118 (setq ido-enable-flex-matching t)
2119 (setq ido-max-directory-size 100000)
2120 (ido-mode (quote both))
2123 Now to enable it in org-mode, use the following:
2124 #+begin_src emacs-lisp
2125 (setq org-completion-use-ido t)
2126 (setq org-refile-use-outline-path nil)
2127 (setq org-refile-allow-creating-parent-nodes 'confirm)
2129 The last line enables the creation of nodes on the fly.
2131 If you refile into files that are not in your agenda file list, you can add them as target like this (replace file1\_done, etc with your files):
2132 #+begin_src emacs-lisp
2133 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2136 For refiling it is often not useful to include targets that have a DONE state. It's easy to remove them by using the verify-refile-target hook.
2137 #+begin_src emacs-lisp
2138 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2139 ; added check to only include headlines, e.g. line must have at least one child
2140 (defun my/verify-refile-target ()
2141 "Exclude todo keywords with a DONE state from refile targets"
2142 (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2143 (save-excursion (org-goto-first-child))
2145 (setq org-refile-target-verify-function 'my/verify-refile-target)
2147 Now when looking for a refile target, you can use the full power of ido to find them. Ctrl-R can be used to switch between different options that ido offers.
2149 ** Using ido-completing-read to find attachments
2151 #+index: Attachment!ido completion
2155 Org-attach is great for quickly linking files to a project. But if you
2156 use org-attach extensively you might find yourself wanting to browse
2157 all the files you've attached to org headlines. This is not easy to do
2158 manually, since the directories containing the files are not human
2159 readable (i.e., they are based on automatically generated ids). Here's
2160 some code to browse those files using ido (obviously, you need to be
2163 #+begin_src emacs-lisp
2164 (load-library "find-lisp")
2166 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2168 (defun my-ido-find-org-attach ()
2169 "Find files in org-attachment directory"
2171 (let* ((enable-recursive-minibuffers t)
2172 (files (find-lisp-find-files org-attach-directory "."))
2175 (cons (file-name-nondirectory x)
2179 (remove-duplicates (mapcar #'car file-assoc-list)
2181 (filename (ido-completing-read "Org attachments: " filename-list nil t))
2182 (longname (cdr (assoc filename file-assoc-list))))
2183 (ido-set-current-directory
2184 (if (file-directory-p longname)
2186 (file-name-directory longname)))
2187 (setq ido-exit 'refresh
2188 ido-text-init ido-text
2192 (add-hook 'ido-setup-hook 'ido-my-keys)
2194 (defun ido-my-keys ()
2195 "Add my keybindings for ido."
2196 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2199 To browse your org attachments using ido fuzzy matching and/or the
2200 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2203 ** Link to Gnus messages by Message-Id
2204 #+index: Link!Gnus message by Message-Id
2205 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2206 discussion about linking to Gnus messages without encoding the folder
2207 name in the link. The following code hooks in to the store-link
2208 function in Gnus to capture links by Message-Id when in nnml folders,
2209 and then provides a link type "mid" which can open this link. The
2210 =mde-org-gnus-open-message-link= function uses the
2211 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2212 scan. It will go through them, in order, asking each to locate the
2213 message and opening it from the first one that reports success.
2215 It has only been tested with a single nnml backend, so there may be
2216 bugs lurking here and there.
2218 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2221 #+begin_src emacs-lisp
2222 ;; Support for saving Gnus messages by Message-ID
2223 (defun mde-org-gnus-save-by-mid ()
2224 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2225 (when (eq major-mode 'gnus-article-mode)
2226 (gnus-article-show-summary))
2227 (let* ((group gnus-newsgroup-name)
2228 (method (gnus-find-method-for-group group)))
2229 (when (eq 'nnml (car method))
2230 (let* ((article (gnus-summary-article-number))
2231 (header (gnus-summary-article-header article))
2232 (from (mail-header-from header))
2235 (let ((mid (mail-header-id header)))
2236 (if (string-match "<\\(.*\\)>" mid)
2237 (match-string 1 mid)
2238 (error "Malformed message ID header %s" mid)))))
2239 (date (mail-header-date header))
2240 (subject (gnus-summary-subject-string)))
2241 (org-store-link-props :type "mid" :from from :subject subject
2242 :message-id message-id :group group
2243 :link (org-make-link "mid:" message-id))
2244 (apply 'org-store-link-props
2245 :description (org-email-link-description)
2246 org-store-link-plist)
2249 (defvar mde-mid-resolve-methods '()
2250 "List of methods to try when resolving message ID's. For Gnus,
2251 it is a cons of 'gnus and the select (type and name).")
2252 (setq mde-mid-resolve-methods
2255 (defvar mde-org-gnus-open-level 1
2256 "Level at which Gnus is started when opening a link")
2257 (defun mde-org-gnus-open-message-link (msgid)
2258 "Open a message link with Gnus"
2260 (require 'org-table)
2261 (catch 'method-found
2262 (message "[MID linker] Resolving %s" msgid)
2263 (dolist (method mde-mid-resolve-methods)
2265 ((and (eq (car method) 'gnus)
2266 (eq (cadr method) 'nnml))
2267 (funcall (cdr (assq 'gnus org-link-frame-setup))
2268 mde-org-gnus-open-level)
2269 (when gnus-other-frame-object
2270 (select-frame gnus-other-frame-object))
2271 (let* ((msg-info (nnml-find-group-number
2272 (concat "<" msgid ">")
2274 (group (and msg-info (car msg-info)))
2275 (message (and msg-info (cdr msg-info)))
2277 (if (gnus-methods-equal-p
2281 (gnus-group-full-name group (cdr method))))))
2283 (gnus-summary-read-group qname nil t)
2284 (gnus-summary-goto-article message nil t))
2285 (throw 'method-found t)))
2286 (t (error "Unknown link type"))))))
2288 (eval-after-load 'org-gnus
2290 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2291 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2294 ** Store link to a message when sending in Gnus
2295 #+index: Link!Store link to a message when sending in Gnus
2296 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2298 #+begin_src emacs-lisp
2299 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2300 "Send message with `message-send-and-exit' and store org link to message copy.
2301 If multiple groups appear in the Gcc header, the link refers to
2302 the copy in the last group."
2306 (message-narrow-to-headers)
2307 (let ((gcc (car (last
2308 (message-unquote-tokens
2309 (message-tokenize-header
2310 (mail-fetch-field "gcc" nil t) " ,")))))
2311 (buf (current-buffer))
2312 (message-kill-buffer-on-exit nil)
2313 id to from subject desc link newsgroup xarchive)
2314 (message-send-and-exit arg)
2316 ;; gcc group found ...
2318 (save-current-buffer
2319 (progn (set-buffer buf)
2320 (setq id (org-remove-angle-brackets
2321 (mail-fetch-field "Message-ID")))
2322 (setq to (mail-fetch-field "To"))
2323 (setq from (mail-fetch-field "From"))
2324 (setq subject (mail-fetch-field "Subject"))))
2325 (org-store-link-props :type "gnus" :from from :subject subject
2326 :message-id id :group gcc :to to)
2327 (setq desc (org-email-link-description))
2328 (setq link (org-gnus-article-link
2329 gcc newsgroup id xarchive))
2330 (setq org-stored-links
2331 (cons (list link desc) org-stored-links)))
2332 ;; no gcc group found ...
2333 (message "Can not create Org link: No Gcc header found."))))))
2335 (define-key message-mode-map [(control c) (control meta c)]
2336 'ulf-message-send-and-org-gnus-store-link)
2339 ** Send html messages and attachments with Wanderlust
2342 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2343 similar functionality for both Wanderlust and Gnus. The hack below is
2344 still somewhat different: It allows you to toggle sending of html
2345 messages within Wanderlust transparently. I.e. html markup of the
2346 message body is created right before sending starts.
2348 *** Send HTML message
2350 Putting the code below in your .emacs adds following four functions:
2352 - dmj/wl-send-html-message
2354 Function that does the job: Convert everything between "--text
2355 follows this line--" and first mime entity (read: attachment) or
2356 end of buffer into html markup using `org-export-region-as-html'
2357 and replaces original body with a multipart MIME entity with the
2358 plain text version of body and the html markup version. Thus a
2359 recipient that prefers html messages can see the html markup,
2360 recipients that prefer or depend on plain text can see the plain
2363 Cannot be called interactively: It is hooked into SEMI's
2364 `mime-edit-translate-hook' if message should be HTML message.
2366 - dmj/wl-send-html-message-draft-init
2368 Cannot be called interactively: It is hooked into WL's
2369 `wl-mail-setup-hook' and provides a buffer local variable to
2372 - dmj/wl-send-html-message-draft-maybe
2374 Cannot be called interactively: It is hooked into WL's
2375 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2376 `mime-edit-translate-hook' depending on whether HTML message is
2379 - dmj/wl-send-html-message-toggle
2381 Toggles sending of HTML message. If toggled on, the letters
2382 "HTML" appear in the mode line.
2384 Call it interactively! Or bind it to a key in `wl-draft-mode'.
2386 If you have to send HTML messages regularly you can set a global
2387 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2388 toggle on sending HTML message by default.
2390 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2391 Google's web front end. As you can see you have the whole markup of
2392 Org at your service: *bold*, /italics/, tables, lists...
2394 So even if you feel uncomfortable with sending HTML messages at least
2395 you send HTML that looks quite good.
2397 #+begin_src emacs-lisp
2398 (defun dmj/wl-send-html-message ()
2399 "Send message as html message.
2400 Convert body of message to html using
2401 `org-export-region-as-html'."
2404 (let (beg end html text)
2405 (goto-char (point-min))
2406 (re-search-forward "^--text follows this line--$")
2407 ;; move to beginning of next line
2408 (beginning-of-line 2)
2410 (if (not (re-search-forward "^--\\[\\[" nil t))
2411 (setq end (point-max))
2416 (setq text (buffer-substring-no-properties beg end))
2422 (when (re-search-backward "^-- \n" nil t)
2423 ;; preserve link breaks in signature
2424 (insert "\n#+BEGIN_VERSE\n")
2425 (goto-char (point-max))
2426 (insert "\n#+END_VERSE\n")
2428 (setq html (org-export-region-as-html
2429 (point-min) (point-max) t 'string))))
2430 (delete-region beg end)
2433 "--" "<<alternative>>-{\n"
2434 "--" "[[text/plain]]\n" text
2435 "--" "[[text/html]]\n" html
2436 "--" "}-<<alternative>>\n")))))
2438 (defun dmj/wl-send-html-message-toggle ()
2439 "Toggle sending of html message."
2441 (setq dmj/wl-send-html-message-toggled-p
2442 (if dmj/wl-send-html-message-toggled-p
2444 (message "Sending html message toggled %s"
2445 (if dmj/wl-send-html-message-toggled-p
2448 (defun dmj/wl-send-html-message-draft-init ()
2449 "Create buffer local settings for maybe sending html message."
2450 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2451 (setq dmj/wl-send-html-message-toggled-p nil))
2452 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2453 (add-to-list 'global-mode-string
2454 '(:eval (if (eq major-mode 'wl-draft-mode)
2455 dmj/wl-send-html-message-toggled-p))))
2457 (defun dmj/wl-send-html-message-maybe ()
2458 "Maybe send this message as html message.
2460 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2461 non-nil, add `dmj/wl-send-html-message' to
2462 `mime-edit-translate-hook'."
2463 (if dmj/wl-send-html-message-toggled-p
2464 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2465 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2467 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2468 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2469 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2472 *** Attach HTML of region or subtree
2474 Instead of sending a complete HTML message you might only send parts
2475 of an Org file as HTML for the poor souls who are plagued with
2476 non-proportional fonts in their mail program that messes up pretty
2479 This short function does the trick: It exports region or subtree to
2480 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2481 and clipboard. If a region is active, it uses the region, the
2482 complete subtree otherwise.
2484 #+begin_src emacs-lisp
2485 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2486 "Export region between BEG and END as html attachment.
2487 If BEG and END are not set, use current subtree. Region or
2488 subtree is exported to html without header and footer, prefixed
2489 with a mime entity string and pushed to clipboard and killring.
2490 When called with prefix, mime entity is not marked as
2492 (interactive "r\nP")
2494 (let* ((beg (if (region-active-p) (region-beginning)
2496 (org-back-to-heading)
2498 (end (if (region-active-p) (region-end)
2500 (org-end-of-subtree)
2502 (html (concat "--[[text/html"
2503 (if arg "" "\nContent-Disposition: attachment")
2505 (org-export-region-as-html beg end t 'string))))
2506 (when (fboundp 'x-set-selection)
2507 (ignore-errors (x-set-selection 'PRIMARY html))
2508 (ignore-errors (x-set-selection 'CLIPBOARD html)))
2509 (message "html export done, pushed to kill ring and clipboard"))))
2512 *** Adopting for Gnus
2514 The whole magic lies in the special strings that mark a HTML
2515 attachment. So you might just have to find out what these special
2516 strings are in message-mode and modify the functions accordingly.
2517 ** Add sunrise/sunset times to the agenda.
2518 #+index: Agenda!Diary s-expressions
2521 The diary package provides the function =diary-sunrise-sunset= which can be used
2522 in a diary s-expression in some agenda file like this:
2524 #+begin_src org-mode
2525 %%(diary-sunrise-sunset)
2528 Seb Vauban asked if it is possible to put sunrise and sunset in
2529 separate lines. Here is a hack to do that. It adds two functions (they
2530 have to be available before the agenda is shown, so I add them early
2531 in my org-config file which is sourced from .emacs, but you'll have to
2532 suit yourself here) that just parse the output of
2533 diary-sunrise-sunset, instead of doing the right thing which would be
2534 to take advantage of the data structures that diary/solar.el provides.
2535 In short, a hack - so perfectly suited for inclusion here :-)
2537 The functions (and latitude/longitude settings which you have to modify for
2538 your location) are as follows:
2540 #+begin_src emacs-lisp
2541 (setq calendar-latitude 48.2)
2542 (setq calendar-longitude 16.4)
2543 (setq calendar-location-name "Vienna, Austria")
2545 (autoload 'solar-sunrise-sunset "solar.el")
2546 (autoload 'solar-time-string "solar.el")
2547 (defun diary-sunrise ()
2548 "Local time of sunrise as a diary entry.
2549 The diary entry can contain `%s' which will be replaced with
2550 `calendar-location-name'."
2551 (let ((l (solar-sunrise-sunset date)))
2554 (if (string= entry "")
2556 (format entry (eval calendar-location-name))) " "
2557 (solar-time-string (caar l) nil)))))
2559 (defun diary-sunset ()
2560 "Local time of sunset as a diary entry.
2561 The diary entry can contain `%s' which will be replaced with
2562 `calendar-location-name'."
2563 (let ((l (solar-sunrise-sunset date)))
2566 (if (string= entry "")
2568 (format entry (eval calendar-location-name))) " "
2569 (solar-time-string (caadr l) nil)))))
2572 You also need to add a couple of diary s-expressions in one of your agenda
2575 #+begin_src org-mode
2576 %%(diary-sunrise)Sunrise in %s
2580 This will show sunrise with the location and sunset without it.
2582 The thread on the mailing list that started this can be found [[http://thread.gmane.org/gmane.emacs.orgmode/38723Here%20is%20a%20pointer%20to%20the%20thread%20on%20the%20mailing%20list][here]].
2583 In comparison to the version posted on the mailing list, this one
2584 gets rid of the timezone information and can show the location.
2585 ** Export BBDB contacts to org-contacts.el
2586 #+index: Address Book!BBDB to org-contacts
2587 Try this tool by Wes Hardaker:
2589 http://www.hardakers.net/code/bbdb-to-org-contacts/
2591 ** Calculating date differences - how to write a simple elisp function
2592 #+index: Timestamp!date calculations
2593 #+index: Elisp!technique
2595 Alexander Wingård asked how to calculate the number of days between a
2596 time stamp in his org file and today (see
2597 http://thread.gmane.org/gmane.emacs.orgmode/46881). Although the
2598 resulting answer is probably not of general interest, the method might
2599 be useful to a budding Elisp programmer.
2601 Alexander started from an already existing org function,
2602 =org-evaluate-time-range=. When this function is called in the context
2603 of a time range (two time stamps separated by "=--="), it calculates the
2604 number of days between the two dates and outputs the result in Emacs's
2605 echo area. What he wanted was a similar function that, when called from
2606 the context of a single time stamp, would calculate the number of days
2607 between the date in the time stamp and today. The result should go to
2608 the same place: Emacs's echo area.
2610 The solution presented in the mail thread is as follows:
2612 #+begin_src emacs-lisp
2613 (defun aw/org-evaluate-time-range (&optional to-buffer)
2615 (if (org-at-date-range-p t)
2616 (org-evaluate-time-range to-buffer)
2617 ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
2618 (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
2621 (goto-char (point-at-bol))
2622 (re-search-forward org-ts-regexp (point-at-eol) t)
2623 (if (not (org-at-timestamp-p t))
2624 (error "No timestamp here"))
2625 (goto-char (match-beginning 0))
2626 (org-insert-time-stamp (current-time) nil nil)
2628 (org-evaluate-time-range to-buffer)))))
2631 The function assumes that point is on some line with some time stamp
2632 (or a date range) in it. Note that =org-evaluate-time-range= does not care
2633 whether the first date is earlier than the second: it will always output
2634 the number of days between the earlier date and the later date.
2636 As stated before, the function itself is of limited interest (although
2637 it satisfied Alexander's need).The *method* used might be of wider
2638 interest however, so here is a short explanation.
2640 The idea is that we want =org-evaluate-time-range= to do all the
2641 heavy lifting, but that function requires that it be in a date-range
2642 context. So the function first checks whether it's in a date range
2643 context already: if so, it calls =org-evaluate-time-range= directly
2644 to do the work. The trick now is to arrange things so we can call this
2645 same function in the case where we do *not* have a date range
2646 context. In that case, we manufacture one: we create a temporary
2647 buffer, copy the line with the purported time stamp to the temp
2648 buffer, find the time stamp (signal an error if no time stamp is
2649 found) and insert a new time stamp with the current time before the
2650 existing time stamp, followed by "=--=": voilà, we now have a time range
2651 on which we can apply our old friend =org-evaluate-time-range= to
2652 produce the answer. Because of the above-mentioned property
2653 of =org-evaluate-time-range=, it does not matter if the existing
2654 time stamp is earlier or later than the current time: the correct
2655 number of days is output.
2657 Note that at the end of the call to =with-temp-buffer=, the temporary
2658 buffer goes away. It was just used as a scratch pad for the function
2659 to do some figuring.
2661 The idea of using a temp buffer as a scratch pad has wide
2662 applicability in Emacs programming. The rest of the work is knowing
2663 enough about facilities provided by Emacs (e.g. regexp searching) and
2664 by Org (e.g. checking for time stamps and generating a time stamp) so
2665 that you don't reinvent the wheel, and impedance-matching between the
2668 ** ibuffer and org files
2670 Neil Smithline posted this snippet to let you browse org files with
2673 #+BEGIN_SRC emacs-lisp
2676 (defun org-ibuffer ()
2677 "Open an `ibuffer' window showing only `org-mode' buffers."
2679 (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
2682 ** Enable org-mode links in other modes
2684 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
2686 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
2688 * Hacking Org: Working with Org-mode and External Programs.
2689 ** Use Org-mode with Screen [Andrew Hyatt]
2690 #+index: Link!to screen session
2691 "The general idea is that you start a task in which all the work will
2692 take place in a shell. This usually is not a leaf-task for me, but
2693 usually the parent of a leaf task. From a task in your org-file, M-x
2694 ash-org-screen will prompt for the name of a session. Give it a name,
2695 and it will insert a link. Open the link at any time to go the screen
2696 session containing your work!"
2698 http://article.gmane.org/gmane.emacs.orgmode/5276
2700 #+BEGIN_SRC emacs-lisp
2703 (defun ash-org-goto-screen (name)
2704 "Open the screen with the specified name in the window"
2705 (interactive "MScreen name: ")
2706 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2707 (if (member screen-buffer-name
2708 (mapcar 'buffer-name (buffer-list)))
2709 (switch-to-buffer screen-buffer-name)
2710 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2712 (defun ash-org-screen-buffer-name (name)
2713 "Returns the buffer name corresponding to the screen name given."
2714 (concat "*screen " name "*"))
2716 (defun ash-org-screen-helper (name arg)
2717 ;; Pick the name of the new buffer.
2718 (let ((term-ansi-buffer-name
2719 (generate-new-buffer-name
2720 (ash-org-screen-buffer-name name))))
2721 (setq term-ansi-buffer-name
2722 (term-ansi-make-term
2723 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2724 (set-buffer term-ansi-buffer-name)
2727 (term-set-escape-char ?\C-x)
2728 term-ansi-buffer-name))
2730 (defun ash-org-screen (name)
2731 "Start a screen session with name"
2732 (interactive "MScreen name: ")
2734 (ash-org-screen-helper name "-S"))
2735 (insert-string (concat "[[screen:" name "]]")))
2737 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2738 ;; \"%s\")") to org-link-abbrev-alist.
2741 ** Org Agenda + Appt + Zenity
2743 :CUSTOM_ID: org-agenda-appt-zenity
2746 #+index: Appointment!reminders
2747 #+index: Appt!Zenity
2749 <a name="agenda-appt-zenity"></a>
2751 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It makes sure your agenda
2752 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2755 #+BEGIN_SRC emacs-lisp
2756 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2757 ; For org appointment reminders
2759 ;; Get appointments for today
2760 (defun my-org-agenda-to-appt ()
2762 (setq appt-time-msg-list nil)
2763 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
2764 (org-agenda-to-appt)))
2766 ;; Run once, activate and schedule refresh
2767 (my-org-agenda-to-appt)
2769 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2772 (setq appt-message-warning-time 15)
2773 (setq appt-display-interval 5)
2775 ; Update appt each time agenda opened.
2776 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2778 ; Setup zenify, we tell appt to use window, and replace default function
2779 (setq appt-display-format 'window)
2780 (setq appt-disp-window-function (function my-appt-disp-window))
2782 (defun my-appt-disp-window (min-to-app new-time msg)
2783 (save-window-excursion (shell-command (concat
2784 "/usr/bin/zenity --info --title='Appointment' --text='"
2785 msg "' &") nil nil)))
2788 ** Org-Mode + gnome-osd
2789 #+index: Appointment!reminders
2790 #+index: Appt!gnome-osd
2791 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2792 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2795 #+index: Agenda!Views
2796 #+index: Agenda!and Remind (external program)
2799 http://article.gmane.org/gmane.emacs.orgmode/5073
2802 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2803 command line calendaring program. Its features supersede the possibilities
2804 of orgmode in the area of date specifying, so that I want to use it
2805 combined with orgmode.
2807 Using the script below I'm able use remind and incorporate its output in my
2808 agenda views. The default of using 13 months look ahead is easily
2809 changed. It just happens I sometimes like to look a year into the
2813 ** Useful webjumps for conkeror
2814 #+index: Shortcuts!conkeror
2815 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2816 your =~/.conkerorrc= file:
2819 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2820 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2823 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2824 Org-mode mailing list.
2826 ** Use MathJax for HTML export without requiring JavaScript
2827 #+index: Export!MathJax
2828 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2830 If you like the results but do not want JavaScript in the exported pages,
2831 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2832 HTML file from the exported version. It can also embed all referenced fonts
2833 within the HTML file itself, so there are no dependencies to external files.
2835 The download archive contains an elisp file which integrates it into the Org
2836 export process (configurable per file with a "#+StaticMathJax:" line).
2838 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2839 ** Search Org files using lgrep
2840 #+index: search!lgrep
2841 Matt Lundin suggests this:
2843 #+begin_src emacs-lisp
2844 (defun my-org-grep (search &optional context)
2845 "Search for word in org files.
2847 Prefix argument determines number of lines."
2848 (interactive "sSearch for: \nP")
2849 (let ((grep-find-ignored-files '("#*" ".#*"))
2850 (grep-template (concat "grep <X> -i -nH "
2852 (concat "-C" (number-to-string context)))
2854 (lgrep search "*org*" "/home/matt/org/")))
2856 (global-set-key (kbd "<f8>") 'my-org-grep)
2859 ** Automatic screenshot insertion
2860 #+index: Link!screenshot
2861 Suggested by Russell Adams
2863 #+begin_src emacs-lisp
2864 (defun my-org-screenshot ()
2865 "Take a screenshot into a time stamped unique-named file in the
2866 same directory as the org-buffer and insert a link to this file."
2871 (concat (buffer-file-name)
2873 (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
2874 (call-process "import" nil nil nil filename)
2875 (insert (concat "[[" filename "]]"))
2876 (org-display-inline-images))
2879 ** Capture invitations/appointments from MS Exchange emails
2880 #+index: Appointment!MS Exchange
2881 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
2882 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
2884 ** Audio/video file playback within org mode
2885 #+index: Link!audio/video
2886 Paul Sexton provided code that makes =file:= links to audio or video files
2887 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
2888 media player library. The user can pause, skip forward and backward in the
2889 track, and so on from without leaving Emacs. Links can also contain a time
2890 after a double colon -- when this is present, playback will begin at that
2891 position in the track.
2893 See the file [[file:code/elisp/org-player.el][org-player.el]]
2895 ** Under X11 Keep a window with the current agenda items at all time
2896 #+index: Agenda!dedicated window
2897 I struggle to keep (in emacs) a window with the agenda at all times.
2898 For a long time I have wanted a sticky window that keeps this
2899 information, and then use my window manager to place it and remove its
2900 decorations (I can also force its placement in the stack: top always,
2903 I wrote a small program in qt that simply monitors an HTML file and
2904 displays it. Nothing more. It does the work for me, and maybe somebody
2905 else will find it useful. It relies on exporting the agenda as HTML
2906 every time the org file is saved, and then this little program
2907 displays the html file. The window manager is responsible of removing
2908 decorations, making it sticky, and placing it in same place always.
2910 Here is a screenshot (see window to the bottom right). The decorations
2911 are removed by the window manager:
2913 http://turingmachine.org/hacking/org-mode/orgdisplay.png
2915 Here is the code. As I said, very, very simple, but maybe somebody will
2918 http://turingmachine.org/hacking/org-mode/
2922 ** Script (thru procmail) to output emails to an Org file
2923 #+index: Conversion!email to org file
2924 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
2926 : I've [...] created some procmail and shell glue that takes emails and
2927 : inserts them into an org-file so that I can capture stuff on the go using
2928 : the email program.
2930 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
2932 ** Save File With Different Format for Headings (fileconversion)
2934 :CUSTOM_ID: fileconversion
2936 #+index: Conversion!fileconversion
2938 Using hooks and on the fly
2939 - when writing a buffer to the file replace the leading stars from headings
2941 - when reading a file into the buffer replace the file chars with leading
2944 To change to save an Org file in one of the formats or back just add or
2945 remove the keyword in the STARTUP line and save.
2947 Now you can also change to Fundamental mode to see how the file looks like
2948 on the level of the file, go back to Org mode, reenter Org mode or change to
2949 any other major mode and the conversion gets done whenever necessary.
2951 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
2953 :CUSTOM_ID: hidestarsfile
2955 #+index: Conversion!fileconversion hidestarsfile
2957 This is like "a cleaner outline view":
2958 http://orgmode.org/manual/Clean-view.html
2960 Example of the _file content_ first with leading stars as usual and below
2961 without leading stars through "#+STARTUP: odd hidestars hidestarsfile":
2964 #+STARTUP: odd hidestars
2976 #+STARTUP: odd hidestars hidestarsfile
2987 The latter is convenient for better human readability when an Org file,
2988 additionally to Emacs, is read with a file viewer or, for smaller edits,
2989 with an editor not capable of the Org file format.
2991 hidestarsfile is a hack and can not become part of the Org core:
2992 - An Org file with hidestarsfile can not contain list items with a star as
2993 bullet due to the syntax conflict at read time. Mark E. Shoulson suggested
2994 to use the non-breaking space which is now implemented in fileconversion
2995 as nbspstarsfile as an alternative for hidestarsfile. Although I don't
2996 recommend it because an editor like typically e. g. Emacs may render the
2997 non-breaking space differently from the space 0x20.
2998 - An Org file with hidestarsfile can almost not be edited with an Org mode
2999 without added functionality of hidestarsfile as long as the file is not
3002 *** Headings in Markdown Format (markdownstarsfile)
3004 :CUSTOM_ID: markdownstarsfile
3006 #+index: Conversion!fileconversion markdownstarsfile
3008 For "oddeven" you can use markdownstarsfile to be readable or even basically
3009 editable with Markdown (does not make much sense with "odd", see
3010 org-convert-to-odd-levels and org-convert-to-oddeven-levels for how to
3013 Example of the _file content_:
3016 #+STARTUP: oddeven markdownstarsfile
3018 1. first item of numbered list (same format in Org and Markdown)
3020 - first item of unordered list (same format in Org and Markdown)
3022 + first item of unordered list (same format in Org and Markdown)
3023 #### section level 4
3024 * first item of unordered list (same format in Org and Markdown)
3025 * avoid this item type to be compatible with Org hidestarsfile
3028 An Org file with markdownstarsfile can not contain code comment lines
3029 prefixed with "#", even not when within source blocks.
3033 :CUSTOM_ID: fileconversion-code
3035 #+index: Conversion!fileconversion emacs-lisp code
3037 #+BEGIN_SRC emacs-lisp
3038 ;; - fileconversion version 0.6
3039 ;; - DISCLAIMER: Make a backup of your Org files before using
3040 ;; my-org-fileconv-*.
3041 ;; - supported formats: hidestarsfile, markdownstarsfile
3043 ;; design summary: fileconversion is a round robin of two states
3044 ;; linked by two actions:
3045 ;; - state my-org-fileconv-level-org-p is nil: the level is "file"
3047 ;; - action my-org-fileconv-decode: replace file char with '*'
3048 ;; - state my-org-fileconv-level-org-p is t: the level is "Org"
3050 ;; - action my-org-fileconv-encode replace '*' with file char
3052 (defvar my-org-fileconv-level-org-p nil
3053 "Whether level of buffer is Org or only file.
3054 nil means the level is file (encoded), non-nil means the level is Org
3056 (make-variable-buffer-local 'my-org-fileconv-level-org-p)
3057 ;; survive a change of major mode that does kill-all-local-variables,
3058 ;; e. g. when reentering Org mode through “C-c C-c” on a STARTUP line
3059 (put 'my-org-fileconv-level-org-p 'permanent-local t)
3061 (add-hook 'org-mode-hook 'my-org-fileconv-init
3062 ;; _append_ to hook to have a higher chance that a message
3063 ;; from this function will be visible as the last message in
3066 ;; hook addition global
3069 (defun my-org-fileconv-init ()
3071 ;; instrument only when converting really from/to an Org _file_, not
3072 ;; e. g. for a temp Org buffer unrelated to a file like used e. g.
3073 ;; when calling the old Org exporter
3074 (when (buffer-file-name)
3075 (message "INF: my-org-fileconv-init, buffer: %s" (buffer-name))
3076 (my-org-fileconv-decode)
3077 ;; the hooks are not permanent-local, this way and as needed they
3078 ;; will disappear when the major mode of the buffer changes
3079 (add-hook 'change-major-mode-hook 'my-org-fileconv-encode nil
3080 ;; hook addition limited to buffer locally
3082 (add-hook 'before-save-hook 'my-org-fileconv-encode nil
3083 ;; hook addition limited to buffer locally
3085 (add-hook 'after-save-hook 'my-org-fileconv-decode nil
3086 ;; hook addition limited to buffer locally
3089 (defun my-org-fileconv-re ()
3090 "Check whether there is a STARTUP line for fileconversion.
3091 If found then return the expressions required for the conversion."
3093 (beginning-of-buffer)
3094 (let (re-list (count 0))
3095 (while (re-search-forward "^#\\+STARTUP:" nil t)
3096 ;; #+STARTUP: hidestarsfile
3097 (when (string-match-p "\\bhidestarsfile\\b"
3098 (thing-at-point 'line))
3100 ;; - line starting with star for bold emphasis
3101 ;; - line of stars to underline section title in loosely
3102 ;; quoted ASCII style (star at end of line)
3103 (setq re-list '("\\(\\* \\)" ; common-re
3105 (setq count (1+ count)))
3106 ;; #+STARTUP: nbspstarsfile
3107 (when (string-match-p "\\bnbspstarsfile\\b"
3108 (thing-at-point 'line))
3109 (setq re-list '("\\(\\* \\)" ; common-re
3110 ?\xa0)) ; file-char non-breaking space
3111 (setq count (1+ count)))
3112 ;; #+STARTUP: markdownstarsfile
3113 (when (string-match-p "\\bmarkdownstarsfile\\b"
3114 (thing-at-point 'line))
3117 (setq re-list '("\\( \\)" ; common-re
3119 (setq count (1+ count))))
3121 (error "ERR: more than one fileconversion found"))
3124 (defun my-org-fileconv-decode ()
3125 "In headings replace file char with '*'."
3126 (let ((re-list (my-org-fileconv-re)))
3127 (when (and re-list (not my-org-fileconv-level-org-p))
3128 ;; no `save-excursion' to be able to keep point in case of error
3129 (let* ((common-re (nth 0 re-list))
3130 (file-char (nth 1 re-list))
3131 (file-re (concat "^" (string file-char) "+" common-re))
3132 (org-re (concat "^\\*+" common-re))
3135 (beginning-of-buffer)
3137 (when (re-search-forward org-re nil t)
3138 (goto-char (match-beginning 0))
3141 "ERR: my-org-fileconv-decode syntax conflict at point"))
3142 (beginning-of-buffer)
3144 (with-silent-modifications
3145 (while (re-search-forward file-re nil t)
3146 (goto-char (match-beginning 0))
3147 ;; faster than a lisp call of insert and delete on each
3149 (setq len (- (match-beginning 1) (match-beginning 0)))
3150 (insert-char ?* len)
3154 ;; notes for ediff when only one file has fileconversion:
3155 ;; - The changes to the buffer with fileconversion until here
3156 ;; are not regarded by ediff-files because the first call to
3157 ;; diff is made with the bare files directly. Only
3158 ;; ediff-update-diffs and ediff-buffers write the decoded
3159 ;; buffers to temp files and then call diff with them.
3160 ;; - Workarounds (choose one):
3161 ;; - after ediff-files first do a "!" (ediff-update-diffs)
3162 ;; in the "*Ediff Control Panel*"
3163 ;; - instead of using ediff-files first open the files and
3164 ;; then run ediff-buffers (better for e. g. a script that
3165 ;; takes two files as arguments and uses "emacs --eval")
3167 ;; the level is Org most of all when no fileconversion is in effect
3168 (setq my-org-fileconv-level-org-p t))
3170 (defun my-org-fileconv-encode ()
3171 "In headings replace '*' with file char."
3172 (let ((re-list (my-org-fileconv-re)))
3173 (when (and re-list my-org-fileconv-level-org-p)
3174 ;; no `save-excursion' to be able to keep point in case of error
3175 (let* ((common-re (nth 0 re-list))
3176 (file-char (nth 1 re-list))
3177 (file-re (concat "^" (string file-char) "+" common-re))
3178 (org-re (concat "^\\*+" common-re))
3181 (beginning-of-buffer)
3183 (when (re-search-forward file-re nil t)
3184 (goto-char (match-beginning 0))
3187 "ERR: my-org-fileconv-encode syntax conflict at point"))
3188 (beginning-of-buffer)
3190 (with-silent-modifications
3191 (while (re-search-forward org-re nil t)
3192 (goto-char (match-beginning 0))
3193 ;; faster than a lisp call of insert and delete on each
3195 (setq len (- (match-beginning 1) (match-beginning 0)))
3196 (insert-char file-char len)
3199 (setq my-org-fileconv-level-org-p nil))))
3200 nil) ;; for the hook
3205 ** Meaningful diff for org files in a git repository
3206 #+index: git!diff org files
3207 Since most diff utilities are primarily meant for source code, it is
3208 difficult to read diffs of text files like ~.org~ files easily. If you
3209 version your org directory with a SCM like git you will know what I
3210 mean. However for git, there is a way around. You can use
3211 =gitattributes= to define a custom diff driver for org files. Then a
3212 regular expression can be used to configure how the diff driver
3213 recognises a "function".
3215 Put the following in your =<org_dir>/.gitattributes=.
3217 Then put the following lines in =<org_dir>/.git/config=
3219 : xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3221 This will let you see diffs for org files with each hunk identified by
3222 the unmodified headline closest to the changes. After the
3223 configuration a diff should look something like the example below.
3226 diff --git a/org-hacks.org b/org-hacks.org
3227 index a0672ea..92a08f7 100644
3230 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3232 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3234 +** Meaningful diff for org files in a git repository
3236 +Since most diff utilities are primarily meant for source code, it is
3237 +difficult to read diffs of text files like ~.org~ files easily. If you
3238 +version your org directory with a SCM like git you will know what I
3239 +mean. However for git, there is a way around. You can use
3240 +=gitattributes= to define a custom diff driver for org files. Then a
3241 +regular expression can be used to configure how the diff driver
3242 +recognises a "function".
3244 +Put the following in your =<org_dir>/.gitattributes=.
3246 +Then put the following lines in =<org_dir>/.git/config=
3248 +: xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3252 ** Cooking? Brewing?
3255 ** Opening devonthink links
3257 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3258 links from org-mode.
3262 ** Cooking? Brewing?
3263 #+index: beer!brewing
3264 #+index: cooking!conversions
3265 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3267 It currently does metric/english conversion, and a few other tricks.
3268 Basically I just use calc’s units code. I think scaling recipes, or
3269 turning percentages into weights would be pretty easy.
3271 https://gitorious.org/org-cook/org-cook
3273 There is also, for those interested:
3275 https://gitorious.org/org-brew/org-brew
3277 for brewing beer. This is again, mostly just calc functions, including
3278 hydrometer correction, abv calculation, priming sugar for a given CO_2
3279 volume, etc. More integration with org-mode should be possible: for
3280 instance it would be nice to be able to use a lookup table (of ingredients)
3281 to calculate target original gravity, IBUs, etc.