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.
23 *** Picking up a random task in the global TODO list
25 Tony day [[http://mid.gmane.org/m2zk19l1me.fsf%2540gmail.com][shared]] [[https://gist.github.com/4343164][this gist]] to pick up a
28 ** Building and Managing Org
29 *** Generating autoloads and Compiling Org without make
31 :CUSTOM_ID: compiling-org-without-make
34 #+index: Compilation!without make
36 Compilation is optional, but you _must_ update the autoloads file
37 each time you update org, even when you run org uncompiled!
39 Starting with Org 7.9 you'll find functions for creating the
40 autoload files and do byte-compilation in =mk/org-fixup.el=. When
41 you execute the commands below, your current directory must be where
42 org has been unpacked into, in other words the file =README= should
43 be found in your current directory and the directories =lisp= and
44 =etc= should be subdirectories of it. The command =emacs= should be
45 found in your =PATH= and start the Emacs version you are using. To
46 make just the autoloads file do:
47 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
48 To make the autoloads file and byte-compile org:
49 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
50 To make the autoloads file and byte-compile all of org again:
51 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
52 If you are not using Git, you'll have to make fake version strings
53 first if =org-version.el= is not already available (if it is, you
54 could also edit the version strings there).
55 : emacs -batch -Q -L lisp -l ../mk/org-fixup \
56 : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
57 : (org-make-autoloads))'
59 POSIX shell for its quoting. Windows =CMD.exe= has quite different
60 quoting rules and this won't work, so your other option is to start
62 : emacs -Q -L lisp -l ../mk/org-fixup
63 then paste the following into the =*scratch*= buffer
64 #+BEGIN_SRC emacs-lisp
65 (let ((org-fake-release "7.9.1")
66 (org-fake-git-version "7.9.1-fake"))
69 position the cursor after the closing paren and press =C-j= or =C-x
70 C-e= to evaluate the form. Of course you can replace
71 =org-make-autoloads= with =org-make-autoloads-compile= or even
72 =org-make-autoloads-compile-force= if you wish with both variants.
74 For *older org versions only* (that do not yet have
75 =mk/org-fixup.el=), you can use the definitions below. To use
76 this function, adjust the variables =my/org-lisp-directory= and
77 =my/org-compile-sources= to suit your needs. If you have
78 byte-compiled org, but want to run org uncompiled again, just remove
79 all =*.elc= files in the =lisp/= directory, set
80 =my/org-compile-sources= to =nil=.
82 #+BEGIN_SRC emacs-lisp
83 (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
84 "Directory where your org-mode files live.")
86 (defvar my/org-compile-sources t
87 "If `nil', never compile org-sources. `my/compile-org' will only create
88 the autoloads file `org-loaddefs.el' then. If `t', compile the sources, too.")
90 ;; Customize: (must end with a slash!)
91 (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")
94 (setq my/org-compile-sources t)
96 (defun my/compile-org(&optional directory)
97 "Generate autoloads file org-loaddefs.el. Optionally compile
98 all *.el files that come with org-mode."
100 (defun my/compile-org()
101 "Generate autoloads file org-loaddefs.el. Optionally compile
102 all *.el files that come with org-mode."
104 (let ((dirlisp (file-name-directory my/org-lisp-directory)))
105 (add-to-list 'load-path dirlisp)
107 (let ((generated-autoload-file (concat dirlisp "org-loaddefs.el")))
108 ;; create the org-loaddefs file
109 (update-directory-autoloads dirlisp)
110 (when my/org-compile-sources
111 ;; optionally byte-compile
112 (byte-recompile-directory dirlisp 0 'force)))))
116 #+index: Initialization!Reload
118 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
119 function to reload org files.
121 Normally you want to use the compiled files since they are faster.
122 If you update your org files you can easily reload them with
126 If you run into a bug and want to generate a useful backtrace you can
127 reload the source files instead of the compiled files with
131 and turn on the "Enter Debugger On Error" option. Redo the action
132 that generates the error and cut and paste the resulting backtrace.
133 To switch back to the compiled version just reload again with
137 *** Check for possibly problematic old link escapes
139 :CUSTOM_ID: check-old-link-escapes
142 Starting with version 7.5 Org uses [[http://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
143 and with a modified algorithm to determine which characters to escape
146 As a side effect this modified behaviour might break existing links if
147 they contain a sequence of characters that look like a percent escape
148 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
150 The function below can be used to perform a preliminary check for such
151 links in an Org mode file. It will run through all links in the file
152 and issue a warning if it finds a percent escape sequence which is not
153 in old Org's list of known percent escapes.
155 #+begin_src emacs-lisp
156 (defun dmaus/org-check-percent-escapes ()
157 "*Check buffer for possibly problematic old link escapes."
159 (when (eq major-mode 'org-mode)
160 (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
161 "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
162 (unless (boundp 'warning-suppress-types)
163 (setq warning-suppress-types nil))
166 (goto-char (point-min))
167 (while (re-search-forward org-any-link-re nil t)
168 (let ((end (match-end 0)))
169 (goto-char (match-beginning 0))
170 (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
171 (let ((escape (match-string-no-properties 0)))
172 (unless (member (upcase escape) old-escapes)
173 (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
180 ** Structure Movement and Editing
181 *** Show next/prev heading tidily
183 #+index: Navigation!Heading
185 These close the current heading and open the next/previous heading.
187 #+begin_src emacs-lisp
188 (defun ded/org-show-next-heading-tidily ()
189 "Show next entry, keeping other entries closed."
190 (if (save-excursion (end-of-line) (outline-invisible-p))
191 (progn (org-show-entry) (show-children))
192 (outline-next-heading)
193 (unless (and (bolp) (org-on-heading-p))
194 (org-up-heading-safe)
196 (error "Boundary reached"))
202 (defun ded/org-show-previous-heading-tidily ()
203 "Show previous entry, keeping other entries closed."
205 (outline-previous-heading)
206 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
209 (error "Boundary reached"))
215 (setq org-use-speed-commands t)
216 (add-to-list 'org-speed-commands-user
217 '("n" ded/org-show-next-heading-tidily))
218 (add-to-list 'org-speed-commands-user
219 '("p" ded/org-show-previous-heading-tidily))
222 *** Promote all items in subtree
223 #+index: Structure Editing!Promote
226 This function will promote all items in a subtree. Since I use
227 subtrees primarily to organize projects, the function is somewhat
228 unimaginatively called my-org-un-project:
230 #+begin_src emacs-lisp
231 (defun my-org-un-project ()
233 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
237 *** Turn a heading into an Org link
239 :CUSTOM_ID: heading-to-link
241 #+index: Structure Editing!Heading
242 #+index: Link!Turn a heading into a
245 #+begin_src emacs-lisp
246 (defun dmj:turn-headline-into-org-mode-link ()
247 "Replace word at point by an Org mode link."
249 (when (org-at-heading-p)
250 (let ((hl-text (nth 4 (org-heading-components))))
251 (unless (or (null hl-text)
252 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
254 (search-forward hl-text (point-at-eol))
257 (format "[[file:%s.org][%s]]"
258 (org-link-escape hl-text)
259 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
260 nil (- (point) (length hl-text)) (point))))))
263 *** Using M-up and M-down to transpose paragraphs
264 #+index: Structure Editing!paragraphs
266 From Paul Sexton: By default, if used within ordinary paragraphs in
267 org mode, =M-up= and =M-down= transpose *lines* (not sentences). The
268 following code makes these keys transpose paragraphs, keeping the
269 point at the start of the moved paragraph. Behavior in tables and
270 headings is unaffected. It would be easy to modify this to transpose
273 #+begin_src emacs-lisp
274 (defun org-transpose-paragraphs (arg)
276 (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
277 (thing-at-point 'sentence))
278 (transpose-paragraphs arg)
280 (re-search-forward "[[:graph:]]")
281 (goto-char (match-beginning 0))
284 (add-to-list 'org-metaup-hook
285 (lambda () (interactive) (org-transpose-paragraphs -1)))
286 (add-to-list 'org-metadown-hook
287 (lambda () (interactive) (org-transpose-paragraphs 1)))
289 *** Changelog support for org headers
290 #+index: Structure Editing!Heading
293 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
294 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
295 headline as the "current function" if you add a changelog entry from an org
298 #+BEGIN_SRC emacs-lisp
299 (defun org-log-current-defun ()
301 (org-back-to-heading)
302 (if (looking-at org-complex-heading-regexp)
305 (add-hook 'org-mode-hook
307 (make-variable-buffer-local 'add-log-current-defun-function)
308 (setq add-log-current-defun-function 'org-log-current-defun)))
311 *** Different org-cycle-level behavior
312 #+index: Cycling!behavior
315 In recent org versions, when your point (cursor) is at the end of an
316 empty header line (like after you first created the header), the TAB
317 key (=org-cycle=) has a special behavior: it cycles the headline through
318 all possible levels. However, I did not like the way it determined
319 "all possible levels," so I rewrote the whole function, along with a
320 couple of supporting functions.
322 The original function's definition of "all possible levels" was "every
323 level from 1 to one more than the initial level of the current
324 headline before you started cycling." My new definition is "every
325 level from 1 to one more than the previous headline's level." So, if
326 you have a headline at level 4 and you use ALT+RET to make a new
327 headline below it, it will cycle between levels 1 and 5, inclusive.
329 The main advantage of my custom =org-cycle-level= function is that it
330 is stateless: the next level in the cycle is determined entirely by
331 the contents of the buffer, and not what command you executed last.
332 This makes it more predictable, I hope.
334 #+BEGIN_SRC emacs-lisp
337 (defun org-point-at-end-of-empty-headline ()
338 "If point is at the end of an empty headline, return t, else nil."
339 (and (looking-at "[ \t]*$")
341 (beginning-of-line 1)
342 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
344 (defun org-level-increment ()
345 "Return the number of stars that will be added or removed at a
346 time to headlines when structure editing, based on the value of
347 `org-odd-levels-only'."
348 (if org-odd-levels-only 2 1))
350 (defvar org-previous-line-level-cached nil)
352 (defun org-recalculate-previous-line-level ()
353 "Same as `org-get-previous-line-level', but does not use cached
354 value. It does *set* the cached value, though."
355 (set 'org-previous-line-level-cached
356 (let ((current-level (org-current-level))
357 (prev-level (when (> (line-number-at-pos) 1)
360 (org-current-level)))))
361 (cond ((null current-level) nil) ; Before first headline
362 ((null prev-level) 0) ; At first headline
365 (defun org-get-previous-line-level ()
366 "Return the outline depth of the last headline before the
367 current line. Returns 0 for the first headline in the buffer, and
368 nil if before the first headline."
369 ;; This calculation is quite expensive, with all the regex searching
370 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
371 ;; the last value of this command.
372 (or (and (eq last-command 'org-cycle-level)
373 org-previous-line-level-cached)
374 (org-recalculate-previous-line-level)))
376 (defun org-cycle-level ()
378 (let ((org-adapt-indentation nil))
379 (when (org-point-at-end-of-empty-headline)
380 (setq this-command 'org-cycle-level) ;Only needed for caching
381 (let ((cur-level (org-current-level))
382 (prev-level (org-get-previous-line-level)))
384 ;; If first headline in file, promote to top-level.
386 (loop repeat (/ (- cur-level 1) (org-level-increment))
387 do (org-do-promote)))
388 ;; If same level as prev, demote one.
389 ((= prev-level cur-level)
391 ;; If parent is top-level, promote to top level if not already.
393 (loop repeat (/ (- cur-level 1) (org-level-increment))
394 do (org-do-promote)))
395 ;; If top-level, return to prev-level.
397 (loop repeat (/ (- prev-level 1) (org-level-increment))
399 ;; If less than prev-level, promote one.
400 ((< cur-level prev-level)
402 ;; If deeper than prev-level, promote until higher than
404 ((> cur-level prev-level)
405 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
406 do (org-do-promote))))
410 *** Count words in an Org buffer
411 #FIXME: Does not fit too well under Structure. Any idea where to put it?
412 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
414 #+begin_src emacs-lisp
415 (defun org-word-count (beg end
416 &optional count-latex-macro-args?
418 "Report the number of words in the Org mode buffer or selected region.
422 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
423 - hyperlinks (but does count words in hyperlink descriptions)
424 - tags, priorities, and TODO keywords in headers
425 - sections tagged as 'not for export'.
427 The text of footnote definitions is ignored, unless the optional argument
428 COUNT-FOOTNOTES? is non-nil.
430 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
431 includes LaTeX macro arguments (the material between {curly braces}).
432 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
436 (setf beg (point-min)
439 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
442 (while (< (point) end)
445 ((or (org-in-commented-line) (org-at-table-p))
447 ;; Ignore hyperlinks. But if link has a description, count
448 ;; the words within the description.
449 ((looking-at org-bracket-link-analytic-regexp)
450 (when (match-string-no-properties 5)
451 (let ((desc (match-string-no-properties 5)))
453 (incf wc (length (remove "" (org-split-string
455 (goto-char (match-end 0)))
456 ((looking-at org-any-link-re)
457 (goto-char (match-end 0)))
458 ;; Ignore source code blocks.
459 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
461 ;; Ignore inline source blocks, counting them as 1 word.
464 (looking-at org-babel-inline-src-block-regexp))
465 (goto-char (match-end 0))
467 ;; Count latex macros as 1 word, ignoring their arguments.
470 (looking-at latex-macro-regexp))
471 (goto-char (if count-latex-macro-args?
476 ((and (not count-footnotes?)
477 (or (org-footnote-at-definition-p)
478 (org-footnote-at-reference-p)))
481 (let ((contexts (org-context)))
483 ;; Ignore tags and TODO keywords, etc.
484 ((or (assoc :todo-keyword contexts)
485 (assoc :priority contexts)
486 (assoc :keyword contexts)
487 (assoc :checkbox contexts))
489 ;; Ignore sections marked with tags that are
490 ;; excluded from export.
491 ((assoc :tags contexts)
492 (if (intersection (org-get-tags-at) org-export-exclude-tags
494 (org-forward-same-level 1)
498 (re-search-forward "\\w+\\W*")))
499 (message (format "%d words in %s." wc
500 (if mark-active "region" "buffer")))))
503 *** Check for misplaced SCHEDULED and DEADLINE cookies
505 The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
506 below* the headline -- like this:
510 , SCHEDULED: <2012-04-09 lun.>
513 This is what =org-scheduled= and =org-deadline= (and other similar
514 commands) do. And the manual explicitely tell people to stick to this
515 format (see the section "8.3.1 Inserting deadlines or schedules").
517 If you think you might have subtrees with misplaced =SCHEDULED= and
518 =DEADLINE= cookies, this command lets you check the current buffer:
520 #+begin_src emacs-lisp
521 (defun org-check-misformatted-subtree ()
522 "Check misformatted entries in the current buffer."
527 (when (and (move-beginning-of-line 2)
528 (not (looking-at org-heading-regexp)))
529 (if (or (and (org-get-scheduled-time (point))
530 (not (looking-at (concat "^.*" org-scheduled-regexp))))
531 (and (org-get-deadline-time (point))
532 (not (looking-at (concat "^.*" org-deadline-regexp)))))
533 (when (y-or-n-p "Fix this subtree? ")
534 (message "Call the function again when you're done fixing this subtree.")
536 (message "All subtrees checked."))))))
539 *** Sorting list by checkbox type
541 #+index: checkbox!sorting
543 You can use a custom function to sort list by checkbox type. Here is a
544 function suggested by Carsten:
546 #+BEGIN_SRC emacs-lisp
547 (defun org-sort-list-by-checkbox-type ()
548 "Sort list items according to Checkbox state."
553 (if (looking-at org-list-full-item-re)
554 (cdr (assoc (match-string 3)
555 '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
560 *** Align all tables in a file
562 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
564 #+begin_src emacs-lisp
565 (defun my-align-all-tables ()
567 (org-table-map-tables 'org-table-align 'quietly))
571 #+index: Table!Calculation
573 :CUSTOM_ID: transpose-table
576 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
577 see.) There are also other solutions:
579 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
580 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]]
582 - with org-babel and R: provided by Dan Davison in the mailing list (old
583 =#+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]]
585 - with field coordinates in formulas (=@#= and =$#=): see [[file:org-hacks.org::#field-coordinates-in-formulas-transpose-table][Worg]].
587 *** Manipulate hours/minutes/seconds in table formulas
588 #+index: Table!hours-minutes-seconds
589 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
590 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
591 "=d=" is any digit) as time values in Org-mode table formula. These
592 functions have now been wrapped up into a =with-time= macro which can
593 be used in table formula to translate table cell values to and from
594 numerical values for algebraic manipulation.
596 Here is the code implementing this macro.
597 #+begin_src emacs-lisp :results silent
598 (defun org-time-string-to-seconds (s)
599 "Convert a string HH:MM:SS to a number of seconds."
602 (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
603 (let ((hour (string-to-number (match-string 1 s)))
604 (min (string-to-number (match-string 2 s)))
605 (sec (string-to-number (match-string 3 s))))
606 (+ (* hour 3600) (* min 60) sec)))
608 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
609 (let ((min (string-to-number (match-string 1 s)))
610 (sec (string-to-number (match-string 2 s))))
612 ((stringp s) (string-to-number s))
615 (defun org-time-seconds-to-string (secs)
616 "Convert a number of seconds to a time string."
617 (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
618 ((>= secs 60) (format-seconds "%m:%.2s" secs))
619 (t (format-seconds "%s" secs))))
621 (defmacro with-time (time-output-p &rest exprs)
622 "Evaluate an org-table formula, converting all fields that look
623 like time data to integer seconds. If TIME-OUTPUT-P then return
624 the result as a time value."
626 (if time-output-p 'org-time-seconds-to-string 'identity)
634 (list 'with-time nil el)
635 (org-time-string-to-seconds el)))
640 Which allows the following forms of table manipulation such as adding
641 and subtracting time values.
642 : | Date | Start | Lunch | Back | End | Sum |
643 : |------------------+-------+-------+-------+-------+------|
644 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
645 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
647 and dividing time values by integers
648 : | time | miles | minutes/mile |
649 : |-------+-------+--------------|
650 : | 34:43 | 2.9 | 11:58 |
651 : | 32:15 | 2.77 | 11:38 |
652 : | 33:56 | 3.0 | 11:18 |
653 : | 52:22 | 4.62 | 11:20 |
654 : #+TBLFM: $3='(with-time t (/ $1 $2))
656 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
657 Elisp formulas) to compute time durations. For example:
659 : | Task 1 | Task 2 | Total |
660 : |--------+--------+---------|
661 : | 35:00 | 35:00 | 1:10:00 |
662 : #+TBLFM: @2$3=$1+$2;T
664 *** Dates computation
666 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of
667 dates stored in an org table.
669 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
673 | Start Date | End Date | Duration |
674 |------------+------------+----------|
675 | 2004.08.07 | 2005.07.08 | 335 |
676 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
678 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
679 above). The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
680 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
683 #+index: Table!Calculation
684 As with Times computation, the following code allows Computation with
685 Hex values in Org-mode tables using the =with-hex= macro.
687 Here is the code implementing this macro.
688 #+begin_src emacs-lisp
689 (defun org-hex-strip-lead (str)
690 (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
691 (substring str 2) str))
693 (defun org-hex-to-hex (int)
696 (defun org-hex-to-dec (str)
699 (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
703 (setf out (+ (* out 16)
704 (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
705 (coerce (match-string 1 str) 'list))
707 ((stringp str) (string-to-number str))
710 (defmacro with-hex (hex-output-p &rest exprs)
711 "Evaluate an org-table formula, converting all fields that look
712 like hexadecimal to decimal integers. If HEX-OUTPUT-P then
713 return the result as a hex value."
715 (if hex-output-p 'org-hex-to-hex 'identity)
722 (list 'with-hex nil el)
723 (org-hex-to-dec el)))
728 Which allows the following forms of table manipulation such as adding
729 and subtracting hex values.
730 | 0x10 | 0x0 | 0x10 | 16 |
731 | 0x20 | 0x1 | 0x21 | 33 |
732 | 0x30 | 0x2 | 0x32 | 50 |
733 | 0xf0 | 0xf | 0xff | 255 |
734 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
736 *** Field coordinates in formulas (=@#= and =$#=)
738 :CUSTOM_ID: field-coordinates-in-formulas
740 #+index: Table!Field Coordinates
743 Following are some use cases that can be implemented with the “field
744 coordinates in formulas” described in the corresponding chapter in the
745 [[http://orgmode.org/manual/References.html#References][Org manual]].
747 **** Copy a column from a remote table into a column
749 :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
752 current column =$3= = remote column =$2=:
753 : #+TBLFM: $3 = remote(FOO, @@#$2)
755 **** Copy a row from a remote table transposed into a column
757 :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
760 current column =$1= = transposed remote row =@1=:
761 : #+TBLFM: $1 = remote(FOO, @$#$@#)
765 :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
770 This is more like a demonstration of using “field coordinates in formulas”
771 and is bound to be slow for large tables. See the discussion in the mailing
773 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
774 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
775 For more efficient solutions see
776 [[file:org-hacks.org::#transpose-table][Worg]].
778 To transpose this 4x7 table
781 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
782 : |------+------+------+------+------+------+------|
783 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
784 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
785 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
787 start with a 7x4 table without any horizontal line (to have filled
788 also the column header) and yet empty:
798 Then add the =TBLFM= line below. After recalculation this will end up with
801 : | year | min | avg | max |
802 : | 2004 | 401 | 402 | 403 |
803 : | 2005 | 501 | 502 | 503 |
804 : | 2006 | 601 | 602 | 603 |
805 : | 2007 | 701 | 702 | 703 |
806 : | 2008 | 801 | 802 | 803 |
807 : | 2009 | 901 | 902 | 903 |
808 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
810 The formula simply exchanges row and column numbers by taking
811 - the absolute remote row number =@$#= from the current column number =$#=
812 - the absolute remote column number =$@#= from the current row number =@#=
814 Formulas to be taken over from the remote table will have to be transformed
817 **** Dynamic variation of ranges
821 In this example all columns next to =quote= are calculated from the column
822 =quote= and show the average change of the time series =quote[year]=
823 during the period of the preceding =1=, =2=, =3= or =4= years:
825 : | year | quote | 1 a | 2 a | 3 a | 4 a |
826 : |------+-------+-------+-------+-------+-------|
827 : | 2005 | 10 | | | | |
828 : | 2006 | 12 | 0.200 | | | |
829 : | 2007 | 14 | 0.167 | 0.183 | | |
830 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
831 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
832 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
834 The important part of the formula without the field blanking is:
836 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
838 which is the Emacs Calc implementation of the equation
840 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
842 where /i/ is the current time and /a/ is the length of the preceding period.
844 *** Change the column sequence in one row only
845 #+index: Table!Editing
847 :CUSTOM_ID: column-sequence-in-row
852 The functions below can be used to change the column sequence in one row
853 only, without affecting the other rows above and below like with M-<left> or
854 M-<right> (org-table-move-column). Please see the docstring of the functions
855 for more explanations. Below is one example per function, with this original
856 table as the starting point for each example:
858 : | e | 9 | 10 | 11 |
861 **** Move in row left
863 1) place point at "10" in original table
864 2) result of M-x my-org-table-move-column-in-row-left:
866 : | e | 10 | 9 | 11 |
869 **** Move in row right
871 1) place point at "9" in original table
872 2) result of M-x my-org-table-move-column-in-row-right:
874 : | e | 10 | 9 | 11 |
877 **** Rotate in row left
879 1) place point at "9" in original table
880 2) result of M-x my-org-table-rotate-column-in-row-left:
882 : | e | 10 | 11 | 9 |
885 **** Rotate in row right
887 1) place point at "9" in original table
888 2) result of M-x my-org-table-rotate-column-in-row-right:
890 : | e | 11 | 9 | 10 |
895 #+BEGIN_SRC emacs-lisp
896 (defun my-org-table-move-column-in-row-right ()
897 "Move column to the right, limited to the current row."
899 (my-org-table-move-column-in-row nil))
900 (defun my-org-table-move-column-in-row-left ()
901 "Move column to the left, limited to the current row."
903 (my-org-table-move-column-in-row 'left))
905 (defun my-org-table-move-column-in-row (&optional left)
906 "Move the current column to the right, limited to the current row.
907 With arg LEFT, move to the left. For repeated invocation the point follows
908 the value and changes to the target colum. Does not fix formulas."
909 ;; derived from `org-table-move-column'
911 (if (not (org-at-table-p))
912 (error "Not at a table"))
913 (org-table-find-dataline)
914 (org-table-check-inside-data-field)
915 (let* ((col (org-table-current-column))
916 (col1 (if left (1- col) col))
917 ;; Current cursor position
918 (colpos (if left (1- col) (1+ col))))
919 (if (and left (= col 1))
920 (error "Cannot move column further left"))
921 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
922 (error "Cannot move column further right"))
923 (org-table-goto-column col1 t)
924 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
925 (replace-match "|\\2|\\1|"))
926 (org-table-goto-column colpos)
929 (defun my-org-table-rotate-column-in-row-right ()
930 "Rotate column to the right, limited to the current row."
932 (my-org-table-rotate-column-in-row nil))
933 (defun my-org-table-rotate-column-in-row-left ()
934 "Rotate column to the left, limited to the current row."
936 (my-org-table-rotate-column-in-row 'left))
938 (defun my-org-table-rotate-column-in-row (&optional left)
939 "Rotate the current column to the right, limited to the current row.
940 With arg LEFT, rotate to the left. The boundaries of the rotation range are
941 the current and the most right column for both directions. For repeated
942 invocation the point stays on the current column. Does not fix formulas."
943 ;; derived from `org-table-move-column'
945 (if (not (org-at-table-p))
946 (error "Not at a table"))
947 (org-table-find-dataline)
948 (org-table-check-inside-data-field)
949 (let ((col (org-table-current-column)))
950 (org-table-goto-column col t)
951 (and (looking-at (if left
952 "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
953 "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
954 (replace-match "|\\2|\\1|"))
955 (org-table-goto-column col)
961 As hack I have this in an Org buffer to change temporarily to the desired
962 behavior with C-c C-c on one of the three snippets:
964 : #+begin_src emacs-lisp :results silent
965 : (org-defkey org-mode-map [(meta left)]
966 : 'my-org-table-move-column-in-row-left)
967 : (org-defkey org-mode-map [(meta right)]
968 : 'my-org-table-move-column-in-row-right)
969 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
970 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
974 : #+begin_src emacs-lisp :results silent
975 : (org-defkey org-mode-map [(meta left)]
976 : 'my-org-table-rotate-column-in-row-left)
977 : (org-defkey org-mode-map [(meta right)]
978 : 'my-org-table-rotate-column-in-row-right)
979 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
980 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
983 : - back to original:
984 : #+begin_src emacs-lisp :results silent
985 : (org-defkey org-mode-map [(meta left)] 'org-metaleft)
986 : (org-defkey org-mode-map [(meta right)] 'org-metaright)
987 : (org-defkey org-mode-map [(left)] 'backward-char)
988 : (org-defkey org-mode-map [(right)] 'forward-char)
991 **** reasons why this is not put into the Org core
993 I consider this as only a hack for several reasons:
994 - Generalization: The existing org-table-move-column function could be
995 enhanced with additional optional parameters to incorporate these
996 functionalities and could be used as the only function for better
997 maintainability. Now it's only a copy/paste hack of several similar
998 functions with simple modifications.
999 - Bindings: Should be convenient for repetition like M-<right>. What
1000 should be bound where, what has to be left unbound?
1001 - Does not fix formulas. Could be resolved for field formulas but
1002 most probably not for column or range formulas and this can lead
1003 to confusion. AFAIK all "official" table manipulations fix formulas.
1004 - Completeness: Not all variations and combinations are covered yet
1005 - left-right, up-down
1006 - move, rotate with range to end, rotate with range to begin
1007 - whole column/row, only in-row/in-column
1009 ** Capture and Remember
1010 *** Customize the size of the frame for remember
1011 #+index: Remember!frame
1012 #+index: Customization!remember
1013 (Note: this hack is likely out of date due to the development of
1017 On emacs-orgmode, Ryan C. Thompson suggested this:
1020 I am using org-remember set to open a new frame when used,
1021 and the default frame size is much too large. To fix this, I have
1022 designed some advice and a custom variable to implement custom
1023 parameters for the remember frame:
1026 #+begin_src emacs-lisp
1027 (defcustom remember-frame-alist nil
1028 "Additional frame parameters for dedicated remember frame."
1032 (defadvice remember (around remember-frame-parameters activate)
1033 "Set some frame parameters for the remember frame."
1034 (let ((default-frame-alist (append remember-frame-alist
1035 default-frame-alist)))
1039 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1040 reasonable size for the frame.
1042 *** [[#heading-to-link][Turn a heading into an org link]]
1043 *** Quickaccess to the link part of hyperlinks
1044 #+index: Link!Referent
1045 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1046 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1047 which is indeed kind of cumbersome.
1049 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1051 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1052 #+begin_src emacs-lisp
1054 (lambda (&optional arg)
1057 (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1061 #+begin_src emacs-lisp
1062 (defun my-org-extract-link ()
1063 "Extract the link location at point and put it on the killring."
1065 (when (org-in-regexp org-bracket-link-regexp 1)
1066 (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1069 They put the link destination on the killring and can be easily bound to a key.
1071 *** Insert link with HTML title as default description
1072 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1073 from HTML <title> tag and use it as a default link description. Here is a way to
1076 #+begin_src emacs-lisp
1077 (require 'mm-url) ; to include mm-url-decode-entities-string
1079 (defun my-org-insert-link ()
1080 "Insert org link where default description is set to html title."
1082 (let* ((url (read-string "URL: "))
1083 (title (get-html-title-from-url url)))
1084 (org-insert-link nil url title)))
1086 (defun get-html-title-from-url (url)
1087 "Return content in <title> tag."
1088 (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1090 (set-buffer download-buffer)
1091 (beginning-of-buffer)
1092 (setq x1 (search-forward "<title>"))
1093 (search-forward "</title>")
1094 (setq x2 (search-backward "<"))
1095 (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1098 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1100 ** Archiving Content in Org-Mode
1101 *** Preserve top level headings when archiving to a file
1102 #+index: Archiving!Preserve top level headings
1105 To preserve (somewhat) the integrity of your archive structure while
1106 archiving lower level items to a file, you can use the following
1109 #+begin_src emacs-lisp
1110 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1111 (let ((org-archive-location
1112 (if (save-excursion (org-back-to-heading)
1113 (> (org-outline-level) 1))
1114 (concat (car (split-string org-archive-location "::"))
1116 (car (org-get-outline-path)))
1117 org-archive-location)))
1121 Thus, if you have an outline structure such as...
1129 ...archiving "Subsubheading" to a new file will set the location in
1130 the new file to the top level heading:
1137 While this hack obviously destroys the outline hierarchy somewhat, it
1138 at least preserves the logic of level one groupings.
1140 A slightly more complex version of this hack will not only keep the
1141 archive organized by top-level headings, but will also preserve the
1142 tags found on those headings:
1144 #+begin_src emacs-lisp
1145 (defun my-org-inherited-no-file-tags ()
1146 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1147 (ltags (org-entry-get nil "TAGS")))
1150 (replace-regexp-in-string (concat tag ":") "" tags)))
1151 (append org-file-tags (when ltags (split-string ltags ":" t))))
1152 (if (string= ":" tags) nil tags)))
1154 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1155 (let ((tags (my-org-inherited-no-file-tags))
1156 (org-archive-location
1157 (if (save-excursion (org-back-to-heading)
1158 (> (org-outline-level) 1))
1159 (concat (car (split-string org-archive-location "::"))
1161 (car (org-get-outline-path)))
1162 org-archive-location)))
1164 (with-current-buffer (find-file-noselect (org-extract-archive-file))
1166 (while (org-up-heading-safe))
1167 (org-set-tags-to tags)))))
1170 *** Archive in a date tree
1171 #+index: Archiving!date tree
1172 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1174 (Make sure org-datetree.el is loaded for this to work.)
1176 #+begin_src emacs-lisp
1177 ;; (setq org-archive-location "%s_archive::date-tree")
1178 (defadvice org-archive-subtree
1179 (around org-archive-subtree-to-data-tree activate)
1180 "org-archive-subtree to date-tree"
1182 (string= "date-tree"
1183 (org-extract-archive-heading
1184 (org-get-local-archive-location)))
1185 (let* ((dct (decode-time (org-current-time)))
1189 (this-buffer (current-buffer))
1190 (location (org-get-local-archive-location))
1191 (afile (org-extract-archive-file location))
1192 (org-archive-location
1193 (format "%s::*** %04d-%02d-%02d %s" afile y m d
1194 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1195 (message "afile=%s" afile)
1197 (error "Invalid `org-archive-location'"))
1199 (switch-to-buffer (find-file-noselect afile))
1200 (org-datetree-find-year-create y)
1201 (org-datetree-find-month-create y m)
1202 (org-datetree-find-day-create y m d)
1204 (switch-to-buffer this-buffer))
1209 *** Add inherited tags to archived entries
1210 #+index: Archiving!Add inherited tags
1211 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1212 advise the function like this:
1215 (defadvice org-archive-subtree
1216 (before add-inherited-tags-before-org-archive-subtree activate)
1217 "add inherited tags before org-archive-subtree"
1218 (org-set-tags-to (org-get-tags-at)))
1221 ** Using and Managing Org-Metadata
1222 *** Remove redundant tags of headlines
1223 #+index: Tag!Remove redundant
1226 A small function that processes all headlines in current buffer and
1227 removes tags that are local to a headline and inherited by a parent
1228 headline or the #+FILETAGS: statement.
1230 #+BEGIN_SRC emacs-lisp
1231 (defun dmj/org-remove-redundant-tags ()
1232 "Remove redundant tags of headlines in current buffer.
1234 A tag is considered redundant if it is local to a headline and
1235 inherited by a parent headline."
1237 (when (eq major-mode 'org-mode)
1241 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1242 local inherited tag)
1243 (dolist (tag alltags)
1244 (if (get-text-property 0 'inherited tag)
1245 (push tag inherited) (push tag local)))
1247 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1251 *** Remove empty property drawers
1252 #+index: Drawer!Empty
1253 David Maus proposed this:
1255 #+begin_src emacs-lisp
1256 (defun dmj:org:remove-empty-propert-drawers ()
1257 "*Remove all empty property drawers in current file."
1259 (unless (eq major-mode 'org-mode)
1260 (error "You need to turn on Org mode for this function."))
1262 (goto-char (point-min))
1263 (while (re-search-forward ":PROPERTIES:" nil t)
1265 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1268 *** Group task list by a property
1269 #+index: Agenda!Group task list
1270 This advice allows you to group a task list in Org-Mode. To use it,
1271 set the variable =org-agenda-group-by-property= to the name of a
1272 property in the option list for a TODO or TAGS search. The resulting
1273 agenda view will group tasks by that property prior to searching.
1275 #+begin_src emacs-lisp
1276 (defvar org-agenda-group-by-property nil
1277 "Set this in org-mode agenda views to group tasks by property")
1279 (defun org-group-bucket-items (prop items)
1281 (dolist (item items)
1282 (let* ((marker (get-text-property 0 'org-marker item))
1283 (pvalue (org-entry-get marker prop t))
1284 (cell (assoc pvalue buckets)))
1286 (setcdr cell (cons item (cdr cell)))
1287 (setq buckets (cons (cons pvalue (list item))
1289 (setq buckets (mapcar (lambda (bucket)
1291 (reverse (cdr bucket))))
1293 (sort buckets (lambda (i1 i2)
1294 (string< (car i1) (car i2))))))
1296 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1297 (list &optional nosort))
1298 "Prepare bucketed agenda entry lists"
1299 (if org-agenda-group-by-property
1300 ;; bucketed, handle appropriately
1302 (dolist (bucket (org-group-bucket-items
1303 org-agenda-group-by-property
1305 (let ((header (concat "Property "
1306 org-agenda-group-by-property
1308 (or (car bucket) "<nil>") ":\n")))
1309 (add-text-properties 0 (1- (length header))
1310 (list 'face 'org-agenda-structure)
1314 ;; recursively process
1315 (let ((org-agenda-group-by-property nil))
1316 (org-finalize-agenda-entries
1317 (cdr bucket) nosort))
1319 (setq ad-return-value text))
1321 (ad-activate 'org-finalize-agenda-entries)
1323 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1326 Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1328 A small hook run when clocking out of a task that prompts for a note
1329 when the tag "=clockout_note=" is found in a headline. It uses the tag
1330 ("=clockout_note=") so inheritance can also be used...
1332 #+begin_src emacs-lisp
1333 (defun rgr/check-for-clock-out-note()
1336 (org-back-to-heading)
1337 (let ((tags (org-get-tags)))
1338 (and tags (message "tags: %s " tags)
1339 (when (member "clocknote" tags)
1342 (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1344 *** Dynamically adjust tag position
1345 #+index: Tag!position
1346 Here is a bit of code that allows you to have the tags always
1347 right-adjusted in the buffer.
1349 This is useful when you have bigger window than default window-size
1350 and you dislike the aesthetics of having the tag in the middle of the
1353 This hack solves the problem of adjusting it whenever you change the
1355 Before saving it will revert the file to having the tag position be
1356 left-adjusted so that if you track your files with version control,
1357 you won't run into artificial diffs just because the window-size
1360 *IMPORTANT*: This is probably slow on very big files.
1362 #+begin_src emacs-lisp
1363 (setq ba/org-adjust-tags-column t)
1365 (defun ba/org-adjust-tags-column-reset-tags ()
1366 "In org-mode buffers it will reset tag position according to
1369 (not (string= (buffer-name) "*Remember*"))
1370 (eql major-mode 'org-mode))
1371 (let ((b-m-p (buffer-modified-p)))
1374 (goto-char (point-min))
1375 (command-execute 'outline-next-visible-heading)
1376 ;; disable (message) that org-set-tags generates
1377 (flet ((message (&rest ignored) nil))
1379 (set-buffer-modified-p b-m-p))
1382 (defun ba/org-adjust-tags-column-now ()
1383 "Right-adjust `org-tags-column' value, then reset tag position."
1384 (set (make-local-variable 'org-tags-column)
1385 (- (- (window-width) (length org-ellipsis))))
1386 (ba/org-adjust-tags-column-reset-tags))
1388 (defun ba/org-adjust-tags-column-maybe ()
1389 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1390 (when ba/org-adjust-tags-column
1391 (ba/org-adjust-tags-column-now)))
1393 (defun ba/org-adjust-tags-column-before-save ()
1394 "Tags need to be left-adjusted when saving."
1395 (when ba/org-adjust-tags-column
1396 (setq org-tags-column 1)
1397 (ba/org-adjust-tags-column-reset-tags)))
1399 (defun ba/org-adjust-tags-column-after-save ()
1400 "Revert left-adjusted tag position done by before-save hook."
1401 (ba/org-adjust-tags-column-maybe)
1402 (set-buffer-modified-p nil))
1404 ; automatically align tags on right-hand side
1405 (add-hook 'window-configuration-change-hook
1406 'ba/org-adjust-tags-column-maybe)
1407 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1408 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1409 (add-hook 'org-agenda-mode-hook '(lambda ()
1410 (setq org-agenda-tags-column (- (window-width)))))
1412 ; between invoking org-refile and displaying the prompt (which
1413 ; triggers window-configuration-change-hook) tags might adjust,
1414 ; which invalidates the org-refile cache
1415 (defadvice org-refile (around org-refile-disable-adjust-tags)
1416 "Disable dynamically adjusting tags"
1417 (let ((ba/org-adjust-tags-column nil))
1419 (ad-activate 'org-refile)
1421 *** Use an "attach" link type to open files without worrying about their location
1422 #+index: Link!Attach
1423 -- Darlan Cavalcante Moreira
1425 In the setup part in my org-files I put:
1428 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1431 Now I can use the "attach" link type, but org will ask me if I want to
1432 allow executing the elisp code. To avoid this you can even set
1433 org-confirm-elisp-link-function to nil (I don't like this because it allows
1434 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1439 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1441 This works very well.
1443 ** Org Agenda and Task Management
1444 *** Make it easier to set org-agenda-files from multiple directories
1445 #+index: Agenda!Files
1448 #+begin_src emacs-lisp
1449 (defun my-org-list-files (dirs ext)
1450 "Function to create list of org files in multiple subdirectories.
1451 This can be called to generate a list of files for
1452 org-agenda-files or org-refile-targets.
1454 DIRS is a list of directories.
1456 EXT is a list of the extensions of files to be included."
1457 (let ((dirs (if (listp dirs)
1460 (ext (if (listp ext)
1470 (file-expand-wildcards
1471 (concat (file-name-as-directory x) "*" y)))))
1476 (when (or (string-match "/.#" x)
1477 (string-match "#$" x))
1478 (setq files (delete x files))))
1482 (defvar my-org-agenda-directories '("~/org/")
1483 "List of directories containing org files.")
1484 (defvar my-org-agenda-extensions '(".org")
1485 "List of extensions of agenda files")
1487 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1488 (setq my-org-agenda-extensions '(".org" ".ref"))
1490 (defun my-org-set-agenda-files ()
1492 (setq org-agenda-files (my-org-list-files
1493 my-org-agenda-directories
1494 my-org-agenda-extensions)))
1496 (my-org-set-agenda-files)
1499 The code above will set your "default" agenda files to all files
1500 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1501 You can change these values by setting the variables
1502 my-org-agenda-extensions and my-org-agenda-directories. The function
1503 my-org-agenda-files-by-filetag uses these two variables to determine
1504 which files to search for filetags (i.e., the larger set from which
1505 the subset will be drawn).
1507 You can also easily use my-org-list-files to "mix and match"
1508 directories and extensions to generate different lists of agenda
1511 *** Restrict org-agenda-files by filetag
1512 #+index: Agenda!Files
1514 :CUSTOM_ID: set-agenda-files-by-filetag
1518 It is often helpful to limit yourself to a subset of your agenda
1519 files. For instance, at work, you might want to see only files related
1520 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1521 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
1522 commands]]. These solutions, however, require reapplying a filter each
1523 time you call the agenda or writing several new custom agenda commands
1524 for each context. Another solution is to use directories for different
1525 types of tasks and to change your agenda files with a function that
1526 sets org-agenda-files to the appropriate directory. But this relies on
1527 hard and static boundaries between files.
1529 The following functions allow for a more dynamic approach to selecting
1530 a subset of files based on filetags:
1532 #+begin_src emacs-lisp
1533 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1534 "Restrict org agenda files only to those containing filetag."
1536 (let* ((tagslist (my-org-get-all-filetags))
1538 (completing-read "Tag: "
1539 (mapcar 'car tagslist)))))
1540 (org-agenda-remove-restriction-lock 'noupdate)
1541 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1542 (setq org-agenda-overriding-restriction 'files)))
1544 (defun my-org-get-all-filetags ()
1545 "Get list of filetags from all default org-files."
1546 (let ((files org-agenda-files)
1548 (save-window-excursion
1549 (while (setq x (pop files))
1550 (set-buffer (find-file-noselect x))
1553 (let ((tagfiles (assoc y tagslist)))
1555 (setcdr tagfiles (cons x (cdr tagfiles)))
1556 (add-to-list 'tagslist (list y x)))))
1557 (my-org-get-filetags)))
1560 (defun my-org-get-filetags ()
1561 "Get list of filetags for current buffer"
1562 (let ((ftags org-file-tags)
1566 (org-substring-no-properties x))
1570 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1571 with all filetags in your "normal" agenda files. When you select a
1572 tag, org-agenda-files will be restricted to only those files
1573 containing the filetag. To release the restriction, type C-c C-x >
1574 (org-agenda-remove-restriction-lock).
1576 *** Highlight the agenda line under cursor
1577 #+index: Agenda!Highlight
1578 This is useful to make sure what task you are operating on.
1580 #+BEGIN_SRC emacs-lisp
1581 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1586 #+BEGIN_SRC emacs-lisp
1587 ;; hl-line seems to be only for emacs
1589 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1591 ;; highline-mode does not work straightaway in tty mode.
1592 ;; I use a black background
1594 '(highline-face ((((type tty) (class color))
1595 (:background "white" :foreground "black")))))
1598 *** Split frame horizontally for agenda
1599 #+index: Agenda!frame
1600 If you would like to split the frame into two side-by-side windows when
1601 displaying the agenda, try this hack from Jan Rehders, which uses the
1602 `toggle-window-split' from
1604 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1606 #+BEGIN_SRC emacs-lisp
1607 ;; Patch org-mode to use vertical splitting
1608 (defadvice org-prepare-agenda (after org-fix-split)
1609 (toggle-window-split))
1610 (ad-activate 'org-prepare-agenda)
1613 *** Automatically add an appointment when clocking in a task
1614 #+index: Clock!Automatically add an appointment when clocking in a task
1615 #+index: Appointment!Automatically add an appointment when clocking in a task
1616 #+BEGIN_SRC emacs-lisp
1617 ;; Make sure you have a sensible value for `appt-message-warning-time'
1618 (defvar bzg-org-clock-in-appt-delay 100
1619 "Number of minutes for setting an appointment by clocking-in")
1622 This function let's you add an appointment for the current entry.
1623 This can be useful when you need a reminder.
1625 #+BEGIN_SRC emacs-lisp
1626 (defun bzg-org-clock-in-add-appt (&optional n)
1627 "Add an appointment for the Org entry at point in N minutes."
1630 (org-back-to-heading t)
1631 (looking-at org-complex-heading-regexp)
1632 (let* ((msg (match-string-no-properties 4))
1633 (ct-time (decode-time))
1634 (appt-min (+ (cadr ct-time)
1635 (or n bzg-org-clock-in-appt-delay)))
1636 (appt-time ; define the time for the appointment
1637 (progn (setf (cadr ct-time) appt-min) ct-time)))
1638 (appt-add (format-time-string
1639 "%H:%M" (apply 'encode-time appt-time)) msg)
1640 (if (interactive-p) (message "New appointment for %s" msg)))))
1643 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1646 #+BEGIN_SRC emacs-lisp
1647 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1648 "Add an appointment when clocking a task in."
1649 (bzg-org-clock-in-add-appt))
1652 You may also want to delete the associated appointment when clocking
1653 out. This function does this:
1655 #+BEGIN_SRC emacs-lisp
1656 (defun bzg-org-clock-out-delete-appt nil
1657 "When clocking out, delete any associated appointment."
1660 (org-back-to-heading t)
1661 (looking-at org-complex-heading-regexp)
1662 (let* ((msg (match-string-no-properties 4)))
1663 (setq appt-time-msg-list
1667 (if (not (string-match (regexp-quote msg)
1668 (cadr appt))) appt))
1669 appt-time-msg-list)))
1673 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1675 #+BEGIN_SRC emacs-lisp
1676 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1677 "Delete an appointment when clocking a task out."
1678 (bzg-org-clock-out-delete-appt))
1681 *IMPORTANT*: You can add appointment by clocking in in both an
1682 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1683 agenda buffer with the advice above will bring an error.
1685 *** Using external programs for appointments reminders
1686 #+index: Appointment!reminders
1687 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1689 *** Remove from agenda time grid lines that are in an appointment
1690 #+index: Agenda!time grid
1691 #+index: Appointment!Remove from agenda time grid lines
1692 The agenda shows lines for the time grid. Some people think that
1693 these lines are a distraction when there are appointments at those
1694 times. You can get rid of the lines which coincide exactly with the
1695 beginning of an appointment. Michael Ekstrand has written a piece of
1696 advice that also removes lines that are somewhere inside an
1699 #+begin_src emacs-lisp
1700 (defun org-time-to-minutes (time)
1701 "Convert an HHMM time to minutes"
1702 (+ (* (/ time 100) 60) (% time 100)))
1704 (defun org-time-from-minutes (minutes)
1705 "Convert a number of minutes to an HHMM time"
1706 (+ (* (/ minutes 60) 100) (% minutes 60)))
1708 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1709 (list ndays todayp))
1710 (if (member 'remove-match (car org-agenda-time-grid))
1711 (flet ((extract-window
1713 (let ((start (get-text-property 1 'time-of-day line))
1714 (dur (get-text-property 1 'duration line)))
1718 (org-time-from-minutes
1719 (+ dur (org-time-to-minutes start)))))
1722 (let* ((windows (delq nil (mapcar 'extract-window list)))
1723 (org-agenda-time-grid
1724 (list (car org-agenda-time-grid)
1725 (cadr org-agenda-time-grid)
1728 (find-if (lambda (w)
1731 (and (>= time (car w))
1734 (caddr org-agenda-time-grid)))))
1737 (ad-activate 'org-agenda-add-time-grid-maybe)
1739 *** Disable version control for Org mode agenda files
1740 #+index: Agenda!Files
1743 Even if you use Git to track your agenda files you might not need
1744 vc-mode to be enabled for these files.
1746 #+begin_src emacs-lisp
1747 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1748 (defun dmj/disable-vc-for-agenda-files-hook ()
1749 "Disable vc-mode for Org agenda files."
1750 (if (and (fboundp 'org-agenda-file-p)
1751 (org-agenda-file-p (buffer-file-name)))
1752 (remove-hook 'find-file-hook 'vc-find-file-hook)
1753 (add-hook 'find-file-hook 'vc-find-file-hook)))
1756 *** Easy customization of TODO colors
1757 #+index: Customization!Todo keywords
1758 #+index: Todo keywords!Customization
1762 Here is some code I came up with some code to make it easier to
1763 customize the colors of various TODO keywords. As long as you just
1764 want a different color and nothing else, you can customize the
1765 variable org-todo-keyword-faces and use just a string color (i.e. a
1766 string of the color name) as the face, and then org-get-todo-face
1767 will convert the color to a face, inheriting everything else from
1768 the standard org-todo face.
1770 To demonstrate, I currently have org-todo-keyword-faces set to
1772 #+BEGIN_SRC emacs-lisp
1773 (("IN PROGRESS" . "dark orange")
1774 ("WAITING" . "red4")
1775 ("CANCELED" . "saddle brown"))
1778 Here's the code, in a form you can put in your =.emacs=
1780 #+BEGIN_SRC emacs-lisp
1781 (eval-after-load 'org-faces
1783 (defcustom org-todo-keyword-faces nil
1784 "Faces for specific TODO keywords.
1785 This is a list of cons cells, with TODO keywords in the car and
1786 faces in the cdr. The face can be a symbol, a color, or a
1787 property list of attributes, like (:foreground \"blue\" :weight
1788 bold :underline t)."
1793 (string :tag "Keyword")
1794 (choice color (sexp :tag "Face")))))))
1796 (eval-after-load 'org
1798 (defun org-get-todo-face-from-color (color)
1799 "Returns a specification for a face that inherits from org-todo
1800 face and has the given color as foreground. Returns nil if
1803 `(:inherit org-warning :foreground ,color)))
1805 (defun org-get-todo-face (kwd)
1806 "Get the right face for a TODO keyword KWD.
1807 If KWD is a number, get the corresponding match group."
1808 (if (numberp kwd) (setq kwd (match-string kwd)))
1809 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1811 (org-get-todo-face-from-color face)
1813 (and (member kwd org-done-keywords) 'org-done)
1817 *** Add an effort estimate on the fly when clocking in
1818 #+index: Effort estimate!Add when clocking in
1819 #+index: Clock!Effort estimate
1820 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1821 This way you can easily have a "tea-timer" for your tasks when they
1822 don't already have an effort estimate.
1824 #+begin_src emacs-lisp
1825 (add-hook 'org-clock-in-prepare-hook
1826 'my-org-mode-ask-effort)
1828 (defun my-org-mode-ask-effort ()
1829 "Ask for an effort estimate when clocking in."
1830 (unless (org-entry-get (point) "Effort")
1834 (org-entry-get-multivalued-property (point) "Effort"))))
1835 (unless (equal effort "")
1836 (org-set-property "Effort" effort)))))
1839 Or you can use a default effort for such a timer:
1841 #+begin_src emacs-lisp
1842 (add-hook 'org-clock-in-prepare-hook
1843 'my-org-mode-add-default-effort)
1845 (defvar org-clock-default-effort "1:00")
1847 (defun my-org-mode-add-default-effort ()
1848 "Add a default effort estimation."
1849 (unless (org-entry-get (point) "Effort")
1850 (org-set-property "Effort" org-clock-default-effort)))
1853 *** Use idle timer for automatic agenda views
1854 #+index: Agenda view!Refresh
1855 From John Wiegley's mailing list post (March 18, 2010):
1858 I have the following snippet in my .emacs file, which I find very
1859 useful. Basically what it does is that if I don't touch my Emacs for 5
1860 minutes, it displays the current agenda. This keeps my tasks "always
1861 in mind" whenever I come back to Emacs after doing something else,
1862 whereas before I had a tendency to forget that it was there.
1865 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1867 #+begin_src emacs-lisp
1868 (defun jump-to-org-agenda ()
1870 (let ((buf (get-buffer "*Org Agenda*"))
1873 (if (setq wind (get-buffer-window buf))
1874 (select-window wind)
1875 (if (called-interactively-p)
1877 (select-window (display-buffer buf t t))
1878 (org-fit-window-to-buffer)
1879 ;; (org-agenda-redo)
1881 (with-selected-window (display-buffer buf)
1882 (org-fit-window-to-buffer)
1883 ;; (org-agenda-redo)
1885 (call-interactively 'org-agenda-list)))
1886 ;;(let ((buf (get-buffer "*Calendar*")))
1887 ;; (unless (get-buffer-window buf)
1888 ;; (org-agenda-goto-calendar)))
1891 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1895 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1897 *** Refresh the agenda view regularly
1898 #+index: Agenda view!Refresh
1899 Hack sent by Kiwon Um:
1901 #+begin_src emacs-lisp
1902 (defun kiwon/org-agenda-redo-in-other-window ()
1903 "Call org-agenda-redo function even in the non-agenda buffer."
1905 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1907 (with-selected-window agenda-window (org-agenda-redo)))))
1908 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1911 *** Reschedule agenda items to today with a single command
1912 #+index: Agenda!Reschedule
1913 This was suggested by Carsten in reply to David Abrahams:
1915 #+begin_example emacs-lisp
1916 (defun org-agenda-reschedule-to-today ()
1918 (flet ((org-read-date (&rest rest) (current-time)))
1919 (call-interactively 'org-agenda-schedule)))
1922 *** Mark subtree DONE along with all subheadings
1923 #+index: Subtree!subheadings
1924 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
1926 #+begin_src emacs-lisp
1927 (defun bh/mark-subtree-done ()
1930 (let ((limit (point)))
1932 (exchange-point-and-mark)
1933 (while (> (point) limit)
1935 (outline-previous-visible-heading 1))
1936 (org-todo "DONE"))))
1939 Then M-x bh/mark-subtree-done.
1941 *** Mark heading done when all checkboxes are checked.
1943 :CUSTOM_ID: mark-done-when-all-checkboxes-checked
1948 An item consists of a list with checkboxes. When all of the
1949 checkboxes are checked, the item should be considered complete and its
1950 TODO state should be automatically changed to DONE. The code below
1951 does that. This version is slightly enhanced over the one in the
1953 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
1954 reset the state back to TODO if a checkbox is unchecked.
1956 Note that the code requires that a checkbox statistics cookie (the [/]
1957 or [%] thingie in the headline - see the [[http://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
1958 manual) be present in order for it to work. Note also that it is too
1959 dumb to figure out whether the item has a TODO state in the first
1960 place: if there is a statistics cookie, a TODO/DONE state will be
1961 added willy-nilly any time that the statistics cookie is changed.
1963 #+begin_src emacs-lisp
1964 ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
1965 (eval-after-load 'org-list
1966 '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
1968 (defun ndk/checkbox-list-complete ()
1970 (org-back-to-heading t)
1971 (let ((beg (point)) end)
1975 (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
1977 (if (equal (match-string 1) "100%")
1978 ;; all done - do the state change
1981 (if (and (> (match-end 2) (match-beginning 2))
1982 (equal (match-string 2) (match-string 3)))
1984 (org-todo 'todo)))))))
1987 *** Links to custom agenda views
1989 :CUSTOM_ID: links-to-agenda-views
1991 #+index: Agenda view!Links to
1992 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
1994 If you have custom agenda commands defined to some key, say w, then
1995 the following will serve as a link to the custom agenda buffer.
1996 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
1998 Clicking on it will prompt if you want to execute the elisp code. If
1999 you would rather not have the prompt or would want to respond with a
2000 single letter, ~y~ or ~n~, take a look at the docstrings of the
2001 variables =org-confirm-elisp-link-function= and
2002 =org-confirm-elisp-link-not-regexp=. Please take special note of the
2003 security risk associated with completely disabling the prompting
2006 ** Exporting org files
2007 *** Export Org to Org and handle includes.
2008 #+index: Export!handle includes
2009 Nick Dokos came up with this useful function:
2011 #+begin_src emacs-lisp
2012 (defun org-to-org-handle-includes ()
2013 "Copy the contents of the current buffer to OUTFILE,
2014 recursively processing #+INCLUDEs."
2015 (let* ((s (buffer-string))
2016 (fname (buffer-file-name))
2017 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
2021 (org-export-handle-include-files-recurse)
2024 (delete-region (point-min) (point-max))
2029 *** Specifying LaTeX commands to floating environments
2031 :CUSTOM_ID: latex-command-for-floats
2034 #+index: Export!LaTeX
2035 The keyword ~placement~ can be used to specify placement options to
2036 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2037 LaTeX export. Org passes along everything passed in options as long as
2038 there are no spaces. One can take advantage of this to pass other
2039 LaTeX commands and have their scope limited to the floating
2042 For example one can set the fontsize of a table different from the
2043 default normal size by putting something like =\footnotesize= right
2044 after the placement options. During LaTeX export using the
2045 ~#+ATTR_LaTeX:~ line below:
2048 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2051 exports the associated floating environment as shown in the following
2055 \begin{table}[<options>]\footnotesize
2060 It should be noted that this hack does not work for beamer export of
2061 tables since the =table= environment is not used. As an ugly
2062 workaround, one can use the following:
2065 ,#+LATEX: {\footnotesize
2066 ,#+ATTR_LaTeX: align=rr
2073 *** Styling code sections with CSS
2075 #+index: HTML!Styling code sections with CSS
2077 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2078 to HTML using =<pre>= tags, and assigned CSS classes by their content
2079 type. For example, Perl content will have an opening tag like
2080 =<pre class="src src-perl">=. You can use those classes to add styling
2081 to the output, such as here where a small language tag is added at the
2082 top of each kind of code box:
2085 (setq org-export-html-style
2086 "<style type=\"text/css\">
2087 <!--/*--><![CDATA[/*><!--*/
2088 .src { background-color: #F5FFF5; position: relative; overflow: visible; }
2089 .src:before { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2090 .src-sh:before { content: 'sh'; }
2091 .src-bash:before { content: 'sh'; }
2092 .src-R:before { content: 'R'; }
2093 .src-perl:before { content: 'Perl'; }
2094 .src-sql:before { content: 'SQL'; }
2095 .example { background-color: #FFF5F5; }
2100 Additionally, we use color to distinguish code output (the =.example=
2101 class) from input (all the =.src-*= classes).
2103 * Hacking Org: Working with Org-mode and other Emacs Packages.
2104 ** org-remember-anything
2106 #+index: Remember!Anything
2108 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2110 #+BEGIN_SRC emacs-lisp
2111 (defvar org-remember-anything
2112 '((name . "Org Remember")
2113 (candidates . (lambda () (mapcar 'car org-remember-templates)))
2114 (action . (lambda (name)
2115 (let* ((orig-template org-remember-templates)
2116 (org-remember-templates
2117 (list (assoc name orig-template))))
2118 (call-interactively 'org-remember))))))
2121 You can add it to your 'anything-sources' variable and open remember directly
2122 from anything. I imagine this would be more interesting for people with many
2123 remember templates, so that you are out of keys to assign those to.
2125 ** Org-mode and saveplace.el
2127 Fix a problem with =saveplace.el= putting you back in a folded position:
2129 #+begin_src emacs-lisp
2130 (add-hook 'org-mode-hook
2132 (when (outline-invisible-p)
2134 (outline-previous-visible-heading 1)
2135 (org-show-subtree)))))
2138 ** Using ido-mode for org-refile (and archiving via refile)
2140 First set up ido-mode, for example using:
2142 #+begin_src emacs-lisp
2143 ; use ido mode for completion
2144 (setq ido-everywhere t)
2145 (setq ido-enable-flex-matching t)
2146 (setq ido-max-directory-size 100000)
2147 (ido-mode (quote both))
2150 Now to enable it in org-mode, use the following:
2151 #+begin_src emacs-lisp
2152 (setq org-completion-use-ido t)
2153 (setq org-refile-use-outline-path nil)
2154 (setq org-refile-allow-creating-parent-nodes 'confirm)
2156 The last line enables the creation of nodes on the fly.
2158 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):
2159 #+begin_src emacs-lisp
2160 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2163 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.
2164 #+begin_src emacs-lisp
2165 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2166 ; added check to only include headlines, e.g. line must have at least one child
2167 (defun my/verify-refile-target ()
2168 "Exclude todo keywords with a DONE state from refile targets"
2169 (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2170 (save-excursion (org-goto-first-child))
2172 (setq org-refile-target-verify-function 'my/verify-refile-target)
2174 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.
2176 ** Using ido-completing-read to find attachments
2178 #+index: Attachment!ido completion
2182 Org-attach is great for quickly linking files to a project. But if you
2183 use org-attach extensively you might find yourself wanting to browse
2184 all the files you've attached to org headlines. This is not easy to do
2185 manually, since the directories containing the files are not human
2186 readable (i.e., they are based on automatically generated ids). Here's
2187 some code to browse those files using ido (obviously, you need to be
2190 #+begin_src emacs-lisp
2191 (load-library "find-lisp")
2193 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2195 (defun my-ido-find-org-attach ()
2196 "Find files in org-attachment directory"
2198 (let* ((enable-recursive-minibuffers t)
2199 (files (find-lisp-find-files org-attach-directory "."))
2202 (cons (file-name-nondirectory x)
2206 (remove-duplicates (mapcar #'car file-assoc-list)
2208 (filename (ido-completing-read "Org attachments: " filename-list nil t))
2209 (longname (cdr (assoc filename file-assoc-list))))
2210 (ido-set-current-directory
2211 (if (file-directory-p longname)
2213 (file-name-directory longname)))
2214 (setq ido-exit 'refresh
2215 ido-text-init ido-text
2219 (add-hook 'ido-setup-hook 'ido-my-keys)
2221 (defun ido-my-keys ()
2222 "Add my keybindings for ido."
2223 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2226 To browse your org attachments using ido fuzzy matching and/or the
2227 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2230 ** Link to Gnus messages by Message-Id
2231 #+index: Link!Gnus message by Message-Id
2232 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2233 discussion about linking to Gnus messages without encoding the folder
2234 name in the link. The following code hooks in to the store-link
2235 function in Gnus to capture links by Message-Id when in nnml folders,
2236 and then provides a link type "mid" which can open this link. The
2237 =mde-org-gnus-open-message-link= function uses the
2238 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2239 scan. It will go through them, in order, asking each to locate the
2240 message and opening it from the first one that reports success.
2242 It has only been tested with a single nnml backend, so there may be
2243 bugs lurking here and there.
2245 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2248 #+begin_src emacs-lisp
2249 ;; Support for saving Gnus messages by Message-ID
2250 (defun mde-org-gnus-save-by-mid ()
2251 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2252 (when (eq major-mode 'gnus-article-mode)
2253 (gnus-article-show-summary))
2254 (let* ((group gnus-newsgroup-name)
2255 (method (gnus-find-method-for-group group)))
2256 (when (eq 'nnml (car method))
2257 (let* ((article (gnus-summary-article-number))
2258 (header (gnus-summary-article-header article))
2259 (from (mail-header-from header))
2262 (let ((mid (mail-header-id header)))
2263 (if (string-match "<\\(.*\\)>" mid)
2264 (match-string 1 mid)
2265 (error "Malformed message ID header %s" mid)))))
2266 (date (mail-header-date header))
2267 (subject (gnus-summary-subject-string)))
2268 (org-store-link-props :type "mid" :from from :subject subject
2269 :message-id message-id :group group
2270 :link (org-make-link "mid:" message-id))
2271 (apply 'org-store-link-props
2272 :description (org-email-link-description)
2273 org-store-link-plist)
2276 (defvar mde-mid-resolve-methods '()
2277 "List of methods to try when resolving message ID's. For Gnus,
2278 it is a cons of 'gnus and the select (type and name).")
2279 (setq mde-mid-resolve-methods
2282 (defvar mde-org-gnus-open-level 1
2283 "Level at which Gnus is started when opening a link")
2284 (defun mde-org-gnus-open-message-link (msgid)
2285 "Open a message link with Gnus"
2287 (require 'org-table)
2288 (catch 'method-found
2289 (message "[MID linker] Resolving %s" msgid)
2290 (dolist (method mde-mid-resolve-methods)
2292 ((and (eq (car method) 'gnus)
2293 (eq (cadr method) 'nnml))
2294 (funcall (cdr (assq 'gnus org-link-frame-setup))
2295 mde-org-gnus-open-level)
2296 (when gnus-other-frame-object
2297 (select-frame gnus-other-frame-object))
2298 (let* ((msg-info (nnml-find-group-number
2299 (concat "<" msgid ">")
2301 (group (and msg-info (car msg-info)))
2302 (message (and msg-info (cdr msg-info)))
2304 (if (gnus-methods-equal-p
2308 (gnus-group-full-name group (cdr method))))))
2310 (gnus-summary-read-group qname nil t)
2311 (gnus-summary-goto-article message nil t))
2312 (throw 'method-found t)))
2313 (t (error "Unknown link type"))))))
2315 (eval-after-load 'org-gnus
2317 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2318 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2321 ** Store link to a message when sending in Gnus
2322 #+index: Link!Store link to a message when sending in Gnus
2323 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2325 #+begin_src emacs-lisp
2326 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2327 "Send message with `message-send-and-exit' and store org link to message copy.
2328 If multiple groups appear in the Gcc header, the link refers to
2329 the copy in the last group."
2333 (message-narrow-to-headers)
2334 (let ((gcc (car (last
2335 (message-unquote-tokens
2336 (message-tokenize-header
2337 (mail-fetch-field "gcc" nil t) " ,")))))
2338 (buf (current-buffer))
2339 (message-kill-buffer-on-exit nil)
2340 id to from subject desc link newsgroup xarchive)
2341 (message-send-and-exit arg)
2343 ;; gcc group found ...
2345 (save-current-buffer
2346 (progn (set-buffer buf)
2347 (setq id (org-remove-angle-brackets
2348 (mail-fetch-field "Message-ID")))
2349 (setq to (mail-fetch-field "To"))
2350 (setq from (mail-fetch-field "From"))
2351 (setq subject (mail-fetch-field "Subject"))))
2352 (org-store-link-props :type "gnus" :from from :subject subject
2353 :message-id id :group gcc :to to)
2354 (setq desc (org-email-link-description))
2355 (setq link (org-gnus-article-link
2356 gcc newsgroup id xarchive))
2357 (setq org-stored-links
2358 (cons (list link desc) org-stored-links)))
2359 ;; no gcc group found ...
2360 (message "Can not create Org link: No Gcc header found."))))))
2362 (define-key message-mode-map [(control c) (control meta c)]
2363 'ulf-message-send-and-org-gnus-store-link)
2366 ** Send html messages and attachments with Wanderlust
2369 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2370 similar functionality for both Wanderlust and Gnus. The hack below is
2371 still somewhat different: It allows you to toggle sending of html
2372 messages within Wanderlust transparently. I.e. html markup of the
2373 message body is created right before sending starts.
2375 *** Send HTML message
2377 Putting the code below in your .emacs adds following four functions:
2379 - dmj/wl-send-html-message
2381 Function that does the job: Convert everything between "--text
2382 follows this line--" and first mime entity (read: attachment) or
2383 end of buffer into html markup using `org-export-region-as-html'
2384 and replaces original body with a multipart MIME entity with the
2385 plain text version of body and the html markup version. Thus a
2386 recipient that prefers html messages can see the html markup,
2387 recipients that prefer or depend on plain text can see the plain
2390 Cannot be called interactively: It is hooked into SEMI's
2391 `mime-edit-translate-hook' if message should be HTML message.
2393 - dmj/wl-send-html-message-draft-init
2395 Cannot be called interactively: It is hooked into WL's
2396 `wl-mail-setup-hook' and provides a buffer local variable to
2399 - dmj/wl-send-html-message-draft-maybe
2401 Cannot be called interactively: It is hooked into WL's
2402 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2403 `mime-edit-translate-hook' depending on whether HTML message is
2406 - dmj/wl-send-html-message-toggle
2408 Toggles sending of HTML message. If toggled on, the letters
2409 "HTML" appear in the mode line.
2411 Call it interactively! Or bind it to a key in `wl-draft-mode'.
2413 If you have to send HTML messages regularly you can set a global
2414 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2415 toggle on sending HTML message by default.
2417 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2418 Google's web front end. As you can see you have the whole markup of
2419 Org at your service: *bold*, /italics/, tables, lists...
2421 So even if you feel uncomfortable with sending HTML messages at least
2422 you send HTML that looks quite good.
2424 #+begin_src emacs-lisp
2425 (defun dmj/wl-send-html-message ()
2426 "Send message as html message.
2427 Convert body of message to html using
2428 `org-export-region-as-html'."
2431 (let (beg end html text)
2432 (goto-char (point-min))
2433 (re-search-forward "^--text follows this line--$")
2434 ;; move to beginning of next line
2435 (beginning-of-line 2)
2437 (if (not (re-search-forward "^--\\[\\[" nil t))
2438 (setq end (point-max))
2443 (setq text (buffer-substring-no-properties beg end))
2449 (when (re-search-backward "^-- \n" nil t)
2450 ;; preserve link breaks in signature
2451 (insert "\n#+BEGIN_VERSE\n")
2452 (goto-char (point-max))
2453 (insert "\n#+END_VERSE\n")
2455 (setq html (org-export-region-as-html
2456 (point-min) (point-max) t 'string))))
2457 (delete-region beg end)
2460 "--" "<<alternative>>-{\n"
2461 "--" "[[text/plain]]\n" text
2462 "--" "[[text/html]]\n" html
2463 "--" "}-<<alternative>>\n")))))
2465 (defun dmj/wl-send-html-message-toggle ()
2466 "Toggle sending of html message."
2468 (setq dmj/wl-send-html-message-toggled-p
2469 (if dmj/wl-send-html-message-toggled-p
2471 (message "Sending html message toggled %s"
2472 (if dmj/wl-send-html-message-toggled-p
2475 (defun dmj/wl-send-html-message-draft-init ()
2476 "Create buffer local settings for maybe sending html message."
2477 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2478 (setq dmj/wl-send-html-message-toggled-p nil))
2479 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2480 (add-to-list 'global-mode-string
2481 '(:eval (if (eq major-mode 'wl-draft-mode)
2482 dmj/wl-send-html-message-toggled-p))))
2484 (defun dmj/wl-send-html-message-maybe ()
2485 "Maybe send this message as html message.
2487 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2488 non-nil, add `dmj/wl-send-html-message' to
2489 `mime-edit-translate-hook'."
2490 (if dmj/wl-send-html-message-toggled-p
2491 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2492 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2494 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2495 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2496 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2499 *** Attach HTML of region or subtree
2501 Instead of sending a complete HTML message you might only send parts
2502 of an Org file as HTML for the poor souls who are plagued with
2503 non-proportional fonts in their mail program that messes up pretty
2506 This short function does the trick: It exports region or subtree to
2507 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2508 and clipboard. If a region is active, it uses the region, the
2509 complete subtree otherwise.
2511 #+begin_src emacs-lisp
2512 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2513 "Export region between BEG and END as html attachment.
2514 If BEG and END are not set, use current subtree. Region or
2515 subtree is exported to html without header and footer, prefixed
2516 with a mime entity string and pushed to clipboard and killring.
2517 When called with prefix, mime entity is not marked as
2519 (interactive "r\nP")
2521 (let* ((beg (if (region-active-p) (region-beginning)
2523 (org-back-to-heading)
2525 (end (if (region-active-p) (region-end)
2527 (org-end-of-subtree)
2529 (html (concat "--[[text/html"
2530 (if arg "" "\nContent-Disposition: attachment")
2532 (org-export-region-as-html beg end t 'string))))
2533 (when (fboundp 'x-set-selection)
2534 (ignore-errors (x-set-selection 'PRIMARY html))
2535 (ignore-errors (x-set-selection 'CLIPBOARD html)))
2536 (message "html export done, pushed to kill ring and clipboard"))))
2539 *** Adopting for Gnus
2541 The whole magic lies in the special strings that mark a HTML
2542 attachment. So you might just have to find out what these special
2543 strings are in message-mode and modify the functions accordingly.
2544 ** Add sunrise/sunset times to the agenda.
2545 #+index: Agenda!Diary s-expressions
2548 The diary package provides the function =diary-sunrise-sunset= which can be used
2549 in a diary s-expression in some agenda file like this:
2551 #+begin_src org-mode
2552 %%(diary-sunrise-sunset)
2555 Seb Vauban asked if it is possible to put sunrise and sunset in
2556 separate lines. Here is a hack to do that. It adds two functions (they
2557 have to be available before the agenda is shown, so I add them early
2558 in my org-config file which is sourced from .emacs, but you'll have to
2559 suit yourself here) that just parse the output of
2560 diary-sunrise-sunset, instead of doing the right thing which would be
2561 to take advantage of the data structures that diary/solar.el provides.
2562 In short, a hack - so perfectly suited for inclusion here :-)
2564 The functions (and latitude/longitude settings which you have to modify for
2565 your location) are as follows:
2567 #+begin_src emacs-lisp
2568 (setq calendar-latitude 48.2)
2569 (setq calendar-longitude 16.4)
2570 (setq calendar-location-name "Vienna, Austria")
2572 (autoload 'solar-sunrise-sunset "solar.el")
2573 (autoload 'solar-time-string "solar.el")
2574 (defun diary-sunrise ()
2575 "Local time of sunrise as a diary entry.
2576 The diary entry can contain `%s' which will be replaced with
2577 `calendar-location-name'."
2578 (let ((l (solar-sunrise-sunset date)))
2581 (if (string= entry "")
2583 (format entry (eval calendar-location-name))) " "
2584 (solar-time-string (caar l) nil)))))
2586 (defun diary-sunset ()
2587 "Local time of sunset as a diary entry.
2588 The diary entry can contain `%s' which will be replaced with
2589 `calendar-location-name'."
2590 (let ((l (solar-sunrise-sunset date)))
2593 (if (string= entry "")
2595 (format entry (eval calendar-location-name))) " "
2596 (solar-time-string (caadr l) nil)))))
2599 You also need to add a couple of diary s-expressions in one of your agenda
2602 #+begin_src org-mode
2603 %%(diary-sunrise)Sunrise in %s
2607 This will show sunrise with the location and sunset without it.
2609 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]].
2610 In comparison to the version posted on the mailing list, this one
2611 gets rid of the timezone information and can show the location.
2612 ** Add lunar phases to the agenda.
2613 #+index: Agenda!Diary s-expressions
2616 Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
2617 This can be used to display lunar phases in the agenda display with the
2620 #+begin_src emacs-lisp
2623 (org-no-warnings (defvar date))
2624 (defun org-lunar-phases ()
2625 "Show lunar phase in Agenda buffer."
2627 (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
2628 (phase (cl-find-if (lambda (phase) (equal (car phase) date))
2631 (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
2632 (substring (nth 1 phase) 0 5))))))
2635 Add the following line to an agenda file:
2637 #+begin_src org-mode
2640 %%(org-lunar-phases)
2643 This should display an entry on new moon, first/last quarter moon, and on full
2644 moon. You can customize the entries by customizing =lunar-phase-names=.
2646 E.g., to add Unicode symbols:
2648 #+begin_src emacs-lisp
2649 (setq lunar-phase-names
2650 '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
2651 "☽ First Quarter Moon"
2652 "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
2653 "☾ Last Quarter Moon"))
2656 Unicode 6 even provides symbols for the Moon with nice faces. But those
2657 symbols are currently barely supported in fonts.
2658 See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].
2660 ** Export BBDB contacts to org-contacts.el
2661 #+index: Address Book!BBDB to org-contacts
2662 Try this tool by Wes Hardaker:
2664 http://www.hardakers.net/code/bbdb-to-org-contacts/
2666 ** Calculating date differences - how to write a simple elisp function
2667 #+index: Timestamp!date calculations
2668 #+index: Elisp!technique
2670 Alexander Wingård asked how to calculate the number of days between a
2671 time stamp in his org file and today (see
2672 http://thread.gmane.org/gmane.emacs.orgmode/46881). Although the
2673 resulting answer is probably not of general interest, the method might
2674 be useful to a budding Elisp programmer.
2676 Alexander started from an already existing org function,
2677 =org-evaluate-time-range=. When this function is called in the context
2678 of a time range (two time stamps separated by "=--="), it calculates the
2679 number of days between the two dates and outputs the result in Emacs's
2680 echo area. What he wanted was a similar function that, when called from
2681 the context of a single time stamp, would calculate the number of days
2682 between the date in the time stamp and today. The result should go to
2683 the same place: Emacs's echo area.
2685 The solution presented in the mail thread is as follows:
2687 #+begin_src emacs-lisp
2688 (defun aw/org-evaluate-time-range (&optional to-buffer)
2690 (if (org-at-date-range-p t)
2691 (org-evaluate-time-range to-buffer)
2692 ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
2693 (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
2696 (goto-char (point-at-bol))
2697 (re-search-forward org-ts-regexp (point-at-eol) t)
2698 (if (not (org-at-timestamp-p t))
2699 (error "No timestamp here"))
2700 (goto-char (match-beginning 0))
2701 (org-insert-time-stamp (current-time) nil nil)
2703 (org-evaluate-time-range to-buffer)))))
2706 The function assumes that point is on some line with some time stamp
2707 (or a date range) in it. Note that =org-evaluate-time-range= does not care
2708 whether the first date is earlier than the second: it will always output
2709 the number of days between the earlier date and the later date.
2711 As stated before, the function itself is of limited interest (although
2712 it satisfied Alexander's need).The *method* used might be of wider
2713 interest however, so here is a short explanation.
2715 The idea is that we want =org-evaluate-time-range= to do all the
2716 heavy lifting, but that function requires that it be in a date-range
2717 context. So the function first checks whether it's in a date range
2718 context already: if so, it calls =org-evaluate-time-range= directly
2719 to do the work. The trick now is to arrange things so we can call this
2720 same function in the case where we do *not* have a date range
2721 context. In that case, we manufacture one: we create a temporary
2722 buffer, copy the line with the purported time stamp to the temp
2723 buffer, find the time stamp (signal an error if no time stamp is
2724 found) and insert a new time stamp with the current time before the
2725 existing time stamp, followed by "=--=": voilà, we now have a time range
2726 on which we can apply our old friend =org-evaluate-time-range= to
2727 produce the answer. Because of the above-mentioned property
2728 of =org-evaluate-time-range=, it does not matter if the existing
2729 time stamp is earlier or later than the current time: the correct
2730 number of days is output.
2732 Note that at the end of the call to =with-temp-buffer=, the temporary
2733 buffer goes away. It was just used as a scratch pad for the function
2734 to do some figuring.
2736 The idea of using a temp buffer as a scratch pad has wide
2737 applicability in Emacs programming. The rest of the work is knowing
2738 enough about facilities provided by Emacs (e.g. regexp searching) and
2739 by Org (e.g. checking for time stamps and generating a time stamp) so
2740 that you don't reinvent the wheel, and impedance-matching between the
2743 ** ibuffer and org files
2745 Neil Smithline posted this snippet to let you browse org files with
2748 #+BEGIN_SRC emacs-lisp
2751 (defun org-ibuffer ()
2752 "Open an `ibuffer' window showing only `org-mode' buffers."
2754 (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
2757 ** Enable org-mode links in other modes
2759 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
2761 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
2763 * Hacking Org: Working with Org-mode and External Programs.
2764 ** Use Org-mode with Screen [Andrew Hyatt]
2765 #+index: Link!to screen session
2766 "The general idea is that you start a task in which all the work will
2767 take place in a shell. This usually is not a leaf-task for me, but
2768 usually the parent of a leaf task. From a task in your org-file, M-x
2769 ash-org-screen will prompt for the name of a session. Give it a name,
2770 and it will insert a link. Open the link at any time to go the screen
2771 session containing your work!"
2773 http://article.gmane.org/gmane.emacs.orgmode/5276
2775 #+BEGIN_SRC emacs-lisp
2778 (defun ash-org-goto-screen (name)
2779 "Open the screen with the specified name in the window"
2780 (interactive "MScreen name: ")
2781 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2782 (if (member screen-buffer-name
2783 (mapcar 'buffer-name (buffer-list)))
2784 (switch-to-buffer screen-buffer-name)
2785 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2787 (defun ash-org-screen-buffer-name (name)
2788 "Returns the buffer name corresponding to the screen name given."
2789 (concat "*screen " name "*"))
2791 (defun ash-org-screen-helper (name arg)
2792 ;; Pick the name of the new buffer.
2793 (let ((term-ansi-buffer-name
2794 (generate-new-buffer-name
2795 (ash-org-screen-buffer-name name))))
2796 (setq term-ansi-buffer-name
2797 (term-ansi-make-term
2798 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2799 (set-buffer term-ansi-buffer-name)
2802 (term-set-escape-char ?\C-x)
2803 term-ansi-buffer-name))
2805 (defun ash-org-screen (name)
2806 "Start a screen session with name"
2807 (interactive "MScreen name: ")
2809 (ash-org-screen-helper name "-S"))
2810 (insert-string (concat "[[screen:" name "]]")))
2812 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2813 ;; \"%s\")") to org-link-abbrev-alist.
2816 ** Org Agenda + Appt + Zenity
2818 :CUSTOM_ID: org-agenda-appt-zenity
2821 #+index: Appointment!reminders
2822 #+index: Appt!Zenity
2824 <a name="agenda-appt-zenity"></a>
2826 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It makes sure your agenda
2827 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2830 #+BEGIN_SRC emacs-lisp
2831 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2832 ; For org appointment reminders
2834 ;; Get appointments for today
2835 (defun my-org-agenda-to-appt ()
2837 (setq appt-time-msg-list nil)
2838 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
2839 (org-agenda-to-appt)))
2841 ;; Run once, activate and schedule refresh
2842 (my-org-agenda-to-appt)
2844 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2847 (setq appt-message-warning-time 15)
2848 (setq appt-display-interval 5)
2850 ; Update appt each time agenda opened.
2851 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2853 ; Setup zenify, we tell appt to use window, and replace default function
2854 (setq appt-display-format 'window)
2855 (setq appt-disp-window-function (function my-appt-disp-window))
2857 (defun my-appt-disp-window (min-to-app new-time msg)
2858 (save-window-excursion (shell-command (concat
2859 "/usr/bin/zenity --info --title='Appointment' --text='"
2860 msg "' &") nil nil)))
2863 ** Org-Mode + gnome-osd
2864 #+index: Appointment!reminders
2865 #+index: Appt!gnome-osd
2866 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2867 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2870 #+index: Agenda!Views
2871 #+index: Agenda!and Remind (external program)
2874 http://article.gmane.org/gmane.emacs.orgmode/5073
2877 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2878 command line calendaring program. Its features supersede the possibilities
2879 of orgmode in the area of date specifying, so that I want to use it
2880 combined with orgmode.
2882 Using the script below I'm able use remind and incorporate its output in my
2883 agenda views. The default of using 13 months look ahead is easily
2884 changed. It just happens I sometimes like to look a year into the
2888 ** Useful webjumps for conkeror
2889 #+index: Shortcuts!conkeror
2890 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2891 your =~/.conkerorrc= file:
2894 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2895 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2898 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2899 Org-mode mailing list.
2901 ** Use MathJax for HTML export without requiring JavaScript
2902 #+index: Export!MathJax
2903 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2905 If you like the results but do not want JavaScript in the exported pages,
2906 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2907 HTML file from the exported version. It can also embed all referenced fonts
2908 within the HTML file itself, so there are no dependencies to external files.
2910 The download archive contains an elisp file which integrates it into the Org
2911 export process (configurable per file with a "#+StaticMathJax:" line).
2913 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2914 ** Search Org files using lgrep
2915 #+index: search!lgrep
2916 Matt Lundin suggests this:
2918 #+begin_src emacs-lisp
2919 (defun my-org-grep (search &optional context)
2920 "Search for word in org files.
2922 Prefix argument determines number of lines."
2923 (interactive "sSearch for: \nP")
2924 (let ((grep-find-ignored-files '("#*" ".#*"))
2925 (grep-template (concat "grep <X> -i -nH "
2927 (concat "-C" (number-to-string context)))
2929 (lgrep search "*org*" "/home/matt/org/")))
2931 (global-set-key (kbd "<f8>") 'my-org-grep)
2934 ** Automatic screenshot insertion
2935 #+index: Link!screenshot
2936 Suggested by Russell Adams
2938 #+begin_src emacs-lisp
2939 (defun my-org-screenshot ()
2940 "Take a screenshot into a time stamped unique-named file in the
2941 same directory as the org-buffer and insert a link to this file."
2946 (concat (buffer-file-name)
2948 (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
2949 (call-process "import" nil nil nil filename)
2950 (insert (concat "[[" filename "]]"))
2951 (org-display-inline-images))
2954 ** Capture invitations/appointments from MS Exchange emails
2955 #+index: Appointment!MS Exchange
2956 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
2957 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
2959 ** Audio/video file playback within org mode
2960 #+index: Link!audio/video
2961 Paul Sexton provided code that makes =file:= links to audio or video files
2962 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
2963 media player library. The user can pause, skip forward and backward in the
2964 track, and so on from without leaving Emacs. Links can also contain a time
2965 after a double colon -- when this is present, playback will begin at that
2966 position in the track.
2968 See the file [[file:code/elisp/org-player.el][org-player.el]]
2970 ** Under X11 Keep a window with the current agenda items at all time
2971 #+index: Agenda!dedicated window
2972 I struggle to keep (in emacs) a window with the agenda at all times.
2973 For a long time I have wanted a sticky window that keeps this
2974 information, and then use my window manager to place it and remove its
2975 decorations (I can also force its placement in the stack: top always,
2978 I wrote a small program in qt that simply monitors an HTML file and
2979 displays it. Nothing more. It does the work for me, and maybe somebody
2980 else will find it useful. It relies on exporting the agenda as HTML
2981 every time the org file is saved, and then this little program
2982 displays the html file. The window manager is responsible of removing
2983 decorations, making it sticky, and placing it in same place always.
2985 Here is a screenshot (see window to the bottom right). The decorations
2986 are removed by the window manager:
2988 http://turingmachine.org/hacking/org-mode/orgdisplay.png
2990 Here is the code. As I said, very, very simple, but maybe somebody will
2993 http://turingmachine.org/hacking/org-mode/
2997 ** Script (thru procmail) to output emails to an Org file
2998 #+index: Conversion!email to org file
2999 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
3001 : I've [...] created some procmail and shell glue that takes emails and
3002 : inserts them into an org-file so that I can capture stuff on the go using
3003 : the email program.
3005 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3007 ** Save File With Different Format for Headings (fileconversion)
3009 :CUSTOM_ID: fileconversion
3011 #+index: Conversion!fileconversion
3013 Using hooks and on the fly
3014 - when writing a buffer to the file replace the leading stars from headings
3016 - when reading a file into the buffer replace the file chars with leading
3019 To change to save an Org file in one of the formats or back just add or
3020 remove the keyword in the STARTUP line and save.
3022 Now you can also change to Fundamental mode to see how the file looks like
3023 on the level of the file, go back to Org mode, reenter Org mode or change to
3024 any other major mode and the conversion gets done whenever necessary.
3026 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
3028 :CUSTOM_ID: hidestarsfile
3030 #+index: Conversion!fileconversion hidestarsfile
3032 This is like "a cleaner outline view":
3033 http://orgmode.org/manual/Clean-view.html
3035 Example of the _file content_ first with leading stars as usual and below
3036 without leading stars through "#+STARTUP: odd hidestars hidestarsfile":
3039 #+STARTUP: odd hidestars
3051 #+STARTUP: odd hidestars hidestarsfile
3062 The latter is convenient for better human readability when an Org file,
3063 additionally to Emacs, is read with a file viewer or, for smaller edits,
3064 with an editor not capable of the Org file format.
3066 hidestarsfile is a hack and can not become part of the Org core:
3067 - An Org file with hidestarsfile can not contain list items with a star as
3068 bullet due to the syntax conflict at read time. Mark E. Shoulson suggested
3069 to use the non-breaking space which is now implemented in fileconversion
3070 as nbspstarsfile as an alternative for hidestarsfile. Although I don't
3071 recommend it because an editor like typically e. g. Emacs may render the
3072 non-breaking space differently from the space 0x20.
3073 - An Org file with hidestarsfile can almost not be edited with an Org mode
3074 without added functionality of hidestarsfile as long as the file is not
3077 *** Headings in Markdown Format (markdownstarsfile)
3079 :CUSTOM_ID: markdownstarsfile
3081 #+index: Conversion!fileconversion markdownstarsfile
3083 For "oddeven" you can use markdownstarsfile to be readable or even basically
3084 editable with Markdown (does not make much sense with "odd", see
3085 org-convert-to-odd-levels and org-convert-to-oddeven-levels for how to
3088 Example of the _file content_:
3091 #+STARTUP: oddeven markdownstarsfile
3093 1. first item of numbered list (same format in Org and Markdown)
3095 - first item of unordered list (same format in Org and Markdown)
3097 + first item of unordered list (same format in Org and Markdown)
3098 #### section level 4
3099 * first item of unordered list (same format in Org and Markdown)
3100 * avoid this item type to be compatible with Org hidestarsfile
3103 An Org file with markdownstarsfile can not contain code comment lines
3104 prefixed with "#", even not when within source blocks.
3108 :CUSTOM_ID: fileconversion-code
3110 #+index: Conversion!fileconversion emacs-lisp code
3112 #+BEGIN_SRC emacs-lisp
3113 ;; - fileconversion version 0.6
3114 ;; - DISCLAIMER: Make a backup of your Org files before using
3115 ;; my-org-fileconv-*.
3116 ;; - supported formats: hidestarsfile, markdownstarsfile
3118 ;; design summary: fileconversion is a round robin of two states
3119 ;; linked by two actions:
3120 ;; - state my-org-fileconv-level-org-p is nil: the level is "file"
3122 ;; - action my-org-fileconv-decode: replace file char with '*'
3123 ;; - state my-org-fileconv-level-org-p is t: the level is "Org"
3125 ;; - action my-org-fileconv-encode replace '*' with file char
3127 (defvar my-org-fileconv-level-org-p nil
3128 "Whether level of buffer is Org or only file.
3129 nil means the level is file (encoded), non-nil means the level is Org
3131 (make-variable-buffer-local 'my-org-fileconv-level-org-p)
3132 ;; survive a change of major mode that does kill-all-local-variables,
3133 ;; e. g. when reentering Org mode through “C-c C-c” on a STARTUP line
3134 (put 'my-org-fileconv-level-org-p 'permanent-local t)
3136 (add-hook 'org-mode-hook 'my-org-fileconv-init
3137 ;; _append_ to hook to have a higher chance that a message
3138 ;; from this function will be visible as the last message in
3141 ;; hook addition global
3144 (defun my-org-fileconv-init ()
3146 ;; instrument only when converting really from/to an Org _file_, not
3147 ;; e. g. for a temp Org buffer unrelated to a file like used e. g.
3148 ;; when calling the old Org exporter
3149 (when (buffer-file-name)
3150 (message "INF: my-org-fileconv-init, buffer: %s" (buffer-name))
3151 (my-org-fileconv-decode)
3152 ;; the hooks are not permanent-local, this way and as needed they
3153 ;; will disappear when the major mode of the buffer changes
3154 (add-hook 'change-major-mode-hook 'my-org-fileconv-encode nil
3155 ;; hook addition limited to buffer locally
3157 (add-hook 'before-save-hook 'my-org-fileconv-encode nil
3158 ;; hook addition limited to buffer locally
3160 (add-hook 'after-save-hook 'my-org-fileconv-decode nil
3161 ;; hook addition limited to buffer locally
3164 (defun my-org-fileconv-re ()
3165 "Check whether there is a STARTUP line for fileconversion.
3166 If found then return the expressions required for the conversion."
3168 (beginning-of-buffer)
3169 (let (re-list (count 0))
3170 (while (re-search-forward "^#\\+STARTUP:" nil t)
3171 ;; #+STARTUP: hidestarsfile
3172 (when (string-match-p "\\bhidestarsfile\\b"
3173 (thing-at-point 'line))
3175 ;; - line starting with star for bold emphasis
3176 ;; - line of stars to underline section title in loosely
3177 ;; quoted ASCII style (star at end of line)
3178 (setq re-list '("\\(\\* \\)" ; common-re
3180 (setq count (1+ count)))
3181 ;; #+STARTUP: nbspstarsfile
3182 (when (string-match-p "\\bnbspstarsfile\\b"
3183 (thing-at-point 'line))
3184 (setq re-list '("\\(\\* \\)" ; common-re
3185 ?\xa0)) ; file-char non-breaking space
3186 (setq count (1+ count)))
3187 ;; #+STARTUP: markdownstarsfile
3188 (when (string-match-p "\\bmarkdownstarsfile\\b"
3189 (thing-at-point 'line))
3192 (setq re-list '("\\( \\)" ; common-re
3194 (setq count (1+ count))))
3196 (error "ERR: more than one fileconversion found"))
3199 (defun my-org-fileconv-decode ()
3200 "In headings replace file char with '*'."
3201 (let ((re-list (my-org-fileconv-re)))
3202 (when (and re-list (not my-org-fileconv-level-org-p))
3203 ;; no `save-excursion' to be able to keep point in case of error
3204 (let* ((common-re (nth 0 re-list))
3205 (file-char (nth 1 re-list))
3206 (file-re (concat "^" (string file-char) "+" common-re))
3207 (org-re (concat "^\\*+" common-re))
3210 (beginning-of-buffer)
3212 (when (re-search-forward org-re nil t)
3213 (goto-char (match-beginning 0))
3216 "ERR: my-org-fileconv-decode syntax conflict at point"))
3217 (beginning-of-buffer)
3219 (with-silent-modifications
3220 (while (re-search-forward file-re nil t)
3221 (goto-char (match-beginning 0))
3222 ;; faster than a lisp call of insert and delete on each
3224 (setq len (- (match-beginning 1) (match-beginning 0)))
3225 (insert-char ?* len)
3229 ;; notes for ediff when only one file has fileconversion:
3230 ;; - The changes to the buffer with fileconversion until here
3231 ;; are not regarded by ediff-files because the first call to
3232 ;; diff is made with the bare files directly. Only
3233 ;; ediff-update-diffs and ediff-buffers write the decoded
3234 ;; buffers to temp files and then call diff with them.
3235 ;; - Workarounds (choose one):
3236 ;; - after ediff-files first do a "!" (ediff-update-diffs)
3237 ;; in the "*Ediff Control Panel*"
3238 ;; - instead of using ediff-files first open the files and
3239 ;; then run ediff-buffers (better for e. g. a script that
3240 ;; takes two files as arguments and uses "emacs --eval")
3242 ;; the level is Org most of all when no fileconversion is in effect
3243 (setq my-org-fileconv-level-org-p t))
3245 (defun my-org-fileconv-encode ()
3246 "In headings replace '*' with file char."
3247 (let ((re-list (my-org-fileconv-re)))
3248 (when (and re-list my-org-fileconv-level-org-p)
3249 ;; no `save-excursion' to be able to keep point in case of error
3250 (let* ((common-re (nth 0 re-list))
3251 (file-char (nth 1 re-list))
3252 (file-re (concat "^" (string file-char) "+" common-re))
3253 (org-re (concat "^\\*+" common-re))
3256 (beginning-of-buffer)
3258 (when (re-search-forward file-re nil t)
3259 (goto-char (match-beginning 0))
3262 "ERR: my-org-fileconv-encode syntax conflict at point"))
3263 (beginning-of-buffer)
3265 (with-silent-modifications
3266 (while (re-search-forward org-re nil t)
3267 (goto-char (match-beginning 0))
3268 ;; faster than a lisp call of insert and delete on each
3270 (setq len (- (match-beginning 1) (match-beginning 0)))
3271 (insert-char file-char len)
3274 (setq my-org-fileconv-level-org-p nil))))
3275 nil) ;; for the hook
3280 ** Meaningful diff for org files in a git repository
3281 #+index: git!diff org files
3282 Since most diff utilities are primarily meant for source code, it is
3283 difficult to read diffs of text files like ~.org~ files easily. If you
3284 version your org directory with a SCM like git you will know what I
3285 mean. However for git, there is a way around. You can use
3286 =gitattributes= to define a custom diff driver for org files. Then a
3287 regular expression can be used to configure how the diff driver
3288 recognises a "function".
3290 Put the following in your =<org_dir>/.gitattributes=.
3292 Then put the following lines in =<org_dir>/.git/config=
3294 : xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3296 This will let you see diffs for org files with each hunk identified by
3297 the unmodified headline closest to the changes. After the
3298 configuration a diff should look something like the example below.
3301 diff --git a/org-hacks.org b/org-hacks.org
3302 index a0672ea..92a08f7 100644
3305 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3307 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3309 +** Meaningful diff for org files in a git repository
3311 +Since most diff utilities are primarily meant for source code, it is
3312 +difficult to read diffs of text files like ~.org~ files easily. If you
3313 +version your org directory with a SCM like git you will know what I
3314 +mean. However for git, there is a way around. You can use
3315 +=gitattributes= to define a custom diff driver for org files. Then a
3316 +regular expression can be used to configure how the diff driver
3317 +recognises a "function".
3319 +Put the following in your =<org_dir>/.gitattributes=.
3321 +Then put the following lines in =<org_dir>/.git/config=
3323 +: xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3327 ** Cooking? Brewing?
3330 ** Opening devonthink links
3332 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3333 links from org-mode.
3337 ** Cooking? Brewing?
3338 #+index: beer!brewing
3339 #+index: cooking!conversions
3340 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3342 It currently does metric/english conversion, and a few other tricks.
3343 Basically I just use calc’s units code. I think scaling recipes, or
3344 turning percentages into weights would be pretty easy.
3346 https://gitorious.org/org-cook/org-cook
3348 There is also, for those interested:
3350 https://gitorious.org/org-brew/org-brew
3352 for brewing beer. This is again, mostly just calc functions, including
3353 hydrometer correction, abv calculation, priming sugar for a given CO_2
3354 volume, etc. More integration with org-mode should be possible: for
3355 instance it would be nice to be able to use a lookup table (of ingredients)
3356 to calculate target original gravity, IBUs, etc.