1 #+TITLE: Org ad hoc code, quick hacks and workarounds
3 #+EMAIL: mdl AT imapmail DOT org
4 #+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
5 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate
6 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
7 #+TAGS: Write(w) Update(u) Fix(f) Check(c)
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.
544 Here is a 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))))
559 Use the function above directly on the list. If you want to use an
560 equivalent function after =C-c ^ f=, use this one instead:
562 #+BEGIN_SRC emacs-lisp
563 (defun org-sort-list-by-checkbox-type-1 ()
565 (if (looking-at org-list-full-item-re)
566 (cdr (assoc (match-string 3)
567 '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
572 *** Align all tables in a file
574 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
576 #+begin_src emacs-lisp
577 (defun my-align-all-tables ()
579 (org-table-map-tables 'org-table-align 'quietly))
583 #+index: Table!Calculation
585 :CUSTOM_ID: transpose-table
588 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
589 see.) There are also other solutions:
591 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
592 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]]
594 - with org-babel and R: provided by Dan Davison in the mailing list (old
595 =#+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]]
597 - with field coordinates in formulas (=@#= and =$#=): see [[file:org-hacks.org::#field-coordinates-in-formulas-transpose-table][Worg]].
599 *** Manipulate hours/minutes/seconds in table formulas
600 #+index: Table!hours-minutes-seconds
601 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
602 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
603 "=d=" is any digit) as time values in Org-mode table formula. These
604 functions have now been wrapped up into a =with-time= macro which can
605 be used in table formula to translate table cell values to and from
606 numerical values for algebraic manipulation.
608 Here is the code implementing this macro.
609 #+begin_src emacs-lisp :results silent
610 (defun org-time-string-to-seconds (s)
611 "Convert a string HH:MM:SS to a number of seconds."
614 (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
615 (let ((hour (string-to-number (match-string 1 s)))
616 (min (string-to-number (match-string 2 s)))
617 (sec (string-to-number (match-string 3 s))))
618 (+ (* hour 3600) (* min 60) sec)))
620 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
621 (let ((min (string-to-number (match-string 1 s)))
622 (sec (string-to-number (match-string 2 s))))
624 ((stringp s) (string-to-number s))
627 (defun org-time-seconds-to-string (secs)
628 "Convert a number of seconds to a time string."
629 (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
630 ((>= secs 60) (format-seconds "%m:%.2s" secs))
631 (t (format-seconds "%s" secs))))
633 (defmacro with-time (time-output-p &rest exprs)
634 "Evaluate an org-table formula, converting all fields that look
635 like time data to integer seconds. If TIME-OUTPUT-P then return
636 the result as a time value."
638 (if time-output-p 'org-time-seconds-to-string 'identity)
646 (list 'with-time nil el)
647 (org-time-string-to-seconds el)))
652 Which allows the following forms of table manipulation such as adding
653 and subtracting time values.
654 : | Date | Start | Lunch | Back | End | Sum |
655 : |------------------+-------+-------+-------+-------+------|
656 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
657 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
659 and dividing time values by integers
660 : | time | miles | minutes/mile |
661 : |-------+-------+--------------|
662 : | 34:43 | 2.9 | 11:58 |
663 : | 32:15 | 2.77 | 11:38 |
664 : | 33:56 | 3.0 | 11:18 |
665 : | 52:22 | 4.62 | 11:20 |
666 : #+TBLFM: $3='(with-time t (/ $1 $2))
668 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
669 Elisp formulas) to compute time durations. For example:
671 : | Task 1 | Task 2 | Total |
672 : |--------+--------+---------|
673 : | 35:00 | 35:00 | 1:10:00 |
674 : #+TBLFM: @2$3=$1+$2;T
676 *** Dates computation
678 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of
679 dates stored in an org table.
681 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
685 | Start Date | End Date | Duration |
686 |------------+------------+----------|
687 | 2004.08.07 | 2005.07.08 | 335 |
688 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
690 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
691 above). The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
692 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
695 #+index: Table!Calculation
696 As with Times computation, the following code allows Computation with
697 Hex values in Org-mode tables using the =with-hex= macro.
699 Here is the code implementing this macro.
700 #+begin_src emacs-lisp
701 (defun org-hex-strip-lead (str)
702 (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
703 (substring str 2) str))
705 (defun org-hex-to-hex (int)
708 (defun org-hex-to-dec (str)
711 (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
715 (setf out (+ (* out 16)
716 (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
717 (coerce (match-string 1 str) 'list))
719 ((stringp str) (string-to-number str))
722 (defmacro with-hex (hex-output-p &rest exprs)
723 "Evaluate an org-table formula, converting all fields that look
724 like hexadecimal to decimal integers. If HEX-OUTPUT-P then
725 return the result as a hex value."
727 (if hex-output-p 'org-hex-to-hex 'identity)
734 (list 'with-hex nil el)
735 (org-hex-to-dec el)))
740 Which allows the following forms of table manipulation such as adding
741 and subtracting hex values.
742 | 0x10 | 0x0 | 0x10 | 16 |
743 | 0x20 | 0x1 | 0x21 | 33 |
744 | 0x30 | 0x2 | 0x32 | 50 |
745 | 0xf0 | 0xf | 0xff | 255 |
746 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
748 *** Field coordinates in formulas (=@#= and =$#=)
750 :CUSTOM_ID: field-coordinates-in-formulas
752 #+index: Table!Field Coordinates
755 Following are some use cases that can be implemented with the “field
756 coordinates in formulas” described in the corresponding chapter in the
757 [[http://orgmode.org/manual/References.html#References][Org manual]].
759 **** Copy a column from a remote table into a column
761 :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
764 current column =$3= = remote column =$2=:
765 : #+TBLFM: $3 = remote(FOO, @@#$2)
767 **** Copy a row from a remote table transposed into a column
769 :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
772 current column =$1= = transposed remote row =@1=:
773 : #+TBLFM: $1 = remote(FOO, @$#$@#)
777 :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
782 This is more like a demonstration of using “field coordinates in formulas”
783 and is bound to be slow for large tables. See the discussion in the mailing
785 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
786 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
787 For more efficient solutions see
788 [[file:org-hacks.org::#transpose-table][Worg]].
790 To transpose this 4x7 table
793 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
794 : |------+------+------+------+------+------+------|
795 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
796 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
797 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
799 start with a 7x4 table without any horizontal line (to have filled
800 also the column header) and yet empty:
810 Then add the =TBLFM= line below. After recalculation this will end up with
813 : | year | min | avg | max |
814 : | 2004 | 401 | 402 | 403 |
815 : | 2005 | 501 | 502 | 503 |
816 : | 2006 | 601 | 602 | 603 |
817 : | 2007 | 701 | 702 | 703 |
818 : | 2008 | 801 | 802 | 803 |
819 : | 2009 | 901 | 902 | 903 |
820 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
822 The formula simply exchanges row and column numbers by taking
823 - the absolute remote row number =@$#= from the current column number =$#=
824 - the absolute remote column number =$@#= from the current row number =@#=
826 Formulas to be taken over from the remote table will have to be transformed
829 **** Dynamic variation of ranges
833 In this example all columns next to =quote= are calculated from the column
834 =quote= and show the average change of the time series =quote[year]=
835 during the period of the preceding =1=, =2=, =3= or =4= years:
837 : | year | quote | 1 a | 2 a | 3 a | 4 a |
838 : |------+-------+-------+-------+-------+-------|
839 : | 2005 | 10 | | | | |
840 : | 2006 | 12 | 0.200 | | | |
841 : | 2007 | 14 | 0.167 | 0.183 | | |
842 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
843 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
844 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
846 The important part of the formula without the field blanking is:
848 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
850 which is the Emacs Calc implementation of the equation
852 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
854 where /i/ is the current time and /a/ is the length of the preceding period.
856 *** Change the column sequence in one row only
857 #+index: Table!Editing
859 :CUSTOM_ID: column-sequence-in-row
864 The functions below can be used to change the column sequence in one row
865 only, without affecting the other rows above and below like with M-<left> or
866 M-<right> (org-table-move-column). Please see the docstring of the functions
867 for more explanations. Below is one example per function, with this original
868 table as the starting point for each example:
870 : | e | 9 | 10 | 11 |
873 **** Move in row left
875 1) place point at "10" in original table
876 2) result of M-x my-org-table-move-column-in-row-left:
878 : | e | 10 | 9 | 11 |
881 **** Move in row right
883 1) place point at "9" in original table
884 2) result of M-x my-org-table-move-column-in-row-right:
886 : | e | 10 | 9 | 11 |
889 **** Rotate in row left
891 1) place point at "9" in original table
892 2) result of M-x my-org-table-rotate-column-in-row-left:
894 : | e | 10 | 11 | 9 |
897 **** Rotate in row right
899 1) place point at "9" in original table
900 2) result of M-x my-org-table-rotate-column-in-row-right:
902 : | e | 11 | 9 | 10 |
907 #+BEGIN_SRC emacs-lisp
908 (defun my-org-table-move-column-in-row-right ()
909 "Move column to the right, limited to the current row."
911 (my-org-table-move-column-in-row nil))
912 (defun my-org-table-move-column-in-row-left ()
913 "Move column to the left, limited to the current row."
915 (my-org-table-move-column-in-row 'left))
917 (defun my-org-table-move-column-in-row (&optional left)
918 "Move the current column to the right, limited to the current row.
919 With arg LEFT, move to the left. For repeated invocation the point follows
920 the value and changes to the target colum. Does not fix formulas."
921 ;; derived from `org-table-move-column'
923 (if (not (org-at-table-p))
924 (error "Not at a table"))
925 (org-table-find-dataline)
926 (org-table-check-inside-data-field)
927 (let* ((col (org-table-current-column))
928 (col1 (if left (1- col) col))
929 ;; Current cursor position
930 (colpos (if left (1- col) (1+ col))))
931 (if (and left (= col 1))
932 (error "Cannot move column further left"))
933 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
934 (error "Cannot move column further right"))
935 (org-table-goto-column col1 t)
936 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
937 (replace-match "|\\2|\\1|"))
938 (org-table-goto-column colpos)
941 (defun my-org-table-rotate-column-in-row-right ()
942 "Rotate column to the right, limited to the current row."
944 (my-org-table-rotate-column-in-row nil))
945 (defun my-org-table-rotate-column-in-row-left ()
946 "Rotate column to the left, limited to the current row."
948 (my-org-table-rotate-column-in-row 'left))
950 (defun my-org-table-rotate-column-in-row (&optional left)
951 "Rotate the current column to the right, limited to the current row.
952 With arg LEFT, rotate to the left. The boundaries of the rotation range are
953 the current and the most right column for both directions. For repeated
954 invocation the point stays on the current column. Does not fix formulas."
955 ;; derived from `org-table-move-column'
957 (if (not (org-at-table-p))
958 (error "Not at a table"))
959 (org-table-find-dataline)
960 (org-table-check-inside-data-field)
961 (let ((col (org-table-current-column)))
962 (org-table-goto-column col t)
963 (and (looking-at (if left
964 "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
965 "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
966 (replace-match "|\\2|\\1|"))
967 (org-table-goto-column col)
973 As hack I have this in an Org buffer to change temporarily to the desired
974 behavior with C-c C-c on one of the three snippets:
976 : #+begin_src emacs-lisp :results silent
977 : (org-defkey org-mode-map [(meta left)]
978 : 'my-org-table-move-column-in-row-left)
979 : (org-defkey org-mode-map [(meta right)]
980 : 'my-org-table-move-column-in-row-right)
981 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
982 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
986 : #+begin_src emacs-lisp :results silent
987 : (org-defkey org-mode-map [(meta left)]
988 : 'my-org-table-rotate-column-in-row-left)
989 : (org-defkey org-mode-map [(meta right)]
990 : 'my-org-table-rotate-column-in-row-right)
991 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
992 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
995 : - back to original:
996 : #+begin_src emacs-lisp :results silent
997 : (org-defkey org-mode-map [(meta left)] 'org-metaleft)
998 : (org-defkey org-mode-map [(meta right)] 'org-metaright)
999 : (org-defkey org-mode-map [(left)] 'backward-char)
1000 : (org-defkey org-mode-map [(right)] 'forward-char)
1003 **** reasons why this is not put into the Org core
1005 I consider this as only a hack for several reasons:
1006 - Generalization: The existing org-table-move-column function could be
1007 enhanced with additional optional parameters to incorporate these
1008 functionalities and could be used as the only function for better
1009 maintainability. Now it's only a copy/paste hack of several similar
1010 functions with simple modifications.
1011 - Bindings: Should be convenient for repetition like M-<right>. What
1012 should be bound where, what has to be left unbound?
1013 - Does not fix formulas. Could be resolved for field formulas but
1014 most probably not for column or range formulas and this can lead
1015 to confusion. AFAIK all "official" table manipulations fix formulas.
1016 - Completeness: Not all variations and combinations are covered yet
1017 - left-right, up-down
1018 - move, rotate with range to end, rotate with range to begin
1019 - whole column/row, only in-row/in-column
1021 ** Capture and Remember
1022 *** Customize the size of the frame for remember
1023 #+index: Remember!frame
1024 #+index: Customization!remember
1025 (Note: this hack is likely out of date due to the development of
1029 On emacs-orgmode, Ryan C. Thompson suggested this:
1032 I am using org-remember set to open a new frame when used,
1033 and the default frame size is much too large. To fix this, I have
1034 designed some advice and a custom variable to implement custom
1035 parameters for the remember frame:
1038 #+begin_src emacs-lisp
1039 (defcustom remember-frame-alist nil
1040 "Additional frame parameters for dedicated remember frame."
1044 (defadvice remember (around remember-frame-parameters activate)
1045 "Set some frame parameters for the remember frame."
1046 (let ((default-frame-alist (append remember-frame-alist
1047 default-frame-alist)))
1051 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1052 reasonable size for the frame.
1054 *** [[#heading-to-link][Turn a heading into an org link]]
1055 *** Quickaccess to the link part of hyperlinks
1056 #+index: Link!Referent
1057 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1058 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1059 which is indeed kind of cumbersome.
1061 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1063 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1064 #+begin_src emacs-lisp
1066 (lambda (&optional arg)
1069 (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1073 #+begin_src emacs-lisp
1074 (defun my-org-extract-link ()
1075 "Extract the link location at point and put it on the killring."
1077 (when (org-in-regexp org-bracket-link-regexp 1)
1078 (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1081 They put the link destination on the killring and can be easily bound to a key.
1083 *** Insert link with HTML title as default description
1084 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1085 from HTML <title> tag and use it as a default link description. Here is a way to
1088 #+begin_src emacs-lisp
1089 (require 'mm-url) ; to include mm-url-decode-entities-string
1091 (defun my-org-insert-link ()
1092 "Insert org link where default description is set to html title."
1094 (let* ((url (read-string "URL: "))
1095 (title (get-html-title-from-url url)))
1096 (org-insert-link nil url title)))
1098 (defun get-html-title-from-url (url)
1099 "Return content in <title> tag."
1100 (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1102 (set-buffer download-buffer)
1103 (beginning-of-buffer)
1104 (setq x1 (search-forward "<title>"))
1105 (search-forward "</title>")
1106 (setq x2 (search-backward "<"))
1107 (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1110 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1112 ** Archiving Content in Org-Mode
1113 *** Preserve top level headings when archiving to a file
1114 #+index: Archiving!Preserve top level headings
1117 To preserve (somewhat) the integrity of your archive structure while
1118 archiving lower level items to a file, you can use the following
1121 #+begin_src emacs-lisp
1122 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1123 (let ((org-archive-location
1124 (if (save-excursion (org-back-to-heading)
1125 (> (org-outline-level) 1))
1126 (concat (car (split-string org-archive-location "::"))
1128 (car (org-get-outline-path)))
1129 org-archive-location)))
1133 Thus, if you have an outline structure such as...
1141 ...archiving "Subsubheading" to a new file will set the location in
1142 the new file to the top level heading:
1149 While this hack obviously destroys the outline hierarchy somewhat, it
1150 at least preserves the logic of level one groupings.
1152 A slightly more complex version of this hack will not only keep the
1153 archive organized by top-level headings, but will also preserve the
1154 tags found on those headings:
1156 #+begin_src emacs-lisp
1157 (defun my-org-inherited-no-file-tags ()
1158 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1159 (ltags (org-entry-get nil "TAGS")))
1162 (replace-regexp-in-string (concat tag ":") "" tags)))
1163 (append org-file-tags (when ltags (split-string ltags ":" t))))
1164 (if (string= ":" tags) nil tags)))
1166 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1167 (let ((tags (my-org-inherited-no-file-tags))
1168 (org-archive-location
1169 (if (save-excursion (org-back-to-heading)
1170 (> (org-outline-level) 1))
1171 (concat (car (split-string org-archive-location "::"))
1173 (car (org-get-outline-path)))
1174 org-archive-location)))
1176 (with-current-buffer (find-file-noselect (org-extract-archive-file))
1178 (while (org-up-heading-safe))
1179 (org-set-tags-to tags)))))
1182 *** Archive in a date tree
1183 #+index: Archiving!date tree
1184 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1186 (Make sure org-datetree.el is loaded for this to work.)
1188 #+begin_src emacs-lisp
1189 ;; (setq org-archive-location "%s_archive::date-tree")
1190 (defadvice org-archive-subtree
1191 (around org-archive-subtree-to-data-tree activate)
1192 "org-archive-subtree to date-tree"
1194 (string= "date-tree"
1195 (org-extract-archive-heading
1196 (org-get-local-archive-location)))
1197 (let* ((dct (decode-time (org-current-time)))
1201 (this-buffer (current-buffer))
1202 (location (org-get-local-archive-location))
1203 (afile (org-extract-archive-file location))
1204 (org-archive-location
1205 (format "%s::*** %04d-%02d-%02d %s" afile y m d
1206 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1207 (message "afile=%s" afile)
1209 (error "Invalid `org-archive-location'"))
1211 (switch-to-buffer (find-file-noselect afile))
1212 (org-datetree-find-year-create y)
1213 (org-datetree-find-month-create y m)
1214 (org-datetree-find-day-create y m d)
1216 (switch-to-buffer this-buffer))
1221 *** Add inherited tags to archived entries
1222 #+index: Archiving!Add inherited tags
1223 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1224 advise the function like this:
1227 (defadvice org-archive-subtree
1228 (before add-inherited-tags-before-org-archive-subtree activate)
1229 "add inherited tags before org-archive-subtree"
1230 (org-set-tags-to (org-get-tags-at)))
1233 ** Using and Managing Org-Metadata
1234 *** Remove redundant tags of headlines
1235 #+index: Tag!Remove redundant
1238 A small function that processes all headlines in current buffer and
1239 removes tags that are local to a headline and inherited by a parent
1240 headline or the #+FILETAGS: statement.
1242 #+BEGIN_SRC emacs-lisp
1243 (defun dmj/org-remove-redundant-tags ()
1244 "Remove redundant tags of headlines in current buffer.
1246 A tag is considered redundant if it is local to a headline and
1247 inherited by a parent headline."
1249 (when (eq major-mode 'org-mode)
1253 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1254 local inherited tag)
1255 (dolist (tag alltags)
1256 (if (get-text-property 0 'inherited tag)
1257 (push tag inherited) (push tag local)))
1259 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1263 *** Remove empty property drawers
1264 #+index: Drawer!Empty
1265 David Maus proposed this:
1267 #+begin_src emacs-lisp
1268 (defun dmj:org:remove-empty-propert-drawers ()
1269 "*Remove all empty property drawers in current file."
1271 (unless (eq major-mode 'org-mode)
1272 (error "You need to turn on Org mode for this function."))
1274 (goto-char (point-min))
1275 (while (re-search-forward ":PROPERTIES:" nil t)
1277 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1280 *** Group task list by a property
1281 #+index: Agenda!Group task list
1282 This advice allows you to group a task list in Org-Mode. To use it,
1283 set the variable =org-agenda-group-by-property= to the name of a
1284 property in the option list for a TODO or TAGS search. The resulting
1285 agenda view will group tasks by that property prior to searching.
1287 #+begin_src emacs-lisp
1288 (defvar org-agenda-group-by-property nil
1289 "Set this in org-mode agenda views to group tasks by property")
1291 (defun org-group-bucket-items (prop items)
1293 (dolist (item items)
1294 (let* ((marker (get-text-property 0 'org-marker item))
1295 (pvalue (org-entry-get marker prop t))
1296 (cell (assoc pvalue buckets)))
1298 (setcdr cell (cons item (cdr cell)))
1299 (setq buckets (cons (cons pvalue (list item))
1301 (setq buckets (mapcar (lambda (bucket)
1303 (reverse (cdr bucket))))
1305 (sort buckets (lambda (i1 i2)
1306 (string< (car i1) (car i2))))))
1308 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1309 (list &optional nosort))
1310 "Prepare bucketed agenda entry lists"
1311 (if org-agenda-group-by-property
1312 ;; bucketed, handle appropriately
1314 (dolist (bucket (org-group-bucket-items
1315 org-agenda-group-by-property
1317 (let ((header (concat "Property "
1318 org-agenda-group-by-property
1320 (or (car bucket) "<nil>") ":\n")))
1321 (add-text-properties 0 (1- (length header))
1322 (list 'face 'org-agenda-structure)
1326 ;; recursively process
1327 (let ((org-agenda-group-by-property nil))
1328 (org-finalize-agenda-entries
1329 (cdr bucket) nosort))
1331 (setq ad-return-value text))
1333 (ad-activate 'org-finalize-agenda-entries)
1335 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1338 Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1340 A small hook run when clocking out of a task that prompts for a note
1341 when the tag "=clockout_note=" is found in a headline. It uses the tag
1342 ("=clockout_note=") so inheritance can also be used...
1344 #+begin_src emacs-lisp
1345 (defun rgr/check-for-clock-out-note()
1348 (org-back-to-heading)
1349 (let ((tags (org-get-tags)))
1350 (and tags (message "tags: %s " tags)
1351 (when (member "clocknote" tags)
1354 (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1356 *** Dynamically adjust tag position
1357 #+index: Tag!position
1358 Here is a bit of code that allows you to have the tags always
1359 right-adjusted in the buffer.
1361 This is useful when you have bigger window than default window-size
1362 and you dislike the aesthetics of having the tag in the middle of the
1365 This hack solves the problem of adjusting it whenever you change the
1367 Before saving it will revert the file to having the tag position be
1368 left-adjusted so that if you track your files with version control,
1369 you won't run into artificial diffs just because the window-size
1372 *IMPORTANT*: This is probably slow on very big files.
1374 #+begin_src emacs-lisp
1375 (setq ba/org-adjust-tags-column t)
1377 (defun ba/org-adjust-tags-column-reset-tags ()
1378 "In org-mode buffers it will reset tag position according to
1381 (not (string= (buffer-name) "*Remember*"))
1382 (eql major-mode 'org-mode))
1383 (let ((b-m-p (buffer-modified-p)))
1386 (goto-char (point-min))
1387 (command-execute 'outline-next-visible-heading)
1388 ;; disable (message) that org-set-tags generates
1389 (flet ((message (&rest ignored) nil))
1391 (set-buffer-modified-p b-m-p))
1394 (defun ba/org-adjust-tags-column-now ()
1395 "Right-adjust `org-tags-column' value, then reset tag position."
1396 (set (make-local-variable 'org-tags-column)
1397 (- (- (window-width) (length org-ellipsis))))
1398 (ba/org-adjust-tags-column-reset-tags))
1400 (defun ba/org-adjust-tags-column-maybe ()
1401 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1402 (when ba/org-adjust-tags-column
1403 (ba/org-adjust-tags-column-now)))
1405 (defun ba/org-adjust-tags-column-before-save ()
1406 "Tags need to be left-adjusted when saving."
1407 (when ba/org-adjust-tags-column
1408 (setq org-tags-column 1)
1409 (ba/org-adjust-tags-column-reset-tags)))
1411 (defun ba/org-adjust-tags-column-after-save ()
1412 "Revert left-adjusted tag position done by before-save hook."
1413 (ba/org-adjust-tags-column-maybe)
1414 (set-buffer-modified-p nil))
1416 ; automatically align tags on right-hand side
1417 (add-hook 'window-configuration-change-hook
1418 'ba/org-adjust-tags-column-maybe)
1419 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1420 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1421 (add-hook 'org-agenda-mode-hook '(lambda ()
1422 (setq org-agenda-tags-column (- (window-width)))))
1424 ; between invoking org-refile and displaying the prompt (which
1425 ; triggers window-configuration-change-hook) tags might adjust,
1426 ; which invalidates the org-refile cache
1427 (defadvice org-refile (around org-refile-disable-adjust-tags)
1428 "Disable dynamically adjusting tags"
1429 (let ((ba/org-adjust-tags-column nil))
1431 (ad-activate 'org-refile)
1433 *** Use an "attach" link type to open files without worrying about their location
1434 #+index: Link!Attach
1435 -- Darlan Cavalcante Moreira
1437 In the setup part in my org-files I put:
1440 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1443 Now I can use the "attach" link type, but org will ask me if I want to
1444 allow executing the elisp code. To avoid this you can even set
1445 org-confirm-elisp-link-function to nil (I don't like this because it allows
1446 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1451 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1453 This works very well.
1455 ** Org Agenda and Task Management
1456 *** Make it easier to set org-agenda-files from multiple directories
1457 #+index: Agenda!Files
1460 #+begin_src emacs-lisp
1461 (defun my-org-list-files (dirs ext)
1462 "Function to create list of org files in multiple subdirectories.
1463 This can be called to generate a list of files for
1464 org-agenda-files or org-refile-targets.
1466 DIRS is a list of directories.
1468 EXT is a list of the extensions of files to be included."
1469 (let ((dirs (if (listp dirs)
1472 (ext (if (listp ext)
1482 (file-expand-wildcards
1483 (concat (file-name-as-directory x) "*" y)))))
1488 (when (or (string-match "/.#" x)
1489 (string-match "#$" x))
1490 (setq files (delete x files))))
1494 (defvar my-org-agenda-directories '("~/org/")
1495 "List of directories containing org files.")
1496 (defvar my-org-agenda-extensions '(".org")
1497 "List of extensions of agenda files")
1499 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1500 (setq my-org-agenda-extensions '(".org" ".ref"))
1502 (defun my-org-set-agenda-files ()
1504 (setq org-agenda-files (my-org-list-files
1505 my-org-agenda-directories
1506 my-org-agenda-extensions)))
1508 (my-org-set-agenda-files)
1511 The code above will set your "default" agenda files to all files
1512 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1513 You can change these values by setting the variables
1514 my-org-agenda-extensions and my-org-agenda-directories. The function
1515 my-org-agenda-files-by-filetag uses these two variables to determine
1516 which files to search for filetags (i.e., the larger set from which
1517 the subset will be drawn).
1519 You can also easily use my-org-list-files to "mix and match"
1520 directories and extensions to generate different lists of agenda
1523 *** Restrict org-agenda-files by filetag
1524 #+index: Agenda!Files
1526 :CUSTOM_ID: set-agenda-files-by-filetag
1530 It is often helpful to limit yourself to a subset of your agenda
1531 files. For instance, at work, you might want to see only files related
1532 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1533 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
1534 commands]]. These solutions, however, require reapplying a filter each
1535 time you call the agenda or writing several new custom agenda commands
1536 for each context. Another solution is to use directories for different
1537 types of tasks and to change your agenda files with a function that
1538 sets org-agenda-files to the appropriate directory. But this relies on
1539 hard and static boundaries between files.
1541 The following functions allow for a more dynamic approach to selecting
1542 a subset of files based on filetags:
1544 #+begin_src emacs-lisp
1545 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1546 "Restrict org agenda files only to those containing filetag."
1548 (let* ((tagslist (my-org-get-all-filetags))
1550 (completing-read "Tag: "
1551 (mapcar 'car tagslist)))))
1552 (org-agenda-remove-restriction-lock 'noupdate)
1553 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1554 (setq org-agenda-overriding-restriction 'files)))
1556 (defun my-org-get-all-filetags ()
1557 "Get list of filetags from all default org-files."
1558 (let ((files org-agenda-files)
1560 (save-window-excursion
1561 (while (setq x (pop files))
1562 (set-buffer (find-file-noselect x))
1565 (let ((tagfiles (assoc y tagslist)))
1567 (setcdr tagfiles (cons x (cdr tagfiles)))
1568 (add-to-list 'tagslist (list y x)))))
1569 (my-org-get-filetags)))
1572 (defun my-org-get-filetags ()
1573 "Get list of filetags for current buffer"
1574 (let ((ftags org-file-tags)
1578 (org-substring-no-properties x))
1582 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1583 with all filetags in your "normal" agenda files. When you select a
1584 tag, org-agenda-files will be restricted to only those files
1585 containing the filetag. To release the restriction, type C-c C-x >
1586 (org-agenda-remove-restriction-lock).
1588 *** Highlight the agenda line under cursor
1589 #+index: Agenda!Highlight
1590 This is useful to make sure what task you are operating on.
1592 #+BEGIN_SRC emacs-lisp
1593 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1598 #+BEGIN_SRC emacs-lisp
1599 ;; hl-line seems to be only for emacs
1601 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1603 ;; highline-mode does not work straightaway in tty mode.
1604 ;; I use a black background
1606 '(highline-face ((((type tty) (class color))
1607 (:background "white" :foreground "black")))))
1610 *** Split frame horizontally for agenda
1611 #+index: Agenda!frame
1612 If you would like to split the frame into two side-by-side windows when
1613 displaying the agenda, try this hack from Jan Rehders, which uses the
1614 `toggle-window-split' from
1616 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1618 #+BEGIN_SRC emacs-lisp
1619 ;; Patch org-mode to use vertical splitting
1620 (defadvice org-prepare-agenda (after org-fix-split)
1621 (toggle-window-split))
1622 (ad-activate 'org-prepare-agenda)
1625 *** Automatically add an appointment when clocking in a task
1626 #+index: Clock!Automatically add an appointment when clocking in a task
1627 #+index: Appointment!Automatically add an appointment when clocking in a task
1628 #+BEGIN_SRC emacs-lisp
1629 ;; Make sure you have a sensible value for `appt-message-warning-time'
1630 (defvar bzg-org-clock-in-appt-delay 100
1631 "Number of minutes for setting an appointment by clocking-in")
1634 This function let's you add an appointment for the current entry.
1635 This can be useful when you need a reminder.
1637 #+BEGIN_SRC emacs-lisp
1638 (defun bzg-org-clock-in-add-appt (&optional n)
1639 "Add an appointment for the Org entry at point in N minutes."
1642 (org-back-to-heading t)
1643 (looking-at org-complex-heading-regexp)
1644 (let* ((msg (match-string-no-properties 4))
1645 (ct-time (decode-time))
1646 (appt-min (+ (cadr ct-time)
1647 (or n bzg-org-clock-in-appt-delay)))
1648 (appt-time ; define the time for the appointment
1649 (progn (setf (cadr ct-time) appt-min) ct-time)))
1650 (appt-add (format-time-string
1651 "%H:%M" (apply 'encode-time appt-time)) msg)
1652 (if (interactive-p) (message "New appointment for %s" msg)))))
1655 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1658 #+BEGIN_SRC emacs-lisp
1659 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1660 "Add an appointment when clocking a task in."
1661 (bzg-org-clock-in-add-appt))
1664 You may also want to delete the associated appointment when clocking
1665 out. This function does this:
1667 #+BEGIN_SRC emacs-lisp
1668 (defun bzg-org-clock-out-delete-appt nil
1669 "When clocking out, delete any associated appointment."
1672 (org-back-to-heading t)
1673 (looking-at org-complex-heading-regexp)
1674 (let* ((msg (match-string-no-properties 4)))
1675 (setq appt-time-msg-list
1679 (if (not (string-match (regexp-quote msg)
1680 (cadr appt))) appt))
1681 appt-time-msg-list)))
1685 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1687 #+BEGIN_SRC emacs-lisp
1688 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1689 "Delete an appointment when clocking a task out."
1690 (bzg-org-clock-out-delete-appt))
1693 *IMPORTANT*: You can add appointment by clocking in in both an
1694 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1695 agenda buffer with the advice above will bring an error.
1697 *** Using external programs for appointments reminders
1698 #+index: Appointment!reminders
1699 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1701 *** Remove from agenda time grid lines that are in an appointment
1702 #+index: Agenda!time grid
1703 #+index: Appointment!Remove from agenda time grid lines
1704 The agenda shows lines for the time grid. Some people think that
1705 these lines are a distraction when there are appointments at those
1706 times. You can get rid of the lines which coincide exactly with the
1707 beginning of an appointment. Michael Ekstrand has written a piece of
1708 advice that also removes lines that are somewhere inside an
1711 #+begin_src emacs-lisp
1712 (defun org-time-to-minutes (time)
1713 "Convert an HHMM time to minutes"
1714 (+ (* (/ time 100) 60) (% time 100)))
1716 (defun org-time-from-minutes (minutes)
1717 "Convert a number of minutes to an HHMM time"
1718 (+ (* (/ minutes 60) 100) (% minutes 60)))
1720 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1721 (list ndays todayp))
1722 (if (member 'remove-match (car org-agenda-time-grid))
1723 (flet ((extract-window
1725 (let ((start (get-text-property 1 'time-of-day line))
1726 (dur (get-text-property 1 'duration line)))
1730 (org-time-from-minutes
1731 (+ dur (org-time-to-minutes start)))))
1734 (let* ((windows (delq nil (mapcar 'extract-window list)))
1735 (org-agenda-time-grid
1736 (list (car org-agenda-time-grid)
1737 (cadr org-agenda-time-grid)
1740 (find-if (lambda (w)
1743 (and (>= time (car w))
1746 (caddr org-agenda-time-grid)))))
1749 (ad-activate 'org-agenda-add-time-grid-maybe)
1751 *** Disable version control for Org mode agenda files
1752 #+index: Agenda!Files
1755 Even if you use Git to track your agenda files you might not need
1756 vc-mode to be enabled for these files.
1758 #+begin_src emacs-lisp
1759 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1760 (defun dmj/disable-vc-for-agenda-files-hook ()
1761 "Disable vc-mode for Org agenda files."
1762 (if (and (fboundp 'org-agenda-file-p)
1763 (org-agenda-file-p (buffer-file-name)))
1764 (remove-hook 'find-file-hook 'vc-find-file-hook)
1765 (add-hook 'find-file-hook 'vc-find-file-hook)))
1768 *** Easy customization of TODO colors
1769 #+index: Customization!Todo keywords
1770 #+index: Todo keywords!Customization
1774 Here is some code I came up with some code to make it easier to
1775 customize the colors of various TODO keywords. As long as you just
1776 want a different color and nothing else, you can customize the
1777 variable org-todo-keyword-faces and use just a string color (i.e. a
1778 string of the color name) as the face, and then org-get-todo-face
1779 will convert the color to a face, inheriting everything else from
1780 the standard org-todo face.
1782 To demonstrate, I currently have org-todo-keyword-faces set to
1784 #+BEGIN_SRC emacs-lisp
1785 (("IN PROGRESS" . "dark orange")
1786 ("WAITING" . "red4")
1787 ("CANCELED" . "saddle brown"))
1790 Here's the code, in a form you can put in your =.emacs=
1792 #+BEGIN_SRC emacs-lisp
1793 (eval-after-load 'org-faces
1795 (defcustom org-todo-keyword-faces nil
1796 "Faces for specific TODO keywords.
1797 This is a list of cons cells, with TODO keywords in the car and
1798 faces in the cdr. The face can be a symbol, a color, or a
1799 property list of attributes, like (:foreground \"blue\" :weight
1800 bold :underline t)."
1805 (string :tag "Keyword")
1806 (choice color (sexp :tag "Face")))))))
1808 (eval-after-load 'org
1810 (defun org-get-todo-face-from-color (color)
1811 "Returns a specification for a face that inherits from org-todo
1812 face and has the given color as foreground. Returns nil if
1815 `(:inherit org-warning :foreground ,color)))
1817 (defun org-get-todo-face (kwd)
1818 "Get the right face for a TODO keyword KWD.
1819 If KWD is a number, get the corresponding match group."
1820 (if (numberp kwd) (setq kwd (match-string kwd)))
1821 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1823 (org-get-todo-face-from-color face)
1825 (and (member kwd org-done-keywords) 'org-done)
1829 *** Add an effort estimate on the fly when clocking in
1830 #+index: Effort estimate!Add when clocking in
1831 #+index: Clock!Effort estimate
1832 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1833 This way you can easily have a "tea-timer" for your tasks when they
1834 don't already have an effort estimate.
1836 #+begin_src emacs-lisp
1837 (add-hook 'org-clock-in-prepare-hook
1838 'my-org-mode-ask-effort)
1840 (defun my-org-mode-ask-effort ()
1841 "Ask for an effort estimate when clocking in."
1842 (unless (org-entry-get (point) "Effort")
1846 (org-entry-get-multivalued-property (point) "Effort"))))
1847 (unless (equal effort "")
1848 (org-set-property "Effort" effort)))))
1851 Or you can use a default effort for such a timer:
1853 #+begin_src emacs-lisp
1854 (add-hook 'org-clock-in-prepare-hook
1855 'my-org-mode-add-default-effort)
1857 (defvar org-clock-default-effort "1:00")
1859 (defun my-org-mode-add-default-effort ()
1860 "Add a default effort estimation."
1861 (unless (org-entry-get (point) "Effort")
1862 (org-set-property "Effort" org-clock-default-effort)))
1865 *** Use idle timer for automatic agenda views
1866 #+index: Agenda view!Refresh
1867 From John Wiegley's mailing list post (March 18, 2010):
1870 I have the following snippet in my .emacs file, which I find very
1871 useful. Basically what it does is that if I don't touch my Emacs for 5
1872 minutes, it displays the current agenda. This keeps my tasks "always
1873 in mind" whenever I come back to Emacs after doing something else,
1874 whereas before I had a tendency to forget that it was there.
1877 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1879 #+begin_src emacs-lisp
1880 (defun jump-to-org-agenda ()
1882 (let ((buf (get-buffer "*Org Agenda*"))
1885 (if (setq wind (get-buffer-window buf))
1886 (select-window wind)
1887 (if (called-interactively-p)
1889 (select-window (display-buffer buf t t))
1890 (org-fit-window-to-buffer)
1891 ;; (org-agenda-redo)
1893 (with-selected-window (display-buffer buf)
1894 (org-fit-window-to-buffer)
1895 ;; (org-agenda-redo)
1897 (call-interactively 'org-agenda-list)))
1898 ;;(let ((buf (get-buffer "*Calendar*")))
1899 ;; (unless (get-buffer-window buf)
1900 ;; (org-agenda-goto-calendar)))
1903 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1907 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1909 *** Refresh the agenda view regularly
1910 #+index: Agenda view!Refresh
1911 Hack sent by Kiwon Um:
1913 #+begin_src emacs-lisp
1914 (defun kiwon/org-agenda-redo-in-other-window ()
1915 "Call org-agenda-redo function even in the non-agenda buffer."
1917 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1919 (with-selected-window agenda-window (org-agenda-redo)))))
1920 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1923 *** Reschedule agenda items to today with a single command
1924 #+index: Agenda!Reschedule
1925 This was suggested by Carsten in reply to David Abrahams:
1927 #+begin_example emacs-lisp
1928 (defun org-agenda-reschedule-to-today ()
1930 (flet ((org-read-date (&rest rest) (current-time)))
1931 (call-interactively 'org-agenda-schedule)))
1934 *** Mark subtree DONE along with all subheadings
1935 #+index: Subtree!subheadings
1936 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
1938 #+begin_src emacs-lisp
1939 (defun bh/mark-subtree-done ()
1942 (let ((limit (point)))
1944 (exchange-point-and-mark)
1945 (while (> (point) limit)
1947 (outline-previous-visible-heading 1))
1948 (org-todo "DONE"))))
1951 Then M-x bh/mark-subtree-done.
1953 *** Mark heading done when all checkboxes are checked.
1955 :CUSTOM_ID: mark-done-when-all-checkboxes-checked
1960 An item consists of a list with checkboxes. When all of the
1961 checkboxes are checked, the item should be considered complete and its
1962 TODO state should be automatically changed to DONE. The code below
1963 does that. This version is slightly enhanced over the one in the
1965 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
1966 reset the state back to TODO if a checkbox is unchecked.
1968 Note that the code requires that a checkbox statistics cookie (the [/]
1969 or [%] thingie in the headline - see the [[http://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
1970 manual) be present in order for it to work. Note also that it is too
1971 dumb to figure out whether the item has a TODO state in the first
1972 place: if there is a statistics cookie, a TODO/DONE state will be
1973 added willy-nilly any time that the statistics cookie is changed.
1975 #+begin_src emacs-lisp
1976 ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
1977 (eval-after-load 'org-list
1978 '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
1980 (defun ndk/checkbox-list-complete ()
1982 (org-back-to-heading t)
1983 (let ((beg (point)) end)
1987 (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
1989 (if (equal (match-string 1) "100%")
1990 ;; all done - do the state change
1993 (if (and (> (match-end 2) (match-beginning 2))
1994 (equal (match-string 2) (match-string 3)))
1996 (org-todo 'todo)))))))
1999 *** Links to custom agenda views
2001 :CUSTOM_ID: links-to-agenda-views
2003 #+index: Agenda view!Links to
2004 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
2006 If you have custom agenda commands defined to some key, say w, then
2007 the following will serve as a link to the custom agenda buffer.
2008 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
2010 Clicking on it will prompt if you want to execute the elisp code. If
2011 you would rather not have the prompt or would want to respond with a
2012 single letter, ~y~ or ~n~, take a look at the docstrings of the
2013 variables =org-confirm-elisp-link-function= and
2014 =org-confirm-elisp-link-not-regexp=. Please take special note of the
2015 security risk associated with completely disabling the prompting
2018 ** Exporting org files
2019 *** Export Org to Org and handle includes.
2020 #+index: Export!handle includes
2021 Nick Dokos came up with this useful function:
2023 #+begin_src emacs-lisp
2024 (defun org-to-org-handle-includes ()
2025 "Copy the contents of the current buffer to OUTFILE,
2026 recursively processing #+INCLUDEs."
2027 (let* ((s (buffer-string))
2028 (fname (buffer-file-name))
2029 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
2033 (org-export-handle-include-files-recurse)
2036 (delete-region (point-min) (point-max))
2041 *** Specifying LaTeX commands to floating environments
2043 :CUSTOM_ID: latex-command-for-floats
2046 #+index: Export!LaTeX
2047 The keyword ~placement~ can be used to specify placement options to
2048 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2049 LaTeX export. Org passes along everything passed in options as long as
2050 there are no spaces. One can take advantage of this to pass other
2051 LaTeX commands and have their scope limited to the floating
2054 For example one can set the fontsize of a table different from the
2055 default normal size by putting something like =\footnotesize= right
2056 after the placement options. During LaTeX export using the
2057 ~#+ATTR_LaTeX:~ line below:
2060 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2063 exports the associated floating environment as shown in the following
2067 \begin{table}[<options>]\footnotesize
2072 It should be noted that this hack does not work for beamer export of
2073 tables since the =table= environment is not used. As an ugly
2074 workaround, one can use the following:
2077 ,#+LATEX: {\footnotesize
2078 ,#+ATTR_LaTeX: align=rr
2085 *** Styling code sections with CSS
2087 #+index: HTML!Styling code sections with CSS
2089 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2090 to HTML using =<pre>= tags, and assigned CSS classes by their content
2091 type. For example, Perl content will have an opening tag like
2092 =<pre class="src src-perl">=. You can use those classes to add styling
2093 to the output, such as here where a small language tag is added at the
2094 top of each kind of code box:
2097 (setq org-export-html-style
2098 "<style type=\"text/css\">
2099 <!--/*--><![CDATA[/*><!--*/
2100 .src { background-color: #F5FFF5; position: relative; overflow: visible; }
2101 .src:before { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2102 .src-sh:before { content: 'sh'; }
2103 .src-bash:before { content: 'sh'; }
2104 .src-R:before { content: 'R'; }
2105 .src-perl:before { content: 'Perl'; }
2106 .src-sql:before { content: 'SQL'; }
2107 .example { background-color: #FFF5F5; }
2112 Additionally, we use color to distinguish code output (the =.example=
2113 class) from input (all the =.src-*= classes).
2115 * Hacking Org: Working with Org-mode and other Emacs Packages.
2116 ** org-remember-anything
2118 #+index: Remember!Anything
2120 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2122 #+BEGIN_SRC emacs-lisp
2123 (defvar org-remember-anything
2124 '((name . "Org Remember")
2125 (candidates . (lambda () (mapcar 'car org-remember-templates)))
2126 (action . (lambda (name)
2127 (let* ((orig-template org-remember-templates)
2128 (org-remember-templates
2129 (list (assoc name orig-template))))
2130 (call-interactively 'org-remember))))))
2133 You can add it to your 'anything-sources' variable and open remember directly
2134 from anything. I imagine this would be more interesting for people with many
2135 remember templates, so that you are out of keys to assign those to.
2137 ** Org-mode and saveplace.el
2139 Fix a problem with =saveplace.el= putting you back in a folded position:
2141 #+begin_src emacs-lisp
2142 (add-hook 'org-mode-hook
2144 (when (outline-invisible-p)
2146 (outline-previous-visible-heading 1)
2147 (org-show-subtree)))))
2150 ** Using ido-mode for org-refile (and archiving via refile)
2152 First set up ido-mode, for example using:
2154 #+begin_src emacs-lisp
2155 ; use ido mode for completion
2156 (setq ido-everywhere t)
2157 (setq ido-enable-flex-matching t)
2158 (setq ido-max-directory-size 100000)
2159 (ido-mode (quote both))
2162 Now to enable it in org-mode, use the following:
2163 #+begin_src emacs-lisp
2164 (setq org-completion-use-ido t)
2165 (setq org-refile-use-outline-path nil)
2166 (setq org-refile-allow-creating-parent-nodes 'confirm)
2168 The last line enables the creation of nodes on the fly.
2170 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):
2171 #+begin_src emacs-lisp
2172 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2175 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.
2176 #+begin_src emacs-lisp
2177 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2178 ; added check to only include headlines, e.g. line must have at least one child
2179 (defun my/verify-refile-target ()
2180 "Exclude todo keywords with a DONE state from refile targets"
2181 (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2182 (save-excursion (org-goto-first-child))
2184 (setq org-refile-target-verify-function 'my/verify-refile-target)
2186 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.
2188 ** Using ido-completing-read to find attachments
2190 #+index: Attachment!ido completion
2194 Org-attach is great for quickly linking files to a project. But if you
2195 use org-attach extensively you might find yourself wanting to browse
2196 all the files you've attached to org headlines. This is not easy to do
2197 manually, since the directories containing the files are not human
2198 readable (i.e., they are based on automatically generated ids). Here's
2199 some code to browse those files using ido (obviously, you need to be
2202 #+begin_src emacs-lisp
2203 (load-library "find-lisp")
2205 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2207 (defun my-ido-find-org-attach ()
2208 "Find files in org-attachment directory"
2210 (let* ((enable-recursive-minibuffers t)
2211 (files (find-lisp-find-files org-attach-directory "."))
2214 (cons (file-name-nondirectory x)
2218 (remove-duplicates (mapcar #'car file-assoc-list)
2220 (filename (ido-completing-read "Org attachments: " filename-list nil t))
2221 (longname (cdr (assoc filename file-assoc-list))))
2222 (ido-set-current-directory
2223 (if (file-directory-p longname)
2225 (file-name-directory longname)))
2226 (setq ido-exit 'refresh
2227 ido-text-init ido-text
2231 (add-hook 'ido-setup-hook 'ido-my-keys)
2233 (defun ido-my-keys ()
2234 "Add my keybindings for ido."
2235 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2238 To browse your org attachments using ido fuzzy matching and/or the
2239 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2242 ** Link to Gnus messages by Message-Id
2243 #+index: Link!Gnus message by Message-Id
2244 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2245 discussion about linking to Gnus messages without encoding the folder
2246 name in the link. The following code hooks in to the store-link
2247 function in Gnus to capture links by Message-Id when in nnml folders,
2248 and then provides a link type "mid" which can open this link. The
2249 =mde-org-gnus-open-message-link= function uses the
2250 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2251 scan. It will go through them, in order, asking each to locate the
2252 message and opening it from the first one that reports success.
2254 It has only been tested with a single nnml backend, so there may be
2255 bugs lurking here and there.
2257 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2260 #+begin_src emacs-lisp
2261 ;; Support for saving Gnus messages by Message-ID
2262 (defun mde-org-gnus-save-by-mid ()
2263 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2264 (when (eq major-mode 'gnus-article-mode)
2265 (gnus-article-show-summary))
2266 (let* ((group gnus-newsgroup-name)
2267 (method (gnus-find-method-for-group group)))
2268 (when (eq 'nnml (car method))
2269 (let* ((article (gnus-summary-article-number))
2270 (header (gnus-summary-article-header article))
2271 (from (mail-header-from header))
2274 (let ((mid (mail-header-id header)))
2275 (if (string-match "<\\(.*\\)>" mid)
2276 (match-string 1 mid)
2277 (error "Malformed message ID header %s" mid)))))
2278 (date (mail-header-date header))
2279 (subject (gnus-summary-subject-string)))
2280 (org-store-link-props :type "mid" :from from :subject subject
2281 :message-id message-id :group group
2282 :link (org-make-link "mid:" message-id))
2283 (apply 'org-store-link-props
2284 :description (org-email-link-description)
2285 org-store-link-plist)
2288 (defvar mde-mid-resolve-methods '()
2289 "List of methods to try when resolving message ID's. For Gnus,
2290 it is a cons of 'gnus and the select (type and name).")
2291 (setq mde-mid-resolve-methods
2294 (defvar mde-org-gnus-open-level 1
2295 "Level at which Gnus is started when opening a link")
2296 (defun mde-org-gnus-open-message-link (msgid)
2297 "Open a message link with Gnus"
2299 (require 'org-table)
2300 (catch 'method-found
2301 (message "[MID linker] Resolving %s" msgid)
2302 (dolist (method mde-mid-resolve-methods)
2304 ((and (eq (car method) 'gnus)
2305 (eq (cadr method) 'nnml))
2306 (funcall (cdr (assq 'gnus org-link-frame-setup))
2307 mde-org-gnus-open-level)
2308 (when gnus-other-frame-object
2309 (select-frame gnus-other-frame-object))
2310 (let* ((msg-info (nnml-find-group-number
2311 (concat "<" msgid ">")
2313 (group (and msg-info (car msg-info)))
2314 (message (and msg-info (cdr msg-info)))
2316 (if (gnus-methods-equal-p
2320 (gnus-group-full-name group (cdr method))))))
2322 (gnus-summary-read-group qname nil t)
2323 (gnus-summary-goto-article message nil t))
2324 (throw 'method-found t)))
2325 (t (error "Unknown link type"))))))
2327 (eval-after-load 'org-gnus
2329 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2330 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2333 ** Store link to a message when sending in Gnus
2334 #+index: Link!Store link to a message when sending in Gnus
2335 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2337 #+begin_src emacs-lisp
2338 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2339 "Send message with `message-send-and-exit' and store org link to message copy.
2340 If multiple groups appear in the Gcc header, the link refers to
2341 the copy in the last group."
2345 (message-narrow-to-headers)
2346 (let ((gcc (car (last
2347 (message-unquote-tokens
2348 (message-tokenize-header
2349 (mail-fetch-field "gcc" nil t) " ,")))))
2350 (buf (current-buffer))
2351 (message-kill-buffer-on-exit nil)
2352 id to from subject desc link newsgroup xarchive)
2353 (message-send-and-exit arg)
2355 ;; gcc group found ...
2357 (save-current-buffer
2358 (progn (set-buffer buf)
2359 (setq id (org-remove-angle-brackets
2360 (mail-fetch-field "Message-ID")))
2361 (setq to (mail-fetch-field "To"))
2362 (setq from (mail-fetch-field "From"))
2363 (setq subject (mail-fetch-field "Subject"))))
2364 (org-store-link-props :type "gnus" :from from :subject subject
2365 :message-id id :group gcc :to to)
2366 (setq desc (org-email-link-description))
2367 (setq link (org-gnus-article-link
2368 gcc newsgroup id xarchive))
2369 (setq org-stored-links
2370 (cons (list link desc) org-stored-links)))
2371 ;; no gcc group found ...
2372 (message "Can not create Org link: No Gcc header found."))))))
2374 (define-key message-mode-map [(control c) (control meta c)]
2375 'ulf-message-send-and-org-gnus-store-link)
2378 ** Send html messages and attachments with Wanderlust
2381 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2382 similar functionality for both Wanderlust and Gnus. The hack below is
2383 still somewhat different: It allows you to toggle sending of html
2384 messages within Wanderlust transparently. I.e. html markup of the
2385 message body is created right before sending starts.
2387 *** Send HTML message
2389 Putting the code below in your .emacs adds following four functions:
2391 - dmj/wl-send-html-message
2393 Function that does the job: Convert everything between "--text
2394 follows this line--" and first mime entity (read: attachment) or
2395 end of buffer into html markup using `org-export-region-as-html'
2396 and replaces original body with a multipart MIME entity with the
2397 plain text version of body and the html markup version. Thus a
2398 recipient that prefers html messages can see the html markup,
2399 recipients that prefer or depend on plain text can see the plain
2402 Cannot be called interactively: It is hooked into SEMI's
2403 `mime-edit-translate-hook' if message should be HTML message.
2405 - dmj/wl-send-html-message-draft-init
2407 Cannot be called interactively: It is hooked into WL's
2408 `wl-mail-setup-hook' and provides a buffer local variable to
2411 - dmj/wl-send-html-message-draft-maybe
2413 Cannot be called interactively: It is hooked into WL's
2414 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2415 `mime-edit-translate-hook' depending on whether HTML message is
2418 - dmj/wl-send-html-message-toggle
2420 Toggles sending of HTML message. If toggled on, the letters
2421 "HTML" appear in the mode line.
2423 Call it interactively! Or bind it to a key in `wl-draft-mode'.
2425 If you have to send HTML messages regularly you can set a global
2426 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2427 toggle on sending HTML message by default.
2429 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2430 Google's web front end. As you can see you have the whole markup of
2431 Org at your service: *bold*, /italics/, tables, lists...
2433 So even if you feel uncomfortable with sending HTML messages at least
2434 you send HTML that looks quite good.
2436 #+begin_src emacs-lisp
2437 (defun dmj/wl-send-html-message ()
2438 "Send message as html message.
2439 Convert body of message to html using
2440 `org-export-region-as-html'."
2443 (let (beg end html text)
2444 (goto-char (point-min))
2445 (re-search-forward "^--text follows this line--$")
2446 ;; move to beginning of next line
2447 (beginning-of-line 2)
2449 (if (not (re-search-forward "^--\\[\\[" nil t))
2450 (setq end (point-max))
2455 (setq text (buffer-substring-no-properties beg end))
2461 (when (re-search-backward "^-- \n" nil t)
2462 ;; preserve link breaks in signature
2463 (insert "\n#+BEGIN_VERSE\n")
2464 (goto-char (point-max))
2465 (insert "\n#+END_VERSE\n")
2467 (setq html (org-export-region-as-html
2468 (point-min) (point-max) t 'string))))
2469 (delete-region beg end)
2472 "--" "<<alternative>>-{\n"
2473 "--" "[[text/plain]]\n" text
2474 "--" "[[text/html]]\n" html
2475 "--" "}-<<alternative>>\n")))))
2477 (defun dmj/wl-send-html-message-toggle ()
2478 "Toggle sending of html message."
2480 (setq dmj/wl-send-html-message-toggled-p
2481 (if dmj/wl-send-html-message-toggled-p
2483 (message "Sending html message toggled %s"
2484 (if dmj/wl-send-html-message-toggled-p
2487 (defun dmj/wl-send-html-message-draft-init ()
2488 "Create buffer local settings for maybe sending html message."
2489 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2490 (setq dmj/wl-send-html-message-toggled-p nil))
2491 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2492 (add-to-list 'global-mode-string
2493 '(:eval (if (eq major-mode 'wl-draft-mode)
2494 dmj/wl-send-html-message-toggled-p))))
2496 (defun dmj/wl-send-html-message-maybe ()
2497 "Maybe send this message as html message.
2499 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2500 non-nil, add `dmj/wl-send-html-message' to
2501 `mime-edit-translate-hook'."
2502 (if dmj/wl-send-html-message-toggled-p
2503 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2504 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2506 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2507 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2508 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2511 *** Attach HTML of region or subtree
2513 Instead of sending a complete HTML message you might only send parts
2514 of an Org file as HTML for the poor souls who are plagued with
2515 non-proportional fonts in their mail program that messes up pretty
2518 This short function does the trick: It exports region or subtree to
2519 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2520 and clipboard. If a region is active, it uses the region, the
2521 complete subtree otherwise.
2523 #+begin_src emacs-lisp
2524 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2525 "Export region between BEG and END as html attachment.
2526 If BEG and END are not set, use current subtree. Region or
2527 subtree is exported to html without header and footer, prefixed
2528 with a mime entity string and pushed to clipboard and killring.
2529 When called with prefix, mime entity is not marked as
2531 (interactive "r\nP")
2533 (let* ((beg (if (region-active-p) (region-beginning)
2535 (org-back-to-heading)
2537 (end (if (region-active-p) (region-end)
2539 (org-end-of-subtree)
2541 (html (concat "--[[text/html"
2542 (if arg "" "\nContent-Disposition: attachment")
2544 (org-export-region-as-html beg end t 'string))))
2545 (when (fboundp 'x-set-selection)
2546 (ignore-errors (x-set-selection 'PRIMARY html))
2547 (ignore-errors (x-set-selection 'CLIPBOARD html)))
2548 (message "html export done, pushed to kill ring and clipboard"))))
2551 *** Adopting for Gnus
2553 The whole magic lies in the special strings that mark a HTML
2554 attachment. So you might just have to find out what these special
2555 strings are in message-mode and modify the functions accordingly.
2556 ** Add sunrise/sunset times to the agenda.
2557 #+index: Agenda!Diary s-expressions
2560 The diary package provides the function =diary-sunrise-sunset= which can be used
2561 in a diary s-expression in some agenda file like this:
2563 #+begin_src org-mode
2564 %%(diary-sunrise-sunset)
2567 Seb Vauban asked if it is possible to put sunrise and sunset in
2568 separate lines. Here is a hack to do that. It adds two functions (they
2569 have to be available before the agenda is shown, so I add them early
2570 in my org-config file which is sourced from .emacs, but you'll have to
2571 suit yourself here) that just parse the output of
2572 diary-sunrise-sunset, instead of doing the right thing which would be
2573 to take advantage of the data structures that diary/solar.el provides.
2574 In short, a hack - so perfectly suited for inclusion here :-)
2576 The functions (and latitude/longitude settings which you have to modify for
2577 your location) are as follows:
2579 #+begin_src emacs-lisp
2580 (setq calendar-latitude 48.2)
2581 (setq calendar-longitude 16.4)
2582 (setq calendar-location-name "Vienna, Austria")
2584 (autoload 'solar-sunrise-sunset "solar.el")
2585 (autoload 'solar-time-string "solar.el")
2586 (defun diary-sunrise ()
2587 "Local time of sunrise 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 (caar l) nil)))))
2598 (defun diary-sunset ()
2599 "Local time of sunset as a diary entry.
2600 The diary entry can contain `%s' which will be replaced with
2601 `calendar-location-name'."
2602 (let ((l (solar-sunrise-sunset date)))
2605 (if (string= entry "")
2607 (format entry (eval calendar-location-name))) " "
2608 (solar-time-string (caadr l) nil)))))
2611 You also need to add a couple of diary s-expressions in one of your agenda
2614 #+begin_src org-mode
2615 %%(diary-sunrise)Sunrise in %s
2619 This will show sunrise with the location and sunset without it.
2621 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]].
2622 In comparison to the version posted on the mailing list, this one
2623 gets rid of the timezone information and can show the location.
2624 ** Add lunar phases to the agenda.
2625 #+index: Agenda!Diary s-expressions
2628 Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
2629 This can be used to display lunar phases in the agenda display with the
2632 #+begin_src emacs-lisp
2635 (org-no-warnings (defvar date))
2636 (defun org-lunar-phases ()
2637 "Show lunar phase in Agenda buffer."
2639 (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
2640 (phase (cl-find-if (lambda (phase) (equal (car phase) date))
2643 (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
2644 (substring (nth 1 phase) 0 5))))))
2647 Add the following line to an agenda file:
2649 #+begin_src org-mode
2652 %%(org-lunar-phases)
2655 This should display an entry on new moon, first/last quarter moon, and on full
2656 moon. You can customize the entries by customizing =lunar-phase-names=.
2658 E.g., to add Unicode symbols:
2660 #+begin_src emacs-lisp
2661 (setq lunar-phase-names
2662 '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
2663 "☽ First Quarter Moon"
2664 "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
2665 "☾ Last Quarter Moon"))
2668 Unicode 6 even provides symbols for the Moon with nice faces. But those
2669 symbols are currently barely supported in fonts.
2670 See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].
2672 ** Export BBDB contacts to org-contacts.el
2673 #+index: Address Book!BBDB to org-contacts
2674 Try this tool by Wes Hardaker:
2676 http://www.hardakers.net/code/bbdb-to-org-contacts/
2678 ** Calculating date differences - how to write a simple elisp function
2679 #+index: Timestamp!date calculations
2680 #+index: Elisp!technique
2682 Alexander Wingård asked how to calculate the number of days between a
2683 time stamp in his org file and today (see
2684 http://thread.gmane.org/gmane.emacs.orgmode/46881). Although the
2685 resulting answer is probably not of general interest, the method might
2686 be useful to a budding Elisp programmer.
2688 Alexander started from an already existing org function,
2689 =org-evaluate-time-range=. When this function is called in the context
2690 of a time range (two time stamps separated by "=--="), it calculates the
2691 number of days between the two dates and outputs the result in Emacs's
2692 echo area. What he wanted was a similar function that, when called from
2693 the context of a single time stamp, would calculate the number of days
2694 between the date in the time stamp and today. The result should go to
2695 the same place: Emacs's echo area.
2697 The solution presented in the mail thread is as follows:
2699 #+begin_src emacs-lisp
2700 (defun aw/org-evaluate-time-range (&optional to-buffer)
2702 (if (org-at-date-range-p t)
2703 (org-evaluate-time-range to-buffer)
2704 ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
2705 (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
2708 (goto-char (point-at-bol))
2709 (re-search-forward org-ts-regexp (point-at-eol) t)
2710 (if (not (org-at-timestamp-p t))
2711 (error "No timestamp here"))
2712 (goto-char (match-beginning 0))
2713 (org-insert-time-stamp (current-time) nil nil)
2715 (org-evaluate-time-range to-buffer)))))
2718 The function assumes that point is on some line with some time stamp
2719 (or a date range) in it. Note that =org-evaluate-time-range= does not care
2720 whether the first date is earlier than the second: it will always output
2721 the number of days between the earlier date and the later date.
2723 As stated before, the function itself is of limited interest (although
2724 it satisfied Alexander's need).The *method* used might be of wider
2725 interest however, so here is a short explanation.
2727 The idea is that we want =org-evaluate-time-range= to do all the
2728 heavy lifting, but that function requires that it be in a date-range
2729 context. So the function first checks whether it's in a date range
2730 context already: if so, it calls =org-evaluate-time-range= directly
2731 to do the work. The trick now is to arrange things so we can call this
2732 same function in the case where we do *not* have a date range
2733 context. In that case, we manufacture one: we create a temporary
2734 buffer, copy the line with the purported time stamp to the temp
2735 buffer, find the time stamp (signal an error if no time stamp is
2736 found) and insert a new time stamp with the current time before the
2737 existing time stamp, followed by "=--=": voilà, we now have a time range
2738 on which we can apply our old friend =org-evaluate-time-range= to
2739 produce the answer. Because of the above-mentioned property
2740 of =org-evaluate-time-range=, it does not matter if the existing
2741 time stamp is earlier or later than the current time: the correct
2742 number of days is output.
2744 Note that at the end of the call to =with-temp-buffer=, the temporary
2745 buffer goes away. It was just used as a scratch pad for the function
2746 to do some figuring.
2748 The idea of using a temp buffer as a scratch pad has wide
2749 applicability in Emacs programming. The rest of the work is knowing
2750 enough about facilities provided by Emacs (e.g. regexp searching) and
2751 by Org (e.g. checking for time stamps and generating a time stamp) so
2752 that you don't reinvent the wheel, and impedance-matching between the
2755 ** ibuffer and org files
2757 Neil Smithline posted this snippet to let you browse org files with
2760 #+BEGIN_SRC emacs-lisp
2763 (defun org-ibuffer ()
2764 "Open an `ibuffer' window showing only `org-mode' buffers."
2766 (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
2769 ** Enable org-mode links in other modes
2771 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
2773 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
2775 * Hacking Org: Working with Org-mode and External Programs.
2776 ** Use Org-mode with Screen [Andrew Hyatt]
2777 #+index: Link!to screen session
2778 "The general idea is that you start a task in which all the work will
2779 take place in a shell. This usually is not a leaf-task for me, but
2780 usually the parent of a leaf task. From a task in your org-file, M-x
2781 ash-org-screen will prompt for the name of a session. Give it a name,
2782 and it will insert a link. Open the link at any time to go the screen
2783 session containing your work!"
2785 http://article.gmane.org/gmane.emacs.orgmode/5276
2787 #+BEGIN_SRC emacs-lisp
2790 (defun ash-org-goto-screen (name)
2791 "Open the screen with the specified name in the window"
2792 (interactive "MScreen name: ")
2793 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2794 (if (member screen-buffer-name
2795 (mapcar 'buffer-name (buffer-list)))
2796 (switch-to-buffer screen-buffer-name)
2797 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2799 (defun ash-org-screen-buffer-name (name)
2800 "Returns the buffer name corresponding to the screen name given."
2801 (concat "*screen " name "*"))
2803 (defun ash-org-screen-helper (name arg)
2804 ;; Pick the name of the new buffer.
2805 (let ((term-ansi-buffer-name
2806 (generate-new-buffer-name
2807 (ash-org-screen-buffer-name name))))
2808 (setq term-ansi-buffer-name
2809 (term-ansi-make-term
2810 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2811 (set-buffer term-ansi-buffer-name)
2814 (term-set-escape-char ?\C-x)
2815 term-ansi-buffer-name))
2817 (defun ash-org-screen (name)
2818 "Start a screen session with name"
2819 (interactive "MScreen name: ")
2821 (ash-org-screen-helper name "-S"))
2822 (insert-string (concat "[[screen:" name "]]")))
2824 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2825 ;; \"%s\")") to org-link-abbrev-alist.
2828 ** Org Agenda + Appt + Zenity
2830 :CUSTOM_ID: org-agenda-appt-zenity
2833 #+index: Appointment!reminders
2834 #+index: Appt!Zenity
2836 <a name="agenda-appt-zenity"></a>
2838 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It makes sure your agenda
2839 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2842 #+BEGIN_SRC emacs-lisp
2843 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2844 ; For org appointment reminders
2846 ;; Get appointments for today
2847 (defun my-org-agenda-to-appt ()
2849 (setq appt-time-msg-list nil)
2850 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
2851 (org-agenda-to-appt)))
2853 ;; Run once, activate and schedule refresh
2854 (my-org-agenda-to-appt)
2856 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2859 (setq appt-message-warning-time 15)
2860 (setq appt-display-interval 5)
2862 ; Update appt each time agenda opened.
2863 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2865 ; Setup zenify, we tell appt to use window, and replace default function
2866 (setq appt-display-format 'window)
2867 (setq appt-disp-window-function (function my-appt-disp-window))
2869 (defun my-appt-disp-window (min-to-app new-time msg)
2870 (save-window-excursion (shell-command (concat
2871 "/usr/bin/zenity --info --title='Appointment' --text='"
2872 msg "' &") nil nil)))
2875 ** Org-Mode + gnome-osd
2876 #+index: Appointment!reminders
2877 #+index: Appt!gnome-osd
2878 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2879 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2881 ** txt2org convert text data to org-mode tables
2884 I often find it useful to generate Org-mode tables on the command line
2885 from tab-separated data. The following awk script makes this easy to
2886 do. Text data is read from STDIN on a pipe and any command line
2887 arguments are interpreted as rows at which to insert hlines.
2889 Here are two usage examples.
2890 1. running the following
2891 : $ cat <<EOF|~/src/config/bin/txt2org
2903 2. and the following (notice the command line argument)
2904 : $ cat <<EOF|~/src/config/bin/txt2org 1
2912 : | strings | numbers |
2913 : |---------+---------|
2919 Here is the script itself
2923 # Read tab separated data from STDIN and output an Org-mode table.
2925 # Optional command line arguments specify row numbers at which to
2929 for(i=1; i<ARGC; i++){
2930 hlines[ARGV[i]+1]=1; ARGV[i] = "-"; } }
2933 if(NF > max_nf){ max_nf = NF; };
2934 for(f=1; f<=NF; f++){
2935 if(length($f) > lengths[f]){ lengths[f] = length($f); };
2940 for(f=1; f<=max_nf; f++){
2941 for(i=0; i<(lengths[f] + 2); i++){ hline_str=hline_str "-"; }
2942 if( f != max_nf){ hline_str=hline_str "+"; }
2943 else { hline_str=hline_str "|"; } }
2945 for(r=1; r<=NR; r++){ # rows
2946 if(hlines[r] == 1){ print hline_str; }
2948 for(f=1; f<=max_nf; f++){ # columns
2949 cell=row[r][f]; padding=""
2950 for(i=0; i<(lengths[f] - length(cell)); i++){ padding=padding " "; }
2951 # for now just print everything right-aligned
2952 # if(cell ~ /[0-9.]/){ printf " %s%s |", cell, padding; }
2953 # else{ printf " %s%s |", padding, cell; }
2954 printf " %s%s |", padding, cell; }
2957 if(hlines[NR+1]){ print hline_str; } }
2961 #+index: Agenda!Views
2962 #+index: Agenda!and Remind (external program)
2965 http://article.gmane.org/gmane.emacs.orgmode/5073
2968 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2969 command line calendaring program. Its features supersede the possibilities
2970 of orgmode in the area of date specifying, so that I want to use it
2971 combined with orgmode.
2973 Using the script below I'm able use remind and incorporate its output in my
2974 agenda views. The default of using 13 months look ahead is easily
2975 changed. It just happens I sometimes like to look a year into the
2979 ** Useful webjumps for conkeror
2980 #+index: Shortcuts!conkeror
2981 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2982 your =~/.conkerorrc= file:
2985 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2986 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2989 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2990 Org-mode mailing list.
2992 ** Use MathJax for HTML export without requiring JavaScript
2993 #+index: Export!MathJax
2994 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2996 If you like the results but do not want JavaScript in the exported pages,
2997 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2998 HTML file from the exported version. It can also embed all referenced fonts
2999 within the HTML file itself, so there are no dependencies to external files.
3001 The download archive contains an elisp file which integrates it into the Org
3002 export process (configurable per file with a "#+StaticMathJax:" line).
3004 Read README.org and the comments in org-static-mathjax.el for usage instructions.
3005 ** Search Org files using lgrep
3006 #+index: search!lgrep
3007 Matt Lundin suggests this:
3009 #+begin_src emacs-lisp
3010 (defun my-org-grep (search &optional context)
3011 "Search for word in org files.
3013 Prefix argument determines number of lines."
3014 (interactive "sSearch for: \nP")
3015 (let ((grep-find-ignored-files '("#*" ".#*"))
3016 (grep-template (concat "grep <X> -i -nH "
3018 (concat "-C" (number-to-string context)))
3020 (lgrep search "*org*" "/home/matt/org/")))
3022 (global-set-key (kbd "<f8>") 'my-org-grep)
3025 ** Automatic screenshot insertion
3026 #+index: Link!screenshot
3027 Suggested by Russell Adams
3029 #+begin_src emacs-lisp
3030 (defun my-org-screenshot ()
3031 "Take a screenshot into a time stamped unique-named file in the
3032 same directory as the org-buffer and insert a link to this file."
3037 (concat (buffer-file-name)
3039 (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
3040 (call-process "import" nil nil nil filename)
3041 (insert (concat "[[" filename "]]"))
3042 (org-display-inline-images))
3045 ** Capture invitations/appointments from MS Exchange emails
3046 #+index: Appointment!MS Exchange
3047 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
3048 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
3050 ** Audio/video file playback within org mode
3051 #+index: Link!audio/video
3052 Paul Sexton provided code that makes =file:= links to audio or video files
3053 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
3054 media player library. The user can pause, skip forward and backward in the
3055 track, and so on from without leaving Emacs. Links can also contain a time
3056 after a double colon -- when this is present, playback will begin at that
3057 position in the track.
3059 See the file [[file:code/elisp/org-player.el][org-player.el]]
3061 ** Under X11 Keep a window with the current agenda items at all time
3062 #+index: Agenda!dedicated window
3063 I struggle to keep (in emacs) a window with the agenda at all times.
3064 For a long time I have wanted a sticky window that keeps this
3065 information, and then use my window manager to place it and remove its
3066 decorations (I can also force its placement in the stack: top always,
3069 I wrote a small program in qt that simply monitors an HTML file and
3070 displays it. Nothing more. It does the work for me, and maybe somebody
3071 else will find it useful. It relies on exporting the agenda as HTML
3072 every time the org file is saved, and then this little program
3073 displays the html file. The window manager is responsible of removing
3074 decorations, making it sticky, and placing it in same place always.
3076 Here is a screenshot (see window to the bottom right). The decorations
3077 are removed by the window manager:
3079 http://turingmachine.org/hacking/org-mode/orgdisplay.png
3081 Here is the code. As I said, very, very simple, but maybe somebody will
3084 http://turingmachine.org/hacking/org-mode/
3088 ** Script (thru procmail) to output emails to an Org file
3089 #+index: Conversion!email to org file
3090 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
3092 : I've [...] created some procmail and shell glue that takes emails and
3093 : inserts them into an org-file so that I can capture stuff on the go using
3094 : the email program.
3096 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3098 ** Save File With Different Format for Headings (fileconversion)
3100 :CUSTOM_ID: fileconversion
3102 #+index: Conversion!fileconversion
3104 Using hooks and on the fly
3105 - when writing a buffer to the file replace the leading stars from headings
3107 - when reading a file into the buffer replace the file chars with leading
3110 To change to save an Org file in one of the formats or back just add or
3111 remove the keyword in the STARTUP line and save.
3113 Now you can also change to Fundamental mode to see how the file looks like
3114 on the level of the file, go back to Org mode, reenter Org mode or change to
3115 any other major mode and the conversion gets done whenever necessary.
3117 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
3119 :CUSTOM_ID: hidestarsfile
3121 #+index: Conversion!fileconversion hidestarsfile
3123 This is like "a cleaner outline view":
3124 http://orgmode.org/manual/Clean-view.html
3126 Example of the _file content_ first with leading stars as usual and below
3127 without leading stars through "#+STARTUP: odd hidestars hidestarsfile":
3130 #+STARTUP: odd hidestars
3142 #+STARTUP: odd hidestars hidestarsfile
3153 The latter is convenient for better human readability when an Org file,
3154 additionally to Emacs, is read with a file viewer or, for smaller edits,
3155 with an editor not capable of the Org file format.
3157 hidestarsfile is a hack and can not become part of the Org core:
3158 - An Org file with hidestarsfile can not contain list items with a star as
3159 bullet due to the syntax conflict at read time. Mark E. Shoulson suggested
3160 to use the non-breaking space which is now implemented in fileconversion
3161 as nbspstarsfile as an alternative for hidestarsfile. Although I don't
3162 recommend it because an editor like typically e. g. Emacs may render the
3163 non-breaking space differently from the space 0x20.
3164 - An Org file with hidestarsfile can almost not be edited with an Org mode
3165 without added functionality of hidestarsfile as long as the file is not
3168 *** Headings in Markdown Format (markdownstarsfile)
3170 :CUSTOM_ID: markdownstarsfile
3172 #+index: Conversion!fileconversion markdownstarsfile
3174 For "oddeven" you can use markdownstarsfile to be readable or even basically
3175 editable with Markdown (does not make much sense with "odd", see
3176 org-convert-to-odd-levels and org-convert-to-oddeven-levels for how to
3179 Example of the _file content_:
3182 #+STARTUP: oddeven markdownstarsfile
3184 1. first item of numbered list (same format in Org and Markdown)
3186 - first item of unordered list (same format in Org and Markdown)
3188 + first item of unordered list (same format in Org and Markdown)
3189 #### section level 4
3190 * first item of unordered list (same format in Org and Markdown)
3191 * avoid this item type to be compatible with Org hidestarsfile
3194 An Org file with markdownstarsfile can not contain code comment lines
3195 prefixed with "#", even not when within source blocks.
3199 :CUSTOM_ID: fileconversion-code
3201 #+index: Conversion!fileconversion emacs-lisp code
3203 #+BEGIN_SRC emacs-lisp
3204 ;; - fileconversion version 0.6
3205 ;; - DISCLAIMER: Make a backup of your Org files before using
3206 ;; my-org-fileconv-*.
3207 ;; - supported formats: hidestarsfile, markdownstarsfile
3209 ;; design summary: fileconversion is a round robin of two states
3210 ;; linked by two actions:
3211 ;; - state my-org-fileconv-level-org-p is nil: the level is "file"
3213 ;; - action my-org-fileconv-decode: replace file char with '*'
3214 ;; - state my-org-fileconv-level-org-p is t: the level is "Org"
3216 ;; - action my-org-fileconv-encode replace '*' with file char
3218 (defvar my-org-fileconv-level-org-p nil
3219 "Whether level of buffer is Org or only file.
3220 nil means the level is file (encoded), non-nil means the level is Org
3222 (make-variable-buffer-local 'my-org-fileconv-level-org-p)
3223 ;; survive a change of major mode that does kill-all-local-variables,
3224 ;; e. g. when reentering Org mode through “C-c C-c” on a STARTUP line
3225 (put 'my-org-fileconv-level-org-p 'permanent-local t)
3227 (add-hook 'org-mode-hook 'my-org-fileconv-init
3228 ;; _append_ to hook to have a higher chance that a message
3229 ;; from this function will be visible as the last message in
3232 ;; hook addition global
3235 (defun my-org-fileconv-init ()
3237 ;; instrument only when converting really from/to an Org _file_, not
3238 ;; e. g. for a temp Org buffer unrelated to a file like used e. g.
3239 ;; when calling the old Org exporter
3240 (when (buffer-file-name)
3241 (message "INF: my-org-fileconv-init, buffer: %s" (buffer-name))
3242 (my-org-fileconv-decode)
3243 ;; the hooks are not permanent-local, this way and as needed they
3244 ;; will disappear when the major mode of the buffer changes
3245 (add-hook 'change-major-mode-hook 'my-org-fileconv-encode nil
3246 ;; hook addition limited to buffer locally
3248 (add-hook 'before-save-hook 'my-org-fileconv-encode nil
3249 ;; hook addition limited to buffer locally
3251 (add-hook 'after-save-hook 'my-org-fileconv-decode nil
3252 ;; hook addition limited to buffer locally
3255 (defun my-org-fileconv-re ()
3256 "Check whether there is a STARTUP line for fileconversion.
3257 If found then return the expressions required for the conversion."
3259 (beginning-of-buffer)
3260 (let (re-list (count 0))
3261 (while (re-search-forward "^#\\+STARTUP:" nil t)
3262 ;; #+STARTUP: hidestarsfile
3263 (when (string-match-p "\\bhidestarsfile\\b"
3264 (thing-at-point 'line))
3266 ;; - line starting with star for bold emphasis
3267 ;; - line of stars to underline section title in loosely
3268 ;; quoted ASCII style (star at end of line)
3269 (setq re-list '("\\(\\* \\)" ; common-re
3271 (setq count (1+ count)))
3272 ;; #+STARTUP: nbspstarsfile
3273 (when (string-match-p "\\bnbspstarsfile\\b"
3274 (thing-at-point 'line))
3275 (setq re-list '("\\(\\* \\)" ; common-re
3276 ?\xa0)) ; file-char non-breaking space
3277 (setq count (1+ count)))
3278 ;; #+STARTUP: markdownstarsfile
3279 (when (string-match-p "\\bmarkdownstarsfile\\b"
3280 (thing-at-point 'line))
3283 (setq re-list '("\\( \\)" ; common-re
3285 (setq count (1+ count))))
3287 (error "ERR: more than one fileconversion found"))
3290 (defun my-org-fileconv-decode ()
3291 "In headings replace file char with '*'."
3292 (let ((re-list (my-org-fileconv-re)))
3293 (when (and re-list (not my-org-fileconv-level-org-p))
3294 ;; no `save-excursion' to be able to keep point in case of error
3295 (let* ((common-re (nth 0 re-list))
3296 (file-char (nth 1 re-list))
3297 (file-re (concat "^" (string file-char) "+" common-re))
3298 (org-re (concat "^\\*+" common-re))
3301 (beginning-of-buffer)
3303 (when (re-search-forward org-re nil t)
3304 (goto-char (match-beginning 0))
3307 "ERR: my-org-fileconv-decode syntax conflict at point"))
3308 (beginning-of-buffer)
3310 (with-silent-modifications
3311 (while (re-search-forward file-re nil t)
3312 (goto-char (match-beginning 0))
3313 ;; faster than a lisp call of insert and delete on each
3315 (setq len (- (match-beginning 1) (match-beginning 0)))
3316 (insert-char ?* len)
3320 ;; notes for ediff when only one file has fileconversion:
3321 ;; - The changes to the buffer with fileconversion until here
3322 ;; are not regarded by ediff-files because the first call to
3323 ;; diff is made with the bare files directly. Only
3324 ;; ediff-update-diffs and ediff-buffers write the decoded
3325 ;; buffers to temp files and then call diff with them.
3326 ;; - Workarounds (choose one):
3327 ;; - after ediff-files first do a "!" (ediff-update-diffs)
3328 ;; in the "*Ediff Control Panel*"
3329 ;; - instead of using ediff-files first open the files and
3330 ;; then run ediff-buffers (better for e. g. a script that
3331 ;; takes two files as arguments and uses "emacs --eval")
3333 ;; the level is Org most of all when no fileconversion is in effect
3334 (setq my-org-fileconv-level-org-p t))
3336 (defun my-org-fileconv-encode ()
3337 "In headings replace '*' with file char."
3338 (let ((re-list (my-org-fileconv-re)))
3339 (when (and re-list my-org-fileconv-level-org-p)
3340 ;; no `save-excursion' to be able to keep point in case of error
3341 (let* ((common-re (nth 0 re-list))
3342 (file-char (nth 1 re-list))
3343 (file-re (concat "^" (string file-char) "+" common-re))
3344 (org-re (concat "^\\*+" common-re))
3347 (beginning-of-buffer)
3349 (when (re-search-forward file-re nil t)
3350 (goto-char (match-beginning 0))
3353 "ERR: my-org-fileconv-encode syntax conflict at point"))
3354 (beginning-of-buffer)
3356 (with-silent-modifications
3357 (while (re-search-forward org-re nil t)
3358 (goto-char (match-beginning 0))
3359 ;; faster than a lisp call of insert and delete on each
3361 (setq len (- (match-beginning 1) (match-beginning 0)))
3362 (insert-char file-char len)
3365 (setq my-org-fileconv-level-org-p nil))))
3366 nil) ;; for the hook
3371 ** Meaningful diff for org files in a git repository
3372 #+index: git!diff org files
3373 Since most diff utilities are primarily meant for source code, it is
3374 difficult to read diffs of text files like ~.org~ files easily. If you
3375 version your org directory with a SCM like git you will know what I
3376 mean. However for git, there is a way around. You can use
3377 =gitattributes= to define a custom diff driver for org files. Then a
3378 regular expression can be used to configure how the diff driver
3379 recognises a "function".
3381 Put the following in your =<org_dir>/.gitattributes=.
3383 Then put the following lines in =<org_dir>/.git/config=
3385 : xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3387 This will let you see diffs for org files with each hunk identified by
3388 the unmodified headline closest to the changes. After the
3389 configuration a diff should look something like the example below.
3392 diff --git a/org-hacks.org b/org-hacks.org
3393 index a0672ea..92a08f7 100644
3396 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3398 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3400 +** Meaningful diff for org files in a git repository
3402 +Since most diff utilities are primarily meant for source code, it is
3403 +difficult to read diffs of text files like ~.org~ files easily. If you
3404 +version your org directory with a SCM like git you will know what I
3405 +mean. However for git, there is a way around. You can use
3406 +=gitattributes= to define a custom diff driver for org files. Then a
3407 +regular expression can be used to configure how the diff driver
3408 +recognises a "function".
3410 +Put the following in your =<org_dir>/.gitattributes=.
3412 +Then put the following lines in =<org_dir>/.git/config=
3414 +: xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3418 ** Cooking? Brewing?
3421 ** Opening devonthink links
3423 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3424 links from org-mode.
3428 ** Cooking? Brewing?
3429 #+index: beer!brewing
3430 #+index: cooking!conversions
3431 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3433 It currently does metric/english conversion, and a few other tricks.
3434 Basically I just use calc’s units code. I think scaling recipes, or
3435 turning percentages into weights would be pretty easy.
3437 https://gitorious.org/org-cook/org-cook
3439 There is also, for those interested:
3441 https://gitorious.org/org-brew/org-brew
3443 for brewing beer. This is again, mostly just calc functions, including
3444 hydrometer correction, abv calculation, priming sugar for a given CO_2
3445 volume, etc. More integration with org-mode should be possible: for
3446 instance it would be nice to be able to use a lookup table (of ingredients)
3447 to calculate target original gravity, IBUs, etc.