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."))))))
532 *** Sorting list by checkbox type
534 #+index: checkbox!sorting
536 You can use a custom function to sort list by checkbox type. Here is a
537 function suggested by Carsten:
539 #+BEGIN_SRC emacs-lisp
540 (defun org-sort-list-by-checkbox-type ()
541 "Sort list items according to Checkbox state."
546 (if (looking-at org-list-full-item-re)
547 (cdr (assoc (match-string 3)
548 '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
553 *** Align all tables in a file
555 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
557 #+begin_src emacs-lisp
558 (defun my-align-all-tables ()
560 (org-table-map-tables 'org-table-align 'quietly))
564 #+index: Table!Calculation
566 :CUSTOM_ID: transpose-table
569 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
570 see.) There are also other solutions:
572 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
573 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]]
575 - with org-babel and R: provided by Dan Davison in the mailing list (old
576 =#+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]]
578 - with field coordinates in formulas (=@#= and =$#=): see [[file:org-hacks.org::#field-coordinates-in-formulas-transpose-table][Worg]].
580 *** Manipulate hours/minutes/seconds in table formulas
581 #+index: Table!hours-minutes-seconds
582 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
583 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
584 "=d=" is any digit) as time values in Org-mode table formula. These
585 functions have now been wrapped up into a =with-time= macro which can
586 be used in table formula to translate table cell values to and from
587 numerical values for algebraic manipulation.
589 Here is the code implementing this macro.
590 #+begin_src emacs-lisp :results silent
591 (defun org-time-string-to-seconds (s)
592 "Convert a string HH:MM:SS to a number of seconds."
595 (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
596 (let ((hour (string-to-number (match-string 1 s)))
597 (min (string-to-number (match-string 2 s)))
598 (sec (string-to-number (match-string 3 s))))
599 (+ (* hour 3600) (* min 60) sec)))
601 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
602 (let ((min (string-to-number (match-string 1 s)))
603 (sec (string-to-number (match-string 2 s))))
605 ((stringp s) (string-to-number s))
608 (defun org-time-seconds-to-string (secs)
609 "Convert a number of seconds to a time string."
610 (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
611 ((>= secs 60) (format-seconds "%m:%.2s" secs))
612 (t (format-seconds "%s" secs))))
614 (defmacro with-time (time-output-p &rest exprs)
615 "Evaluate an org-table formula, converting all fields that look
616 like time data to integer seconds. If TIME-OUTPUT-P then return
617 the result as a time value."
619 (if time-output-p 'org-time-seconds-to-string 'identity)
627 (list 'with-time nil el)
628 (org-time-string-to-seconds el)))
633 Which allows the following forms of table manipulation such as adding
634 and subtracting time values.
635 : | Date | Start | Lunch | Back | End | Sum |
636 : |------------------+-------+-------+-------+-------+------|
637 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
638 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
640 and dividing time values by integers
641 : | time | miles | minutes/mile |
642 : |-------+-------+--------------|
643 : | 34:43 | 2.9 | 11:58 |
644 : | 32:15 | 2.77 | 11:38 |
645 : | 33:56 | 3.0 | 11:18 |
646 : | 52:22 | 4.62 | 11:20 |
647 : #+TBLFM: $3='(with-time t (/ $1 $2))
649 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
650 Elisp formulas) to compute time durations. For example:
652 : | Task 1 | Task 2 | Total |
653 : |--------+--------+---------|
654 : | 35:00 | 35:00 | 1:10:00 |
655 : #+TBLFM: @2$3=$1+$2;T
657 *** Dates computation
659 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of
660 dates stored in an org table.
662 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
666 | Start Date | End Date | Duration |
667 |------------+------------+----------|
668 | 2004.08.07 | 2005.07.08 | 335 |
669 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
671 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
672 above). The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
673 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
676 #+index: Table!Calculation
677 As with Times computation, the following code allows Computation with
678 Hex values in Org-mode tables using the =with-hex= macro.
680 Here is the code implementing this macro.
681 #+begin_src emacs-lisp
682 (defun org-hex-strip-lead (str)
683 (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
684 (substring str 2) str))
686 (defun org-hex-to-hex (int)
689 (defun org-hex-to-dec (str)
692 (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
696 (setf out (+ (* out 16)
697 (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
698 (coerce (match-string 1 str) 'list))
700 ((stringp str) (string-to-number str))
703 (defmacro with-hex (hex-output-p &rest exprs)
704 "Evaluate an org-table formula, converting all fields that look
705 like hexadecimal to decimal integers. If HEX-OUTPUT-P then
706 return the result as a hex value."
708 (if hex-output-p 'org-hex-to-hex 'identity)
715 (list 'with-hex nil el)
716 (org-hex-to-dec el)))
721 Which allows the following forms of table manipulation such as adding
722 and subtracting hex values.
723 | 0x10 | 0x0 | 0x10 | 16 |
724 | 0x20 | 0x1 | 0x21 | 33 |
725 | 0x30 | 0x2 | 0x32 | 50 |
726 | 0xf0 | 0xf | 0xff | 255 |
727 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
729 *** Field coordinates in formulas (=@#= and =$#=)
731 :CUSTOM_ID: field-coordinates-in-formulas
733 #+index: Table!Field Coordinates
736 Following are some use cases that can be implemented with the “field
737 coordinates in formulas” described in the corresponding chapter in the
738 [[http://orgmode.org/manual/References.html#References][Org manual]].
740 **** Copy a column from a remote table into a column
742 :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
745 current column =$3= = remote column =$2=:
746 : #+TBLFM: $3 = remote(FOO, @@#$2)
748 **** Copy a row from a remote table transposed into a column
750 :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
753 current column =$1= = transposed remote row =@1=:
754 : #+TBLFM: $1 = remote(FOO, @$#$@#)
758 :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
763 This is more like a demonstration of using “field coordinates in formulas”
764 and is bound to be slow for large tables. See the discussion in the mailing
766 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
767 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
768 For more efficient solutions see
769 [[file:org-hacks.org::#transpose-table][Worg]].
771 To transpose this 4x7 table
774 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
775 : |------+------+------+------+------+------+------|
776 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
777 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
778 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
780 start with a 7x4 table without any horizontal line (to have filled
781 also the column header) and yet empty:
791 Then add the =TBLFM= line below. After recalculation this will end up with
794 : | year | min | avg | max |
795 : | 2004 | 401 | 402 | 403 |
796 : | 2005 | 501 | 502 | 503 |
797 : | 2006 | 601 | 602 | 603 |
798 : | 2007 | 701 | 702 | 703 |
799 : | 2008 | 801 | 802 | 803 |
800 : | 2009 | 901 | 902 | 903 |
801 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
803 The formula simply exchanges row and column numbers by taking
804 - the absolute remote row number =@$#= from the current column number =$#=
805 - the absolute remote column number =$@#= from the current row number =@#=
807 Formulas to be taken over from the remote table will have to be transformed
810 **** Dynamic variation of ranges
814 In this example all columns next to =quote= are calculated from the column
815 =quote= and show the average change of the time series =quote[year]=
816 during the period of the preceding =1=, =2=, =3= or =4= years:
818 : | year | quote | 1 a | 2 a | 3 a | 4 a |
819 : |------+-------+-------+-------+-------+-------|
820 : | 2005 | 10 | | | | |
821 : | 2006 | 12 | 0.200 | | | |
822 : | 2007 | 14 | 0.167 | 0.183 | | |
823 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
824 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
825 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
827 The important part of the formula without the field blanking is:
829 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
831 which is the Emacs Calc implementation of the equation
833 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
835 where /i/ is the current time and /a/ is the length of the preceding period.
837 *** Change the column sequence in one row only
838 #+index: Table!Editing
840 :CUSTOM_ID: column-sequence-in-row
845 The functions below can be used to change the column sequence in one row
846 only, without affecting the other rows above and below like with M-<left> or
847 M-<right> (org-table-move-column). Please see the docstring of the functions
848 for more explanations. Below is one example per function, with this original
849 table as the starting point for each example:
851 : | e | 9 | 10 | 11 |
854 **** Move in row left
856 1) place point at "10" in original table
857 2) result of M-x my-org-table-move-column-in-row-left:
859 : | e | 10 | 9 | 11 |
862 **** Move in row right
864 1) place point at "9" in original table
865 2) result of M-x my-org-table-move-column-in-row-right:
867 : | e | 10 | 9 | 11 |
870 **** Rotate in row left
872 1) place point at "9" in original table
873 2) result of M-x my-org-table-rotate-column-in-row-left:
875 : | e | 10 | 11 | 9 |
878 **** Rotate in row right
880 1) place point at "9" in original table
881 2) result of M-x my-org-table-rotate-column-in-row-right:
883 : | e | 11 | 9 | 10 |
888 #+BEGIN_SRC emacs-lisp
889 (defun my-org-table-move-column-in-row-right ()
890 "Move column to the right, limited to the current row."
892 (my-org-table-move-column-in-row nil))
893 (defun my-org-table-move-column-in-row-left ()
894 "Move column to the left, limited to the current row."
896 (my-org-table-move-column-in-row 'left))
898 (defun my-org-table-move-column-in-row (&optional left)
899 "Move the current column to the right, limited to the current row.
900 With arg LEFT, move to the left. For repeated invocation the point follows
901 the value and changes to the target colum. Does not fix formulas."
902 ;; derived from `org-table-move-column'
904 (if (not (org-at-table-p))
905 (error "Not at a table"))
906 (org-table-find-dataline)
907 (org-table-check-inside-data-field)
908 (let* ((col (org-table-current-column))
909 (col1 (if left (1- col) col))
910 ;; Current cursor position
911 (colpos (if left (1- col) (1+ col))))
912 (if (and left (= col 1))
913 (error "Cannot move column further left"))
914 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
915 (error "Cannot move column further right"))
916 (org-table-goto-column col1 t)
917 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
918 (replace-match "|\\2|\\1|"))
919 (org-table-goto-column colpos)
922 (defun my-org-table-rotate-column-in-row-right ()
923 "Rotate column to the right, limited to the current row."
925 (my-org-table-rotate-column-in-row nil))
926 (defun my-org-table-rotate-column-in-row-left ()
927 "Rotate column to the left, limited to the current row."
929 (my-org-table-rotate-column-in-row 'left))
931 (defun my-org-table-rotate-column-in-row (&optional left)
932 "Rotate the current column to the right, limited to the current row.
933 With arg LEFT, rotate to the left. The boundaries of the rotation range are
934 the current and the most right column for both directions. For repeated
935 invocation the point stays on the current column. Does not fix formulas."
936 ;; derived from `org-table-move-column'
938 (if (not (org-at-table-p))
939 (error "Not at a table"))
940 (org-table-find-dataline)
941 (org-table-check-inside-data-field)
942 (let ((col (org-table-current-column)))
943 (org-table-goto-column col t)
944 (and (looking-at (if left
945 "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
946 "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
947 (replace-match "|\\2|\\1|"))
948 (org-table-goto-column col)
954 As hack I have this in an Org buffer to change temporarily to the desired
955 behavior with C-c C-c on one of the three snippets:
957 : #+begin_src emacs-lisp :results silent
958 : (org-defkey org-mode-map [(meta left)]
959 : 'my-org-table-move-column-in-row-left)
960 : (org-defkey org-mode-map [(meta right)]
961 : 'my-org-table-move-column-in-row-right)
962 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
963 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
967 : #+begin_src emacs-lisp :results silent
968 : (org-defkey org-mode-map [(meta left)]
969 : 'my-org-table-rotate-column-in-row-left)
970 : (org-defkey org-mode-map [(meta right)]
971 : 'my-org-table-rotate-column-in-row-right)
972 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
973 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
976 : - back to original:
977 : #+begin_src emacs-lisp :results silent
978 : (org-defkey org-mode-map [(meta left)] 'org-metaleft)
979 : (org-defkey org-mode-map [(meta right)] 'org-metaright)
980 : (org-defkey org-mode-map [(left)] 'backward-char)
981 : (org-defkey org-mode-map [(right)] 'forward-char)
984 **** reasons why this is not put into the Org core
986 I consider this as only a hack for several reasons:
987 - Generalization: The existing org-table-move-column function could be
988 enhanced with additional optional parameters to incorporate these
989 functionalities and could be used as the only function for better
990 maintainability. Now it's only a copy/paste hack of several similar
991 functions with simple modifications.
992 - Bindings: Should be convenient for repetition like M-<right>. What
993 should be bound where, what has to be left unbound?
994 - Does not fix formulas. Could be resolved for field formulas but
995 most probably not for column or range formulas and this can lead
996 to confusion. AFAIK all "official" table manipulations fix formulas.
997 - Completeness: Not all variations and combinations are covered yet
998 - left-right, up-down
999 - move, rotate with range to end, rotate with range to begin
1000 - whole column/row, only in-row/in-column
1002 ** Capture and Remember
1003 *** Customize the size of the frame for remember
1004 #+index: Remember!frame
1005 #+index: Customization!remember
1006 (Note: this hack is likely out of date due to the development of
1010 On emacs-orgmode, Ryan C. Thompson suggested this:
1013 I am using org-remember set to open a new frame when used,
1014 and the default frame size is much too large. To fix this, I have
1015 designed some advice and a custom variable to implement custom
1016 parameters for the remember frame:
1019 #+begin_src emacs-lisp
1020 (defcustom remember-frame-alist nil
1021 "Additional frame parameters for dedicated remember frame."
1025 (defadvice remember (around remember-frame-parameters activate)
1026 "Set some frame parameters for the remember frame."
1027 (let ((default-frame-alist (append remember-frame-alist
1028 default-frame-alist)))
1032 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1033 reasonable size for the frame.
1035 *** [[#heading-to-link][Turn a heading into an org link]]
1036 *** Quickaccess to the link part of hyperlinks
1037 #+index: Link!Referent
1038 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1039 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1040 which is indeed kind of cumbersome.
1042 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1044 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1045 #+begin_src emacs-lisp
1047 (lambda (&optional arg)
1050 (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1054 #+begin_src emacs-lisp
1055 (defun my-org-extract-link ()
1056 "Extract the link location at point and put it on the killring."
1058 (when (org-in-regexp org-bracket-link-regexp 1)
1059 (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1062 They put the link destination on the killring and can be easily bound to a key.
1064 *** Insert link with HTML title as default description
1065 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1066 from HTML <title> tag and use it as a default link description. Here is a way to
1069 #+begin_src emacs-lisp
1070 (require 'mm-url) ; to include mm-url-decode-entities-string
1072 (defun my-org-insert-link ()
1073 "Insert org link where default description is set to html title."
1075 (let* ((url (read-string "URL: "))
1076 (title (get-html-title-from-url url)))
1077 (org-insert-link nil url title)))
1079 (defun get-html-title-from-url (url)
1080 "Return content in <title> tag."
1081 (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1083 (set-buffer download-buffer)
1084 (beginning-of-buffer)
1085 (setq x1 (search-forward "<title>"))
1086 (search-forward "</title>")
1087 (setq x2 (search-backward "<"))
1088 (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1091 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1093 ** Archiving Content in Org-Mode
1094 *** Preserve top level headings when archiving to a file
1095 #+index: Archiving!Preserve top level headings
1098 To preserve (somewhat) the integrity of your archive structure while
1099 archiving lower level items to a file, you can use the following
1102 #+begin_src emacs-lisp
1103 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1104 (let ((org-archive-location
1105 (if (save-excursion (org-back-to-heading)
1106 (> (org-outline-level) 1))
1107 (concat (car (split-string org-archive-location "::"))
1109 (car (org-get-outline-path)))
1110 org-archive-location)))
1114 Thus, if you have an outline structure such as...
1122 ...archiving "Subsubheading" to a new file will set the location in
1123 the new file to the top level heading:
1130 While this hack obviously destroys the outline hierarchy somewhat, it
1131 at least preserves the logic of level one groupings.
1133 A slightly more complex version of this hack will not only keep the
1134 archive organized by top-level headings, but will also preserve the
1135 tags found on those headings:
1137 #+begin_src emacs-lisp
1138 (defun my-org-inherited-no-file-tags ()
1139 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1140 (ltags (org-entry-get nil "TAGS")))
1143 (replace-regexp-in-string (concat tag ":") "" tags)))
1144 (append org-file-tags (when ltags (split-string ltags ":" t))))
1145 (if (string= ":" tags) nil tags)))
1147 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1148 (let ((tags (my-org-inherited-no-file-tags))
1149 (org-archive-location
1150 (if (save-excursion (org-back-to-heading)
1151 (> (org-outline-level) 1))
1152 (concat (car (split-string org-archive-location "::"))
1154 (car (org-get-outline-path)))
1155 org-archive-location)))
1157 (with-current-buffer (find-file-noselect (org-extract-archive-file))
1159 (while (org-up-heading-safe))
1160 (org-set-tags-to tags)))))
1163 *** Archive in a date tree
1164 #+index: Archiving!date tree
1165 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1167 (Make sure org-datetree.el is loaded for this to work.)
1169 #+begin_src emacs-lisp
1170 ;; (setq org-archive-location "%s_archive::date-tree")
1171 (defadvice org-archive-subtree
1172 (around org-archive-subtree-to-data-tree activate)
1173 "org-archive-subtree to date-tree"
1175 (string= "date-tree"
1176 (org-extract-archive-heading
1177 (org-get-local-archive-location)))
1178 (let* ((dct (decode-time (org-current-time)))
1182 (this-buffer (current-buffer))
1183 (location (org-get-local-archive-location))
1184 (afile (org-extract-archive-file location))
1185 (org-archive-location
1186 (format "%s::*** %04d-%02d-%02d %s" afile y m d
1187 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1188 (message "afile=%s" afile)
1190 (error "Invalid `org-archive-location'"))
1192 (switch-to-buffer (find-file-noselect afile))
1193 (org-datetree-find-year-create y)
1194 (org-datetree-find-month-create y m)
1195 (org-datetree-find-day-create y m d)
1197 (switch-to-buffer this-buffer))
1202 *** Add inherited tags to archived entries
1203 #+index: Archiving!Add inherited tags
1204 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1205 advise the function like this:
1208 (defadvice org-archive-subtree
1209 (before add-inherited-tags-before-org-archive-subtree activate)
1210 "add inherited tags before org-archive-subtree"
1211 (org-set-tags-to (org-get-tags-at)))
1214 ** Using and Managing Org-Metadata
1215 *** Remove redundant tags of headlines
1216 #+index: Tag!Remove redundant
1219 A small function that processes all headlines in current buffer and
1220 removes tags that are local to a headline and inherited by a parent
1221 headline or the #+FILETAGS: statement.
1223 #+BEGIN_SRC emacs-lisp
1224 (defun dmj/org-remove-redundant-tags ()
1225 "Remove redundant tags of headlines in current buffer.
1227 A tag is considered redundant if it is local to a headline and
1228 inherited by a parent headline."
1230 (when (eq major-mode 'org-mode)
1234 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1235 local inherited tag)
1236 (dolist (tag alltags)
1237 (if (get-text-property 0 'inherited tag)
1238 (push tag inherited) (push tag local)))
1240 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1244 *** Remove empty property drawers
1245 #+index: Drawer!Empty
1246 David Maus proposed this:
1248 #+begin_src emacs-lisp
1249 (defun dmj:org:remove-empty-propert-drawers ()
1250 "*Remove all empty property drawers in current file."
1252 (unless (eq major-mode 'org-mode)
1253 (error "You need to turn on Org mode for this function."))
1255 (goto-char (point-min))
1256 (while (re-search-forward ":PROPERTIES:" nil t)
1258 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1261 *** Group task list by a property
1262 #+index: Agenda!Group task list
1263 This advice allows you to group a task list in Org-Mode. To use it,
1264 set the variable =org-agenda-group-by-property= to the name of a
1265 property in the option list for a TODO or TAGS search. The resulting
1266 agenda view will group tasks by that property prior to searching.
1268 #+begin_src emacs-lisp
1269 (defvar org-agenda-group-by-property nil
1270 "Set this in org-mode agenda views to group tasks by property")
1272 (defun org-group-bucket-items (prop items)
1274 (dolist (item items)
1275 (let* ((marker (get-text-property 0 'org-marker item))
1276 (pvalue (org-entry-get marker prop t))
1277 (cell (assoc pvalue buckets)))
1279 (setcdr cell (cons item (cdr cell)))
1280 (setq buckets (cons (cons pvalue (list item))
1282 (setq buckets (mapcar (lambda (bucket)
1284 (reverse (cdr bucket))))
1286 (sort buckets (lambda (i1 i2)
1287 (string< (car i1) (car i2))))))
1289 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1290 (list &optional nosort))
1291 "Prepare bucketed agenda entry lists"
1292 (if org-agenda-group-by-property
1293 ;; bucketed, handle appropriately
1295 (dolist (bucket (org-group-bucket-items
1296 org-agenda-group-by-property
1298 (let ((header (concat "Property "
1299 org-agenda-group-by-property
1301 (or (car bucket) "<nil>") ":\n")))
1302 (add-text-properties 0 (1- (length header))
1303 (list 'face 'org-agenda-structure)
1307 ;; recursively process
1308 (let ((org-agenda-group-by-property nil))
1309 (org-finalize-agenda-entries
1310 (cdr bucket) nosort))
1312 (setq ad-return-value text))
1314 (ad-activate 'org-finalize-agenda-entries)
1316 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1319 Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1321 A small hook run when clocking out of a task that prompts for a note
1322 when the tag "=clockout_note=" is found in a headline. It uses the tag
1323 ("=clockout_note=") so inheritance can also be used...
1325 #+begin_src emacs-lisp
1326 (defun rgr/check-for-clock-out-note()
1329 (org-back-to-heading)
1330 (let ((tags (org-get-tags)))
1331 (and tags (message "tags: %s " tags)
1332 (when (member "clocknote" tags)
1335 (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1337 *** Dynamically adjust tag position
1338 #+index: Tag!position
1339 Here is a bit of code that allows you to have the tags always
1340 right-adjusted in the buffer.
1342 This is useful when you have bigger window than default window-size
1343 and you dislike the aesthetics of having the tag in the middle of the
1346 This hack solves the problem of adjusting it whenever you change the
1348 Before saving it will revert the file to having the tag position be
1349 left-adjusted so that if you track your files with version control,
1350 you won't run into artificial diffs just because the window-size
1353 *IMPORTANT*: This is probably slow on very big files.
1355 #+begin_src emacs-lisp
1356 (setq ba/org-adjust-tags-column t)
1358 (defun ba/org-adjust-tags-column-reset-tags ()
1359 "In org-mode buffers it will reset tag position according to
1362 (not (string= (buffer-name) "*Remember*"))
1363 (eql major-mode 'org-mode))
1364 (let ((b-m-p (buffer-modified-p)))
1367 (goto-char (point-min))
1368 (command-execute 'outline-next-visible-heading)
1369 ;; disable (message) that org-set-tags generates
1370 (flet ((message (&rest ignored) nil))
1372 (set-buffer-modified-p b-m-p))
1375 (defun ba/org-adjust-tags-column-now ()
1376 "Right-adjust `org-tags-column' value, then reset tag position."
1377 (set (make-local-variable 'org-tags-column)
1378 (- (- (window-width) (length org-ellipsis))))
1379 (ba/org-adjust-tags-column-reset-tags))
1381 (defun ba/org-adjust-tags-column-maybe ()
1382 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1383 (when ba/org-adjust-tags-column
1384 (ba/org-adjust-tags-column-now)))
1386 (defun ba/org-adjust-tags-column-before-save ()
1387 "Tags need to be left-adjusted when saving."
1388 (when ba/org-adjust-tags-column
1389 (setq org-tags-column 1)
1390 (ba/org-adjust-tags-column-reset-tags)))
1392 (defun ba/org-adjust-tags-column-after-save ()
1393 "Revert left-adjusted tag position done by before-save hook."
1394 (ba/org-adjust-tags-column-maybe)
1395 (set-buffer-modified-p nil))
1397 ; automatically align tags on right-hand side
1398 (add-hook 'window-configuration-change-hook
1399 'ba/org-adjust-tags-column-maybe)
1400 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1401 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1402 (add-hook 'org-agenda-mode-hook '(lambda ()
1403 (setq org-agenda-tags-column (- (window-width)))))
1405 ; between invoking org-refile and displaying the prompt (which
1406 ; triggers window-configuration-change-hook) tags might adjust,
1407 ; which invalidates the org-refile cache
1408 (defadvice org-refile (around org-refile-disable-adjust-tags)
1409 "Disable dynamically adjusting tags"
1410 (let ((ba/org-adjust-tags-column nil))
1412 (ad-activate 'org-refile)
1414 *** Use an "attach" link type to open files without worrying about their location
1415 #+index: Link!Attach
1416 -- Darlan Cavalcante Moreira
1418 In the setup part in my org-files I put:
1421 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1424 Now I can use the "attach" link type, but org will ask me if I want to
1425 allow executing the elisp code. To avoid this you can even set
1426 org-confirm-elisp-link-function to nil (I don't like this because it allows
1427 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1432 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1434 This works very well.
1436 ** Org Agenda and Task Management
1437 *** Make it easier to set org-agenda-files from multiple directories
1438 #+index: Agenda!Files
1441 #+begin_src emacs-lisp
1442 (defun my-org-list-files (dirs ext)
1443 "Function to create list of org files in multiple subdirectories.
1444 This can be called to generate a list of files for
1445 org-agenda-files or org-refile-targets.
1447 DIRS is a list of directories.
1449 EXT is a list of the extensions of files to be included."
1450 (let ((dirs (if (listp dirs)
1453 (ext (if (listp ext)
1463 (file-expand-wildcards
1464 (concat (file-name-as-directory x) "*" y)))))
1469 (when (or (string-match "/.#" x)
1470 (string-match "#$" x))
1471 (setq files (delete x files))))
1475 (defvar my-org-agenda-directories '("~/org/")
1476 "List of directories containing org files.")
1477 (defvar my-org-agenda-extensions '(".org")
1478 "List of extensions of agenda files")
1480 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1481 (setq my-org-agenda-extensions '(".org" ".ref"))
1483 (defun my-org-set-agenda-files ()
1485 (setq org-agenda-files (my-org-list-files
1486 my-org-agenda-directories
1487 my-org-agenda-extensions)))
1489 (my-org-set-agenda-files)
1492 The code above will set your "default" agenda files to all files
1493 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1494 You can change these values by setting the variables
1495 my-org-agenda-extensions and my-org-agenda-directories. The function
1496 my-org-agenda-files-by-filetag uses these two variables to determine
1497 which files to search for filetags (i.e., the larger set from which
1498 the subset will be drawn).
1500 You can also easily use my-org-list-files to "mix and match"
1501 directories and extensions to generate different lists of agenda
1504 *** Restrict org-agenda-files by filetag
1505 #+index: Agenda!Files
1507 :CUSTOM_ID: set-agenda-files-by-filetag
1511 It is often helpful to limit yourself to a subset of your agenda
1512 files. For instance, at work, you might want to see only files related
1513 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1514 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
1515 commands]]. These solutions, however, require reapplying a filter each
1516 time you call the agenda or writing several new custom agenda commands
1517 for each context. Another solution is to use directories for different
1518 types of tasks and to change your agenda files with a function that
1519 sets org-agenda-files to the appropriate directory. But this relies on
1520 hard and static boundaries between files.
1522 The following functions allow for a more dynamic approach to selecting
1523 a subset of files based on filetags:
1525 #+begin_src emacs-lisp
1526 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1527 "Restrict org agenda files only to those containing filetag."
1529 (let* ((tagslist (my-org-get-all-filetags))
1531 (completing-read "Tag: "
1532 (mapcar 'car tagslist)))))
1533 (org-agenda-remove-restriction-lock 'noupdate)
1534 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1535 (setq org-agenda-overriding-restriction 'files)))
1537 (defun my-org-get-all-filetags ()
1538 "Get list of filetags from all default org-files."
1539 (let ((files org-agenda-files)
1541 (save-window-excursion
1542 (while (setq x (pop files))
1543 (set-buffer (find-file-noselect x))
1546 (let ((tagfiles (assoc y tagslist)))
1548 (setcdr tagfiles (cons x (cdr tagfiles)))
1549 (add-to-list 'tagslist (list y x)))))
1550 (my-org-get-filetags)))
1553 (defun my-org-get-filetags ()
1554 "Get list of filetags for current buffer"
1555 (let ((ftags org-file-tags)
1559 (org-substring-no-properties x))
1563 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1564 with all filetags in your "normal" agenda files. When you select a
1565 tag, org-agenda-files will be restricted to only those files
1566 containing the filetag. To release the restriction, type C-c C-x >
1567 (org-agenda-remove-restriction-lock).
1569 *** Highlight the agenda line under cursor
1570 #+index: Agenda!Highlight
1571 This is useful to make sure what task you are operating on.
1573 #+BEGIN_SRC emacs-lisp
1574 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1579 #+BEGIN_SRC emacs-lisp
1580 ;; hl-line seems to be only for emacs
1582 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1584 ;; highline-mode does not work straightaway in tty mode.
1585 ;; I use a black background
1587 '(highline-face ((((type tty) (class color))
1588 (:background "white" :foreground "black")))))
1591 *** Split frame horizontally for agenda
1592 #+index: Agenda!frame
1593 If you would like to split the frame into two side-by-side windows when
1594 displaying the agenda, try this hack from Jan Rehders, which uses the
1595 `toggle-window-split' from
1597 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1599 #+BEGIN_SRC emacs-lisp
1600 ;; Patch org-mode to use vertical splitting
1601 (defadvice org-prepare-agenda (after org-fix-split)
1602 (toggle-window-split))
1603 (ad-activate 'org-prepare-agenda)
1606 *** Automatically add an appointment when clocking in a task
1607 #+index: Clock!Automatically add an appointment when clocking in a task
1608 #+index: Appointment!Automatically add an appointment when clocking in a task
1609 #+BEGIN_SRC emacs-lisp
1610 ;; Make sure you have a sensible value for `appt-message-warning-time'
1611 (defvar bzg-org-clock-in-appt-delay 100
1612 "Number of minutes for setting an appointment by clocking-in")
1615 This function let's you add an appointment for the current entry.
1616 This can be useful when you need a reminder.
1618 #+BEGIN_SRC emacs-lisp
1619 (defun bzg-org-clock-in-add-appt (&optional n)
1620 "Add an appointment for the Org entry at point in N minutes."
1623 (org-back-to-heading t)
1624 (looking-at org-complex-heading-regexp)
1625 (let* ((msg (match-string-no-properties 4))
1626 (ct-time (decode-time))
1627 (appt-min (+ (cadr ct-time)
1628 (or n bzg-org-clock-in-appt-delay)))
1629 (appt-time ; define the time for the appointment
1630 (progn (setf (cadr ct-time) appt-min) ct-time)))
1631 (appt-add (format-time-string
1632 "%H:%M" (apply 'encode-time appt-time)) msg)
1633 (if (interactive-p) (message "New appointment for %s" msg)))))
1636 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1639 #+BEGIN_SRC emacs-lisp
1640 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1641 "Add an appointment when clocking a task in."
1642 (bzg-org-clock-in-add-appt))
1645 You may also want to delete the associated appointment when clocking
1646 out. This function does this:
1648 #+BEGIN_SRC emacs-lisp
1649 (defun bzg-org-clock-out-delete-appt nil
1650 "When clocking out, delete any associated appointment."
1653 (org-back-to-heading t)
1654 (looking-at org-complex-heading-regexp)
1655 (let* ((msg (match-string-no-properties 4)))
1656 (setq appt-time-msg-list
1660 (if (not (string-match (regexp-quote msg)
1661 (cadr appt))) appt))
1662 appt-time-msg-list)))
1666 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1668 #+BEGIN_SRC emacs-lisp
1669 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1670 "Delete an appointment when clocking a task out."
1671 (bzg-org-clock-out-delete-appt))
1674 *IMPORTANT*: You can add appointment by clocking in in both an
1675 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1676 agenda buffer with the advice above will bring an error.
1678 *** Using external programs for appointments reminders
1679 #+index: Appointment!reminders
1680 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1682 *** Remove from agenda time grid lines that are in an appointment
1683 #+index: Agenda!time grid
1684 #+index: Appointment!Remove from agenda time grid lines
1685 The agenda shows lines for the time grid. Some people think that
1686 these lines are a distraction when there are appointments at those
1687 times. You can get rid of the lines which coincide exactly with the
1688 beginning of an appointment. Michael Ekstrand has written a piece of
1689 advice that also removes lines that are somewhere inside an
1692 #+begin_src emacs-lisp
1693 (defun org-time-to-minutes (time)
1694 "Convert an HHMM time to minutes"
1695 (+ (* (/ time 100) 60) (% time 100)))
1697 (defun org-time-from-minutes (minutes)
1698 "Convert a number of minutes to an HHMM time"
1699 (+ (* (/ minutes 60) 100) (% minutes 60)))
1701 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1702 (list ndays todayp))
1703 (if (member 'remove-match (car org-agenda-time-grid))
1704 (flet ((extract-window
1706 (let ((start (get-text-property 1 'time-of-day line))
1707 (dur (get-text-property 1 'duration line)))
1711 (org-time-from-minutes
1712 (+ dur (org-time-to-minutes start)))))
1715 (let* ((windows (delq nil (mapcar 'extract-window list)))
1716 (org-agenda-time-grid
1717 (list (car org-agenda-time-grid)
1718 (cadr org-agenda-time-grid)
1721 (find-if (lambda (w)
1724 (and (>= time (car w))
1727 (caddr org-agenda-time-grid)))))
1730 (ad-activate 'org-agenda-add-time-grid-maybe)
1732 *** Disable version control for Org mode agenda files
1733 #+index: Agenda!Files
1736 Even if you use Git to track your agenda files you might not need
1737 vc-mode to be enabled for these files.
1739 #+begin_src emacs-lisp
1740 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1741 (defun dmj/disable-vc-for-agenda-files-hook ()
1742 "Disable vc-mode for Org agenda files."
1743 (if (and (fboundp 'org-agenda-file-p)
1744 (org-agenda-file-p (buffer-file-name)))
1745 (remove-hook 'find-file-hook 'vc-find-file-hook)
1746 (add-hook 'find-file-hook 'vc-find-file-hook)))
1749 *** Easy customization of TODO colors
1750 #+index: Customization!Todo keywords
1751 #+index: Todo keywords!Customization
1755 Here is some code I came up with some code to make it easier to
1756 customize the colors of various TODO keywords. As long as you just
1757 want a different color and nothing else, you can customize the
1758 variable org-todo-keyword-faces and use just a string color (i.e. a
1759 string of the color name) as the face, and then org-get-todo-face
1760 will convert the color to a face, inheriting everything else from
1761 the standard org-todo face.
1763 To demonstrate, I currently have org-todo-keyword-faces set to
1765 #+BEGIN_SRC emacs-lisp
1766 (("IN PROGRESS" . "dark orange")
1767 ("WAITING" . "red4")
1768 ("CANCELED" . "saddle brown"))
1771 Here's the code, in a form you can put in your =.emacs=
1773 #+BEGIN_SRC emacs-lisp
1774 (eval-after-load 'org-faces
1776 (defcustom org-todo-keyword-faces nil
1777 "Faces for specific TODO keywords.
1778 This is a list of cons cells, with TODO keywords in the car and
1779 faces in the cdr. The face can be a symbol, a color, or a
1780 property list of attributes, like (:foreground \"blue\" :weight
1781 bold :underline t)."
1786 (string :tag "Keyword")
1787 (choice color (sexp :tag "Face")))))))
1789 (eval-after-load 'org
1791 (defun org-get-todo-face-from-color (color)
1792 "Returns a specification for a face that inherits from org-todo
1793 face and has the given color as foreground. Returns nil if
1796 `(:inherit org-warning :foreground ,color)))
1798 (defun org-get-todo-face (kwd)
1799 "Get the right face for a TODO keyword KWD.
1800 If KWD is a number, get the corresponding match group."
1801 (if (numberp kwd) (setq kwd (match-string kwd)))
1802 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1804 (org-get-todo-face-from-color face)
1806 (and (member kwd org-done-keywords) 'org-done)
1810 *** Add an effort estimate on the fly when clocking in
1811 #+index: Effort estimate!Add when clocking in
1812 #+index: Clock!Effort estimate
1813 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1814 This way you can easily have a "tea-timer" for your tasks when they
1815 don't already have an effort estimate.
1817 #+begin_src emacs-lisp
1818 (add-hook 'org-clock-in-prepare-hook
1819 'my-org-mode-ask-effort)
1821 (defun my-org-mode-ask-effort ()
1822 "Ask for an effort estimate when clocking in."
1823 (unless (org-entry-get (point) "Effort")
1827 (org-entry-get-multivalued-property (point) "Effort"))))
1828 (unless (equal effort "")
1829 (org-set-property "Effort" effort)))))
1832 Or you can use a default effort for such a timer:
1834 #+begin_src emacs-lisp
1835 (add-hook 'org-clock-in-prepare-hook
1836 'my-org-mode-add-default-effort)
1838 (defvar org-clock-default-effort "1:00")
1840 (defun my-org-mode-add-default-effort ()
1841 "Add a default effort estimation."
1842 (unless (org-entry-get (point) "Effort")
1843 (org-set-property "Effort" org-clock-default-effort)))
1846 *** Use idle timer for automatic agenda views
1847 #+index: Agenda view!Refresh
1848 From John Wiegley's mailing list post (March 18, 2010):
1851 I have the following snippet in my .emacs file, which I find very
1852 useful. Basically what it does is that if I don't touch my Emacs for 5
1853 minutes, it displays the current agenda. This keeps my tasks "always
1854 in mind" whenever I come back to Emacs after doing something else,
1855 whereas before I had a tendency to forget that it was there.
1858 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1860 #+begin_src emacs-lisp
1861 (defun jump-to-org-agenda ()
1863 (let ((buf (get-buffer "*Org Agenda*"))
1866 (if (setq wind (get-buffer-window buf))
1867 (select-window wind)
1868 (if (called-interactively-p)
1870 (select-window (display-buffer buf t t))
1871 (org-fit-window-to-buffer)
1872 ;; (org-agenda-redo)
1874 (with-selected-window (display-buffer buf)
1875 (org-fit-window-to-buffer)
1876 ;; (org-agenda-redo)
1878 (call-interactively 'org-agenda-list)))
1879 ;;(let ((buf (get-buffer "*Calendar*")))
1880 ;; (unless (get-buffer-window buf)
1881 ;; (org-agenda-goto-calendar)))
1884 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1888 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1890 *** Refresh the agenda view regularly
1891 #+index: Agenda view!Refresh
1892 Hack sent by Kiwon Um:
1894 #+begin_src emacs-lisp
1895 (defun kiwon/org-agenda-redo-in-other-window ()
1896 "Call org-agenda-redo function even in the non-agenda buffer."
1898 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1900 (with-selected-window agenda-window (org-agenda-redo)))))
1901 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1904 *** Reschedule agenda items to today with a single command
1905 #+index: Agenda!Reschedule
1906 This was suggested by Carsten in reply to David Abrahams:
1908 #+begin_example emacs-lisp
1909 (defun org-agenda-reschedule-to-today ()
1911 (flet ((org-read-date (&rest rest) (current-time)))
1912 (call-interactively 'org-agenda-schedule)))
1915 *** Mark subtree DONE along with all subheadings
1916 #+index: Subtree!subheadings
1917 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
1919 #+begin_src emacs-lisp
1920 (defun bh/mark-subtree-done ()
1923 (let ((limit (point)))
1925 (exchange-point-and-mark)
1926 (while (> (point) limit)
1928 (outline-previous-visible-heading 1))
1929 (org-todo "DONE"))))
1932 Then M-x bh/mark-subtree-done.
1934 *** Mark heading done when all checkboxes are checked.
1936 :CUSTOM_ID: mark-done-when-all-checkboxes-checked
1941 An item consists of a list with checkboxes. When all of the
1942 checkboxes are checked, the item should be considered complete and its
1943 TODO state should be automatically changed to DONE. The code below
1944 does that. This version is slightly enhanced over the one in the
1946 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
1947 reset the state back to TODO if a checkbox is unchecked.
1949 Note that the code requires that a checkbox statistics cookie (the [/]
1950 or [%] thingie in the headline - see the [[http://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
1951 manual) be present in order for it to work. Note also that it is too
1952 dumb to figure out whether the item has a TODO state in the first
1953 place: if there is a statistics cookie, a TODO/DONE state will be
1954 added willy-nilly any time that the statistics cookie is changed.
1956 #+begin_src emacs-lisp
1957 ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
1958 (eval-after-load 'org-list
1959 '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
1961 (defun ndk/checkbox-list-complete ()
1963 (org-back-to-heading t)
1964 (let ((beg (point)) end)
1968 (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
1970 (if (equal (match-string 1) "100%")
1971 ;; all done - do the state change
1974 (if (and (> (match-end 2) (match-beginning 2))
1975 (equal (match-string 2) (match-string 3)))
1977 (org-todo 'todo)))))))
1980 *** Links to custom agenda views
1982 :CUSTOM_ID: links-to-agenda-views
1984 #+index: Agenda view!Links to
1985 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
1987 If you have custom agenda commands defined to some key, say w, then
1988 the following will serve as a link to the custom agenda buffer.
1989 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
1991 Clicking on it will prompt if you want to execute the elisp code. If
1992 you would rather not have the prompt or would want to respond with a
1993 single letter, ~y~ or ~n~, take a look at the docstrings of the
1994 variables =org-confirm-elisp-link-function= and
1995 =org-confirm-elisp-link-not-regexp=. Please take special note of the
1996 security risk associated with completely disabling the prompting
1999 ** Exporting org files
2000 *** Export Org to Org and handle includes.
2001 #+index: Export!handle includes
2002 Nick Dokos came up with this useful function:
2004 #+begin_src emacs-lisp
2005 (defun org-to-org-handle-includes ()
2006 "Copy the contents of the current buffer to OUTFILE,
2007 recursively processing #+INCLUDEs."
2008 (let* ((s (buffer-string))
2009 (fname (buffer-file-name))
2010 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
2014 (org-export-handle-include-files-recurse)
2017 (delete-region (point-min) (point-max))
2022 *** Specifying LaTeX commands to floating environments
2024 :CUSTOM_ID: latex-command-for-floats
2027 #+index: Export!LaTeX
2028 The keyword ~placement~ can be used to specify placement options to
2029 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2030 LaTeX export. Org passes along everything passed in options as long as
2031 there are no spaces. One can take advantage of this to pass other
2032 LaTeX commands and have their scope limited to the floating
2035 For example one can set the fontsize of a table different from the
2036 default normal size by putting something like =\footnotesize= right
2037 after the placement options. During LaTeX export using the
2038 ~#+ATTR_LaTeX:~ line below:
2041 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2044 exports the associated floating environment as shown in the following
2048 \begin{table}[<options>]\footnotesize
2053 It should be noted that this hack does not work for beamer export of
2054 tables since the =table= environment is not used. As an ugly
2055 workaround, one can use the following:
2058 ,#+LATEX: {\footnotesize
2059 ,#+ATTR_LaTeX: align=rr
2066 *** Styling code sections with CSS
2068 #+index: HTML!Styling code sections with CSS
2070 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2071 to HTML using =<pre>= tags, and assigned CSS classes by their content
2072 type. For example, Perl content will have an opening tag like
2073 =<pre class="src src-perl">=. You can use those classes to add styling
2074 to the output, such as here where a small language tag is added at the
2075 top of each kind of code box:
2078 (setq org-export-html-style
2079 "<style type=\"text/css\">
2080 <!--/*--><![CDATA[/*><!--*/
2081 .src { background-color: #F5FFF5; position: relative; overflow: visible; }
2082 .src:before { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2083 .src-sh:before { content: 'sh'; }
2084 .src-bash:before { content: 'sh'; }
2085 .src-R:before { content: 'R'; }
2086 .src-perl:before { content: 'Perl'; }
2087 .src-sql:before { content: 'SQL'; }
2088 .example { background-color: #FFF5F5; }
2093 Additionally, we use color to distinguish code output (the =.example=
2094 class) from input (all the =.src-*= classes).
2096 * Hacking Org: Working with Org-mode and other Emacs Packages.
2097 ** org-remember-anything
2099 #+index: Remember!Anything
2101 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2103 #+BEGIN_SRC emacs-lisp
2104 (defvar org-remember-anything
2105 '((name . "Org Remember")
2106 (candidates . (lambda () (mapcar 'car org-remember-templates)))
2107 (action . (lambda (name)
2108 (let* ((orig-template org-remember-templates)
2109 (org-remember-templates
2110 (list (assoc name orig-template))))
2111 (call-interactively 'org-remember))))))
2114 You can add it to your 'anything-sources' variable and open remember directly
2115 from anything. I imagine this would be more interesting for people with many
2116 remember templates, so that you are out of keys to assign those to.
2118 ** Org-mode and saveplace.el
2120 Fix a problem with =saveplace.el= putting you back in a folded position:
2122 #+begin_src emacs-lisp
2123 (add-hook 'org-mode-hook
2125 (when (outline-invisible-p)
2127 (outline-previous-visible-heading 1)
2128 (org-show-subtree)))))
2131 ** Using ido-mode for org-refile (and archiving via refile)
2133 First set up ido-mode, for example using:
2135 #+begin_src emacs-lisp
2136 ; use ido mode for completion
2137 (setq ido-everywhere t)
2138 (setq ido-enable-flex-matching t)
2139 (setq ido-max-directory-size 100000)
2140 (ido-mode (quote both))
2143 Now to enable it in org-mode, use the following:
2144 #+begin_src emacs-lisp
2145 (setq org-completion-use-ido t)
2146 (setq org-refile-use-outline-path nil)
2147 (setq org-refile-allow-creating-parent-nodes 'confirm)
2149 The last line enables the creation of nodes on the fly.
2151 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):
2152 #+begin_src emacs-lisp
2153 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2156 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.
2157 #+begin_src emacs-lisp
2158 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2159 ; added check to only include headlines, e.g. line must have at least one child
2160 (defun my/verify-refile-target ()
2161 "Exclude todo keywords with a DONE state from refile targets"
2162 (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2163 (save-excursion (org-goto-first-child))
2165 (setq org-refile-target-verify-function 'my/verify-refile-target)
2167 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.
2169 ** Using ido-completing-read to find attachments
2171 #+index: Attachment!ido completion
2175 Org-attach is great for quickly linking files to a project. But if you
2176 use org-attach extensively you might find yourself wanting to browse
2177 all the files you've attached to org headlines. This is not easy to do
2178 manually, since the directories containing the files are not human
2179 readable (i.e., they are based on automatically generated ids). Here's
2180 some code to browse those files using ido (obviously, you need to be
2183 #+begin_src emacs-lisp
2184 (load-library "find-lisp")
2186 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2188 (defun my-ido-find-org-attach ()
2189 "Find files in org-attachment directory"
2191 (let* ((enable-recursive-minibuffers t)
2192 (files (find-lisp-find-files org-attach-directory "."))
2195 (cons (file-name-nondirectory x)
2199 (remove-duplicates (mapcar #'car file-assoc-list)
2201 (filename (ido-completing-read "Org attachments: " filename-list nil t))
2202 (longname (cdr (assoc filename file-assoc-list))))
2203 (ido-set-current-directory
2204 (if (file-directory-p longname)
2206 (file-name-directory longname)))
2207 (setq ido-exit 'refresh
2208 ido-text-init ido-text
2212 (add-hook 'ido-setup-hook 'ido-my-keys)
2214 (defun ido-my-keys ()
2215 "Add my keybindings for ido."
2216 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2219 To browse your org attachments using ido fuzzy matching and/or the
2220 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2223 ** Link to Gnus messages by Message-Id
2224 #+index: Link!Gnus message by Message-Id
2225 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2226 discussion about linking to Gnus messages without encoding the folder
2227 name in the link. The following code hooks in to the store-link
2228 function in Gnus to capture links by Message-Id when in nnml folders,
2229 and then provides a link type "mid" which can open this link. The
2230 =mde-org-gnus-open-message-link= function uses the
2231 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2232 scan. It will go through them, in order, asking each to locate the
2233 message and opening it from the first one that reports success.
2235 It has only been tested with a single nnml backend, so there may be
2236 bugs lurking here and there.
2238 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2241 #+begin_src emacs-lisp
2242 ;; Support for saving Gnus messages by Message-ID
2243 (defun mde-org-gnus-save-by-mid ()
2244 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2245 (when (eq major-mode 'gnus-article-mode)
2246 (gnus-article-show-summary))
2247 (let* ((group gnus-newsgroup-name)
2248 (method (gnus-find-method-for-group group)))
2249 (when (eq 'nnml (car method))
2250 (let* ((article (gnus-summary-article-number))
2251 (header (gnus-summary-article-header article))
2252 (from (mail-header-from header))
2255 (let ((mid (mail-header-id header)))
2256 (if (string-match "<\\(.*\\)>" mid)
2257 (match-string 1 mid)
2258 (error "Malformed message ID header %s" mid)))))
2259 (date (mail-header-date header))
2260 (subject (gnus-summary-subject-string)))
2261 (org-store-link-props :type "mid" :from from :subject subject
2262 :message-id message-id :group group
2263 :link (org-make-link "mid:" message-id))
2264 (apply 'org-store-link-props
2265 :description (org-email-link-description)
2266 org-store-link-plist)
2269 (defvar mde-mid-resolve-methods '()
2270 "List of methods to try when resolving message ID's. For Gnus,
2271 it is a cons of 'gnus and the select (type and name).")
2272 (setq mde-mid-resolve-methods
2275 (defvar mde-org-gnus-open-level 1
2276 "Level at which Gnus is started when opening a link")
2277 (defun mde-org-gnus-open-message-link (msgid)
2278 "Open a message link with Gnus"
2280 (require 'org-table)
2281 (catch 'method-found
2282 (message "[MID linker] Resolving %s" msgid)
2283 (dolist (method mde-mid-resolve-methods)
2285 ((and (eq (car method) 'gnus)
2286 (eq (cadr method) 'nnml))
2287 (funcall (cdr (assq 'gnus org-link-frame-setup))
2288 mde-org-gnus-open-level)
2289 (when gnus-other-frame-object
2290 (select-frame gnus-other-frame-object))
2291 (let* ((msg-info (nnml-find-group-number
2292 (concat "<" msgid ">")
2294 (group (and msg-info (car msg-info)))
2295 (message (and msg-info (cdr msg-info)))
2297 (if (gnus-methods-equal-p
2301 (gnus-group-full-name group (cdr method))))))
2303 (gnus-summary-read-group qname nil t)
2304 (gnus-summary-goto-article message nil t))
2305 (throw 'method-found t)))
2306 (t (error "Unknown link type"))))))
2308 (eval-after-load 'org-gnus
2310 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2311 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2314 ** Store link to a message when sending in Gnus
2315 #+index: Link!Store link to a message when sending in Gnus
2316 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2318 #+begin_src emacs-lisp
2319 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2320 "Send message with `message-send-and-exit' and store org link to message copy.
2321 If multiple groups appear in the Gcc header, the link refers to
2322 the copy in the last group."
2326 (message-narrow-to-headers)
2327 (let ((gcc (car (last
2328 (message-unquote-tokens
2329 (message-tokenize-header
2330 (mail-fetch-field "gcc" nil t) " ,")))))
2331 (buf (current-buffer))
2332 (message-kill-buffer-on-exit nil)
2333 id to from subject desc link newsgroup xarchive)
2334 (message-send-and-exit arg)
2336 ;; gcc group found ...
2338 (save-current-buffer
2339 (progn (set-buffer buf)
2340 (setq id (org-remove-angle-brackets
2341 (mail-fetch-field "Message-ID")))
2342 (setq to (mail-fetch-field "To"))
2343 (setq from (mail-fetch-field "From"))
2344 (setq subject (mail-fetch-field "Subject"))))
2345 (org-store-link-props :type "gnus" :from from :subject subject
2346 :message-id id :group gcc :to to)
2347 (setq desc (org-email-link-description))
2348 (setq link (org-gnus-article-link
2349 gcc newsgroup id xarchive))
2350 (setq org-stored-links
2351 (cons (list link desc) org-stored-links)))
2352 ;; no gcc group found ...
2353 (message "Can not create Org link: No Gcc header found."))))))
2355 (define-key message-mode-map [(control c) (control meta c)]
2356 'ulf-message-send-and-org-gnus-store-link)
2359 ** Send html messages and attachments with Wanderlust
2362 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2363 similar functionality for both Wanderlust and Gnus. The hack below is
2364 still somewhat different: It allows you to toggle sending of html
2365 messages within Wanderlust transparently. I.e. html markup of the
2366 message body is created right before sending starts.
2368 *** Send HTML message
2370 Putting the code below in your .emacs adds following four functions:
2372 - dmj/wl-send-html-message
2374 Function that does the job: Convert everything between "--text
2375 follows this line--" and first mime entity (read: attachment) or
2376 end of buffer into html markup using `org-export-region-as-html'
2377 and replaces original body with a multipart MIME entity with the
2378 plain text version of body and the html markup version. Thus a
2379 recipient that prefers html messages can see the html markup,
2380 recipients that prefer or depend on plain text can see the plain
2383 Cannot be called interactively: It is hooked into SEMI's
2384 `mime-edit-translate-hook' if message should be HTML message.
2386 - dmj/wl-send-html-message-draft-init
2388 Cannot be called interactively: It is hooked into WL's
2389 `wl-mail-setup-hook' and provides a buffer local variable to
2392 - dmj/wl-send-html-message-draft-maybe
2394 Cannot be called interactively: It is hooked into WL's
2395 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2396 `mime-edit-translate-hook' depending on whether HTML message is
2399 - dmj/wl-send-html-message-toggle
2401 Toggles sending of HTML message. If toggled on, the letters
2402 "HTML" appear in the mode line.
2404 Call it interactively! Or bind it to a key in `wl-draft-mode'.
2406 If you have to send HTML messages regularly you can set a global
2407 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2408 toggle on sending HTML message by default.
2410 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2411 Google's web front end. As you can see you have the whole markup of
2412 Org at your service: *bold*, /italics/, tables, lists...
2414 So even if you feel uncomfortable with sending HTML messages at least
2415 you send HTML that looks quite good.
2417 #+begin_src emacs-lisp
2418 (defun dmj/wl-send-html-message ()
2419 "Send message as html message.
2420 Convert body of message to html using
2421 `org-export-region-as-html'."
2424 (let (beg end html text)
2425 (goto-char (point-min))
2426 (re-search-forward "^--text follows this line--$")
2427 ;; move to beginning of next line
2428 (beginning-of-line 2)
2430 (if (not (re-search-forward "^--\\[\\[" nil t))
2431 (setq end (point-max))
2436 (setq text (buffer-substring-no-properties beg end))
2442 (when (re-search-backward "^-- \n" nil t)
2443 ;; preserve link breaks in signature
2444 (insert "\n#+BEGIN_VERSE\n")
2445 (goto-char (point-max))
2446 (insert "\n#+END_VERSE\n")
2448 (setq html (org-export-region-as-html
2449 (point-min) (point-max) t 'string))))
2450 (delete-region beg end)
2453 "--" "<<alternative>>-{\n"
2454 "--" "[[text/plain]]\n" text
2455 "--" "[[text/html]]\n" html
2456 "--" "}-<<alternative>>\n")))))
2458 (defun dmj/wl-send-html-message-toggle ()
2459 "Toggle sending of html message."
2461 (setq dmj/wl-send-html-message-toggled-p
2462 (if dmj/wl-send-html-message-toggled-p
2464 (message "Sending html message toggled %s"
2465 (if dmj/wl-send-html-message-toggled-p
2468 (defun dmj/wl-send-html-message-draft-init ()
2469 "Create buffer local settings for maybe sending html message."
2470 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2471 (setq dmj/wl-send-html-message-toggled-p nil))
2472 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2473 (add-to-list 'global-mode-string
2474 '(:eval (if (eq major-mode 'wl-draft-mode)
2475 dmj/wl-send-html-message-toggled-p))))
2477 (defun dmj/wl-send-html-message-maybe ()
2478 "Maybe send this message as html message.
2480 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2481 non-nil, add `dmj/wl-send-html-message' to
2482 `mime-edit-translate-hook'."
2483 (if dmj/wl-send-html-message-toggled-p
2484 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2485 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2487 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2488 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2489 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2492 *** Attach HTML of region or subtree
2494 Instead of sending a complete HTML message you might only send parts
2495 of an Org file as HTML for the poor souls who are plagued with
2496 non-proportional fonts in their mail program that messes up pretty
2499 This short function does the trick: It exports region or subtree to
2500 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2501 and clipboard. If a region is active, it uses the region, the
2502 complete subtree otherwise.
2504 #+begin_src emacs-lisp
2505 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2506 "Export region between BEG and END as html attachment.
2507 If BEG and END are not set, use current subtree. Region or
2508 subtree is exported to html without header and footer, prefixed
2509 with a mime entity string and pushed to clipboard and killring.
2510 When called with prefix, mime entity is not marked as
2512 (interactive "r\nP")
2514 (let* ((beg (if (region-active-p) (region-beginning)
2516 (org-back-to-heading)
2518 (end (if (region-active-p) (region-end)
2520 (org-end-of-subtree)
2522 (html (concat "--[[text/html"
2523 (if arg "" "\nContent-Disposition: attachment")
2525 (org-export-region-as-html beg end t 'string))))
2526 (when (fboundp 'x-set-selection)
2527 (ignore-errors (x-set-selection 'PRIMARY html))
2528 (ignore-errors (x-set-selection 'CLIPBOARD html)))
2529 (message "html export done, pushed to kill ring and clipboard"))))
2532 *** Adopting for Gnus
2534 The whole magic lies in the special strings that mark a HTML
2535 attachment. So you might just have to find out what these special
2536 strings are in message-mode and modify the functions accordingly.
2537 ** Add sunrise/sunset times to the agenda.
2538 #+index: Agenda!Diary s-expressions
2541 The diary package provides the function =diary-sunrise-sunset= which can be used
2542 in a diary s-expression in some agenda file like this:
2544 #+begin_src org-mode
2545 %%(diary-sunrise-sunset)
2548 Seb Vauban asked if it is possible to put sunrise and sunset in
2549 separate lines. Here is a hack to do that. It adds two functions (they
2550 have to be available before the agenda is shown, so I add them early
2551 in my org-config file which is sourced from .emacs, but you'll have to
2552 suit yourself here) that just parse the output of
2553 diary-sunrise-sunset, instead of doing the right thing which would be
2554 to take advantage of the data structures that diary/solar.el provides.
2555 In short, a hack - so perfectly suited for inclusion here :-)
2557 The functions (and latitude/longitude settings which you have to modify for
2558 your location) are as follows:
2560 #+begin_src emacs-lisp
2561 (setq calendar-latitude 48.2)
2562 (setq calendar-longitude 16.4)
2563 (setq calendar-location-name "Vienna, Austria")
2565 (autoload 'solar-sunrise-sunset "solar.el")
2566 (autoload 'solar-time-string "solar.el")
2567 (defun diary-sunrise ()
2568 "Local time of sunrise as a diary entry.
2569 The diary entry can contain `%s' which will be replaced with
2570 `calendar-location-name'."
2571 (let ((l (solar-sunrise-sunset date)))
2574 (if (string= entry "")
2576 (format entry (eval calendar-location-name))) " "
2577 (solar-time-string (caar l) nil)))))
2579 (defun diary-sunset ()
2580 "Local time of sunset as a diary entry.
2581 The diary entry can contain `%s' which will be replaced with
2582 `calendar-location-name'."
2583 (let ((l (solar-sunrise-sunset date)))
2586 (if (string= entry "")
2588 (format entry (eval calendar-location-name))) " "
2589 (solar-time-string (caadr l) nil)))))
2592 You also need to add a couple of diary s-expressions in one of your agenda
2595 #+begin_src org-mode
2596 %%(diary-sunrise)Sunrise in %s
2600 This will show sunrise with the location and sunset without it.
2602 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]].
2603 In comparison to the version posted on the mailing list, this one
2604 gets rid of the timezone information and can show the location.
2605 ** Add lunar phases to the agenda.
2606 #+index: Agenda!Diary s-expressions
2609 Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
2610 This can be used to display lunar phases in the agenda display with the
2613 #+begin_src emacs-lisp
2616 (org-no-warnings (defvar date))
2617 (defun org-lunar-phases ()
2618 "Show lunar phase in Agenda buffer."
2620 (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
2621 (phase (cl-find-if (lambda (phase) (equal (car phase) date))
2624 (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
2625 (substring (nth 1 phase) 0 5))))))
2628 Add the following line to an agenda file:
2630 #+begin_src org-mode
2636 This should display an entry on new moon, first/last quarter moon, and on full
2637 moon. You can customize the entries by customizing =lunar-phase-names=.
2639 E.g., to add Unicode symbols:
2641 #+begin_src emacs-lisp
2642 (setq lunar-phase-names
2643 '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
2644 "☽ First Quarter Moon"
2645 "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
2646 "☾ Last Quarter Moon"))
2649 Unicode 6 even provides symbols for the Moon with nice faces. But those
2650 symbols are currently barely supported in fonts.
2651 See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].
2653 ** Export BBDB contacts to org-contacts.el
2654 #+index: Address Book!BBDB to org-contacts
2655 Try this tool by Wes Hardaker:
2657 http://www.hardakers.net/code/bbdb-to-org-contacts/
2659 ** Calculating date differences - how to write a simple elisp function
2660 #+index: Timestamp!date calculations
2661 #+index: Elisp!technique
2663 Alexander Wingård asked how to calculate the number of days between a
2664 time stamp in his org file and today (see
2665 http://thread.gmane.org/gmane.emacs.orgmode/46881). Although the
2666 resulting answer is probably not of general interest, the method might
2667 be useful to a budding Elisp programmer.
2669 Alexander started from an already existing org function,
2670 =org-evaluate-time-range=. When this function is called in the context
2671 of a time range (two time stamps separated by "=--="), it calculates the
2672 number of days between the two dates and outputs the result in Emacs's
2673 echo area. What he wanted was a similar function that, when called from
2674 the context of a single time stamp, would calculate the number of days
2675 between the date in the time stamp and today. The result should go to
2676 the same place: Emacs's echo area.
2678 The solution presented in the mail thread is as follows:
2680 #+begin_src emacs-lisp
2681 (defun aw/org-evaluate-time-range (&optional to-buffer)
2683 (if (org-at-date-range-p t)
2684 (org-evaluate-time-range to-buffer)
2685 ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
2686 (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
2689 (goto-char (point-at-bol))
2690 (re-search-forward org-ts-regexp (point-at-eol) t)
2691 (if (not (org-at-timestamp-p t))
2692 (error "No timestamp here"))
2693 (goto-char (match-beginning 0))
2694 (org-insert-time-stamp (current-time) nil nil)
2696 (org-evaluate-time-range to-buffer)))))
2699 The function assumes that point is on some line with some time stamp
2700 (or a date range) in it. Note that =org-evaluate-time-range= does not care
2701 whether the first date is earlier than the second: it will always output
2702 the number of days between the earlier date and the later date.
2704 As stated before, the function itself is of limited interest (although
2705 it satisfied Alexander's need).The *method* used might be of wider
2706 interest however, so here is a short explanation.
2708 The idea is that we want =org-evaluate-time-range= to do all the
2709 heavy lifting, but that function requires that it be in a date-range
2710 context. So the function first checks whether it's in a date range
2711 context already: if so, it calls =org-evaluate-time-range= directly
2712 to do the work. The trick now is to arrange things so we can call this
2713 same function in the case where we do *not* have a date range
2714 context. In that case, we manufacture one: we create a temporary
2715 buffer, copy the line with the purported time stamp to the temp
2716 buffer, find the time stamp (signal an error if no time stamp is
2717 found) and insert a new time stamp with the current time before the
2718 existing time stamp, followed by "=--=": voilà, we now have a time range
2719 on which we can apply our old friend =org-evaluate-time-range= to
2720 produce the answer. Because of the above-mentioned property
2721 of =org-evaluate-time-range=, it does not matter if the existing
2722 time stamp is earlier or later than the current time: the correct
2723 number of days is output.
2725 Note that at the end of the call to =with-temp-buffer=, the temporary
2726 buffer goes away. It was just used as a scratch pad for the function
2727 to do some figuring.
2729 The idea of using a temp buffer as a scratch pad has wide
2730 applicability in Emacs programming. The rest of the work is knowing
2731 enough about facilities provided by Emacs (e.g. regexp searching) and
2732 by Org (e.g. checking for time stamps and generating a time stamp) so
2733 that you don't reinvent the wheel, and impedance-matching between the
2736 ** ibuffer and org files
2738 Neil Smithline posted this snippet to let you browse org files with
2741 #+BEGIN_SRC emacs-lisp
2744 (defun org-ibuffer ()
2745 "Open an `ibuffer' window showing only `org-mode' buffers."
2747 (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
2750 ** Enable org-mode links in other modes
2752 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
2754 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
2756 * Hacking Org: Working with Org-mode and External Programs.
2757 ** Use Org-mode with Screen [Andrew Hyatt]
2758 #+index: Link!to screen session
2759 "The general idea is that you start a task in which all the work will
2760 take place in a shell. This usually is not a leaf-task for me, but
2761 usually the parent of a leaf task. From a task in your org-file, M-x
2762 ash-org-screen will prompt for the name of a session. Give it a name,
2763 and it will insert a link. Open the link at any time to go the screen
2764 session containing your work!"
2766 http://article.gmane.org/gmane.emacs.orgmode/5276
2768 #+BEGIN_SRC emacs-lisp
2771 (defun ash-org-goto-screen (name)
2772 "Open the screen with the specified name in the window"
2773 (interactive "MScreen name: ")
2774 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2775 (if (member screen-buffer-name
2776 (mapcar 'buffer-name (buffer-list)))
2777 (switch-to-buffer screen-buffer-name)
2778 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2780 (defun ash-org-screen-buffer-name (name)
2781 "Returns the buffer name corresponding to the screen name given."
2782 (concat "*screen " name "*"))
2784 (defun ash-org-screen-helper (name arg)
2785 ;; Pick the name of the new buffer.
2786 (let ((term-ansi-buffer-name
2787 (generate-new-buffer-name
2788 (ash-org-screen-buffer-name name))))
2789 (setq term-ansi-buffer-name
2790 (term-ansi-make-term
2791 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2792 (set-buffer term-ansi-buffer-name)
2795 (term-set-escape-char ?\C-x)
2796 term-ansi-buffer-name))
2798 (defun ash-org-screen (name)
2799 "Start a screen session with name"
2800 (interactive "MScreen name: ")
2802 (ash-org-screen-helper name "-S"))
2803 (insert-string (concat "[[screen:" name "]]")))
2805 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2806 ;; \"%s\")") to org-link-abbrev-alist.
2809 ** Org Agenda + Appt + Zenity
2811 :CUSTOM_ID: org-agenda-appt-zenity
2814 #+index: Appointment!reminders
2815 #+index: Appt!Zenity
2817 <a name="agenda-appt-zenity"></a>
2819 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It makes sure your agenda
2820 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2823 #+BEGIN_SRC emacs-lisp
2824 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2825 ; For org appointment reminders
2827 ;; Get appointments for today
2828 (defun my-org-agenda-to-appt ()
2830 (setq appt-time-msg-list nil)
2831 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
2832 (org-agenda-to-appt)))
2834 ;; Run once, activate and schedule refresh
2835 (my-org-agenda-to-appt)
2837 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2840 (setq appt-message-warning-time 15)
2841 (setq appt-display-interval 5)
2843 ; Update appt each time agenda opened.
2844 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2846 ; Setup zenify, we tell appt to use window, and replace default function
2847 (setq appt-display-format 'window)
2848 (setq appt-disp-window-function (function my-appt-disp-window))
2850 (defun my-appt-disp-window (min-to-app new-time msg)
2851 (save-window-excursion (shell-command (concat
2852 "/usr/bin/zenity --info --title='Appointment' --text='"
2853 msg "' &") nil nil)))
2856 ** Org-Mode + gnome-osd
2857 #+index: Appointment!reminders
2858 #+index: Appt!gnome-osd
2859 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2860 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2863 #+index: Agenda!Views
2864 #+index: Agenda!and Remind (external program)
2867 http://article.gmane.org/gmane.emacs.orgmode/5073
2870 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2871 command line calendaring program. Its features supersede the possibilities
2872 of orgmode in the area of date specifying, so that I want to use it
2873 combined with orgmode.
2875 Using the script below I'm able use remind and incorporate its output in my
2876 agenda views. The default of using 13 months look ahead is easily
2877 changed. It just happens I sometimes like to look a year into the
2881 ** Useful webjumps for conkeror
2882 #+index: Shortcuts!conkeror
2883 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2884 your =~/.conkerorrc= file:
2887 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2888 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2891 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2892 Org-mode mailing list.
2894 ** Use MathJax for HTML export without requiring JavaScript
2895 #+index: Export!MathJax
2896 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2898 If you like the results but do not want JavaScript in the exported pages,
2899 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2900 HTML file from the exported version. It can also embed all referenced fonts
2901 within the HTML file itself, so there are no dependencies to external files.
2903 The download archive contains an elisp file which integrates it into the Org
2904 export process (configurable per file with a "#+StaticMathJax:" line).
2906 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2907 ** Search Org files using lgrep
2908 #+index: search!lgrep
2909 Matt Lundin suggests this:
2911 #+begin_src emacs-lisp
2912 (defun my-org-grep (search &optional context)
2913 "Search for word in org files.
2915 Prefix argument determines number of lines."
2916 (interactive "sSearch for: \nP")
2917 (let ((grep-find-ignored-files '("#*" ".#*"))
2918 (grep-template (concat "grep <X> -i -nH "
2920 (concat "-C" (number-to-string context)))
2922 (lgrep search "*org*" "/home/matt/org/")))
2924 (global-set-key (kbd "<f8>") 'my-org-grep)
2927 ** Automatic screenshot insertion
2928 #+index: Link!screenshot
2929 Suggested by Russell Adams
2931 #+begin_src emacs-lisp
2932 (defun my-org-screenshot ()
2933 "Take a screenshot into a time stamped unique-named file in the
2934 same directory as the org-buffer and insert a link to this file."
2939 (concat (buffer-file-name)
2941 (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
2942 (call-process "import" nil nil nil filename)
2943 (insert (concat "[[" filename "]]"))
2944 (org-display-inline-images))
2947 ** Capture invitations/appointments from MS Exchange emails
2948 #+index: Appointment!MS Exchange
2949 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
2950 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
2952 ** Audio/video file playback within org mode
2953 #+index: Link!audio/video
2954 Paul Sexton provided code that makes =file:= links to audio or video files
2955 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
2956 media player library. The user can pause, skip forward and backward in the
2957 track, and so on from without leaving Emacs. Links can also contain a time
2958 after a double colon -- when this is present, playback will begin at that
2959 position in the track.
2961 See the file [[file:code/elisp/org-player.el][org-player.el]]
2963 ** Under X11 Keep a window with the current agenda items at all time
2964 #+index: Agenda!dedicated window
2965 I struggle to keep (in emacs) a window with the agenda at all times.
2966 For a long time I have wanted a sticky window that keeps this
2967 information, and then use my window manager to place it and remove its
2968 decorations (I can also force its placement in the stack: top always,
2971 I wrote a small program in qt that simply monitors an HTML file and
2972 displays it. Nothing more. It does the work for me, and maybe somebody
2973 else will find it useful. It relies on exporting the agenda as HTML
2974 every time the org file is saved, and then this little program
2975 displays the html file. The window manager is responsible of removing
2976 decorations, making it sticky, and placing it in same place always.
2978 Here is a screenshot (see window to the bottom right). The decorations
2979 are removed by the window manager:
2981 http://turingmachine.org/hacking/org-mode/orgdisplay.png
2983 Here is the code. As I said, very, very simple, but maybe somebody will
2986 http://turingmachine.org/hacking/org-mode/
2990 ** Script (thru procmail) to output emails to an Org file
2991 #+index: Conversion!email to org file
2992 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
2994 : I've [...] created some procmail and shell glue that takes emails and
2995 : inserts them into an org-file so that I can capture stuff on the go using
2996 : the email program.
2998 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3000 ** Save File With Different Format for Headings (fileconversion)
3002 :CUSTOM_ID: fileconversion
3004 #+index: Conversion!fileconversion
3006 Using hooks and on the fly
3007 - when writing a buffer to the file replace the leading stars from headings
3009 - when reading a file into the buffer replace the file chars with leading
3012 To change to save an Org file in one of the formats or back just add or
3013 remove the keyword in the STARTUP line and save.
3015 Now you can also change to Fundamental mode to see how the file looks like
3016 on the level of the file, go back to Org mode, reenter Org mode or change to
3017 any other major mode and the conversion gets done whenever necessary.
3019 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
3021 :CUSTOM_ID: hidestarsfile
3023 #+index: Conversion!fileconversion hidestarsfile
3025 This is like "a cleaner outline view":
3026 http://orgmode.org/manual/Clean-view.html
3028 Example of the _file content_ first with leading stars as usual and below
3029 without leading stars through "#+STARTUP: odd hidestars hidestarsfile":
3032 #+STARTUP: odd hidestars
3044 #+STARTUP: odd hidestars hidestarsfile
3055 The latter is convenient for better human readability when an Org file,
3056 additionally to Emacs, is read with a file viewer or, for smaller edits,
3057 with an editor not capable of the Org file format.
3059 hidestarsfile is a hack and can not become part of the Org core:
3060 - An Org file with hidestarsfile can not contain list items with a star as
3061 bullet due to the syntax conflict at read time. Mark E. Shoulson suggested
3062 to use the non-breaking space which is now implemented in fileconversion
3063 as nbspstarsfile as an alternative for hidestarsfile. Although I don't
3064 recommend it because an editor like typically e. g. Emacs may render the
3065 non-breaking space differently from the space 0x20.
3066 - An Org file with hidestarsfile can almost not be edited with an Org mode
3067 without added functionality of hidestarsfile as long as the file is not
3070 *** Headings in Markdown Format (markdownstarsfile)
3072 :CUSTOM_ID: markdownstarsfile
3074 #+index: Conversion!fileconversion markdownstarsfile
3076 For "oddeven" you can use markdownstarsfile to be readable or even basically
3077 editable with Markdown (does not make much sense with "odd", see
3078 org-convert-to-odd-levels and org-convert-to-oddeven-levels for how to
3081 Example of the _file content_:
3084 #+STARTUP: oddeven markdownstarsfile
3086 1. first item of numbered list (same format in Org and Markdown)
3088 - first item of unordered list (same format in Org and Markdown)
3090 + first item of unordered list (same format in Org and Markdown)
3091 #### section level 4
3092 * first item of unordered list (same format in Org and Markdown)
3093 * avoid this item type to be compatible with Org hidestarsfile
3096 An Org file with markdownstarsfile can not contain code comment lines
3097 prefixed with "#", even not when within source blocks.
3101 :CUSTOM_ID: fileconversion-code
3103 #+index: Conversion!fileconversion emacs-lisp code
3105 #+BEGIN_SRC emacs-lisp
3106 ;; - fileconversion version 0.6
3107 ;; - DISCLAIMER: Make a backup of your Org files before using
3108 ;; my-org-fileconv-*.
3109 ;; - supported formats: hidestarsfile, markdownstarsfile
3111 ;; design summary: fileconversion is a round robin of two states
3112 ;; linked by two actions:
3113 ;; - state my-org-fileconv-level-org-p is nil: the level is "file"
3115 ;; - action my-org-fileconv-decode: replace file char with '*'
3116 ;; - state my-org-fileconv-level-org-p is t: the level is "Org"
3118 ;; - action my-org-fileconv-encode replace '*' with file char
3120 (defvar my-org-fileconv-level-org-p nil
3121 "Whether level of buffer is Org or only file.
3122 nil means the level is file (encoded), non-nil means the level is Org
3124 (make-variable-buffer-local 'my-org-fileconv-level-org-p)
3125 ;; survive a change of major mode that does kill-all-local-variables,
3126 ;; e. g. when reentering Org mode through “C-c C-c” on a STARTUP line
3127 (put 'my-org-fileconv-level-org-p 'permanent-local t)
3129 (add-hook 'org-mode-hook 'my-org-fileconv-init
3130 ;; _append_ to hook to have a higher chance that a message
3131 ;; from this function will be visible as the last message in
3134 ;; hook addition global
3137 (defun my-org-fileconv-init ()
3139 ;; instrument only when converting really from/to an Org _file_, not
3140 ;; e. g. for a temp Org buffer unrelated to a file like used e. g.
3141 ;; when calling the old Org exporter
3142 (when (buffer-file-name)
3143 (message "INF: my-org-fileconv-init, buffer: %s" (buffer-name))
3144 (my-org-fileconv-decode)
3145 ;; the hooks are not permanent-local, this way and as needed they
3146 ;; will disappear when the major mode of the buffer changes
3147 (add-hook 'change-major-mode-hook 'my-org-fileconv-encode nil
3148 ;; hook addition limited to buffer locally
3150 (add-hook 'before-save-hook 'my-org-fileconv-encode nil
3151 ;; hook addition limited to buffer locally
3153 (add-hook 'after-save-hook 'my-org-fileconv-decode nil
3154 ;; hook addition limited to buffer locally
3157 (defun my-org-fileconv-re ()
3158 "Check whether there is a STARTUP line for fileconversion.
3159 If found then return the expressions required for the conversion."
3161 (beginning-of-buffer)
3162 (let (re-list (count 0))
3163 (while (re-search-forward "^#\\+STARTUP:" nil t)
3164 ;; #+STARTUP: hidestarsfile
3165 (when (string-match-p "\\bhidestarsfile\\b"
3166 (thing-at-point 'line))
3168 ;; - line starting with star for bold emphasis
3169 ;; - line of stars to underline section title in loosely
3170 ;; quoted ASCII style (star at end of line)
3171 (setq re-list '("\\(\\* \\)" ; common-re
3173 (setq count (1+ count)))
3174 ;; #+STARTUP: nbspstarsfile
3175 (when (string-match-p "\\bnbspstarsfile\\b"
3176 (thing-at-point 'line))
3177 (setq re-list '("\\(\\* \\)" ; common-re
3178 ?\xa0)) ; file-char non-breaking space
3179 (setq count (1+ count)))
3180 ;; #+STARTUP: markdownstarsfile
3181 (when (string-match-p "\\bmarkdownstarsfile\\b"
3182 (thing-at-point 'line))
3185 (setq re-list '("\\( \\)" ; common-re
3187 (setq count (1+ count))))
3189 (error "ERR: more than one fileconversion found"))
3192 (defun my-org-fileconv-decode ()
3193 "In headings replace file char with '*'."
3194 (let ((re-list (my-org-fileconv-re)))
3195 (when (and re-list (not my-org-fileconv-level-org-p))
3196 ;; no `save-excursion' to be able to keep point in case of error
3197 (let* ((common-re (nth 0 re-list))
3198 (file-char (nth 1 re-list))
3199 (file-re (concat "^" (string file-char) "+" common-re))
3200 (org-re (concat "^\\*+" common-re))
3203 (beginning-of-buffer)
3205 (when (re-search-forward org-re nil t)
3206 (goto-char (match-beginning 0))
3209 "ERR: my-org-fileconv-decode syntax conflict at point"))
3210 (beginning-of-buffer)
3212 (with-silent-modifications
3213 (while (re-search-forward file-re nil t)
3214 (goto-char (match-beginning 0))
3215 ;; faster than a lisp call of insert and delete on each
3217 (setq len (- (match-beginning 1) (match-beginning 0)))
3218 (insert-char ?* len)
3222 ;; notes for ediff when only one file has fileconversion:
3223 ;; - The changes to the buffer with fileconversion until here
3224 ;; are not regarded by ediff-files because the first call to
3225 ;; diff is made with the bare files directly. Only
3226 ;; ediff-update-diffs and ediff-buffers write the decoded
3227 ;; buffers to temp files and then call diff with them.
3228 ;; - Workarounds (choose one):
3229 ;; - after ediff-files first do a "!" (ediff-update-diffs)
3230 ;; in the "*Ediff Control Panel*"
3231 ;; - instead of using ediff-files first open the files and
3232 ;; then run ediff-buffers (better for e. g. a script that
3233 ;; takes two files as arguments and uses "emacs --eval")
3235 ;; the level is Org most of all when no fileconversion is in effect
3236 (setq my-org-fileconv-level-org-p t))
3238 (defun my-org-fileconv-encode ()
3239 "In headings replace '*' with file char."
3240 (let ((re-list (my-org-fileconv-re)))
3241 (when (and re-list my-org-fileconv-level-org-p)
3242 ;; no `save-excursion' to be able to keep point in case of error
3243 (let* ((common-re (nth 0 re-list))
3244 (file-char (nth 1 re-list))
3245 (file-re (concat "^" (string file-char) "+" common-re))
3246 (org-re (concat "^\\*+" common-re))
3249 (beginning-of-buffer)
3251 (when (re-search-forward file-re nil t)
3252 (goto-char (match-beginning 0))
3255 "ERR: my-org-fileconv-encode syntax conflict at point"))
3256 (beginning-of-buffer)
3258 (with-silent-modifications
3259 (while (re-search-forward org-re nil t)
3260 (goto-char (match-beginning 0))
3261 ;; faster than a lisp call of insert and delete on each
3263 (setq len (- (match-beginning 1) (match-beginning 0)))
3264 (insert-char file-char len)
3267 (setq my-org-fileconv-level-org-p nil))))
3268 nil) ;; for the hook
3273 ** Meaningful diff for org files in a git repository
3274 #+index: git!diff org files
3275 Since most diff utilities are primarily meant for source code, it is
3276 difficult to read diffs of text files like ~.org~ files easily. If you
3277 version your org directory with a SCM like git you will know what I
3278 mean. However for git, there is a way around. You can use
3279 =gitattributes= to define a custom diff driver for org files. Then a
3280 regular expression can be used to configure how the diff driver
3281 recognises a "function".
3283 Put the following in your =<org_dir>/.gitattributes=.
3285 Then put the following lines in =<org_dir>/.git/config=
3287 : xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3289 This will let you see diffs for org files with each hunk identified by
3290 the unmodified headline closest to the changes. After the
3291 configuration a diff should look something like the example below.
3294 diff --git a/org-hacks.org b/org-hacks.org
3295 index a0672ea..92a08f7 100644
3298 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3300 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3302 +** Meaningful diff for org files in a git repository
3304 +Since most diff utilities are primarily meant for source code, it is
3305 +difficult to read diffs of text files like ~.org~ files easily. If you
3306 +version your org directory with a SCM like git you will know what I
3307 +mean. However for git, there is a way around. You can use
3308 +=gitattributes= to define a custom diff driver for org files. Then a
3309 +regular expression can be used to configure how the diff driver
3310 +recognises a "function".
3312 +Put the following in your =<org_dir>/.gitattributes=.
3314 +Then put the following lines in =<org_dir>/.git/config=
3316 +: xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3320 ** Cooking? Brewing?
3323 ** Opening devonthink links
3325 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3326 links from org-mode.
3330 ** Cooking? Brewing?
3331 #+index: beer!brewing
3332 #+index: cooking!conversions
3333 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3335 It currently does metric/english conversion, and a few other tricks.
3336 Basically I just use calc’s units code. I think scaling recipes, or
3337 turning percentages into weights would be pretty easy.
3339 https://gitorious.org/org-cook/org-cook
3341 There is also, for those interested:
3343 https://gitorious.org/org-brew/org-brew
3345 for brewing beer. This is again, mostly just calc functions, including
3346 hydrometer correction, abv calculation, priming sugar for a given CO_2
3347 volume, etc. More integration with org-mode should be possible: for
3348 instance it would be nice to be able to use a lookup table (of ingredients)
3349 to calculate target original gravity, IBUs, etc.