1 #+OPTIONS: H:3 num:nil toc:t \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate
3 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
4 #+TAGS: Write(w) Update(u) Fix(f) Check(c)
5 #+TITLE: Org ad hoc code, quick hacks and workarounds
7 #+EMAIL: mdl AT imapmail DOT org
12 # This file is the default header for new Org files in Worg. Feel free
13 # to tailor it to your needs.
15 [[file:index.org][{Back to Worg's index}]]
17 This page is for ad hoc bits of code. Feel free to add quick hacks and
20 * Hacking Org: Working within Org-mode.
21 ** Building and Managing Org
22 *** Generating autoloads and Compiling Org without make
24 :CUSTOM_ID: compiling-org-without-make
27 #+index: Compilation!without make
29 Compilation is optional, but you _must_ update the autoloads file
30 each time you update org, even when you run org uncompiled!
32 Starting with Org 7.9 you'll find functions for creating the
33 autoload files and do byte-compilation in =mk/org-fixup.el=. When
34 you execute the commands below, your current directory must be where
35 org has been unpacked into, in other words the file =README= should
36 be found in your current directory and the directories =lisp= and
37 =etc= should be subdirectories of it. The command =emacs= should be
38 found in your =PATH= and start the Emacs version you are using. To
39 make just the autoloads file do:
40 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
41 To make the autoloads file and byte-compile org:
42 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
43 To make the autoloads file and byte-compile all of org again:
44 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
45 If you are not using Git, you'll have to make fake version strings
46 first if =org-version.el= is not already available (if it is, you
47 could also edit the version strings there).
48 : emacs -batch -Q -L lisp -l ../mk/org-fixup \
49 : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
50 : (org-make-autoloads))'
52 POSIX shell for its quoting. Windows =CMD.exe= has quite different
53 quoting rules and this won't work, so your other option is to start
55 : emacs -Q -L lisp -l ../mk/org-fixup
56 then paste the following into the =*scratch*= buffer
57 #+BEGIN_SRC emacs-lisp
58 (let ((org-fake-release "7.9.1")
59 (org-fake-git-version "7.9.1-fake"))
62 position the cursor after the closing paren and press =C-j= or =C-x
63 C-e= to evaluate the form. Of course you can replace
64 =org-make-autoloads= with =org-make-autoloads-compile= or even
65 =org-make-autoloads-compile-force= if you wish with both variants.
67 For *older org versions only* (that do not yet have
68 =mk/org-fixup.el=), you can use the definitions below. To use
69 this function, adjust the variables =my/org-lisp-directory= and
70 =my/org-compile-sources= to suit your needs. If you have
71 byte-compiled org, but want to run org uncompiled again, just remove
72 all =*.elc= files in the =lisp/= directory, set
73 =my/org-compile-sources= to =nil=.
75 #+BEGIN_SRC emacs-lisp
76 (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
77 "Directory where your org-mode files live.")
79 (defvar my/org-compile-sources t
80 "If `nil', never compile org-sources. `my/compile-org' will only create
81 the autoloads file `org-install.el' then. If `t', compile the sources, too.")
83 ;; Customize: (must end with a slash!)
84 (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")
87 (setq my/org-compile-sources t)
89 (defun my/compile-org(&optional directory)
90 "Generate autoloads file org-install.el. Optionally compile
91 all *.el files that come with org-mode."
93 (defun my/compile-org()
94 "Generate autoloads file org-install.el. Optionally compile
95 all *.el files that come with org-mode."
97 (let ((dirlisp (file-name-directory my/org-lisp-directory)))
98 (add-to-list 'load-path dirlisp)
100 (let ((generated-autoload-file (concat dirlisp "org-install.el")))
101 ;; create the org-install file
102 (update-directory-autoloads dirlisp)
103 (when my/org-compile-sources
104 ;; optionally byte-compile
105 (byte-recompile-directory dirlisp 0 'force)))))
109 #+index: Initialization!Reload
111 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
112 function to reload org files.
114 Normally you want to use the compiled files since they are faster.
115 If you update your org files you can easily reload them with
119 If you run into a bug and want to generate a useful backtrace you can
120 reload the source files instead of the compiled files with
124 and turn on the "Enter Debugger On Error" option. Redo the action
125 that generates the error and cut and paste the resulting backtrace.
126 To switch back to the compiled version just reload again with
130 *** Check for possibly problematic old link escapes
132 :CUSTOM_ID: check-old-link-escapes
135 Starting with version 7.5 Org uses [[http://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
136 and with a modified algorithm to determine which characters to escape
139 As a side effect this modified behaviour might break existing links if
140 they contain a sequence of characters that look like a percent escape
141 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
143 The function below can be used to perform a preliminary check for such
144 links in an Org mode file. It will run through all links in the file
145 and issue a warning if it finds a percent escape sequence which is not
146 in old Org's list of known percent escapes.
148 #+begin_src emacs-lisp
149 (defun dmaus/org-check-percent-escapes ()
150 "*Check buffer for possibly problematic old link escapes."
152 (when (eq major-mode 'org-mode)
153 (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
154 "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
155 (unless (boundp 'warning-suppress-types)
156 (setq warning-suppress-types nil))
159 (goto-char (point-min))
160 (while (re-search-forward org-any-link-re nil t)
161 (let ((end (match-end 0)))
162 (goto-char (match-beginning 0))
163 (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
164 (let ((escape (match-string-no-properties 0)))
165 (unless (member (upcase escape) old-escapes)
166 (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
173 ** Structure Movement and Editing
174 *** Show next/prev heading tidily
176 #+index: Navigation!Heading
178 These close the current heading and open the next/previous heading.
180 #+begin_src emacs-lisp
181 (defun ded/org-show-next-heading-tidily ()
182 "Show next entry, keeping other entries closed."
183 (if (save-excursion (end-of-line) (outline-invisible-p))
184 (progn (org-show-entry) (show-children))
185 (outline-next-heading)
186 (unless (and (bolp) (org-on-heading-p))
187 (org-up-heading-safe)
189 (error "Boundary reached"))
195 (defun ded/org-show-previous-heading-tidily ()
196 "Show previous entry, keeping other entries closed."
198 (outline-previous-heading)
199 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
202 (error "Boundary reached"))
208 (setq org-use-speed-commands t)
209 (add-to-list 'org-speed-commands-user
210 '("n" ded/org-show-next-heading-tidily))
211 (add-to-list 'org-speed-commands-user
212 '("p" ded/org-show-previous-heading-tidily))
215 *** Promote all items in subtree
216 #+index: Structure Editing!Promote
219 This function will promote all items in a subtree. Since I use
220 subtrees primarily to organize projects, the function is somewhat
221 unimaginatively called my-org-un-project:
223 #+begin_src emacs-lisp
224 (defun my-org-un-project ()
226 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
230 *** Turn a heading into an Org link
232 :CUSTOM_ID: heading-to-link
234 #+index: Structure Editing!Heading
235 #+index: Link!Turn a heading into a
238 #+begin_src emacs-lisp
239 (defun dmj:turn-headline-into-org-mode-link ()
240 "Replace word at point by an Org mode link."
242 (when (org-at-heading-p)
243 (let ((hl-text (nth 4 (org-heading-components))))
244 (unless (or (null hl-text)
245 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
247 (search-forward hl-text (point-at-eol))
250 (format "[[file:%s.org][%s]]"
251 (org-link-escape hl-text)
252 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
253 nil (- (point) (length hl-text)) (point))))))
256 *** Using M-up and M-down to transpose paragraphs
257 #+index: Structure Editing!paragraphs
259 From Paul Sexton: By default, if used within ordinary paragraphs in
260 org mode, =M-up= and =M-down= transpose *lines* (not sentences). The
261 following code makes these keys transpose paragraphs, keeping the
262 point at the start of the moved paragraph. Behavior in tables and
263 headings is unaffected. It would be easy to modify this to transpose
266 #+begin_src emacs-lisp
267 (defun org-transpose-paragraphs (arg)
269 (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
270 (thing-at-point 'sentence))
271 (transpose-paragraphs arg)
273 (re-search-forward "[[:graph:]]")
274 (goto-char (match-beginning 0))
277 (add-to-list 'org-metaup-hook
278 (lambda () (interactive) (org-transpose-paragraphs -1)))
279 (add-to-list 'org-metadown-hook
280 (lambda () (interactive) (org-transpose-paragraphs 1)))
282 *** Changelog support for org headers
283 #+index: Structure Editing!Heading
286 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
287 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
288 headline as the "current function" if you add a changelog entry from an org
291 #+BEGIN_SRC emacs-lisp
292 (defun org-log-current-defun ()
294 (org-back-to-heading)
295 (if (looking-at org-complex-heading-regexp)
298 (add-hook 'org-mode-hook
300 (make-variable-buffer-local 'add-log-current-defun-function)
301 (setq add-log-current-defun-function 'org-log-current-defun)))
304 *** Different org-cycle-level behavior
305 #+index: Cycling!behavior
308 In recent org versions, when your point (cursor) is at the end of an
309 empty header line (like after you first created the header), the TAB
310 key (=org-cycle=) has a special behavior: it cycles the headline through
311 all possible levels. However, I did not like the way it determined
312 "all possible levels," so I rewrote the whole function, along with a
313 couple of supporting functions.
315 The original function's definition of "all possible levels" was "every
316 level from 1 to one more than the initial level of the current
317 headline before you started cycling." My new definition is "every
318 level from 1 to one more than the previous headline's level." So, if
319 you have a headline at level 4 and you use ALT+RET to make a new
320 headline below it, it will cycle between levels 1 and 5, inclusive.
322 The main advantage of my custom =org-cycle-level= function is that it
323 is stateless: the next level in the cycle is determined entirely by
324 the contents of the buffer, and not what command you executed last.
325 This makes it more predictable, I hope.
327 #+BEGIN_SRC emacs-lisp
330 (defun org-point-at-end-of-empty-headline ()
331 "If point is at the end of an empty headline, return t, else nil."
332 (and (looking-at "[ \t]*$")
334 (beginning-of-line 1)
335 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
337 (defun org-level-increment ()
338 "Return the number of stars that will be added or removed at a
339 time to headlines when structure editing, based on the value of
340 `org-odd-levels-only'."
341 (if org-odd-levels-only 2 1))
343 (defvar org-previous-line-level-cached nil)
345 (defun org-recalculate-previous-line-level ()
346 "Same as `org-get-previous-line-level', but does not use cached
347 value. It does *set* the cached value, though."
348 (set 'org-previous-line-level-cached
349 (let ((current-level (org-current-level))
350 (prev-level (when (> (line-number-at-pos) 1)
353 (org-current-level)))))
354 (cond ((null current-level) nil) ; Before first headline
355 ((null prev-level) 0) ; At first headline
358 (defun org-get-previous-line-level ()
359 "Return the outline depth of the last headline before the
360 current line. Returns 0 for the first headline in the buffer, and
361 nil if before the first headline."
362 ;; This calculation is quite expensive, with all the regex searching
363 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
364 ;; the last value of this command.
365 (or (and (eq last-command 'org-cycle-level)
366 org-previous-line-level-cached)
367 (org-recalculate-previous-line-level)))
369 (defun org-cycle-level ()
371 (let ((org-adapt-indentation nil))
372 (when (org-point-at-end-of-empty-headline)
373 (setq this-command 'org-cycle-level) ;Only needed for caching
374 (let ((cur-level (org-current-level))
375 (prev-level (org-get-previous-line-level)))
377 ;; If first headline in file, promote to top-level.
379 (loop repeat (/ (- cur-level 1) (org-level-increment))
380 do (org-do-promote)))
381 ;; If same level as prev, demote one.
382 ((= prev-level cur-level)
384 ;; If parent is top-level, promote to top level if not already.
386 (loop repeat (/ (- cur-level 1) (org-level-increment))
387 do (org-do-promote)))
388 ;; If top-level, return to prev-level.
390 (loop repeat (/ (- prev-level 1) (org-level-increment))
392 ;; If less than prev-level, promote one.
393 ((< cur-level prev-level)
395 ;; If deeper than prev-level, promote until higher than
397 ((> cur-level prev-level)
398 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
399 do (org-do-promote))))
403 *** Count words in an Org buffer
404 #FIXME: Does not fit too well under Structure. Any idea where to put it?
405 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
407 #+begin_src emacs-lisp
408 (defun org-word-count (beg end
409 &optional count-latex-macro-args?
411 "Report the number of words in the Org mode buffer or selected region.
415 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
416 - hyperlinks (but does count words in hyperlink descriptions)
417 - tags, priorities, and TODO keywords in headers
418 - sections tagged as 'not for export'.
420 The text of footnote definitions is ignored, unless the optional argument
421 COUNT-FOOTNOTES? is non-nil.
423 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
424 includes LaTeX macro arguments (the material between {curly braces}).
425 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
429 (setf beg (point-min)
432 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
435 (while (< (point) end)
438 ((or (org-in-commented-line) (org-at-table-p))
440 ;; Ignore hyperlinks. But if link has a description, count
441 ;; the words within the description.
442 ((looking-at org-bracket-link-analytic-regexp)
443 (when (match-string-no-properties 5)
444 (let ((desc (match-string-no-properties 5)))
446 (incf wc (length (remove "" (org-split-string
448 (goto-char (match-end 0)))
449 ((looking-at org-any-link-re)
450 (goto-char (match-end 0)))
451 ;; Ignore source code blocks.
452 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
454 ;; Ignore inline source blocks, counting them as 1 word.
457 (looking-at org-babel-inline-src-block-regexp))
458 (goto-char (match-end 0))
460 ;; Count latex macros as 1 word, ignoring their arguments.
463 (looking-at latex-macro-regexp))
464 (goto-char (if count-latex-macro-args?
469 ((and (not count-footnotes?)
470 (or (org-footnote-at-definition-p)
471 (org-footnote-at-reference-p)))
474 (let ((contexts (org-context)))
476 ;; Ignore tags and TODO keywords, etc.
477 ((or (assoc :todo-keyword contexts)
478 (assoc :priority contexts)
479 (assoc :keyword contexts)
480 (assoc :checkbox contexts))
482 ;; Ignore sections marked with tags that are
483 ;; excluded from export.
484 ((assoc :tags contexts)
485 (if (intersection (org-get-tags-at) org-export-exclude-tags
487 (org-forward-same-level 1)
491 (re-search-forward "\\w+\\W*")))
492 (message (format "%d words in %s." wc
493 (if mark-active "region" "buffer")))))
496 *** Check for misplaced SCHEDULED and DEADLINE cookies
498 The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
499 below* the headline -- like this:
503 , SCHEDULED: <2012-04-09 lun.>
506 This is what =org-scheduled= and =org-deadline= (and other similar
507 commands) do. And the manual explicitely tell people to stick to this
508 format (see the section "8.3.1 Inserting deadlines or schedules").
510 If you think you might have subtrees with misplaced =SCHEDULED= and
511 =DEADLINE= cookies, this command lets you check the current buffer:
513 #+begin_src emacs-lisp
514 (defun org-check-misformatted-subtree ()
515 "Check misformatted entries in the current buffer."
520 (when (and (move-beginning-of-line 2)
521 (not (looking-at org-heading-regexp)))
522 (if (or (and (org-get-scheduled-time (point))
523 (not (looking-at (concat "^.*" org-scheduled-regexp))))
524 (and (org-get-deadline-time (point))
525 (not (looking-at (concat "^.*" org-deadline-regexp)))))
526 (when (y-or-n-p "Fix this subtree? ")
527 (message "Call the function again when you're done fixing this subtree.")
529 (message "All subtrees checked."))))))
533 *** Align all tables in a file
535 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
537 #+begin_src emacs-lisp
538 (defun my-align-all-tables ()
540 (org-table-map-tables 'org-table-align 'quietly))
544 #+index: Table!Calculation
546 :CUSTOM_ID: transpose-table
549 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
550 see.) There are also other solutions:
552 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
553 list, see [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00239.html][gnu]]
555 - with org-babel and R: provided by Dan Davison in the mailing list (old
556 =#+TBLR:= syntax), see [[http://thread.gmane.org/gmane.emacs.orgmode/10159/focus=10159][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2008-12/msg00454.html][gnu]]
558 - with field coordinates in formulas (=@#= and =$#=): see [[file:org-hacks.org::#field-coordinates-in-formulas-transpose-table][Worg]].
560 *** Manipulate hours/minutes/seconds in table formulas
561 #+index: Table!hours-minutes-seconds
562 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
563 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
564 "=d=" is any digit) as time values in Org-mode table formula. These
565 functions have now been wrapped up into a =with-time= macro which can
566 be used in table formula to translate table cell values to and from
567 numerical values for algebraic manipulation.
569 Here is the code implementing this macro.
570 #+begin_src emacs-lisp :results silent
571 (defun org-time-string-to-seconds (s)
572 "Convert a string HH:MM:SS to a number of seconds."
575 (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
576 (let ((hour (string-to-number (match-string 1 s)))
577 (min (string-to-number (match-string 2 s)))
578 (sec (string-to-number (match-string 3 s))))
579 (+ (* hour 3600) (* min 60) sec)))
581 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
582 (let ((min (string-to-number (match-string 1 s)))
583 (sec (string-to-number (match-string 2 s))))
585 ((stringp s) (string-to-number s))
588 (defun org-time-seconds-to-string (secs)
589 "Convert a number of seconds to a time string."
590 (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
591 ((>= secs 60) (format-seconds "%m:%.2s" secs))
592 (t (format-seconds "%s" secs))))
594 (defmacro with-time (time-output-p &rest exprs)
595 "Evaluate an org-table formula, converting all fields that look
596 like time data to integer seconds. If TIME-OUTPUT-P then return
597 the result as a time value."
599 (if time-output-p 'org-time-seconds-to-string 'identity)
607 (list 'with-time nil el)
608 (org-time-string-to-seconds el)))
613 Which allows the following forms of table manipulation such as adding
614 and subtracting time values.
615 : | Date | Start | Lunch | Back | End | Sum |
616 : |------------------+-------+-------+-------+-------+------|
617 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
618 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
620 and dividing time values by integers
621 : | time | miles | minutes/mile |
622 : |-------+-------+--------------|
623 : | 34:43 | 2.9 | 11:58 |
624 : | 32:15 | 2.77 | 11:38 |
625 : | 33:56 | 3.0 | 11:18 |
626 : | 52:22 | 4.62 | 11:20 |
627 : #+TBLFM: $3='(with-time t (/ $1 $2))
629 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
630 Elisp formulas) to compute time durations. For example:
632 : | Task 1 | Task 2 | Total |
633 : |--------+--------+---------|
634 : | 35:00 | 35:00 | 1:10:00 |
635 : #+TBLFM: @2$3=$1+$2;T
637 *** Dates computation
639 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of
640 dates stored in an org table.
642 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
646 | Start Date | End Date | Duration |
647 |------------+------------+----------|
648 | 2004.08.07 | 2005.07.08 | 335 |
649 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
651 See [[http://thread.gmane.org/gmane.emacs.orgmode/7741][this thread]] as well as [[http://article.gmane.org/gmane.emacs.orgmode/7753][this post]] (which is really a followup on the
652 above). The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
653 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
656 #+index: Table!Calculation
657 As with Times computation, the following code allows Computation with
658 Hex values in Org-mode tables using the =with-hex= macro.
660 Here is the code implementing this macro.
661 #+begin_src emacs-lisp
662 (defun org-hex-strip-lead (str)
663 (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
664 (substring str 2) str))
666 (defun org-hex-to-hex (int)
669 (defun org-hex-to-dec (str)
672 (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
676 (setf out (+ (* out 16)
677 (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
678 (coerce (match-string 1 str) 'list))
680 ((stringp str) (string-to-number str))
683 (defmacro with-hex (hex-output-p &rest exprs)
684 "Evaluate an org-table formula, converting all fields that look
685 like hexadecimal to decimal integers. If HEX-OUTPUT-P then
686 return the result as a hex value."
688 (if hex-output-p 'org-hex-to-hex 'identity)
695 (list 'with-hex nil el)
696 (org-hex-to-dec el)))
701 Which allows the following forms of table manipulation such as adding
702 and subtracting hex values.
703 | 0x10 | 0x0 | 0x10 | 16 |
704 | 0x20 | 0x1 | 0x21 | 33 |
705 | 0x30 | 0x2 | 0x32 | 50 |
706 | 0xf0 | 0xf | 0xff | 255 |
707 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
709 *** Field coordinates in formulas (=@#= and =$#=)
711 :CUSTOM_ID: field-coordinates-in-formulas
713 #+index: Table!Field Coordinates
716 Following are some use cases that can be implemented with the “field
717 coordinates in formulas” described in the corresponding chapter in the
718 [[http://orgmode.org/manual/References.html#References][Org manual]].
720 **** Copy a column from a remote table into a column
722 :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
725 current column =$3= = remote column =$2=:
726 : #+TBLFM: $3 = remote(FOO, @@#$2)
728 **** Copy a row from a remote table transposed into a column
730 :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
733 current column =$1= = transposed remote row =@1=:
734 : #+TBLFM: $1 = remote(FOO, @$#$@#)
738 :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
743 This is more like a demonstration of using “field coordinates in formulas”
744 and is bound to be slow for large tables. See the discussion in the mailing
746 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
747 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
748 For more efficient solutions see
749 [[file:org-hacks.org::#transpose-table][Worg]].
751 To transpose this 4x7 table
754 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
755 : |------+------+------+------+------+------+------|
756 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
757 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
758 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
760 start with a 7x4 table without any horizontal line (to have filled
761 also the column header) and yet empty:
771 Then add the =TBLFM= line below. After recalculation this will end up with
774 : | year | min | avg | max |
775 : | 2004 | 401 | 402 | 403 |
776 : | 2005 | 501 | 502 | 503 |
777 : | 2006 | 601 | 602 | 603 |
778 : | 2007 | 701 | 702 | 703 |
779 : | 2008 | 801 | 802 | 803 |
780 : | 2009 | 901 | 902 | 903 |
781 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
783 The formula simply exchanges row and column numbers by taking
784 - the absolute remote row number =@$#= from the current column number =$#=
785 - the absolute remote column number =$@#= from the current row number =@#=
787 Formulas to be taken over from the remote table will have to be transformed
790 **** Dynamic variation of ranges
794 In this example all columns next to =quote= are calculated from the column
795 =quote= and show the average change of the time series =quote[year]=
796 during the period of the preceding =1=, =2=, =3= or =4= years:
798 : | year | quote | 1 a | 2 a | 3 a | 4 a |
799 : |------+-------+-------+-------+-------+-------|
800 : | 2005 | 10 | | | | |
801 : | 2006 | 12 | 0.200 | | | |
802 : | 2007 | 14 | 0.167 | 0.183 | | |
803 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
804 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
805 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
807 The important part of the formula without the field blanking is:
809 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
811 which is the Emacs Calc implementation of the equation
813 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
815 where /i/ is the current time and /a/ is the length of the preceding period.
817 *** Change the column sequence in one row only
818 #+index: Table!Editing
820 :CUSTOM_ID: column-sequence-in-row
825 The functions below can be used to change the column sequence in one row
826 only, without affecting the other rows above and below like with M-<left> or
827 M-<right> (org-table-move-column). Please see the docstring of the functions
828 for more explanations. Below is one example per function, with this original
829 table as the starting point for each example:
831 : | e | 9 | 10 | 11 |
834 **** Move in row left
836 1) place point at "10" in original table
837 2) result of M-x my-org-table-move-column-in-row-left:
839 : | e | 10 | 9 | 11 |
842 **** Move in row right
844 1) place point at "9" in original table
845 2) result of M-x my-org-table-move-column-in-row-right:
847 : | e | 10 | 9 | 11 |
850 **** Rotate in row left
852 1) place point at "9" in original table
853 2) result of M-x my-org-table-rotate-column-in-row-left:
855 : | e | 10 | 11 | 9 |
858 **** Rotate in row right
860 1) place point at "9" in original table
861 2) result of M-x my-org-table-rotate-column-in-row-right:
863 : | e | 11 | 9 | 10 |
868 #+BEGIN_SRC emacs-lisp
869 (defun my-org-table-move-column-in-row-right ()
870 "Move column to the right, limited to the current row."
872 (my-org-table-move-column-in-row nil))
873 (defun my-org-table-move-column-in-row-left ()
874 "Move column to the left, limited to the current row."
876 (my-org-table-move-column-in-row 'left))
878 (defun my-org-table-move-column-in-row (&optional left)
879 "Move the current column to the right, limited to the current row.
880 With arg LEFT, move to the left. For repeated invocation the point follows
881 the value and changes to the target colum. Does not fix formulas."
882 ;; derived from `org-table-move-column'
884 (if (not (org-at-table-p))
885 (error "Not at a table"))
886 (org-table-find-dataline)
887 (org-table-check-inside-data-field)
888 (let* ((col (org-table-current-column))
889 (col1 (if left (1- col) col))
890 ;; Current cursor position
891 (colpos (if left (1- col) (1+ col))))
892 (if (and left (= col 1))
893 (error "Cannot move column further left"))
894 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
895 (error "Cannot move column further right"))
896 (org-table-goto-column col1 t)
897 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
898 (replace-match "|\\2|\\1|"))
899 (org-table-goto-column colpos)
902 (defun my-org-table-rotate-column-in-row-right ()
903 "Rotate column to the right, limited to the current row."
905 (my-org-table-rotate-column-in-row nil))
906 (defun my-org-table-rotate-column-in-row-left ()
907 "Rotate column to the left, limited to the current row."
909 (my-org-table-rotate-column-in-row 'left))
911 (defun my-org-table-rotate-column-in-row (&optional left)
912 "Rotate the current column to the right, limited to the current row.
913 With arg LEFT, rotate to the left. The boundaries of the rotation range are
914 the current and the most right column for both directions. For repeated
915 invocation the point stays on the current column. Does not fix formulas."
916 ;; derived from `org-table-move-column'
918 (if (not (org-at-table-p))
919 (error "Not at a table"))
920 (org-table-find-dataline)
921 (org-table-check-inside-data-field)
922 (let ((col (org-table-current-column)))
923 (org-table-goto-column col t)
924 (and (looking-at (if left
925 "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
926 "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
927 (replace-match "|\\2|\\1|"))
928 (org-table-goto-column col)
934 As hack I have this in an Org buffer to change temporarily to the desired
935 behavior with C-c C-c on one of the three snippets:
937 : #+begin_src emacs-lisp :results silent
938 : (org-defkey org-mode-map [(meta left)]
939 : 'my-org-table-move-column-in-row-left)
940 : (org-defkey org-mode-map [(meta right)]
941 : 'my-org-table-move-column-in-row-right)
942 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
943 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
947 : #+begin_src emacs-lisp :results silent
948 : (org-defkey org-mode-map [(meta left)]
949 : 'my-org-table-rotate-column-in-row-left)
950 : (org-defkey org-mode-map [(meta right)]
951 : 'my-org-table-rotate-column-in-row-right)
952 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
953 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
956 : - back to original:
957 : #+begin_src emacs-lisp :results silent
958 : (org-defkey org-mode-map [(meta left)] 'org-metaleft)
959 : (org-defkey org-mode-map [(meta right)] 'org-metaright)
960 : (org-defkey org-mode-map [(left)] 'backward-char)
961 : (org-defkey org-mode-map [(right)] 'forward-char)
964 **** reasons why this is not put into the Org core
966 I consider this as only a hack for several reasons:
967 - Generalization: The existing org-table-move-column function could be
968 enhanced with additional optional parameters to incorporate these
969 functionalities and could be used as the only function for better
970 maintainability. Now it's only a copy/paste hack of several similar
971 functions with simple modifications.
972 - Bindings: Should be convenient for repetition like M-<right>. What
973 should be bound where, what has to be left unbound?
974 - Does not fix formulas. Could be resolved for field formulas but
975 most probably not for column or range formulas and this can lead
976 to confusion. AFAIK all "official" table manipulations fix formulas.
977 - Completeness: Not all variations and combinations are covered yet
978 - left-right, up-down
979 - move, rotate with range to end, rotate with range to begin
980 - whole column/row, only in-row/in-column
982 ** Capture and Remember
983 *** Customize the size of the frame for remember
984 #+index: Remember!frame
985 #+index: Customization!remember
986 (Note: this hack is likely out of date due to the development of
990 On emacs-orgmode, Ryan C. Thompson suggested this:
993 I am using org-remember set to open a new frame when used,
994 and the default frame size is much too large. To fix this, I have
995 designed some advice and a custom variable to implement custom
996 parameters for the remember frame:
999 #+begin_src emacs-lisp
1000 (defcustom remember-frame-alist nil
1001 "Additional frame parameters for dedicated remember frame."
1005 (defadvice remember (around remember-frame-parameters activate)
1006 "Set some frame parameters for the remember frame."
1007 (let ((default-frame-alist (append remember-frame-alist
1008 default-frame-alist)))
1012 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1013 reasonable size for the frame.
1015 *** [[#heading-to-link][Turn a heading into an org link]]
1016 *** Quickaccess to the link part of hyperlinks
1017 #+index: Link!Referent
1018 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1019 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1020 which is indeed kind of cumbersome.
1022 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1024 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1025 #+begin_src emacs-lisp
1027 (lambda (&optional arg)
1030 (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1034 #+begin_src emacs-lisp
1035 (defun my-org-extract-link ()
1036 "Extract the link location at point and put it on the killring."
1038 (when (org-in-regexp org-bracket-link-regexp 1)
1039 (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1042 They put the link destination on the killring and can be easily bound to a key.
1044 ** Archiving Content in Org-Mode
1045 *** Preserve top level headings when archiving to a file
1046 #+index: Archiving!Preserve top level headings
1049 To preserve (somewhat) the integrity of your archive structure while
1050 archiving lower level items to a file, you can use the following
1053 #+begin_src emacs-lisp
1054 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1055 (let ((org-archive-location
1056 (if (save-excursion (org-back-to-heading)
1057 (> (org-outline-level) 1))
1058 (concat (car (split-string org-archive-location "::"))
1060 (car (org-get-outline-path)))
1061 org-archive-location)))
1065 Thus, if you have an outline structure such as...
1073 ...archiving "Subsubheading" to a new file will set the location in
1074 the new file to the top level heading:
1081 While this hack obviously destroys the outline hierarchy somewhat, it
1082 at least preserves the logic of level one groupings.
1084 A slightly more complex version of this hack will not only keep the
1085 archive organized by top-level headings, but will also preserve the
1086 tags found on those headings:
1088 #+begin_src emacs-lisp
1089 (defun my-org-inherited-no-file-tags ()
1090 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1091 (ltags (org-entry-get nil "TAGS")))
1094 (replace-regexp-in-string (concat tag ":") "" tags)))
1095 (append org-file-tags (when ltags (split-string ltags ":" t))))
1096 (if (string= ":" tags) nil tags)))
1098 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1099 (let ((tags (my-org-inherited-no-file-tags))
1100 (org-archive-location
1101 (if (save-excursion (org-back-to-heading)
1102 (> (org-outline-level) 1))
1103 (concat (car (split-string org-archive-location "::"))
1105 (car (org-get-outline-path)))
1106 org-archive-location)))
1108 (with-current-buffer (find-file-noselect (org-extract-archive-file))
1110 (while (org-up-heading-safe))
1111 (org-set-tags-to tags)))))
1114 *** Archive in a date tree
1115 #+index: Archiving!date tree
1116 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1118 (Make sure org-datetree.el is loaded for this to work.)
1120 #+begin_src emacs-lisp
1121 ;; (setq org-archive-location "%s_archive::date-tree")
1122 (defadvice org-archive-subtree
1123 (around org-archive-subtree-to-data-tree activate)
1124 "org-archive-subtree to date-tree"
1126 (string= "date-tree"
1127 (org-extract-archive-heading
1128 (org-get-local-archive-location)))
1129 (let* ((dct (decode-time (org-current-time)))
1133 (this-buffer (current-buffer))
1134 (location (org-get-local-archive-location))
1135 (afile (org-extract-archive-file location))
1136 (org-archive-location
1137 (format "%s::*** %04d-%02d-%02d %s" afile y m d
1138 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1139 (message "afile=%s" afile)
1141 (error "Invalid `org-archive-location'"))
1143 (switch-to-buffer (find-file-noselect afile))
1144 (org-datetree-find-year-create y)
1145 (org-datetree-find-month-create y m)
1146 (org-datetree-find-day-create y m d)
1148 (switch-to-buffer this-buffer))
1153 *** Add inherited tags to archived entries
1154 #+index: Archiving!Add inherited tags
1155 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1156 advise the function like this:
1159 (defadvice org-archive-subtree
1160 (before add-inherited-tags-before-org-archive-subtree activate)
1161 "add inherited tags before org-archive-subtree"
1162 (org-set-tags-to (org-get-tags-at)))
1165 ** Using and Managing Org-Metadata
1166 *** Remove redundant tags of headlines
1167 #+index: Tag!Remove redundant
1170 A small function that processes all headlines in current buffer and
1171 removes tags that are local to a headline and inherited by a parent
1172 headline or the #+FILETAGS: statement.
1174 #+BEGIN_SRC emacs-lisp
1175 (defun dmj/org-remove-redundant-tags ()
1176 "Remove redundant tags of headlines in current buffer.
1178 A tag is considered redundant if it is local to a headline and
1179 inherited by a parent headline."
1181 (when (eq major-mode 'org-mode)
1185 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1186 local inherited tag)
1187 (dolist (tag alltags)
1188 (if (get-text-property 0 'inherited tag)
1189 (push tag inherited) (push tag local)))
1191 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1195 *** Remove empty property drawers
1196 #+index: Drawer!Empty
1197 David Maus proposed this:
1199 #+begin_src emacs-lisp
1200 (defun dmj:org:remove-empty-propert-drawers ()
1201 "*Remove all empty property drawers in current file."
1203 (unless (eq major-mode 'org-mode)
1204 (error "You need to turn on Org mode for this function."))
1206 (goto-char (point-min))
1207 (while (re-search-forward ":PROPERTIES:" nil t)
1209 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1212 *** Group task list by a property
1213 #+index: Agenda!Group task list
1214 This advice allows you to group a task list in Org-Mode. To use it,
1215 set the variable =org-agenda-group-by-property= to the name of a
1216 property in the option list for a TODO or TAGS search. The resulting
1217 agenda view will group tasks by that property prior to searching.
1219 #+begin_src emacs-lisp
1220 (defvar org-agenda-group-by-property nil
1221 "Set this in org-mode agenda views to group tasks by property")
1223 (defun org-group-bucket-items (prop items)
1225 (dolist (item items)
1226 (let* ((marker (get-text-property 0 'org-marker item))
1227 (pvalue (org-entry-get marker prop t))
1228 (cell (assoc pvalue buckets)))
1230 (setcdr cell (cons item (cdr cell)))
1231 (setq buckets (cons (cons pvalue (list item))
1233 (setq buckets (mapcar (lambda (bucket)
1235 (reverse (cdr bucket))))
1237 (sort buckets (lambda (i1 i2)
1238 (string< (car i1) (car i2))))))
1240 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1241 (list &optional nosort))
1242 "Prepare bucketed agenda entry lists"
1243 (if org-agenda-group-by-property
1244 ;; bucketed, handle appropriately
1246 (dolist (bucket (org-group-bucket-items
1247 org-agenda-group-by-property
1249 (let ((header (concat "Property "
1250 org-agenda-group-by-property
1252 (or (car bucket) "<nil>") ":\n")))
1253 (add-text-properties 0 (1- (length header))
1254 (list 'face 'org-agenda-structure)
1258 ;; recursively process
1259 (let ((org-agenda-group-by-property nil))
1260 (org-finalize-agenda-entries
1261 (cdr bucket) nosort))
1263 (setq ad-return-value text))
1265 (ad-activate 'org-finalize-agenda-entries)
1267 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1270 Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1272 A small hook run when clocking out of a task that prompts for a note
1273 when the tag "=clockout_note=" is found in a headline. It uses the tag
1274 ("=clockout_note=") so inheritance can also be used...
1276 #+begin_src emacs-lisp
1277 (defun rgr/check-for-clock-out-note()
1280 (org-back-to-heading)
1281 (let ((tags (org-get-tags)))
1282 (and tags (message "tags: %s " tags)
1283 (when (member "clocknote" tags)
1286 (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1288 *** Dynamically adjust tag position
1289 #+index: Tag!position
1290 Here is a bit of code that allows you to have the tags always
1291 right-adjusted in the buffer.
1293 This is useful when you have bigger window than default window-size
1294 and you dislike the aesthetics of having the tag in the middle of the
1297 This hack solves the problem of adjusting it whenever you change the
1299 Before saving it will revert the file to having the tag position be
1300 left-adjusted so that if you track your files with version control,
1301 you won't run into artificial diffs just because the window-size
1304 *IMPORTANT*: This is probably slow on very big files.
1306 #+begin_src emacs-lisp
1307 (setq ba/org-adjust-tags-column t)
1309 (defun ba/org-adjust-tags-column-reset-tags ()
1310 "In org-mode buffers it will reset tag position according to
1313 (not (string= (buffer-name) "*Remember*"))
1314 (eql major-mode 'org-mode))
1315 (let ((b-m-p (buffer-modified-p)))
1318 (goto-char (point-min))
1319 (command-execute 'outline-next-visible-heading)
1320 ;; disable (message) that org-set-tags generates
1321 (flet ((message (&rest ignored) nil))
1323 (set-buffer-modified-p b-m-p))
1326 (defun ba/org-adjust-tags-column-now ()
1327 "Right-adjust `org-tags-column' value, then reset tag position."
1328 (set (make-local-variable 'org-tags-column)
1329 (- (- (window-width) (length org-ellipsis))))
1330 (ba/org-adjust-tags-column-reset-tags))
1332 (defun ba/org-adjust-tags-column-maybe ()
1333 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1334 (when ba/org-adjust-tags-column
1335 (ba/org-adjust-tags-column-now)))
1337 (defun ba/org-adjust-tags-column-before-save ()
1338 "Tags need to be left-adjusted when saving."
1339 (when ba/org-adjust-tags-column
1340 (setq org-tags-column 1)
1341 (ba/org-adjust-tags-column-reset-tags)))
1343 (defun ba/org-adjust-tags-column-after-save ()
1344 "Revert left-adjusted tag position done by before-save hook."
1345 (ba/org-adjust-tags-column-maybe)
1346 (set-buffer-modified-p nil))
1348 ; automatically align tags on right-hand side
1349 (add-hook 'window-configuration-change-hook
1350 'ba/org-adjust-tags-column-maybe)
1351 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1352 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1353 (add-hook 'org-agenda-mode-hook '(lambda ()
1354 (setq org-agenda-tags-column (- (window-width)))))
1356 ; between invoking org-refile and displaying the prompt (which
1357 ; triggers window-configuration-change-hook) tags might adjust,
1358 ; which invalidates the org-refile cache
1359 (defadvice org-refile (around org-refile-disable-adjust-tags)
1360 "Disable dynamically adjusting tags"
1361 (let ((ba/org-adjust-tags-column nil))
1363 (ad-activate 'org-refile)
1365 *** Use an "attach" link type to open files without worrying about their location
1366 #+index: Link!Attach
1367 -- Darlan Cavalcante Moreira
1369 In the setup part in my org-files I put:
1372 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1375 Now I can use the "attach" link type, but org will ask me if I want to
1376 allow executing the elisp code. To avoid this you can even set
1377 org-confirm-elisp-link-function to nil (I don't like this because it allows
1378 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1383 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1385 This works very well.
1387 ** Org Agenda and Task Management
1388 *** Make it easier to set org-agenda-files from multiple directories
1389 #+index: Agenda!Files
1392 #+begin_src emacs-lisp
1393 (defun my-org-list-files (dirs ext)
1394 "Function to create list of org files in multiple subdirectories.
1395 This can be called to generate a list of files for
1396 org-agenda-files or org-refile-targets.
1398 DIRS is a list of directories.
1400 EXT is a list of the extensions of files to be included."
1401 (let ((dirs (if (listp dirs)
1404 (ext (if (listp ext)
1414 (file-expand-wildcards
1415 (concat (file-name-as-directory x) "*" y)))))
1420 (when (or (string-match "/.#" x)
1421 (string-match "#$" x))
1422 (setq files (delete x files))))
1426 (defvar my-org-agenda-directories '("~/org/")
1427 "List of directories containing org files.")
1428 (defvar my-org-agenda-extensions '(".org")
1429 "List of extensions of agenda files")
1431 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1432 (setq my-org-agenda-extensions '(".org" ".ref"))
1434 (defun my-org-set-agenda-files ()
1436 (setq org-agenda-files (my-org-list-files
1437 my-org-agenda-directories
1438 my-org-agenda-extensions)))
1440 (my-org-set-agenda-files)
1443 The code above will set your "default" agenda files to all files
1444 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1445 You can change these values by setting the variables
1446 my-org-agenda-extensions and my-org-agenda-directories. The function
1447 my-org-agenda-files-by-filetag uses these two variables to determine
1448 which files to search for filetags (i.e., the larger set from which
1449 the subset will be drawn).
1451 You can also easily use my-org-list-files to "mix and match"
1452 directories and extensions to generate different lists of agenda
1455 *** Restrict org-agenda-files by filetag
1456 #+index: Agenda!Files
1458 :CUSTOM_ID: set-agenda-files-by-filetag
1462 It is often helpful to limit yourself to a subset of your agenda
1463 files. For instance, at work, you might want to see only files related
1464 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1465 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
1466 commands]]. These solutions, however, require reapplying a filter each
1467 time you call the agenda or writing several new custom agenda commands
1468 for each context. Another solution is to use directories for different
1469 types of tasks and to change your agenda files with a function that
1470 sets org-agenda-files to the appropriate directory. But this relies on
1471 hard and static boundaries between files.
1473 The following functions allow for a more dynamic approach to selecting
1474 a subset of files based on filetags:
1476 #+begin_src emacs-lisp
1477 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1478 "Restrict org agenda files only to those containing filetag."
1480 (let* ((tagslist (my-org-get-all-filetags))
1482 (completing-read "Tag: "
1483 (mapcar 'car tagslist)))))
1484 (org-agenda-remove-restriction-lock 'noupdate)
1485 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1486 (setq org-agenda-overriding-restriction 'files)))
1488 (defun my-org-get-all-filetags ()
1489 "Get list of filetags from all default org-files."
1490 (let ((files org-agenda-files)
1492 (save-window-excursion
1493 (while (setq x (pop files))
1494 (set-buffer (find-file-noselect x))
1497 (let ((tagfiles (assoc y tagslist)))
1499 (setcdr tagfiles (cons x (cdr tagfiles)))
1500 (add-to-list 'tagslist (list y x)))))
1501 (my-org-get-filetags)))
1504 (defun my-org-get-filetags ()
1505 "Get list of filetags for current buffer"
1506 (let ((ftags org-file-tags)
1510 (org-substring-no-properties x))
1514 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1515 with all filetags in your "normal" agenda files. When you select a
1516 tag, org-agenda-files will be restricted to only those files
1517 containing the filetag. To release the restriction, type C-c C-x >
1518 (org-agenda-remove-restriction-lock).
1520 *** Highlight the agenda line under cursor
1521 #+index: Agenda!Highlight
1522 This is useful to make sure what task you are operating on.
1524 #+BEGIN_SRC emacs-lisp
1525 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1530 #+BEGIN_SRC emacs-lisp
1531 ;; hl-line seems to be only for emacs
1533 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1535 ;; highline-mode does not work straightaway in tty mode.
1536 ;; I use a black background
1538 '(highline-face ((((type tty) (class color))
1539 (:background "white" :foreground "black")))))
1542 *** Split frame horizontally for agenda
1543 #+index: Agenda!frame
1544 If you would like to split the frame into two side-by-side windows when
1545 displaying the agenda, try this hack from Jan Rehders, which uses the
1546 `toggle-window-split' from
1548 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1550 #+BEGIN_SRC emacs-lisp
1551 ;; Patch org-mode to use vertical splitting
1552 (defadvice org-prepare-agenda (after org-fix-split)
1553 (toggle-window-split))
1554 (ad-activate 'org-prepare-agenda)
1557 *** Automatically add an appointment when clocking in a task
1558 #+index: Clock!Automatically add an appointment when clocking in a task
1559 #+index: Appointment!Automatically add an appointment when clocking in a task
1560 #+BEGIN_SRC emacs-lisp
1561 ;; Make sure you have a sensible value for `appt-message-warning-time'
1562 (defvar bzg-org-clock-in-appt-delay 100
1563 "Number of minutes for setting an appointment by clocking-in")
1566 This function let's you add an appointment for the current entry.
1567 This can be useful when you need a reminder.
1569 #+BEGIN_SRC emacs-lisp
1570 (defun bzg-org-clock-in-add-appt (&optional n)
1571 "Add an appointment for the Org entry at point in N minutes."
1574 (org-back-to-heading t)
1575 (looking-at org-complex-heading-regexp)
1576 (let* ((msg (match-string-no-properties 4))
1577 (ct-time (decode-time))
1578 (appt-min (+ (cadr ct-time)
1579 (or n bzg-org-clock-in-appt-delay)))
1580 (appt-time ; define the time for the appointment
1581 (progn (setf (cadr ct-time) appt-min) ct-time)))
1582 (appt-add (format-time-string
1583 "%H:%M" (apply 'encode-time appt-time)) msg)
1584 (if (interactive-p) (message "New appointment for %s" msg)))))
1587 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1590 #+BEGIN_SRC emacs-lisp
1591 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1592 "Add an appointment when clocking a task in."
1593 (bzg-org-clock-in-add-appt))
1596 You may also want to delete the associated appointment when clocking
1597 out. This function does this:
1599 #+BEGIN_SRC emacs-lisp
1600 (defun bzg-org-clock-out-delete-appt nil
1601 "When clocking out, delete any associated appointment."
1604 (org-back-to-heading t)
1605 (looking-at org-complex-heading-regexp)
1606 (let* ((msg (match-string-no-properties 4)))
1607 (setq appt-time-msg-list
1611 (if (not (string-match (regexp-quote msg)
1612 (cadr appt))) appt))
1613 appt-time-msg-list)))
1617 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1619 #+BEGIN_SRC emacs-lisp
1620 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1621 "Delete an appointment when clocking a task out."
1622 (bzg-org-clock-out-delete-appt))
1625 *IMPORTANT*: You can add appointment by clocking in in both an
1626 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1627 agenda buffer with the advice above will bring an error.
1629 *** Using external programs for appointments reminders
1630 #+index: Appointment!reminders
1631 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1633 *** Remove from agenda time grid lines that are in an appointment
1634 #+index: Agenda!time grid
1635 #+index: Appointment!Remove from agenda time grid lines
1636 The agenda shows lines for the time grid. Some people think that
1637 these lines are a distraction when there are appointments at those
1638 times. You can get rid of the lines which coincide exactly with the
1639 beginning of an appointment. Michael Ekstrand has written a piece of
1640 advice that also removes lines that are somewhere inside an
1643 #+begin_src emacs-lisp
1644 (defun org-time-to-minutes (time)
1645 "Convert an HHMM time to minutes"
1646 (+ (* (/ time 100) 60) (% time 100)))
1648 (defun org-time-from-minutes (minutes)
1649 "Convert a number of minutes to an HHMM time"
1650 (+ (* (/ minutes 60) 100) (% minutes 60)))
1652 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1653 (list ndays todayp))
1654 (if (member 'remove-match (car org-agenda-time-grid))
1655 (flet ((extract-window
1657 (let ((start (get-text-property 1 'time-of-day line))
1658 (dur (get-text-property 1 'duration line)))
1662 (org-time-from-minutes
1663 (+ dur (org-time-to-minutes start)))))
1666 (let* ((windows (delq nil (mapcar 'extract-window list)))
1667 (org-agenda-time-grid
1668 (list (car org-agenda-time-grid)
1669 (cadr org-agenda-time-grid)
1672 (find-if (lambda (w)
1675 (and (>= time (car w))
1678 (caddr org-agenda-time-grid)))))
1681 (ad-activate 'org-agenda-add-time-grid-maybe)
1683 *** Disable version control for Org mode agenda files
1684 #+index: Agenda!Files
1687 Even if you use Git to track your agenda files you might not need
1688 vc-mode to be enabled for these files.
1690 #+begin_src emacs-lisp
1691 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1692 (defun dmj/disable-vc-for-agenda-files-hook ()
1693 "Disable vc-mode for Org agenda files."
1694 (if (and (fboundp 'org-agenda-file-p)
1695 (org-agenda-file-p (buffer-file-name)))
1696 (remove-hook 'find-file-hook 'vc-find-file-hook)
1697 (add-hook 'find-file-hook 'vc-find-file-hook)))
1700 *** Easy customization of TODO colors
1701 #+index: Customization!Todo keywords
1702 #+index: Todo keywords!Customization
1706 Here is some code I came up with some code to make it easier to
1707 customize the colors of various TODO keywords. As long as you just
1708 want a different color and nothing else, you can customize the
1709 variable org-todo-keyword-faces and use just a string color (i.e. a
1710 string of the color name) as the face, and then org-get-todo-face
1711 will convert the color to a face, inheriting everything else from
1712 the standard org-todo face.
1714 To demonstrate, I currently have org-todo-keyword-faces set to
1716 #+BEGIN_SRC emacs-lisp
1717 (("IN PROGRESS" . "dark orange")
1718 ("WAITING" . "red4")
1719 ("CANCELED" . "saddle brown"))
1722 Here's the code, in a form you can put in your =.emacs=
1724 #+BEGIN_SRC emacs-lisp
1725 (eval-after-load 'org-faces
1727 (defcustom org-todo-keyword-faces nil
1728 "Faces for specific TODO keywords.
1729 This is a list of cons cells, with TODO keywords in the car and
1730 faces in the cdr. The face can be a symbol, a color, or a
1731 property list of attributes, like (:foreground \"blue\" :weight
1732 bold :underline t)."
1737 (string :tag "Keyword")
1738 (choice color (sexp :tag "Face")))))))
1740 (eval-after-load 'org
1742 (defun org-get-todo-face-from-color (color)
1743 "Returns a specification for a face that inherits from org-todo
1744 face and has the given color as foreground. Returns nil if
1747 `(:inherit org-warning :foreground ,color)))
1749 (defun org-get-todo-face (kwd)
1750 "Get the right face for a TODO keyword KWD.
1751 If KWD is a number, get the corresponding match group."
1752 (if (numberp kwd) (setq kwd (match-string kwd)))
1753 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1755 (org-get-todo-face-from-color face)
1757 (and (member kwd org-done-keywords) 'org-done)
1761 *** Add an effort estimate on the fly when clocking in
1762 #+index: Effort estimate!Add when clocking in
1763 #+index: Clock!Effort estimate
1764 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1765 This way you can easily have a "tea-timer" for your tasks when they
1766 don't already have an effort estimate.
1768 #+begin_src emacs-lisp
1769 (add-hook 'org-clock-in-prepare-hook
1770 'my-org-mode-ask-effort)
1772 (defun my-org-mode-ask-effort ()
1773 "Ask for an effort estimate when clocking in."
1774 (unless (org-entry-get (point) "Effort")
1778 (org-entry-get-multivalued-property (point) "Effort"))))
1779 (unless (equal effort "")
1780 (org-set-property "Effort" effort)))))
1783 Or you can use a default effort for such a timer:
1785 #+begin_src emacs-lisp
1786 (add-hook 'org-clock-in-prepare-hook
1787 'my-org-mode-add-default-effort)
1789 (defvar org-clock-default-effort "1:00")
1791 (defun my-org-mode-add-default-effort ()
1792 "Add a default effort estimation."
1793 (unless (org-entry-get (point) "Effort")
1794 (org-set-property "Effort" org-clock-default-effort)))
1797 *** Use idle timer for automatic agenda views
1798 #+index: Agenda view!Refresh
1799 From John Wiegley's mailing list post (March 18, 2010):
1802 I have the following snippet in my .emacs file, which I find very
1803 useful. Basically what it does is that if I don't touch my Emacs for 5
1804 minutes, it displays the current agenda. This keeps my tasks "always
1805 in mind" whenever I come back to Emacs after doing something else,
1806 whereas before I had a tendency to forget that it was there.
1809 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1811 #+begin_src emacs-lisp
1812 (defun jump-to-org-agenda ()
1814 (let ((buf (get-buffer "*Org Agenda*"))
1817 (if (setq wind (get-buffer-window buf))
1818 (select-window wind)
1819 (if (called-interactively-p)
1821 (select-window (display-buffer buf t t))
1822 (org-fit-window-to-buffer)
1823 ;; (org-agenda-redo)
1825 (with-selected-window (display-buffer buf)
1826 (org-fit-window-to-buffer)
1827 ;; (org-agenda-redo)
1829 (call-interactively 'org-agenda-list)))
1830 ;;(let ((buf (get-buffer "*Calendar*")))
1831 ;; (unless (get-buffer-window buf)
1832 ;; (org-agenda-goto-calendar)))
1835 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1839 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1841 *** Refresh the agenda view regularly
1842 #+index: Agenda view!Refresh
1843 Hack sent by Kiwon Um:
1845 #+begin_src emacs-lisp
1846 (defun kiwon/org-agenda-redo-in-other-window ()
1847 "Call org-agenda-redo function even in the non-agenda buffer."
1849 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1851 (with-selected-window agenda-window (org-agenda-redo)))))
1852 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1855 *** Reschedule agenda items to today with a single command
1856 #+index: Agenda!Reschedule
1857 This was suggested by Carsten in reply to David Abrahams:
1859 #+begin_example emacs-lisp
1860 (defun org-agenda-reschedule-to-today ()
1862 (flet ((org-read-date (&rest rest) (current-time)))
1863 (call-interactively 'org-agenda-schedule)))
1866 *** Mark subtree DONE along with all subheadings
1867 #+index: Subtree!subheadings
1868 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
1870 #+begin_src emacs-lisp
1871 (defun bh/mark-subtree-done ()
1874 (let ((limit (point)))
1876 (exchange-point-and-mark)
1877 (while (> (point) limit)
1879 (outline-previous-visible-heading 1))
1880 (org-todo "DONE"))))
1883 Then M-x bh/mark-subtree-done.
1885 *** Mark heading done when all checkboxes are checked.
1887 :CUSTOM_ID: mark-done-when-all-checkboxes-checked
1892 An item consists of a list with checkboxes. When all of the
1893 checkboxes are checked, the item should be considered complete and its
1894 TODO state should be automatically changed to DONE. The code below
1895 does that. This version is slightly enhanced over the one in the
1897 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
1898 reset the state back to TODO if a checkbox is unchecked.
1900 Note that the code requires that a checkbox statistics cookie (the [/]
1901 or [%] thingie in the headline - see the [[http://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
1902 manual) be present in order for it to work. Note also that it is too
1903 dumb to figure out whether the item has a TODO state in the first
1904 place: if there is a statistics cookie, a TODO/DONE state will be
1905 added willy-nilly any time that the statistics cookie is changed.
1907 #+begin_src emacs-lisp
1908 ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
1909 (eval-after-load 'org-list
1910 '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
1912 (defun ndk/checkbox-list-complete ()
1914 (org-back-to-heading t)
1915 (let ((beg (point)) end)
1919 (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
1921 (if (equal (match-string 1) "100%")
1922 ;; all done - do the state change
1925 (if (and (> (match-end 2) (match-beginning 2))
1926 (equal (match-string 2) (match-string 3)))
1928 (org-todo 'todo)))))))
1931 *** Links to custom agenda views
1933 :CUSTOM_ID: links-to-agenda-views
1935 #+index: Agenda view!Links to
1936 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
1938 If you have custom agenda commands defined to some key, say w, then
1939 the following will serve as a link to the custom agenda buffer.
1940 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
1942 Clicking on it will prompt if you want to execute the elisp code. If
1943 you would rather not have the prompt or would want to respond with a
1944 single letter, ~y~ or ~n~, take a look at the docstrings of the
1945 variables =org-confirm-elisp-link-function= and
1946 =org-confirm-elisp-link-not-regexp=. Please take special note of the
1947 security risk associated with completely disabling the prompting
1950 ** Exporting org files
1951 *** Export Org to Org and handle includes.
1952 #+index: Export!handle includes
1953 Nick Dokos came up with this useful function:
1955 #+begin_src emacs-lisp
1956 (defun org-to-org-handle-includes ()
1957 "Copy the contents of the current buffer to OUTFILE,
1958 recursively processing #+INCLUDEs."
1959 (let* ((s (buffer-string))
1960 (fname (buffer-file-name))
1961 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
1965 (org-export-handle-include-files-recurse)
1968 (delete-region (point-min) (point-max))
1973 *** Specifying LaTeX commands to floating environments
1975 :CUSTOM_ID: latex-command-for-floats
1978 #+index: Export!LaTeX
1979 The keyword ~placement~ can be used to specify placement options to
1980 floating environments (like =\begin{figure}= and =\begin{table}=}) in
1981 LaTeX export. Org passes along everything passed in options as long as
1982 there are no spaces. One can take advantage of this to pass other
1983 LaTeX commands and have their scope limited to the floating
1986 For example one can set the fontsize of a table different from the
1987 default normal size by putting something like =\footnotesize= right
1988 after the placement options. During LaTeX export using the
1989 ~#+ATTR_LaTeX:~ line below:
1992 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
1995 exports the associated floating environment as shown in the following
1999 \begin{table}[<options>]\footnotesize
2004 It should be noted that this hack does not work for beamer export of
2005 tables since the =table= environment is not used. As an ugly
2006 workaround, one can use the following:
2009 ,#+LATEX: {\footnotesize
2010 ,#+ATTR_LaTeX: align=rr
2017 *** Styling code sections with CSS
2019 #+index: HTML!Styling code sections with CSS
2021 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2022 to HTML using =<pre>= tags, and assigned CSS classes by their content
2023 type. For example, Perl content will have an opening tag like
2024 =<pre class="src src-perl">=. You can use those classes to add styling
2025 to the output, such as here where a small language tag is added at the
2026 top of each kind of code box:
2029 (setq org-export-html-style
2030 "<style type=\"text/css\">
2031 <!--/*--><![CDATA[/*><!--*/
2032 .src { background-color: #F5FFF5; position: relative; overflow: visible; }
2033 .src:before { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2034 .src-sh:before { content: 'sh'; }
2035 .src-bash:before { content: 'sh'; }
2036 .src-R:before { content: 'R'; }
2037 .src-perl:before { content: 'Perl'; }
2038 .src-sql:before { content: 'SQL'; }
2039 .example { background-color: #FFF5F5; }
2044 Additionally, we use color to distinguish code output (the =.example=
2045 class) from input (all the =.src-*= classes).
2047 * Hacking Org: Working with Org-mode and other Emacs Packages.
2048 ** org-remember-anything
2050 #+index: Remember!Anything
2052 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2054 #+BEGIN_SRC emacs-lisp
2055 (defvar org-remember-anything
2056 '((name . "Org Remember")
2057 (candidates . (lambda () (mapcar 'car org-remember-templates)))
2058 (action . (lambda (name)
2059 (let* ((orig-template org-remember-templates)
2060 (org-remember-templates
2061 (list (assoc name orig-template))))
2062 (call-interactively 'org-remember))))))
2065 You can add it to your 'anything-sources' variable and open remember directly
2066 from anything. I imagine this would be more interesting for people with many
2067 remember templates, so that you are out of keys to assign those to.
2069 ** Org-mode and saveplace.el
2071 Fix a problem with =saveplace.el= putting you back in a folded position:
2073 #+begin_src emacs-lisp
2074 (add-hook 'org-mode-hook
2076 (when (outline-invisible-p)
2078 (outline-previous-visible-heading 1)
2079 (org-show-subtree)))))
2082 ** Using ido-completing-read to find attachments
2084 #+index: Attachment!ido completion
2088 Org-attach is great for quickly linking files to a project. But if you
2089 use org-attach extensively you might find yourself wanting to browse
2090 all the files you've attached to org headlines. This is not easy to do
2091 manually, since the directories containing the files are not human
2092 readable (i.e., they are based on automatically generated ids). Here's
2093 some code to browse those files using ido (obviously, you need to be
2096 #+begin_src emacs-lisp
2097 (load-library "find-lisp")
2099 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2101 (defun my-ido-find-org-attach ()
2102 "Find files in org-attachment directory"
2104 (let* ((enable-recursive-minibuffers t)
2105 (files (find-lisp-find-files org-attach-directory "."))
2108 (cons (file-name-nondirectory x)
2112 (remove-duplicates (mapcar #'car file-assoc-list)
2114 (filename (ido-completing-read "Org attachments: " filename-list nil t))
2115 (longname (cdr (assoc filename file-assoc-list))))
2116 (ido-set-current-directory
2117 (if (file-directory-p longname)
2119 (file-name-directory longname)))
2120 (setq ido-exit 'refresh
2121 ido-text-init ido-text
2125 (add-hook 'ido-setup-hook 'ido-my-keys)
2127 (defun ido-my-keys ()
2128 "Add my keybindings for ido."
2129 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2132 To browse your org attachments using ido fuzzy matching and/or the
2133 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2136 ** Link to Gnus messages by Message-Id
2137 #+index: Link!Gnus message by Message-Id
2138 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2139 discussion about linking to Gnus messages without encoding the folder
2140 name in the link. The following code hooks in to the store-link
2141 function in Gnus to capture links by Message-Id when in nnml folders,
2142 and then provides a link type "mid" which can open this link. The
2143 =mde-org-gnus-open-message-link= function uses the
2144 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2145 scan. It will go through them, in order, asking each to locate the
2146 message and opening it from the first one that reports success.
2148 It has only been tested with a single nnml backend, so there may be
2149 bugs lurking here and there.
2151 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2154 #+begin_src emacs-lisp
2155 ;; Support for saving Gnus messages by Message-ID
2156 (defun mde-org-gnus-save-by-mid ()
2157 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2158 (when (eq major-mode 'gnus-article-mode)
2159 (gnus-article-show-summary))
2160 (let* ((group gnus-newsgroup-name)
2161 (method (gnus-find-method-for-group group)))
2162 (when (eq 'nnml (car method))
2163 (let* ((article (gnus-summary-article-number))
2164 (header (gnus-summary-article-header article))
2165 (from (mail-header-from header))
2168 (let ((mid (mail-header-id header)))
2169 (if (string-match "<\\(.*\\)>" mid)
2170 (match-string 1 mid)
2171 (error "Malformed message ID header %s" mid)))))
2172 (date (mail-header-date header))
2173 (subject (gnus-summary-subject-string)))
2174 (org-store-link-props :type "mid" :from from :subject subject
2175 :message-id message-id :group group
2176 :link (org-make-link "mid:" message-id))
2177 (apply 'org-store-link-props
2178 :description (org-email-link-description)
2179 org-store-link-plist)
2182 (defvar mde-mid-resolve-methods '()
2183 "List of methods to try when resolving message ID's. For Gnus,
2184 it is a cons of 'gnus and the select (type and name).")
2185 (setq mde-mid-resolve-methods
2188 (defvar mde-org-gnus-open-level 1
2189 "Level at which Gnus is started when opening a link")
2190 (defun mde-org-gnus-open-message-link (msgid)
2191 "Open a message link with Gnus"
2193 (require 'org-table)
2194 (catch 'method-found
2195 (message "[MID linker] Resolving %s" msgid)
2196 (dolist (method mde-mid-resolve-methods)
2198 ((and (eq (car method) 'gnus)
2199 (eq (cadr method) 'nnml))
2200 (funcall (cdr (assq 'gnus org-link-frame-setup))
2201 mde-org-gnus-open-level)
2202 (when gnus-other-frame-object
2203 (select-frame gnus-other-frame-object))
2204 (let* ((msg-info (nnml-find-group-number
2205 (concat "<" msgid ">")
2207 (group (and msg-info (car msg-info)))
2208 (message (and msg-info (cdr msg-info)))
2210 (if (gnus-methods-equal-p
2214 (gnus-group-full-name group (cdr method))))))
2216 (gnus-summary-read-group qname nil t)
2217 (gnus-summary-goto-article message nil t))
2218 (throw 'method-found t)))
2219 (t (error "Unknown link type"))))))
2221 (eval-after-load 'org-gnus
2223 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2224 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2227 ** Store link to a message when sending in Gnus
2228 #+index: Link!Store link to a message when sending in Gnus
2229 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2231 #+begin_src emacs-lisp
2232 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2233 "Send message with `message-send-and-exit' and store org link to message copy.
2234 If multiple groups appear in the Gcc header, the link refers to
2235 the copy in the last group."
2239 (message-narrow-to-headers)
2240 (let ((gcc (car (last
2241 (message-unquote-tokens
2242 (message-tokenize-header
2243 (mail-fetch-field "gcc" nil t) " ,")))))
2244 (buf (current-buffer))
2245 (message-kill-buffer-on-exit nil)
2246 id to from subject desc link newsgroup xarchive)
2247 (message-send-and-exit arg)
2249 ;; gcc group found ...
2251 (save-current-buffer
2252 (progn (set-buffer buf)
2253 (setq id (org-remove-angle-brackets
2254 (mail-fetch-field "Message-ID")))
2255 (setq to (mail-fetch-field "To"))
2256 (setq from (mail-fetch-field "From"))
2257 (setq subject (mail-fetch-field "Subject"))))
2258 (org-store-link-props :type "gnus" :from from :subject subject
2259 :message-id id :group gcc :to to)
2260 (setq desc (org-email-link-description))
2261 (setq link (org-gnus-article-link
2262 gcc newsgroup id xarchive))
2263 (setq org-stored-links
2264 (cons (list link desc) org-stored-links)))
2265 ;; no gcc group found ...
2266 (message "Can not create Org link: No Gcc header found."))))))
2268 (define-key message-mode-map [(control c) (control meta c)]
2269 'ulf-message-send-and-org-gnus-store-link)
2272 ** Send html messages and attachments with Wanderlust
2275 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2276 similar functionality for both Wanderlust and Gnus. The hack below is
2277 still somewhat different: It allows you to toggle sending of html
2278 messages within Wanderlust transparently. I.e. html markup of the
2279 message body is created right before sending starts.
2281 *** Send HTML message
2283 Putting the code below in your .emacs adds following four functions:
2285 - dmj/wl-send-html-message
2287 Function that does the job: Convert everything between "--text
2288 follows this line--" and first mime entity (read: attachment) or
2289 end of buffer into html markup using `org-export-region-as-html'
2290 and replaces original body with a multipart MIME entity with the
2291 plain text version of body and the html markup version. Thus a
2292 recipient that prefers html messages can see the html markup,
2293 recipients that prefer or depend on plain text can see the plain
2296 Cannot be called interactively: It is hooked into SEMI's
2297 `mime-edit-translate-hook' if message should be HTML message.
2299 - dmj/wl-send-html-message-draft-init
2301 Cannot be called interactively: It is hooked into WL's
2302 `wl-mail-setup-hook' and provides a buffer local variable to
2305 - dmj/wl-send-html-message-draft-maybe
2307 Cannot be called interactively: It is hooked into WL's
2308 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2309 `mime-edit-translate-hook' depending on whether HTML message is
2312 - dmj/wl-send-html-message-toggle
2314 Toggles sending of HTML message. If toggled on, the letters
2315 "HTML" appear in the mode line.
2317 Call it interactively! Or bind it to a key in `wl-draft-mode'.
2319 If you have to send HTML messages regularly you can set a global
2320 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2321 toggle on sending HTML message by default.
2323 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2324 Google's web front end. As you can see you have the whole markup of
2325 Org at your service: *bold*, /italics/, tables, lists...
2327 So even if you feel uncomfortable with sending HTML messages at least
2328 you send HTML that looks quite good.
2330 #+begin_src emacs-lisp
2331 (defun dmj/wl-send-html-message ()
2332 "Send message as html message.
2333 Convert body of message to html using
2334 `org-export-region-as-html'."
2337 (let (beg end html text)
2338 (goto-char (point-min))
2339 (re-search-forward "^--text follows this line--$")
2340 ;; move to beginning of next line
2341 (beginning-of-line 2)
2343 (if (not (re-search-forward "^--\\[\\[" nil t))
2344 (setq end (point-max))
2349 (setq text (buffer-substring-no-properties beg end))
2355 (when (re-search-backward "^-- \n" nil t)
2356 ;; preserve link breaks in signature
2357 (insert "\n#+BEGIN_VERSE\n")
2358 (goto-char (point-max))
2359 (insert "\n#+END_VERSE\n")
2361 (setq html (org-export-region-as-html
2362 (point-min) (point-max) t 'string))))
2363 (delete-region beg end)
2366 "--" "<<alternative>>-{\n"
2367 "--" "[[text/plain]]\n" text
2368 "--" "[[text/html]]\n" html
2369 "--" "}-<<alternative>>\n")))))
2371 (defun dmj/wl-send-html-message-toggle ()
2372 "Toggle sending of html message."
2374 (setq dmj/wl-send-html-message-toggled-p
2375 (if dmj/wl-send-html-message-toggled-p
2377 (message "Sending html message toggled %s"
2378 (if dmj/wl-send-html-message-toggled-p
2381 (defun dmj/wl-send-html-message-draft-init ()
2382 "Create buffer local settings for maybe sending html message."
2383 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2384 (setq dmj/wl-send-html-message-toggled-p nil))
2385 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2386 (add-to-list 'global-mode-string
2387 '(:eval (if (eq major-mode 'wl-draft-mode)
2388 dmj/wl-send-html-message-toggled-p))))
2390 (defun dmj/wl-send-html-message-maybe ()
2391 "Maybe send this message as html message.
2393 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2394 non-nil, add `dmj/wl-send-html-message' to
2395 `mime-edit-translate-hook'."
2396 (if dmj/wl-send-html-message-toggled-p
2397 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2398 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2400 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2401 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2402 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2405 *** Attach HTML of region or subtree
2407 Instead of sending a complete HTML message you might only send parts
2408 of an Org file as HTML for the poor souls who are plagued with
2409 non-proportional fonts in their mail program that messes up pretty
2412 This short function does the trick: It exports region or subtree to
2413 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2414 and clipboard. If a region is active, it uses the region, the
2415 complete subtree otherwise.
2417 #+begin_src emacs-lisp
2418 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2419 "Export region between BEG and END as html attachment.
2420 If BEG and END are not set, use current subtree. Region or
2421 subtree is exported to html without header and footer, prefixed
2422 with a mime entity string and pushed to clipboard and killring.
2423 When called with prefix, mime entity is not marked as
2425 (interactive "r\nP")
2427 (let* ((beg (if (region-active-p) (region-beginning)
2429 (org-back-to-heading)
2431 (end (if (region-active-p) (region-end)
2433 (org-end-of-subtree)
2435 (html (concat "--[[text/html"
2436 (if arg "" "\nContent-Disposition: attachment")
2438 (org-export-region-as-html beg end t 'string))))
2439 (when (fboundp 'x-set-selection)
2440 (ignore-errors (x-set-selection 'PRIMARY html))
2441 (ignore-errors (x-set-selection 'CLIPBOARD html)))
2442 (message "html export done, pushed to kill ring and clipboard"))))
2445 *** Adopting for Gnus
2447 The whole magic lies in the special strings that mark a HTML
2448 attachment. So you might just have to find out what these special
2449 strings are in message-mode and modify the functions accordingly.
2450 ** Add sunrise/sunset times to the agenda.
2451 #+index: Agenda!Diary s-expressions
2454 The diary package provides the function =diary-sunrise-sunset= which can be used
2455 in a diary s-expression in some agenda file like this:
2457 #+begin_src org-mode
2458 %%(diary-sunrise-sunset)
2461 Seb Vauban asked if it is possible to put sunrise and sunset in
2462 separate lines. Here is a hack to do that. It adds two functions (they
2463 have to be available before the agenda is shown, so I add them early
2464 in my org-config file which is sourced from .emacs, but you'll have to
2465 suit yourself here) that just parse the output of
2466 diary-sunrise-sunset, instead of doing the right thing which would be
2467 to take advantage of the data structures that diary/solar.el provides.
2468 In short, a hack - so perfectly suited for inclusion here :-)
2470 The functions (and latitude/longitude settings which you have to modify for
2471 your location) are as follows:
2473 #+begin_src emacs-lisp
2474 (setq calendar-latitude 48.2)
2475 (setq calendar-longitude 16.4)
2476 (setq calendar-location-name "Vienna, Austria")
2478 (autoload 'solar-sunrise-sunset "solar.el")
2479 (autoload 'solar-time-string "solar.el")
2480 (defun diary-sunrise ()
2481 "Local time of sunrise as a diary entry.
2482 The diary entry can contain `%s' which will be replaced with
2483 `calendar-location-name'."
2484 (let ((l (solar-sunrise-sunset date)))
2487 (if (string= entry "")
2489 (format entry (eval calendar-location-name))) " "
2490 (solar-time-string (caar l) nil)))))
2492 (defun diary-sunset ()
2493 "Local time of sunset as a diary entry.
2494 The diary entry can contain `%s' which will be replaced with
2495 `calendar-location-name'."
2496 (let ((l (solar-sunrise-sunset date)))
2499 (if (string= entry "")
2501 (format entry (eval calendar-location-name))) " "
2502 (solar-time-string (caadr l) nil)))))
2505 You also need to add a couple of diary s-expressions in one of your agenda
2508 #+begin_src org-mode
2509 %%(diary-sunrise)Sunrise in %s
2513 This will show sunrise with the location and sunset without it.
2515 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]].
2516 In comparison to the version posted on the mailing list, this one
2517 gets rid of the timezone information and can show the location.
2518 ** Export BBDB contacts to org-contacts.el
2519 #+index: Address Book!BBDB to org-contacts
2520 Try this tool by Wes Hardaker:
2522 http://www.hardakers.net/code/bbdb-to-org-contacts/
2524 ** Calculating date differences - how to write a simple elisp function
2525 #+index: Timestamp!date calculations
2526 #+index: Elisp!technique
2528 Alexander Wingård asked how to calculate the number of days between a
2529 time stamp in his org file and today (see
2530 http://thread.gmane.org/gmane.emacs.orgmode/46881). Although the
2531 resulting answer is probably not of general interest, the method might
2532 be useful to a budding Elisp programmer.
2534 Alexander started from an already existing org function,
2535 =org-evaluate-time-range=. When this function is called in the context
2536 of a time range (two time stamps separated by "=--="), it calculates the
2537 number of days between the two dates and outputs the result in Emacs's
2538 echo area. What he wanted was a similar function that, when called from
2539 the context of a single time stamp, would calculate the number of days
2540 between the date in the time stamp and today. The result should go to
2541 the same place: Emacs's echo area.
2543 The solution presented in the mail thread is as follows:
2545 #+begin_src emacs-lisp
2546 (defun aw/org-evaluate-time-range (&optional to-buffer)
2548 (if (org-at-date-range-p t)
2549 (org-evaluate-time-range to-buffer)
2550 ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
2551 (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
2554 (goto-char (point-at-bol))
2555 (re-search-forward org-ts-regexp (point-at-eol) t)
2556 (if (not (org-at-timestamp-p t))
2557 (error "No timestamp here"))
2558 (goto-char (match-beginning 0))
2559 (org-insert-time-stamp (current-time) nil nil)
2561 (org-evaluate-time-range to-buffer)))))
2564 The function assumes that point is on some line with some time stamp
2565 (or a date range) in it. Note that =org-evaluate-time-range= does not care
2566 whether the first date is earlier than the second: it will always output
2567 the number of days between the earlier date and the later date.
2569 As stated before, the function itself is of limited interest (although
2570 it satisfied Alexander's need).The *method* used might be of wider
2571 interest however, so here is a short explanation.
2573 The idea is that we want =org-evaluate-time-range= to do all the
2574 heavy lifting, but that function requires that it be in a date-range
2575 context. So the function first checks whether it's in a date range
2576 context already: if so, it calls =org-evaluate-time-range= directly
2577 to do the work. The trick now is to arrange things so we can call this
2578 same function in the case where we do *not* have a date range
2579 context. In that case, we manufacture one: we create a temporary
2580 buffer, copy the line with the purported time stamp to the temp
2581 buffer, find the time stamp (signal an error if no time stamp is
2582 found) and insert a new time stamp with the current time before the
2583 existing time stamp, followed by "=--=": voilà, we now have a time range
2584 on which we can apply our old friend =org-evaluate-time-range= to
2585 produce the answer. Because of the above-mentioned property
2586 of =org-evaluate-time-range=, it does not matter if the existing
2587 time stamp is earlier or later than the current time: the correct
2588 number of days is output.
2590 Note that at the end of the call to =with-temp-buffer=, the temporary
2591 buffer goes away. It was just used as a scratch pad for the function
2592 to do some figuring.
2594 The idea of using a temp buffer as a scratch pad has wide
2595 applicability in Emacs programming. The rest of the work is knowing
2596 enough about facilities provided by Emacs (e.g. regexp searching) and
2597 by Org (e.g. checking for time stamps and generating a time stamp) so
2598 that you don't reinvent the wheel, and impedance-matching between the
2601 ** ibuffer and org files
2603 Neil Smithline posted this snippet to let you browse org files with
2606 #+BEGIN_SRC emacs-lisp
2609 (defun org-ibuffer ()
2610 "Open an `ibuffer' window showing only `org-mode' buffers."
2612 (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
2615 ** Enable org-mode links in other modes
2617 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
2619 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
2621 * Hacking Org: Working with Org-mode and External Programs.
2622 ** Use Org-mode with Screen [Andrew Hyatt]
2623 #+index: Link!to screen session
2624 "The general idea is that you start a task in which all the work will
2625 take place in a shell. This usually is not a leaf-task for me, but
2626 usually the parent of a leaf task. From a task in your org-file, M-x
2627 ash-org-screen will prompt for the name of a session. Give it a name,
2628 and it will insert a link. Open the link at any time to go the screen
2629 session containing your work!"
2631 http://article.gmane.org/gmane.emacs.orgmode/5276
2633 #+BEGIN_SRC emacs-lisp
2636 (defun ash-org-goto-screen (name)
2637 "Open the screen with the specified name in the window"
2638 (interactive "MScreen name: ")
2639 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2640 (if (member screen-buffer-name
2641 (mapcar 'buffer-name (buffer-list)))
2642 (switch-to-buffer screen-buffer-name)
2643 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2645 (defun ash-org-screen-buffer-name (name)
2646 "Returns the buffer name corresponding to the screen name given."
2647 (concat "*screen " name "*"))
2649 (defun ash-org-screen-helper (name arg)
2650 ;; Pick the name of the new buffer.
2651 (let ((term-ansi-buffer-name
2652 (generate-new-buffer-name
2653 (ash-org-screen-buffer-name name))))
2654 (setq term-ansi-buffer-name
2655 (term-ansi-make-term
2656 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2657 (set-buffer term-ansi-buffer-name)
2660 (term-set-escape-char ?\C-x)
2661 term-ansi-buffer-name))
2663 (defun ash-org-screen (name)
2664 "Start a screen session with name"
2665 (interactive "MScreen name: ")
2667 (ash-org-screen-helper name "-S"))
2668 (insert-string (concat "[[screen:" name "]]")))
2670 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2671 ;; \"%s\")") to org-link-abbrev-alist.
2674 ** Org Agenda + Appt + Zenity
2676 :CUSTOM_ID: org-agenda-appt-zenity
2679 #+index: Appointment!reminders
2680 #+index: Appt!Zenity
2682 <a name="agenda-appt-zenity"></a>
2684 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It makes sure your agenda
2685 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2688 #+BEGIN_SRC emacs-lisp
2689 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2690 ; For org appointment reminders
2692 ;; Get appointments for today
2693 (defun my-org-agenda-to-appt ()
2695 (setq appt-time-msg-list nil)
2696 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
2697 (org-agenda-to-appt)))
2699 ;; Run once, activate and schedule refresh
2700 (my-org-agenda-to-appt)
2702 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2705 (setq appt-message-warning-time 15)
2706 (setq appt-display-interval 5)
2708 ; Update appt each time agenda opened.
2709 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2711 ; Setup zenify, we tell appt to use window, and replace default function
2712 (setq appt-display-format 'window)
2713 (setq appt-disp-window-function (function my-appt-disp-window))
2715 (defun my-appt-disp-window (min-to-app new-time msg)
2716 (save-window-excursion (shell-command (concat
2717 "/usr/bin/zenity --info --title='Appointment' --text='"
2718 msg "' &") nil nil)))
2721 ** Org-Mode + gnome-osd
2722 #+index: Appointment!reminders
2723 #+index: Appt!gnome-osd
2724 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2725 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2728 #+index: Agenda!Views
2729 #+index: Agenda!and Remind (external program)
2732 http://article.gmane.org/gmane.emacs.orgmode/5073
2735 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2736 command line calendaring program. Its features supersede the possibilities
2737 of orgmode in the area of date specifying, so that I want to use it
2738 combined with orgmode.
2740 Using the script below I'm able use remind and incorporate its output in my
2741 agenda views. The default of using 13 months look ahead is easily
2742 changed. It just happens I sometimes like to look a year into the
2746 ** Useful webjumps for conkeror
2747 #+index: Shortcuts!conkeror
2748 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2749 your =~/.conkerorrc= file:
2752 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2753 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2756 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2757 Org-mode mailing list.
2759 ** Use MathJax for HTML export without requiring JavaScript
2760 #+index: Export!MathJax
2761 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2763 If you like the results but do not want JavaScript in the exported pages,
2764 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2765 HTML file from the exported version. It can also embed all referenced fonts
2766 within the HTML file itself, so there are no dependencies to external files.
2768 The download archive contains an elisp file which integrates it into the Org
2769 export process (configurable per file with a "#+StaticMathJax:" line).
2771 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2772 ** Search Org files using lgrep
2773 #+index: search!lgrep
2774 Matt Lundin suggests this:
2776 #+begin_src emacs-lisp
2777 (defun my-org-grep (search &optional context)
2778 "Search for word in org files.
2780 Prefix argument determines number of lines."
2781 (interactive "sSearch for: \nP")
2782 (let ((grep-find-ignored-files '("#*" ".#*"))
2783 (grep-template (concat "grep <X> -i -nH "
2785 (concat "-C" (number-to-string context)))
2787 (lgrep search "*org*" "/home/matt/org/")))
2789 (global-set-key (kbd "<f8>") 'my-org-grep)
2792 ** Automatic screenshot insertion
2793 #+index: Link!screenshot
2794 Suggested by Russell Adams
2796 #+begin_src emacs-lisp
2797 (defun my-org-screenshot ()
2798 "Take a screenshot into a time stamped unique-named file in the
2799 same directory as the org-buffer and insert a link to this file."
2804 (concat (buffer-file-name)
2806 (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
2807 (call-process "import" nil nil nil filename)
2808 (insert (concat "[[" filename "]]"))
2809 (org-display-inline-images))
2812 ** Capture invitations/appointments from MS Exchange emails
2813 #+index: Appointment!MS Exchange
2814 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
2815 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
2817 ** Audio/video file playback within org mode
2818 #+index: Link!audio/video
2819 Paul Sexton provided code that makes =file:= links to audio or video files
2820 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
2821 media player library. The user can pause, skip forward and backward in the
2822 track, and so on from without leaving Emacs. Links can also contain a time
2823 after a double colon -- when this is present, playback will begin at that
2824 position in the track.
2826 See the file [[file:code/elisp/org-player.el][org-player.el]]
2828 ** Under X11 Keep a window with the current agenda items at all time
2829 #+index: Agenda!dedicated window
2830 I struggle to keep (in emacs) a window with the agenda at all times.
2831 For a long time I have wanted a sticky window that keeps this
2832 information, and then use my window manager to place it and remove its
2833 decorations (I can also force its placement in the stack: top always,
2836 I wrote a small program in qt that simply monitors an HTML file and
2837 displays it. Nothing more. It does the work for me, and maybe somebody
2838 else will find it useful. It relies on exporting the agenda as HTML
2839 every time the org file is saved, and then this little program
2840 displays the html file. The window manager is responsible of removing
2841 decorations, making it sticky, and placing it in same place always.
2843 Here is a screenshot (see window to the bottom right). The decorations
2844 are removed by the window manager:
2846 http://turingmachine.org/hacking/org-mode/orgdisplay.png
2848 Here is the code. As I said, very, very simple, but maybe somebody will
2851 http://turingmachine.org/hacking/org-mode/
2855 ** Script (thru procmail) to output emails to an Org file
2856 #+index: Conversion!email to org file
2857 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
2859 : I've [...] created some procmail and shell glue that takes emails and
2860 : inserts them into an org-file so that I can capture stuff on the go using
2861 : the email program.
2863 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
2865 ** Save File With Different Format for Headings (fileconversion)
2867 :CUSTOM_ID: fileconversion
2869 #+index: Conversion!fileconversion
2871 Using hooks and on the fly
2872 - when writing a buffer to the file replace the leading stars from headings
2874 - when reading a file into the buffer replace the file chars with leading
2877 To change to save an Org file in one of the formats or back just add or
2878 remove the keyword in the STARTUP line and save.
2880 Now you can also change to Fundamental mode to see how the file looks like
2881 on the level of the file, go back to Org mode, reenter Org mode or change to
2882 any other major mode and the conversion gets done whenever necessary.
2884 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
2886 :CUSTOM_ID: hidestarsfile
2888 #+index: Conversion!fileconversion hidestarsfile
2890 This is like "a cleaner outline view":
2891 http://orgmode.org/manual/Clean-view.html
2893 Example of the _file content_ first with leading stars as usual and below
2894 without leading stars through "#+STARTUP: odd hidestars hidestarsfile":
2897 #+STARTUP: odd hidestars
2909 #+STARTUP: odd hidestars hidestarsfile
2920 The latter is convenient for better human readability when an Org file,
2921 additionally to Emacs, is read with a file viewer or, for smaller edits,
2922 with an editor not capable of the Org file format.
2924 hidestarsfile is a hack and can not become part of the Org core:
2925 - An Org file with hidestarsfile can not contain list items with a star as
2926 bullet due to the syntax conflict at read time. Mark E. Shoulson suggested
2927 to use the non-breaking space which is now implemented in fileconversion
2928 as nbspstarsfile as an alternative for hidestarsfile. Although I don't
2929 recommend it because an editor like typically e. g. Emacs may render the
2930 non-breaking space differently from the space 0x20.
2931 - An Org file with hidestarsfile can almost not be edited with an Org mode
2932 without added functionality of hidestarsfile as long as the file is not
2935 *** Headings in Markdown Format (markdownstarsfile)
2937 :CUSTOM_ID: markdownstarsfile
2939 #+index: Conversion!fileconversion markdownstarsfile
2941 For "oddeven" you can use markdownstarsfile to be readable or even basically
2942 editable with Markdown (does not make much sense with "odd", see
2943 org-convert-to-odd-levels and org-convert-to-oddeven-levels for how to
2946 Example of the _file content_:
2949 #+STARTUP: oddeven markdownstarsfile
2951 1. first item of numbered list (same format in Org and Markdown)
2953 - first item of unordered list (same format in Org and Markdown)
2955 + first item of unordered list (same format in Org and Markdown)
2956 #### section level 4
2957 * first item of unordered list (same format in Org and Markdown)
2958 * avoid this item type to be compatible with Org hidestarsfile
2961 An Org file with markdownstarsfile can not contain code comment lines
2962 prefixed with "#", even not when within source blocks.
2966 :CUSTOM_ID: fileconversion-code
2968 #+index: Conversion!fileconversion emacs-lisp code
2970 #+BEGIN_SRC emacs-lisp
2971 ;; - fileconversion version 0.6
2972 ;; - DISCLAIMER: Make a backup of your Org files before using
2973 ;; my-org-fileconv-*.
2974 ;; - supported formats: hidestarsfile, markdownstarsfile
2976 ;; design summary: fileconversion is a round robin of two states
2977 ;; linked by two actions:
2978 ;; - state my-org-fileconv-level-org-p is nil: the level is "file"
2980 ;; - action my-org-fileconv-decode: replace file char with '*'
2981 ;; - state my-org-fileconv-level-org-p is t: the level is "Org"
2983 ;; - action my-org-fileconv-encode replace '*' with file char
2985 (defvar my-org-fileconv-level-org-p nil
2986 "Whether level of buffer is Org or only file.
2987 nil means the level is file (encoded), non-nil means the level is Org
2989 (make-variable-buffer-local 'my-org-fileconv-level-org-p)
2990 ;; survive a change of major mode that does kill-all-local-variables,
2991 ;; e. g. when reentering Org mode through “C-c C-c” on a STARTUP line
2992 (put 'my-org-fileconv-level-org-p 'permanent-local t)
2994 (add-hook 'org-mode-hook 'my-org-fileconv-init
2995 ;; _append_ to hook to have a higher chance that a message
2996 ;; from this function will be visible as the last message in
2999 ;; hook addition global
3002 (defun my-org-fileconv-init ()
3004 ;; instrument only when converting really from/to an Org _file_, not
3005 ;; e. g. for a temp Org buffer unrelated to a file like used e. g.
3006 ;; when calling the old Org exporter
3007 (when (buffer-file-name)
3008 (message "INF: my-org-fileconv-init, buffer: %s" (buffer-name))
3009 (my-org-fileconv-decode)
3010 ;; the hooks are not permanent-local, this way and as needed they
3011 ;; will disappear when the major mode of the buffer changes
3012 (add-hook 'change-major-mode-hook 'my-org-fileconv-encode nil
3013 ;; hook addition limited to buffer locally
3015 (add-hook 'before-save-hook 'my-org-fileconv-encode nil
3016 ;; hook addition limited to buffer locally
3018 (add-hook 'after-save-hook 'my-org-fileconv-decode nil
3019 ;; hook addition limited to buffer locally
3022 (defun my-org-fileconv-re ()
3023 "Check whether there is a STARTUP line for fileconversion.
3024 If found then return the expressions required for the conversion."
3026 (beginning-of-buffer)
3027 (let (re-list (count 0))
3028 (while (re-search-forward "^#\\+STARTUP:" nil t)
3029 ;; #+STARTUP: hidestarsfile
3030 (when (string-match-p "\\bhidestarsfile\\b"
3031 (thing-at-point 'line))
3033 ;; - line starting with star for bold emphasis
3034 ;; - line of stars to underline section title in loosely
3035 ;; quoted ASCII style (star at end of line)
3036 (setq re-list '("\\(\\* \\)" ; common-re
3038 (setq count (1+ count)))
3039 ;; #+STARTUP: nbspstarsfile
3040 (when (string-match-p "\\bnbspstarsfile\\b"
3041 (thing-at-point 'line))
3042 (setq re-list '("\\(\\* \\)" ; common-re
3043 ?\xa0)) ; file-char non-breaking space
3044 (setq count (1+ count)))
3045 ;; #+STARTUP: markdownstarsfile
3046 (when (string-match-p "\\bmarkdownstarsfile\\b"
3047 (thing-at-point 'line))
3050 (setq re-list '("\\( \\)" ; common-re
3052 (setq count (1+ count))))
3054 (error "ERR: more than one fileconversion found"))
3057 (defun my-org-fileconv-decode ()
3058 "In headings replace file char with '*'."
3059 (let ((re-list (my-org-fileconv-re)))
3060 (when (and re-list (not my-org-fileconv-level-org-p))
3061 ;; no `save-excursion' to be able to keep point in case of error
3062 (let* ((common-re (nth 0 re-list))
3063 (file-char (nth 1 re-list))
3064 (file-re (concat "^" (string file-char) "+" common-re))
3065 (org-re (concat "^\\*+" common-re))
3068 (beginning-of-buffer)
3070 (when (re-search-forward org-re nil t)
3071 (goto-char (match-beginning 0))
3074 "ERR: my-org-fileconv-decode syntax conflict at point"))
3075 (beginning-of-buffer)
3077 (with-silent-modifications
3078 (while (re-search-forward file-re nil t)
3079 (goto-char (match-beginning 0))
3080 ;; faster than a lisp call of insert and delete on each
3082 (setq len (- (match-beginning 1) (match-beginning 0)))
3083 (insert-char ?* len)
3087 ;; notes for ediff when only one file has fileconversion:
3088 ;; - The changes to the buffer with fileconversion until here
3089 ;; are not regarded by ediff-files because the first call to
3090 ;; diff is made with the bare files directly. Only
3091 ;; ediff-update-diffs and ediff-buffers write the decoded
3092 ;; buffers to temp files and then call diff with them.
3093 ;; - Workarounds (choose one):
3094 ;; - after ediff-files first do a "!" (ediff-update-diffs)
3095 ;; in the "*Ediff Control Panel*"
3096 ;; - instead of using ediff-files first open the files and
3097 ;; then run ediff-buffers (better for e. g. a script that
3098 ;; takes two files as arguments and uses "emacs --eval")
3100 ;; the level is Org most of all when no fileconversion is in effect
3101 (setq my-org-fileconv-level-org-p t))
3103 (defun my-org-fileconv-encode ()
3104 "In headings replace '*' with file char."
3105 (let ((re-list (my-org-fileconv-re)))
3106 (when (and re-list my-org-fileconv-level-org-p)
3107 ;; no `save-excursion' to be able to keep point in case of error
3108 (let* ((common-re (nth 0 re-list))
3109 (file-char (nth 1 re-list))
3110 (file-re (concat "^" (string file-char) "+" common-re))
3111 (org-re (concat "^\\*+" common-re))
3114 (beginning-of-buffer)
3116 (when (re-search-forward file-re nil t)
3117 (goto-char (match-beginning 0))
3120 "ERR: my-org-fileconv-encode syntax conflict at point"))
3121 (beginning-of-buffer)
3123 (with-silent-modifications
3124 (while (re-search-forward org-re nil t)
3125 (goto-char (match-beginning 0))
3126 ;; faster than a lisp call of insert and delete on each
3128 (setq len (- (match-beginning 1) (match-beginning 0)))
3129 (insert-char file-char len)
3132 (setq my-org-fileconv-level-org-p nil))))
3133 nil) ;; for the hook
3138 ** Meaningful diff for org files in a git repository
3139 #+index: git!diff org files
3140 Since most diff utilities are primarily meant for source code, it is
3141 difficult to read diffs of text files like ~.org~ files easily. If you
3142 version your org directory with a SCM like git you will know what I
3143 mean. However for git, there is a way around. You can use
3144 =gitattributes= to define a custom diff driver for org files. Then a
3145 regular expression can be used to configure how the diff driver
3146 recognises a "function".
3148 Put the following in your =<org_dir>/.gitattributes=.
3150 Then put the following lines in =<org_dir>/.git/config=
3152 : xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3154 This will let you see diffs for org files with each hunk identified by
3155 the unmodified headline closest to the changes. After the
3156 configuration a diff should look something like the example below.
3159 diff --git a/org-hacks.org b/org-hacks.org
3160 index a0672ea..92a08f7 100644
3163 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3165 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3167 +** Meaningful diff for org files in a git repository
3169 +Since most diff utilities are primarily meant for source code, it is
3170 +difficult to read diffs of text files like ~.org~ files easily. If you
3171 +version your org directory with a SCM like git you will know what I
3172 +mean. However for git, there is a way around. You can use
3173 +=gitattributes= to define a custom diff driver for org files. Then a
3174 +regular expression can be used to configure how the diff driver
3175 +recognises a "function".
3177 +Put the following in your =<org_dir>/.gitattributes=.
3179 +Then put the following lines in =<org_dir>/.git/config=
3181 +: xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3185 ** Cooking? Brewing?
3188 ** Opening devonthink links
3190 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3191 links from org-mode.
3195 ** Cooking? Brewing?
3196 #+index: beer!brewing
3197 #+index: cooking!conversions
3198 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3200 It currently does metric/english conversion, and a few other tricks.
3201 Basically I just use calc’s units code. I think scaling recipes, or
3202 turning percentages into weights would be pretty easy.
3204 https://gitorious.org/org-cook/org-cook
3206 There is also, for those interested:
3208 https://gitorious.org/org-brew/org-brew
3210 for brewing beer. This is again, mostly just calc functions, including
3211 hydrometer correction, abv calculation, priming sugar for a given CO_2
3212 volume, etc. More integration with org-mode should be possible: for
3213 instance it would be nice to be able to use a lookup table (of ingredients)
3214 to calculate target original gravity, IBUs, etc.