1 #+TITLE: Org ad hoc code, quick hacks and workarounds
3 #+EMAIL: mdl AT imapmail DOT org
4 #+OPTIONS: H:3 num:nil toc:t \n:nil ::t |:t ^:t -:t f:t *:t tex:t d:(HIDE) tags:not-in-toc
5 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate
6 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
7 #+TAGS: Write(w) Update(u) Fix(f) Check(c)
12 # This file is the default header for new Org files in Worg. Feel free
13 # to tailor it to your needs.
15 [[file:index.org][{Back to Worg's index}]]
17 This page is for ad hoc bits of code. Feel free to add quick hacks and
20 * Hacking Org: Working within Org-mode.
23 *** Picking up a random task in the global TODO list
25 Tony day [[http://mid.gmane.org/m2zk19l1me.fsf@gmail.com][shared]] [[https://gist.github.com/4343164][this gist]] to pick up a
28 ** Building and Managing Org
29 *** Generating autoloads and Compiling Org without make
31 :CUSTOM_ID: compiling-org-without-make
34 #+index: Compilation!without make
36 Compilation is optional, but you _must_ update the autoloads file
37 each time you update org, even when you run org uncompiled!
39 Starting with Org 7.9 you'll find functions for creating the
40 autoload files and do byte-compilation in =mk/org-fixup.el=. When
41 you execute the commands below, your current directory must be where
42 org has been unpacked into, in other words the file =README= should
43 be found in your current directory and the directories =lisp= and
44 =etc= should be subdirectories of it. The command =emacs= should be
45 found in your =PATH= and start the Emacs version you are using. To
46 make just the autoloads file do:
47 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
48 To make the autoloads file and byte-compile org:
49 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
50 To make the autoloads file and byte-compile all of org again:
51 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
52 If you are not using Git, you'll have to make fake version strings
53 first if =org-version.el= is not already available (if it is, you
54 could also edit the version strings there).
55 : emacs -batch -Q -L lisp -l ../mk/org-fixup \
56 : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
57 : (org-make-autoloads))'
59 POSIX shell for its quoting. Windows =CMD.exe= has quite different
60 quoting rules and this won't work, so your other option is to start
62 : emacs -Q -L lisp -l ../mk/org-fixup
63 then paste the following into the =*scratch*= buffer
64 #+BEGIN_SRC emacs-lisp
65 (let ((org-fake-release "7.9.1")
66 (org-fake-git-version "7.9.1-fake"))
69 position the cursor after the closing paren and press =C-j= or =C-x
70 C-e= to evaluate the form. Of course you can replace
71 =org-make-autoloads= with =org-make-autoloads-compile= or even
72 =org-make-autoloads-compile-force= if you wish with both variants.
74 For *older org versions only* (that do not yet have
75 =mk/org-fixup.el=), you can use the definitions below. To use
76 this function, adjust the variables =my/org-lisp-directory= and
77 =my/org-compile-sources= to suit your needs. If you have
78 byte-compiled org, but want to run org uncompiled again, just remove
79 all =*.elc= files in the =lisp/= directory, set
80 =my/org-compile-sources= to =nil=.
82 #+BEGIN_SRC emacs-lisp
83 (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
84 "Directory where your org-mode files live.")
86 (defvar my/org-compile-sources t
87 "If `nil', never compile org-sources. `my/compile-org' will only create
88 the autoloads file `org-loaddefs.el' then. If `t', compile the sources, too.")
90 ;; Customize: (must end with a slash!)
91 (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")
94 (setq my/org-compile-sources t)
96 (defun my/compile-org(&optional directory)
97 "Generate autoloads file org-loaddefs.el. Optionally compile
98 all *.el files that come with org-mode."
100 (defun my/compile-org()
101 "Generate autoloads file org-loaddefs.el. Optionally compile
102 all *.el files that come with org-mode."
104 (let ((dirlisp (file-name-directory my/org-lisp-directory)))
105 (add-to-list 'load-path dirlisp)
107 (let ((generated-autoload-file (concat dirlisp "org-loaddefs.el")))
108 ;; create the org-loaddefs file
109 (update-directory-autoloads dirlisp)
110 (when my/org-compile-sources
111 ;; optionally byte-compile
112 (byte-recompile-directory dirlisp 0 'force)))))
116 #+index: Initialization!Reload
118 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
119 function to reload org files.
121 Normally you want to use the compiled files since they are faster.
122 If you update your org files you can easily reload them with
126 If you run into a bug and want to generate a useful backtrace you can
127 reload the source files instead of the compiled files with
131 and turn on the "Enter Debugger On Error" option. Redo the action
132 that generates the error and cut and paste the resulting backtrace.
133 To switch back to the compiled version just reload again with
137 *** Check for possibly problematic old link escapes
139 :CUSTOM_ID: check-old-link-escapes
142 Starting with version 7.5 Org uses [[https://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
143 and with a modified algorithm to determine which characters to escape
146 As a side effect this modified behaviour might break existing links if
147 they contain a sequence of characters that look like a percent escape
148 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
150 The function below can be used to perform a preliminary check for such
151 links in an Org mode file. It will run through all links in the file
152 and issue a warning if it finds a percent escape sequence which is not
153 in old Org's list of known percent escapes.
155 #+begin_src emacs-lisp
156 (defun dmaus/org-check-percent-escapes ()
157 "*Check buffer for possibly problematic old link escapes."
159 (when (eq major-mode 'org-mode)
160 (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
161 "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
162 (unless (boundp 'warning-suppress-types)
163 (setq warning-suppress-types nil))
166 (goto-char (point-min))
167 (while (re-search-forward org-any-link-re nil t)
168 (let ((end (match-end 0)))
169 (goto-char (match-beginning 0))
170 (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
171 (let ((escape (match-string-no-properties 0)))
172 (unless (member (upcase escape) old-escapes)
173 (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
180 ** Structure Movement and Editing
181 *** Go back to the previous top-level heading
183 #+BEGIN_SRC emacs-lisp
184 (defun org-back-to-top-level-heading ()
185 "Go back to the current top level heading."
187 (or (re-search-backward "^\* " nil t)
188 (goto-char (point-min))))
191 *** Go to a child of the current heading
193 :CUSTOM_ID: org-jump-to-child
195 #+index: Navigation!Heading
196 - [[http://langec.wordpress.com][Christoph Lange]]
198 =org-jump-to-child= in [[file:code/elisp/org-jump.el::(defun%20org-jump-to-child][org-jump.el]] (keybinding suggested there: =C-c o c=) interactively prompts for the title of a child node, i.e. sub-heading, of the current heading and jumps to the child node having that title (in case of ambiguity: the /last/ such node).
200 In the absence of a readily accessible structural representation of the tree outline, this is ipmlemented by walking over all child nodes and collecting their titles and their positions in the file.
202 *** Go to a heading by its ID (=CUSTOM_ID= property)
204 :CUSTOM_ID: org-jump-to-id
206 #+index: Navigation!Heading
207 - [[http://langec.wordpress.com][Christoph Lange]]
209 =org-jump-to-id= in [[file:code/elisp/org-jump.el::(defun%20org-jump-to-id][org-jump.el]] (keybinding suggested there: =C-c o j=) interactively prompts for the one of the =CUSTOM_ID= property values in the current document and jumps to the [first] node that has this ID.
211 This implementation works efficiently in a 5 MB org file with 100 IDs. Together with ido or helm I find it a very user-friendly way of jumping to frequently used headings.
213 I noticed that =org-babel-ref-goto-headline-id= does something similar, so maybe some code could be shared among the two functions.
214 *** Show next/prev heading tidily
216 #+index: Navigation!Heading
218 These close the current heading and open the next/previous heading.
220 #+begin_src emacs-lisp
221 (defun ded/org-show-next-heading-tidily ()
222 "Show next entry, keeping other entries closed."
223 (if (save-excursion (end-of-line) (outline-invisible-p))
224 (progn (org-show-entry) (show-children))
225 (outline-next-heading)
226 (unless (and (bolp) (org-on-heading-p))
227 (org-up-heading-safe)
229 (error "Boundary reached"))
235 (defun ded/org-show-previous-heading-tidily ()
236 "Show previous entry, keeping other entries closed."
238 (outline-previous-heading)
239 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
242 (error "Boundary reached"))
248 (setq org-use-speed-commands t)
249 (add-to-list 'org-speed-commands-user
250 '("n" ded/org-show-next-heading-tidily))
251 (add-to-list 'org-speed-commands-user
252 '("p" ded/org-show-previous-heading-tidily))
255 *** Promote all items in subtree
256 #+index: Structure Editing!Promote
259 This function will promote all items in a subtree. Since I use
260 subtrees primarily to organize projects, the function is somewhat
261 unimaginatively called my-org-un-project:
263 #+begin_src emacs-lisp
264 (defun my-org-un-project ()
266 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
270 *** Turn a heading into an Org link
272 :CUSTOM_ID: heading-to-link
274 #+index: Structure Editing!Heading
275 #+index: Link!Turn a heading into a
278 #+begin_src emacs-lisp
279 (defun dmj:turn-headline-into-org-mode-link ()
280 "Replace word at point by an Org mode link."
282 (when (org-at-heading-p)
283 (let ((hl-text (nth 4 (org-heading-components))))
284 (unless (or (null hl-text)
285 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
287 (search-forward hl-text (point-at-eol))
290 (format "[[file:%s.org][%s]]"
291 (org-link-escape hl-text)
292 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
293 nil (- (point) (length hl-text)) (point))))))
296 *** Using M-up and M-down to transpose paragraphs
297 #+index: Structure Editing!paragraphs
299 From Paul Sexton: By default, if used within ordinary paragraphs in
300 org mode, =M-up= and =M-down= transpose *lines* (not sentences). The
301 following code makes these keys transpose paragraphs, keeping the
302 point at the start of the moved paragraph. Behavior in tables and
303 headings is unaffected. It would be easy to modify this to transpose
306 #+begin_src emacs-lisp
307 (defun org-transpose-paragraphs (arg)
309 (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
310 (thing-at-point 'sentence))
311 (transpose-paragraphs arg)
313 (re-search-forward "[[:graph:]]")
314 (goto-char (match-beginning 0))
317 (add-to-list 'org-metaup-hook
318 (lambda () (interactive) (org-transpose-paragraphs -1)))
319 (add-to-list 'org-metadown-hook
320 (lambda () (interactive) (org-transpose-paragraphs 1)))
322 *** Changelog support for org headers
323 #+index: Structure Editing!Heading
326 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
327 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
328 headline as the "current function" if you add a changelog entry from an org
331 #+BEGIN_SRC emacs-lisp
332 (defun org-log-current-defun ()
334 (org-back-to-heading)
335 (if (looking-at org-complex-heading-regexp)
338 (add-hook 'org-mode-hook
340 (make-variable-buffer-local 'add-log-current-defun-function)
341 (setq add-log-current-defun-function 'org-log-current-defun)))
344 *** Different org-cycle-level behavior
345 #+index: Cycling!behavior
348 In recent org versions, when your point (cursor) is at the end of an
349 empty header line (like after you first created the header), the TAB
350 key (=org-cycle=) has a special behavior: it cycles the headline through
351 all possible levels. However, I did not like the way it determined
352 "all possible levels," so I rewrote the whole function, along with a
353 couple of supporting functions.
355 The original function's definition of "all possible levels" was "every
356 level from 1 to one more than the initial level of the current
357 headline before you started cycling." My new definition is "every
358 level from 1 to one more than the previous headline's level." So, if
359 you have a headline at level 4 and you use ALT+RET to make a new
360 headline below it, it will cycle between levels 1 and 5, inclusive.
362 The main advantage of my custom =org-cycle-level= function is that it
363 is stateless: the next level in the cycle is determined entirely by
364 the contents of the buffer, and not what command you executed last.
365 This makes it more predictable, I hope.
367 #+BEGIN_SRC emacs-lisp
370 (defun org-point-at-end-of-empty-headline ()
371 "If point is at the end of an empty headline, return t, else nil."
372 (and (looking-at "[ \t]*$")
374 (beginning-of-line 1)
375 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
377 (defun org-level-increment ()
378 "Return the number of stars that will be added or removed at a
379 time to headlines when structure editing, based on the value of
380 `org-odd-levels-only'."
381 (if org-odd-levels-only 2 1))
383 (defvar org-previous-line-level-cached nil)
385 (defun org-recalculate-previous-line-level ()
386 "Same as `org-get-previous-line-level', but does not use cached
387 value. It does *set* the cached value, though."
388 (set 'org-previous-line-level-cached
389 (let ((current-level (org-current-level))
390 (prev-level (when (> (line-number-at-pos) 1)
393 (org-current-level)))))
394 (cond ((null current-level) nil) ; Before first headline
395 ((null prev-level) 0) ; At first headline
398 (defun org-get-previous-line-level ()
399 "Return the outline depth of the last headline before the
400 current line. Returns 0 for the first headline in the buffer, and
401 nil if before the first headline."
402 ;; This calculation is quite expensive, with all the regex searching
403 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
404 ;; the last value of this command.
405 (or (and (eq last-command 'org-cycle-level)
406 org-previous-line-level-cached)
407 (org-recalculate-previous-line-level)))
409 (defun org-cycle-level ()
411 (let ((org-adapt-indentation nil))
412 (when (org-point-at-end-of-empty-headline)
413 (setq this-command 'org-cycle-level) ;Only needed for caching
414 (let ((cur-level (org-current-level))
415 (prev-level (org-get-previous-line-level)))
417 ;; If first headline in file, promote to top-level.
419 (loop repeat (/ (- cur-level 1) (org-level-increment))
420 do (org-do-promote)))
421 ;; If same level as prev, demote one.
422 ((= prev-level cur-level)
424 ;; If parent is top-level, promote to top level if not already.
426 (loop repeat (/ (- cur-level 1) (org-level-increment))
427 do (org-do-promote)))
428 ;; If top-level, return to prev-level.
430 (loop repeat (/ (- prev-level 1) (org-level-increment))
432 ;; If less than prev-level, promote one.
433 ((< cur-level prev-level)
435 ;; If deeper than prev-level, promote until higher than
437 ((> cur-level prev-level)
438 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
439 do (org-do-promote))))
443 *** Count words in an Org buffer
444 # FIXME: Does not fit too well under Structure. Any idea where to put it?
445 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
447 #+begin_src emacs-lisp
448 (defun org-word-count (beg end
449 &optional count-latex-macro-args?
451 "Report the number of words in the Org mode buffer or selected region.
455 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
456 - hyperlinks (but does count words in hyperlink descriptions)
457 - tags, priorities, and TODO keywords in headers
458 - sections tagged as 'not for export'.
460 The text of footnote definitions is ignored, unless the optional argument
461 COUNT-FOOTNOTES? is non-nil.
463 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
464 includes LaTeX macro arguments (the material between {curly braces}).
465 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
469 (setf beg (point-min)
472 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
475 (while (< (point) end)
478 ((or (org-in-commented-line) (org-at-table-p))
480 ;; Ignore hyperlinks. But if link has a description, count
481 ;; the words within the description.
482 ((looking-at org-bracket-link-analytic-regexp)
483 (when (match-string-no-properties 5)
484 (let ((desc (match-string-no-properties 5)))
486 (incf wc (length (remove "" (org-split-string
488 (goto-char (match-end 0)))
489 ((looking-at org-any-link-re)
490 (goto-char (match-end 0)))
491 ;; Ignore source code blocks.
492 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
494 ;; Ignore inline source blocks, counting them as 1 word.
497 (looking-at org-babel-inline-src-block-regexp))
498 (goto-char (match-end 0))
500 ;; Count latex macros as 1 word, ignoring their arguments.
503 (looking-at latex-macro-regexp))
504 (goto-char (if count-latex-macro-args?
509 ((and (not count-footnotes?)
510 (or (org-footnote-at-definition-p)
511 (org-footnote-at-reference-p)))
514 (let ((contexts (org-context)))
516 ;; Ignore tags and TODO keywords, etc.
517 ((or (assoc :todo-keyword contexts)
518 (assoc :priority contexts)
519 (assoc :keyword contexts)
520 (assoc :checkbox contexts))
522 ;; Ignore sections marked with tags that are
523 ;; excluded from export.
524 ((assoc :tags contexts)
525 (if (intersection (org-get-tags-at) org-export-exclude-tags
527 (org-forward-same-level 1)
531 (re-search-forward "\\w+\\W*")))
532 (message (format "%d words in %s." wc
533 (if mark-active "region" "buffer")))))
536 *** Check for misplaced SCHEDULED and DEADLINE cookies
538 The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
539 below* the headline -- like this:
543 SCHEDULED: <2012-04-09 lun.>
546 This is what =org-scheduled= and =org-deadline= (and other similar
547 commands) do. And the manual explicitely tell people to stick to this
548 format (see the section "8.3.1 Inserting deadlines or schedules").
550 If you think you might have subtrees with misplaced =SCHEDULED= and
551 =DEADLINE= cookies, this command lets you check the current buffer:
553 #+begin_src emacs-lisp
554 (defun org-check-misformatted-subtree ()
555 "Check misformatted entries in the current buffer."
560 (when (and (move-beginning-of-line 2)
561 (not (looking-at org-heading-regexp)))
562 (if (or (and (org-get-scheduled-time (point))
563 (not (looking-at (concat "^.*" org-scheduled-regexp))))
564 (and (org-get-deadline-time (point))
565 (not (looking-at (concat "^.*" org-deadline-regexp)))))
566 (when (y-or-n-p "Fix this subtree? ")
567 (message "Call the function again when you're done fixing this subtree.")
569 (message "All subtrees checked."))))))
572 *** Sorting list by checkbox type
574 #+index: checkbox!sorting
576 You can use a custom function to sort list by checkbox type.
577 Here is a function suggested by Carsten:
579 #+BEGIN_SRC emacs-lisp
580 (defun org-sort-list-by-checkbox-type ()
581 "Sort list items according to Checkbox state."
586 (if (looking-at org-list-full-item-re)
587 (cdr (assoc (match-string 3)
588 '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
592 Use the function above directly on the list. If you want to use an
593 equivalent function after =C-c ^ f=, use this one instead:
595 #+BEGIN_SRC emacs-lisp
596 (defun org-sort-list-by-checkbox-type-1 ()
598 (if (looking-at org-list-full-item-re)
599 (cdr (assoc (match-string 3)
600 '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
604 *** Adding Licenses to org files
606 You can add pretty standard licenses, such as creative commons or gfdl
607 to org articles using =org-license.el=.
614 *** Align all tables in a file
616 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
618 #+begin_src emacs-lisp
619 (defun my-align-all-tables ()
621 (org-table-map-tables 'org-table-align 'quietly))
626 :CUSTOM_ID: transpose-table
628 #+index: Table!Calculation
630 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
631 see.) There are also other solutions:
633 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
634 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]]
636 - with org-babel and R: provided by Dan Davison in the mailing list (old
637 =#+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]]
639 - with field coordinates in formulas (=@#= and =$#=): see [[#field-coordinates-in-formulas-transpose-table][Worg]].
641 *** Manipulate hours/minutes/seconds in table formulas
642 #+index: Table!hours-minutes-seconds
643 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
644 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
645 "=d=" is any digit) as time values in Org-mode table formula. These
646 functions have now been wrapped up into a =with-time= macro which can
647 be used in table formula to translate table cell values to and from
648 numerical values for algebraic manipulation.
650 Here is the code implementing this macro.
651 #+begin_src emacs-lisp :results silent
652 (defun org-time-string-to-seconds (s)
653 "Convert a string HH:MM:SS to a number of seconds."
656 (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
657 (let ((hour (string-to-number (match-string 1 s)))
658 (min (string-to-number (match-string 2 s)))
659 (sec (string-to-number (match-string 3 s))))
660 (+ (* hour 3600) (* min 60) sec)))
662 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
663 (let ((min (string-to-number (match-string 1 s)))
664 (sec (string-to-number (match-string 2 s))))
666 ((stringp s) (string-to-number s))
669 (defun org-time-seconds-to-string (secs)
670 "Convert a number of seconds to a time string."
671 (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
672 ((>= secs 60) (format-seconds "%m:%.2s" secs))
673 (t (format-seconds "%s" secs))))
675 (defmacro with-time (time-output-p &rest exprs)
676 "Evaluate an org-table formula, converting all fields that look
677 like time data to integer seconds. If TIME-OUTPUT-P then return
678 the result as a time value."
680 (if time-output-p 'org-time-seconds-to-string 'identity)
688 (list 'with-time nil el)
689 (org-time-string-to-seconds el)))
694 Which allows the following forms of table manipulation such as adding
695 and subtracting time values.
696 : | Date | Start | Lunch | Back | End | Sum |
697 : |------------------+-------+-------+-------+-------+------|
698 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
699 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
701 and dividing time values by integers
702 : | time | miles | minutes/mile |
703 : |-------+-------+--------------|
704 : | 34:43 | 2.9 | 11:58 |
705 : | 32:15 | 2.77 | 11:38 |
706 : | 33:56 | 3.0 | 11:18 |
707 : | 52:22 | 4.62 | 11:20 |
708 : #+TBLFM: $3='(with-time t (/ $1 $2))
710 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
711 Elisp formulas) to compute time durations. For example:
713 : | Task 1 | Task 2 | Total |
714 : |--------+--------+---------|
715 : | 35:00 | 35:00 | 1:10:00 |
716 : #+TBLFM: @2$3=$1+$2;T
718 *** Dates computation
720 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of
721 dates stored in an org table.
723 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
727 : | Start Date | End Date | Duration |
728 : |------------+------------+----------|
729 : | 2004.08.07 | 2005.07.08 | 335 |
730 : #+TBLFM: $3=(date(<$2>)-date(<$1>))
732 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
733 above). The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
734 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
737 #+index: Table!Calculation
738 As with Times computation, the following code allows Computation with
739 Hex values in Org-mode tables using the =with-hex= macro.
741 Here is the code implementing this macro.
742 #+begin_src emacs-lisp
743 (defun org-hex-strip-lead (str)
744 (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
745 (substring str 2) str))
747 (defun org-hex-to-hex (int)
750 (defun org-hex-to-dec (str)
753 (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
757 (setf out (+ (* out 16)
758 (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
759 (coerce (match-string 1 str) 'list))
761 ((stringp str) (string-to-number str))
764 (defmacro with-hex (hex-output-p &rest exprs)
765 "Evaluate an org-table formula, converting all fields that look
766 like hexadecimal to decimal integers. If HEX-OUTPUT-P then
767 return the result as a hex value."
769 (if hex-output-p 'org-hex-to-hex 'identity)
776 (list 'with-hex nil el)
777 (org-hex-to-dec el)))
782 Which allows the following forms of table manipulation such as adding
783 and subtracting hex values.
784 | 0x10 | 0x0 | #ERROR | #ERROR |
785 | 0x20 | 0x1 | #ERROR | #ERROR |
786 | 0x30 | 0x2 | #ERROR | #ERROR |
787 | 0xf0 | 0xf | #ERROR | #ERROR |
788 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
790 *** Field coordinates in formulas (=@#= and =$#=)
792 :CUSTOM_ID: field-coordinates-in-formulas
794 #+index: Table!Field Coordinates
797 Following are some use cases that can be implemented with the “field
798 coordinates in formulas” described in the corresponding chapter in the
799 [[https://orgmode.org/manual/References.html#References][Org manual]].
801 **** Copy a column from a remote table into a column
803 :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
806 current column =$3= = remote column =$2=:
807 : #+TBLFM: $3 = remote(FOO, @@#$2)
809 **** Copy a row from a remote table transposed into a column
811 :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
814 current column =$1= = transposed remote row =@1=:
815 : #+TBLFM: $1 = remote(FOO, @$#$@#)
819 :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
824 This is more like a demonstration of using “field coordinates in formulas”
825 and is bound to be slow for large tables. See the discussion in the mailing
827 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
828 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
829 For more efficient solutions see
830 [[#transpose-table][Worg]].
832 To transpose this 4x7 table
835 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
836 : |------+------+------+------+------+------+------|
837 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
838 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
839 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
841 start with a 7x4 table without any horizontal line (to have filled
842 also the column header) and yet empty:
852 Then add the =TBLFM= line below. After recalculation this will end up with
855 : | year | min | avg | max |
856 : | 2004 | 401 | 402 | 403 |
857 : | 2005 | 501 | 502 | 503 |
858 : | 2006 | 601 | 602 | 603 |
859 : | 2007 | 701 | 702 | 703 |
860 : | 2008 | 801 | 802 | 803 |
861 : | 2009 | 901 | 902 | 903 |
862 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
864 The formula simply exchanges row and column numbers by taking
865 - the absolute remote row number =@$#= from the current column number =$#=
866 - the absolute remote column number =$@#= from the current row number =@#=
868 Formulas to be taken over from the remote table will have to be transformed
871 **** Dynamic variation of ranges
875 In this example all columns next to =quote= are calculated from the column
876 =quote= and show the average change of the time series =quote[year]=
877 during the period of the preceding =1=, =2=, =3= or =4= years:
879 : | year | quote | 1 a | 2 a | 3 a | 4 a |
880 : |------+-------+-------+-------+-------+-------|
881 : | 2005 | 10 | | | | |
882 : | 2006 | 12 | 0.200 | | | |
883 : | 2007 | 14 | 0.167 | 0.183 | | |
884 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
885 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
886 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
888 The important part of the formula without the field blanking is:
890 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
892 which is the Emacs Calc implementation of the equation
894 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
896 where /i/ is the current time and /a/ is the length of the preceding period.
898 *** Rearrange one or more field within the same row or column
900 :CUSTOM_ID: field-same-row-or-column
902 #+index: Table!Editing
906 **** Rearrange the column sequence in one row only
908 :CUSTOM_ID: column-sequence-in-row
910 #+index: Table!Editing
912 The functions below can be used to change the column sequence in one
913 row only, without affecting the other rows above and below like with
914 =M-<left>= or =M-<right>= (=org-table-move-column=). See also the
915 docstring of the functions for more explanations. The original table
916 that serves as the starting point for the examples:
919 : | e | 9 | 10 | 11 |
922 ***** Move current field in row
925 1) place point at "10" in original table
926 2) =M-x f-org-table-move-field-in-row-left=
927 3) point is at moved "10"
930 : | e | 10 | 9 | 11 |
935 1) place point at "9" in original table
936 2) =M-x f-org-table-move-field-in-row-right=
937 3) point is at moved "9"
940 : | e | 10 | 9 | 11 |
943 ***** Rotate rest of row (range from current field to end of row)
946 1) place point at @2$2 in original table
947 2) =M-x f-org-table-rotate-rest-of-row-left=
948 3) point is still at @2$2
951 : | e | 10 | 11 | 9 |
956 1) place point at @2$2 in original table
957 2) =M-x f-org-table-rotate-rest-of-row-right=
958 3) point is still at @2$2
961 : | e | 11 | 9 | 10 |
964 ***** Open field in row (table size grows)
966 This is just for completeness, interactively the same as typing =|
969 1) place point at @2$2 in original table
970 2) =M-x f-org-table-open-field-in-row-grow=
971 3) point is still at @2$2
973 : | a | b | c | d | |
974 : | e | | 9 | 10 | 11 |
975 : | f | g | h | i | |
977 **** Rearrange the row sequence in one column only
979 :CUSTOM_ID: row-sequence-in-column
981 #+index: Table!Editing
983 The functions below can be used to change the column sequence in one
984 column only, without affecting the other columns left and right like
985 with =M-<up>= or =M-<down>= (=org-table-move-row=). See also the
986 docstring of the functions for more explanations. The original table
987 that serves as the starting point for the examples:
996 ***** Move current field in column
999 1) place point at "10" in original table
1000 2) =M-x f-org-table-move-field-in-column-up=
1001 3) point is at moved "10"
1012 1) place point at "9" in original table
1013 2) =M-x f-org-table-move-field-in-column-down=
1014 3) point is at moved "9"
1023 ***** Rotate rest of column (range from current field to end of column)
1026 1) place point at @2$2 in original table
1027 2) =M-x f-org-table-rotate-rest-of-column-up=
1028 3) point is still at @2$2
1039 1) place point at @2$2 in original table
1040 2) =M-x f-org-table-rotate-rest-of-column-down=
1041 3) point is still at @2$2
1050 ***** Open field in column (table size grows)
1052 1) place point at @2$2 in original table
1053 2) =M-x f-org-table-open-field-in-column-grow=
1054 3) point is still at @2$2
1064 **** Key bindings for some of the functions
1066 I have this in an Org buffer to change temporarily to the desired
1067 behavior with =C-c C-c= on one of the three code snippets:
1070 : #+begin_src emacs-lisp :results silent
1071 : (org-defkey org-mode-map [(meta left)]
1072 : 'f-org-table-move-field-in-row-left)
1073 : (org-defkey org-mode-map [(meta right)]
1074 : 'f-org-table-move-field-in-row-right)
1075 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
1076 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
1080 : #+begin_src emacs-lisp :results silent
1081 : (org-defkey org-mode-map [(meta left)]
1082 : 'f-org-table-rotate-rest-of-row-left)
1083 : (org-defkey org-mode-map [(meta right)]
1084 : 'f-org-table-rotate-rest-of-row-right)
1085 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
1086 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
1089 : - back to original:
1090 : #+begin_src emacs-lisp :results silent
1091 : (org-defkey org-mode-map [(meta left)] 'org-metaleft)
1092 : (org-defkey org-mode-map [(meta right)] 'org-metaright)
1093 : (org-defkey org-mode-map [(left)] 'backward-char)
1094 : (org-defkey org-mode-map [(right)] 'forward-char)
1101 : f-org-table-move-field-in-column-up
1102 : f-org-table-move-field-in-column-down
1103 : f-org-table-rotate-rest-of-column-up
1104 : f-org-table-rotate-rest-of-column-down
1106 are not yet implemented. They could be done similar to
1107 =f-org-table-open-field-in-column-grow=. A workaround without keeping
1108 horizontal separator lines is to interactively or programmatically
1111 1) Transpose the table, see
1112 [[#transpose-table][Org hacks]].
1113 2) Use =f-org-table-*-column-in-row-*=, see
1114 [[https://orgmode.org/worg/org-hacks.html#column-sequence-in-row][previous
1116 3) Transpose the table.
1118 The other functions:
1120 #+BEGIN_SRC emacs-lisp
1121 (defun f-org-table-move-field-in-row-left ()
1122 "Move current field in row to the left."
1124 (f-org-table-move-field-in-row 'left))
1125 (defun f-org-table-move-field-in-row-right ()
1126 "Move current field in row to the right."
1128 (f-org-table-move-field-in-row nil))
1130 (defun f-org-table-move-field-in-row (&optional left)
1131 "Move current field in row to the right.
1132 With arg LEFT, move to the left. For repeated invocation the
1133 point follows the moved field. Does not fix formulas."
1134 ;; Derived from `org-table-move-column'
1136 (if (not (org-at-table-p))
1137 (error "Not at a table"))
1138 (org-table-find-dataline)
1139 (org-table-check-inside-data-field)
1140 (let* ((col (org-table-current-column))
1141 (col1 (if left (1- col) col))
1142 ;; Current cursor position
1143 (colpos (if left (1- col) (1+ col))))
1144 (if (and left (= col 1))
1145 (error "Cannot move column further left"))
1146 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1147 (error "Cannot move column further right"))
1148 (org-table-goto-column col1 t)
1149 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1150 (replace-match "|\\2|\\1|"))
1151 (org-table-goto-column colpos)
1154 (defun f-org-table-rotate-rest-of-row-left ()
1155 "Rotate rest of row to the left."
1157 (f-org-table-rotate-rest-of-row 'left))
1158 (defun f-org-table-rotate-rest-of-row-right ()
1159 "Rotate rest of row to the right."
1161 (f-org-table-rotate-rest-of-row nil))
1163 (defun f-org-table-rotate-rest-of-row (&optional left)
1164 "Rotate rest of row to the right.
1165 With arg LEFT, rotate to the left. For both directions the
1166 boundaries of the rotation range are the current field and the
1167 field at the end of the row. For repeated invocation the point
1168 stays on the original current field. Does not fix formulas."
1169 ;; Derived from `org-table-move-column'
1171 (if (not (org-at-table-p))
1172 (error "Not at a table"))
1173 (org-table-find-dataline)
1174 (org-table-check-inside-data-field)
1175 (let ((col (org-table-current-column)))
1176 (org-table-goto-column col t)
1177 (and (looking-at (if left
1178 "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
1179 "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
1180 (replace-match "|\\2|\\1|"))
1181 (org-table-goto-column col)
1184 (defun f-org-table-open-field-in-row-grow ()
1185 "Open field in row, move fields to the right by growing table."
1191 (defun f-org-table-open-field-in-column-grow ()
1192 "Open field in column, move all fields downwards by growing table."
1194 (let ((col (org-table-current-column))
1196 ;; Cut all fields downwards in same column
1197 (goto-char (org-table-end))
1199 (while (org-at-table-hline-p) (forward-line -1))
1200 (org-table-goto-column col)
1201 (org-table-cut-region p (point))
1202 ;; Paste at one field below
1205 (org-table-goto-column col)
1206 (org-table-paste-rectangle)
1211 **** Reasons why this is not put into the Org core
1213 I consider this as only a hack for several reasons:
1215 - Generalization: The existing function =org-table-move-column= could
1216 be enhanced with additional optional parameters to incorporate these
1217 functionalities and could be used as the only function for better
1218 maintainability. Now it's only a copy/paste hack of several similar
1219 functions with simple modifications.
1220 - Bindings: Should be convenient for repetition like =M-<right>=.
1221 What should be bound where, what has to be left unbound?
1222 - Does not fix formulas. Could be resolved for field formulas but
1223 most probably not for column or range formulas and this can lead to
1224 confusion. AFAIK all table manipulations found in Org core fix
1226 - Completeness: Not all variations and combinations are covered yet
1227 - move, rotate with range to end, rotate with range to begin, rotate
1229 - left-right, up-down
1231 ** Capture and Remember
1232 *** Customize the size of the frame for remember
1233 #+index: Remember!frame
1234 #+index: Customization!remember
1235 (Note: this hack is likely out of date due to the development of
1238 # FIXME: gmane link?
1239 On emacs-orgmode, Ryan C. Thompson suggested this:
1242 I am using org-remember set to open a new frame when used,
1243 and the default frame size is much too large. To fix this, I have
1244 designed some advice and a custom variable to implement custom
1245 parameters for the remember frame:
1248 #+begin_src emacs-lisp
1249 (defcustom remember-frame-alist nil
1250 "Additional frame parameters for dedicated remember frame."
1254 (defadvice remember (around remember-frame-parameters activate)
1255 "Set some frame parameters for the remember frame."
1256 (let ((default-frame-alist (append remember-frame-alist
1257 default-frame-alist)))
1261 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1262 reasonable size for the frame.
1263 *** [[https://github.com/PhilHudson/org-capture-vars.el][User-defined capture template variables with prompt and completion list]]
1265 *** [[#heading-to-link][Turn a heading into an org link]]
1266 *** Quickaccess to the link part of hyperlinks
1267 #+index: Link!Referent
1268 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1269 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1270 which is indeed kind of cumbersome.
1272 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1274 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1275 #+begin_src emacs-lisp
1277 (lambda (&optional arg)
1280 (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1284 #+begin_src emacs-lisp
1285 (defun my-org-extract-link ()
1286 "Extract the link location at point and put it on the killring."
1288 (when (org-in-regexp org-bracket-link-regexp 1)
1289 (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1292 They put the link destination on the killring and can be easily bound to a key.
1294 *** Insert link with HTML title as default description
1295 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1296 from HTML <title> tag and use it as a default link description. Here is a way to
1299 #+begin_src emacs-lisp
1300 (require 'mm-url) ; to include mm-url-decode-entities-string
1302 (defun my-org-insert-link ()
1303 "Insert org link where default description is set to html title."
1305 (let* ((url (read-string "URL: "))
1306 (title (get-html-title-from-url url)))
1307 (org-insert-link nil url title)))
1309 (defun get-html-title-from-url (url)
1310 "Return content in <title> tag."
1311 (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1313 (set-buffer download-buffer)
1314 (beginning-of-buffer)
1315 (setq x1 (search-forward "<title>"))
1316 (search-forward "</title>")
1317 (setq x2 (search-backward "<"))
1318 (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1321 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1323 ** Archiving Content in Org-Mode
1324 *** Preserve top level headings when archiving to a file
1325 #+index: Archiving!Preserve top level headings
1328 To preserve (somewhat) the integrity of your archive structure while
1329 archiving lower level items to a file, you can use the following
1332 #+begin_src emacs-lisp
1333 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1334 (let ((org-archive-location
1335 (if (save-excursion (org-back-to-heading)
1336 (> (org-outline-level) 1))
1337 (concat (car (split-string org-archive-location "::"))
1339 (car (org-get-outline-path)))
1340 org-archive-location)))
1344 Thus, if you have an outline structure such as...
1352 ...archiving "Subsubheading" to a new file will set the location in
1353 the new file to the top level heading:
1360 While this hack obviously destroys the outline hierarchy somewhat, it
1361 at least preserves the logic of level one groupings.
1363 A slightly more complex version of this hack will not only keep the
1364 archive organized by top-level headings, but will also preserve the
1365 tags found on those headings:
1367 #+begin_src emacs-lisp
1368 (defun my-org-inherited-no-file-tags ()
1369 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1370 (ltags (org-entry-get nil "TAGS")))
1373 (replace-regexp-in-string (concat tag ":") "" tags)))
1374 (append org-file-tags (when ltags (split-string ltags ":" t))))
1375 (if (string= ":" tags) nil tags)))
1377 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1378 (let ((tags (my-org-inherited-no-file-tags))
1379 (org-archive-location
1380 (if (save-excursion (org-back-to-heading)
1381 (> (org-outline-level) 1))
1382 (concat (car (split-string org-archive-location "::"))
1384 (car (org-get-outline-path)))
1385 org-archive-location)))
1387 (with-current-buffer (find-file-noselect (org-extract-archive-file))
1389 (while (org-up-heading-safe))
1390 (org-set-tags-to tags)))))
1393 *** Archive in a date tree
1394 #+index: Archiving!date tree
1395 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1397 (Make sure org-datetree.el is loaded for this to work.)
1399 #+begin_src emacs-lisp
1400 ;; (setq org-archive-location "%s_archive::date-tree")
1401 (defadvice org-archive-subtree
1402 (around org-archive-subtree-to-data-tree activate)
1403 "org-archive-subtree to date-tree"
1405 (string= "date-tree"
1406 (org-extract-archive-heading
1407 (org-get-local-archive-location)))
1408 (let* ((dct (decode-time (org-current-time)))
1412 (this-buffer (current-buffer))
1413 (location (org-get-local-archive-location))
1414 (afile (org-extract-archive-file location))
1415 (org-archive-location
1416 (format "%s::*** %04d-%02d-%02d %s" afile y m d
1417 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1418 (message "afile=%s" afile)
1420 (error "Invalid `org-archive-location'"))
1422 (switch-to-buffer (find-file-noselect afile))
1423 (org-datetree-find-year-create y)
1424 (org-datetree-find-month-create y m)
1425 (org-datetree-find-day-create y m d)
1427 (switch-to-buffer this-buffer))
1432 *** Add inherited tags to archived entries
1433 #+index: Archiving!Add inherited tags
1434 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1435 advise the function like this:
1438 (defadvice org-archive-subtree
1439 (before add-inherited-tags-before-org-archive-subtree activate)
1440 "add inherited tags before org-archive-subtree"
1441 (org-set-tags-to (org-get-tags-at)))
1444 ** Using and Managing Org-Metadata
1445 *** Remove redundant tags of headlines
1446 #+index: Tag!Remove redundant
1449 A small function that processes all headlines in current buffer and
1450 removes tags that are local to a headline and inherited by a parent
1451 headline or the #+FILETAGS: statement.
1453 #+BEGIN_SRC emacs-lisp
1454 (defun dmj/org-remove-redundant-tags ()
1455 "Remove redundant tags of headlines in current buffer.
1457 A tag is considered redundant if it is local to a headline and
1458 inherited by a parent headline."
1460 (when (eq major-mode 'org-mode)
1464 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1465 local inherited tag)
1466 (dolist (tag alltags)
1467 (if (get-text-property 0 'inherited tag)
1468 (push tag inherited) (push tag local)))
1470 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1474 *** Remove empty property drawers
1475 #+index: Drawer!Empty
1476 David Maus proposed this:
1478 #+begin_src emacs-lisp
1479 (defun dmj:org:remove-empty-propert-drawers ()
1480 "*Remove all empty property drawers in current file."
1482 (unless (eq major-mode 'org-mode)
1483 (error "You need to turn on Org mode for this function."))
1485 (goto-char (point-min))
1486 (while (re-search-forward ":PROPERTIES:" nil t)
1488 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1491 *** Group task list by a property
1492 #+index: Agenda!Group task list
1493 This advice allows you to group a task list in Org-Mode. To use it,
1494 set the variable =org-agenda-group-by-property= to the name of a
1495 property in the option list for a TODO or TAGS search. The resulting
1496 agenda view will group tasks by that property prior to searching.
1498 #+begin_src emacs-lisp
1499 (defvar org-agenda-group-by-property nil
1500 "Set this in org-mode agenda views to group tasks by property")
1502 (defun org-group-bucket-items (prop items)
1504 (dolist (item items)
1505 (let* ((marker (get-text-property 0 'org-marker item))
1506 (pvalue (org-entry-get marker prop t))
1507 (cell (assoc pvalue buckets)))
1509 (setcdr cell (cons item (cdr cell)))
1510 (setq buckets (cons (cons pvalue (list item))
1512 (setq buckets (mapcar (lambda (bucket)
1514 (reverse (cdr bucket))))
1516 (sort buckets (lambda (i1 i2)
1517 (string< (car i1) (car i2))))))
1519 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1520 (list &optional nosort))
1521 "Prepare bucketed agenda entry lists"
1522 (if org-agenda-group-by-property
1523 ;; bucketed, handle appropriately
1525 (dolist (bucket (org-group-bucket-items
1526 org-agenda-group-by-property
1528 (let ((header (concat "Property "
1529 org-agenda-group-by-property
1531 (or (car bucket) "<nil>") ":\n")))
1532 (add-text-properties 0 (1- (length header))
1533 (list 'face 'org-agenda-structure)
1537 ;; recursively process
1538 (let ((org-agenda-group-by-property nil))
1539 (org-finalize-agenda-entries
1540 (cdr bucket) nosort))
1542 (setq ad-return-value text))
1544 (ad-activate 'org-finalize-agenda-entries)
1546 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1549 Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1551 A small hook run when clocking out of a task that prompts for a note
1552 when the tag "=clockout_note=" is found in a headline. It uses the tag
1553 ("=clockout_note=") so inheritance can also be used...
1555 #+begin_src emacs-lisp
1556 (defun rgr/check-for-clock-out-note()
1559 (org-back-to-heading)
1560 (let ((tags (org-get-tags)))
1561 (and tags (message "tags: %s " tags)
1562 (when (member "clocknote" tags)
1565 (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1567 *** Dynamically adjust tag position
1568 #+index: Tag!position
1569 Here is a bit of code that allows you to have the tags always
1570 right-adjusted in the buffer.
1572 This is useful when you have bigger window than default window-size
1573 and you dislike the aesthetics of having the tag in the middle of the
1576 This hack solves the problem of adjusting it whenever you change the
1578 Before saving it will revert the file to having the tag position be
1579 left-adjusted so that if you track your files with version control,
1580 you won't run into artificial diffs just because the window-size
1583 *IMPORTANT*: This is probably slow on very big files.
1585 #+begin_src emacs-lisp
1586 (setq ba/org-adjust-tags-column t)
1588 (defun ba/org-adjust-tags-column-reset-tags ()
1589 "In org-mode buffers it will reset tag position according to
1592 (not (string= (buffer-name) "*Remember*"))
1593 (eql major-mode 'org-mode))
1594 (let ((b-m-p (buffer-modified-p)))
1597 (goto-char (point-min))
1598 (command-execute 'outline-next-visible-heading)
1599 ;; disable (message) that org-set-tags generates
1600 (flet ((message (&rest ignored) nil))
1602 (set-buffer-modified-p b-m-p))
1605 (defun ba/org-adjust-tags-column-now ()
1606 "Right-adjust `org-tags-column' value, then reset tag position."
1607 (set (make-local-variable 'org-tags-column)
1608 (- (- (window-width) (length org-ellipsis))))
1609 (ba/org-adjust-tags-column-reset-tags))
1611 (defun ba/org-adjust-tags-column-maybe ()
1612 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1613 (when ba/org-adjust-tags-column
1614 (ba/org-adjust-tags-column-now)))
1616 (defun ba/org-adjust-tags-column-before-save ()
1617 "Tags need to be left-adjusted when saving."
1618 (when ba/org-adjust-tags-column
1619 (setq org-tags-column 1)
1620 (ba/org-adjust-tags-column-reset-tags)))
1622 (defun ba/org-adjust-tags-column-after-save ()
1623 "Revert left-adjusted tag position done by before-save hook."
1624 (ba/org-adjust-tags-column-maybe)
1625 (set-buffer-modified-p nil))
1627 ; automatically align tags on right-hand side
1628 (add-hook 'window-configuration-change-hook
1629 'ba/org-adjust-tags-column-maybe)
1630 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1631 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1632 (add-hook 'org-agenda-mode-hook (lambda ()
1633 (setq org-agenda-tags-column (- (window-width)))))
1635 ; between invoking org-refile and displaying the prompt (which
1636 ; triggers window-configuration-change-hook) tags might adjust,
1637 ; which invalidates the org-refile cache
1638 (defadvice org-refile (around org-refile-disable-adjust-tags)
1639 "Disable dynamically adjusting tags"
1640 (let ((ba/org-adjust-tags-column nil))
1642 (ad-activate 'org-refile)
1644 *** Use an "attach" link type to open files without worrying about their location
1645 #+index: Link!Attach
1646 -- Darlan Cavalcante Moreira
1648 In the setup part in my org-files I put:
1651 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1654 Now I can use the "attach" link type, but org will ask me if I want to
1655 allow executing the elisp code. To avoid this you can even set
1656 org-confirm-elisp-link-function to nil (I don't like this because it allows
1657 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1662 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1664 This works very well.
1666 ** Org Agenda and Task Management
1667 *** Make it easier to set org-agenda-files from multiple directories
1668 #+index: Agenda!Files
1671 #+begin_src emacs-lisp
1672 (defun my-org-list-files (dirs ext)
1673 "Function to create list of org files in multiple subdirectories.
1674 This can be called to generate a list of files for
1675 org-agenda-files or org-refile-targets.
1677 DIRS is a list of directories.
1679 EXT is a list of the extensions of files to be included."
1680 (let ((dirs (if (listp dirs)
1683 (ext (if (listp ext)
1693 (file-expand-wildcards
1694 (concat (file-name-as-directory x) "*" y)))))
1699 (when (or (string-match "/.#" x)
1700 (string-match "#$" x))
1701 (setq files (delete x files))))
1705 (defvar my-org-agenda-directories '("~/org/")
1706 "List of directories containing org files.")
1707 (defvar my-org-agenda-extensions '(".org")
1708 "List of extensions of agenda files")
1710 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1711 (setq my-org-agenda-extensions '(".org" ".ref"))
1713 (defun my-org-set-agenda-files ()
1715 (setq org-agenda-files (my-org-list-files
1716 my-org-agenda-directories
1717 my-org-agenda-extensions)))
1719 (my-org-set-agenda-files)
1722 The code above will set your "default" agenda files to all files
1723 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1724 You can change these values by setting the variables
1725 my-org-agenda-extensions and my-org-agenda-directories. The function
1726 my-org-agenda-files-by-filetag uses these two variables to determine
1727 which files to search for filetags (i.e., the larger set from which
1728 the subset will be drawn).
1730 You can also easily use my-org-list-files to "mix and match"
1731 directories and extensions to generate different lists of agenda
1734 *** Restrict org-agenda-files by filetag
1736 :CUSTOM_ID: set-agenda-files-by-filetag
1738 #+index: Agenda!Files
1741 It is often helpful to limit yourself to a subset of your agenda
1742 files. For instance, at work, you might want to see only files related
1743 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1744 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
1745 commands]]. These solutions, however, require reapplying a filter each
1746 time you call the agenda or writing several new custom agenda commands
1747 for each context. Another solution is to use directories for different
1748 types of tasks and to change your agenda files with a function that
1749 sets org-agenda-files to the appropriate directory. But this relies on
1750 hard and static boundaries between files.
1752 The following functions allow for a more dynamic approach to selecting
1753 a subset of files based on filetags:
1755 #+begin_src emacs-lisp
1756 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1757 "Restrict org agenda files only to those containing filetag."
1759 (let* ((tagslist (my-org-get-all-filetags))
1761 (completing-read "Tag: "
1762 (mapcar 'car tagslist)))))
1763 (org-agenda-remove-restriction-lock 'noupdate)
1764 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1765 (setq org-agenda-overriding-restriction 'files)))
1767 (defun my-org-get-all-filetags ()
1768 "Get list of filetags from all default org-files."
1769 (let ((files org-agenda-files)
1771 (save-window-excursion
1772 (while (setq x (pop files))
1773 (set-buffer (find-file-noselect x))
1776 (let ((tagfiles (assoc y tagslist)))
1778 (setcdr tagfiles (cons x (cdr tagfiles)))
1779 (add-to-list 'tagslist (list y x)))))
1780 (my-org-get-filetags)))
1783 (defun my-org-get-filetags ()
1784 "Get list of filetags for current buffer"
1785 (let ((ftags org-file-tags)
1789 (org-substring-no-properties x))
1793 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1794 with all filetags in your "normal" agenda files. When you select a
1795 tag, org-agenda-files will be restricted to only those files
1796 containing the filetag. To release the restriction, type C-c C-x >
1797 (org-agenda-remove-restriction-lock).
1799 *** Highlight the agenda line under cursor
1800 #+index: Agenda!Highlight
1801 This is useful to make sure what task you are operating on.
1803 #+BEGIN_SRC emacs-lisp
1804 (add-hook 'org-agenda-mode-hook (lambda () (hl-line-mode 1)))
1809 #+BEGIN_SRC emacs-lisp
1810 ;; hl-line seems to be only for emacs
1812 (add-hook 'org-agenda-mode-hook (lambda () (highline-mode 1)))
1814 ;; highline-mode does not work straightaway in tty mode.
1815 ;; I use a black background
1817 '(highline-face ((((type tty) (class color))
1818 (:background "white" :foreground "black")))))
1821 *** Split frame horizontally for agenda
1822 #+index: Agenda!frame
1823 If you would like to split the frame into two side-by-side windows when
1824 displaying the agenda, try this hack from Jan Rehders, which uses the
1825 `toggle-window-split' from
1827 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1829 #+BEGIN_SRC emacs-lisp
1830 ;; Patch org-mode to use vertical splitting
1831 (defadvice org-prepare-agenda (after org-fix-split)
1832 (toggle-window-split))
1833 (ad-activate 'org-prepare-agenda)
1836 *** Automatically add an appointment when clocking in a task
1837 #+index: Clock!Automatically add an appointment when clocking in a task
1838 #+index: Appointment!Automatically add an appointment when clocking in a task
1839 #+BEGIN_SRC emacs-lisp
1840 ;; Make sure you have a sensible value for `appt-message-warning-time'
1841 (defvar bzg-org-clock-in-appt-delay 100
1842 "Number of minutes for setting an appointment by clocking-in")
1845 This function let's you add an appointment for the current entry.
1846 This can be useful when you need a reminder.
1848 #+BEGIN_SRC emacs-lisp
1849 (defun bzg-org-clock-in-add-appt (&optional n)
1850 "Add an appointment for the Org entry at point in N minutes."
1853 (org-back-to-heading t)
1854 (looking-at org-complex-heading-regexp)
1855 (let* ((msg (match-string-no-properties 4))
1856 (ct-time (decode-time))
1857 (appt-min (+ (cadr ct-time)
1858 (or n bzg-org-clock-in-appt-delay)))
1859 (appt-time ; define the time for the appointment
1860 (progn (setf (cadr ct-time) appt-min) ct-time)))
1861 (appt-add (format-time-string
1862 "%H:%M" (apply 'encode-time appt-time)) msg)
1863 (if (interactive-p) (message "New appointment for %s" msg)))))
1866 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1869 #+BEGIN_SRC emacs-lisp
1870 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1871 "Add an appointment when clocking a task in."
1872 (bzg-org-clock-in-add-appt))
1875 You may also want to delete the associated appointment when clocking
1876 out. This function does this:
1878 #+BEGIN_SRC emacs-lisp
1879 (defun bzg-org-clock-out-delete-appt nil
1880 "When clocking out, delete any associated appointment."
1883 (org-back-to-heading t)
1884 (looking-at org-complex-heading-regexp)
1885 (let* ((msg (match-string-no-properties 4)))
1886 (setq appt-time-msg-list
1890 (if (not (string-match (regexp-quote msg)
1891 (cadr appt))) appt))
1892 appt-time-msg-list)))
1896 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1898 #+BEGIN_SRC emacs-lisp
1899 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1900 "Delete an appointment when clocking a task out."
1901 (bzg-org-clock-out-delete-appt))
1904 *IMPORTANT*: You can add appointment by clocking in in both an
1905 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1906 agenda buffer with the advice above will bring an error.
1908 *** Using external programs for appointments reminders
1909 #+index: Appointment!reminders
1910 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1912 *** Remove from agenda time grid lines that are in an appointment
1913 #+index: Agenda!time grid
1914 #+index: Appointment!Remove from agenda time grid lines
1915 The agenda shows lines for the time grid. Some people think that
1916 these lines are a distraction when there are appointments at those
1917 times. You can get rid of the lines which coincide exactly with the
1918 beginning of an appointment. Michael Ekstrand has written a piece of
1919 advice that also removes lines that are somewhere inside an
1922 #+begin_src emacs-lisp
1923 (defun org-time-to-minutes (time)
1924 "Convert an HHMM time to minutes"
1925 (+ (* (/ time 100) 60) (% time 100)))
1927 (defun org-time-from-minutes (minutes)
1928 "Convert a number of minutes to an HHMM time"
1929 (+ (* (/ minutes 60) 100) (% minutes 60)))
1931 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1932 (list ndays todayp))
1933 (if (member 'remove-match (car org-agenda-time-grid))
1934 (flet ((extract-window
1936 (let ((start (get-text-property 1 'time-of-day line))
1937 (dur (get-text-property 1 'duration line)))
1941 (org-time-from-minutes
1942 (+ dur (org-time-to-minutes start)))))
1945 (let* ((windows (delq nil (mapcar 'extract-window list)))
1946 (org-agenda-time-grid
1947 (list (car org-agenda-time-grid)
1948 (cadr org-agenda-time-grid)
1951 (find-if (lambda (w)
1954 (and (>= time (car w))
1957 (caddr org-agenda-time-grid)))))
1960 (ad-activate 'org-agenda-add-time-grid-maybe)
1962 *** Disable version control for Org mode agenda files
1963 #+index: Agenda!Files
1966 Even if you use Git to track your agenda files you might not need
1967 vc-mode to be enabled for these files.
1969 #+begin_src emacs-lisp
1970 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1971 (defun dmj/disable-vc-for-agenda-files-hook ()
1972 "Disable vc-mode for Org agenda files."
1973 (if (and (fboundp 'org-agenda-file-p)
1974 (org-agenda-file-p (buffer-file-name)))
1975 (remove-hook 'find-file-hook 'vc-find-file-hook)
1976 (add-hook 'find-file-hook 'vc-find-file-hook)))
1979 *** Easy customization of TODO colors
1980 #+index: Customization!Todo keywords
1981 #+index: Todo keywords!Customization
1985 Here is some code I came up with some code to make it easier to
1986 customize the colors of various TODO keywords. As long as you just
1987 want a different color and nothing else, you can customize the
1988 variable org-todo-keyword-faces and use just a string color (i.e. a
1989 string of the color name) as the face, and then org-get-todo-face
1990 will convert the color to a face, inheriting everything else from
1991 the standard org-todo face.
1993 To demonstrate, I currently have org-todo-keyword-faces set to
1995 #+BEGIN_SRC emacs-lisp
1996 (("IN PROGRESS" . "dark orange")
1997 ("WAITING" . "red4")
1998 ("CANCELED" . "saddle brown"))
2001 Here's the code, in a form you can put in your =.emacs=
2003 #+BEGIN_SRC emacs-lisp
2004 (eval-after-load 'org-faces
2006 (defcustom org-todo-keyword-faces nil
2007 "Faces for specific TODO keywords.
2008 This is a list of cons cells, with TODO keywords in the car and
2009 faces in the cdr. The face can be a symbol, a color, or a
2010 property list of attributes, like (:foreground \"blue\" :weight
2011 bold :underline t)."
2016 (string :tag "Keyword")
2017 (choice color (sexp :tag "Face")))))))
2019 (eval-after-load 'org
2021 (defun org-get-todo-face-from-color (color)
2022 "Returns a specification for a face that inherits from org-todo
2023 face and has the given color as foreground. Returns nil if
2026 `(:inherit org-warning :foreground ,color)))
2028 (defun org-get-todo-face (kwd)
2029 "Get the right face for a TODO keyword KWD.
2030 If KWD is a number, get the corresponding match group."
2031 (if (numberp kwd) (setq kwd (match-string kwd)))
2032 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
2034 (org-get-todo-face-from-color face)
2036 (and (member kwd org-done-keywords) 'org-done)
2040 *** Add an effort estimate on the fly when clocking in
2041 #+index: Effort estimate!Add when clocking in
2042 #+index: Clock!Effort estimate
2043 You can use =org-clock-in-prepare-hook= to add an effort estimate.
2044 This way you can easily have a "tea-timer" for your tasks when they
2045 don't already have an effort estimate.
2047 #+begin_src emacs-lisp
2048 (add-hook 'org-clock-in-prepare-hook
2049 'my-org-mode-ask-effort)
2051 (defun my-org-mode-ask-effort ()
2052 "Ask for an effort estimate when clocking in."
2053 (unless (org-entry-get (point) "Effort")
2057 (org-entry-get-multivalued-property (point) "Effort"))))
2058 (unless (equal effort "")
2059 (org-set-property "Effort" effort)))))
2062 Or you can use a default effort for such a timer:
2064 #+begin_src emacs-lisp
2065 (add-hook 'org-clock-in-prepare-hook
2066 'my-org-mode-add-default-effort)
2068 (defvar org-clock-default-effort "1:00")
2070 (defun my-org-mode-add-default-effort ()
2071 "Add a default effort estimation."
2072 (unless (org-entry-get (point) "Effort")
2073 (org-set-property "Effort" org-clock-default-effort)))
2076 *** Use idle timer for automatic agenda views
2077 #+index: Agenda view!Refresh
2078 From John Wiegley's mailing list post (March 18, 2010):
2081 I have the following snippet in my .emacs file, which I find very
2082 useful. Basically what it does is that if I don't touch my Emacs for 5
2083 minutes, it displays the current agenda. This keeps my tasks "always
2084 in mind" whenever I come back to Emacs after doing something else,
2085 whereas before I had a tendency to forget that it was there.
2088 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
2090 #+begin_src emacs-lisp
2091 (defun jump-to-org-agenda ()
2093 (let ((buf (get-buffer "*Org Agenda*"))
2096 (if (setq wind (get-buffer-window buf))
2097 (select-window wind)
2098 (if (called-interactively-p)
2100 (select-window (display-buffer buf t t))
2101 (org-fit-window-to-buffer)
2102 ;; (org-agenda-redo)
2104 (with-selected-window (display-buffer buf)
2105 (org-fit-window-to-buffer)
2106 ;; (org-agenda-redo)
2108 (call-interactively 'org-agenda-list)))
2109 ;;(let ((buf (get-buffer "*Calendar*")))
2110 ;; (unless (get-buffer-window buf)
2111 ;; (org-agenda-goto-calendar)))
2114 (run-with-idle-timer 300 t 'jump-to-org-agenda)
2118 : [nil 0 300 0 t jump-to-org-agenda nil idle]
2120 *** Refresh the agenda view regularly
2121 #+index: Agenda view!Refresh
2122 Hack sent by Kiwon Um:
2124 #+begin_src emacs-lisp
2125 (defun kiwon/org-agenda-redo-in-other-window ()
2126 "Call org-agenda-redo function even in the non-agenda buffer."
2128 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
2130 (with-selected-window agenda-window (org-agenda-redo)))))
2131 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
2134 *** Reschedule agenda items to today with a single command
2135 #+index: Agenda!Reschedule
2136 This was suggested by Carsten in reply to David Abrahams:
2138 #+begin_example emacs-lisp
2139 (defun org-agenda-reschedule-to-today ()
2141 (flet ((org-read-date (&rest rest) (current-time)))
2142 (call-interactively 'org-agenda-schedule)))
2145 *** Mark subtree DONE along with all subheadings
2146 #+index: Subtree!subheadings
2147 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
2149 #+begin_src emacs-lisp
2150 (defun bh/mark-subtree-done ()
2153 (let ((limit (point)))
2155 (exchange-point-and-mark)
2156 (while (> (point) limit)
2158 (outline-previous-visible-heading 1))
2159 (org-todo "DONE"))))
2162 Then M-x bh/mark-subtree-done.
2164 *** Mark heading done when all checkboxes are checked.
2166 :CUSTOM_ID: mark-done-when-all-checkboxes-checked
2171 An item consists of a list with checkboxes. When all of the
2172 checkboxes are checked, the item should be considered complete and its
2173 TODO state should be automatically changed to DONE. The code below
2174 does that. This version is slightly enhanced over the one in the
2176 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
2177 reset the state back to TODO if a checkbox is unchecked.
2179 Note that the code requires that a checkbox statistics cookie (the [/]
2180 or [%] thingie in the headline - see the [[https://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
2181 manual) be present in order for it to work. Note also that it is too
2182 dumb to figure out whether the item has a TODO state in the first
2183 place: if there is a statistics cookie, a TODO/DONE state will be
2184 added willy-nilly any time that the statistics cookie is changed.
2186 #+begin_src emacs-lisp
2187 ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
2188 (eval-after-load 'org-list
2189 '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
2191 (defun ndk/checkbox-list-complete ()
2193 (org-back-to-heading t)
2194 (let ((beg (point)) end)
2198 (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
2200 (if (equal (match-string 1) "100%")
2201 ;; all done - do the state change
2204 (if (and (> (match-end 2) (match-beginning 2))
2205 (equal (match-string 2) (match-string 3)))
2207 (org-todo 'todo)))))))
2210 *** Links to custom agenda views
2212 :CUSTOM_ID: links-to-agenda-views
2214 #+index: Agenda view!Links to
2215 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
2217 If you have custom agenda commands defined to some key, say w, then
2218 the following will serve as a link to the custom agenda buffer.
2219 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
2221 Clicking on it will prompt if you want to execute the elisp code. If
2222 you would rather not have the prompt or would want to respond with a
2223 single letter, ~y~ or ~n~, take a look at the docstrings of the
2224 variables =org-confirm-elisp-link-function= and
2225 =org-confirm-elisp-link-not-regexp=. Please take special note of the
2226 security risk associated with completely disabling the prompting
2229 ** Exporting org files
2230 *** Ignoring headlines during export
2232 :CUSTOM_ID: ignoreheadline
2234 #+index: Export!ignore headlines
2235 Sometimes users want to ignore the headline text during export like in
2236 the Beamer exporter (=ox-beamer=). In the [[https://orgmode.org/manual/Beamer-export.html#Beamer-export][Beamer exporter]] one can use
2237 the tag =ignoreheading= to disable the export of a certain headline,
2238 whilst still retaining the content of the headline. We can imitate
2239 this feature in other export backends. Note that this is not a
2240 particularly easy problem, as the Org exporter creates a static
2241 representation of section numbers, table of contents etc.
2243 Consider the following document:
2245 ,* head 1 :noexport:
2246 ,* head 2 :ignoreheading:
2248 ,* =head 4= :ignoreheading:
2251 We want to remove heading 2 and 4.
2253 There are different strategies to accomplish this:
2254 1. The best option is to remove headings tagged with =ignoreheading=
2255 before export starts. This can be accomplished with the hook
2256 =org-export-before-parsing-hook= that runs before the buffer has
2257 been parsed. In the example above, however, =head 2= would not be
2258 exported as it becomes part of =head 1= which is not exporter. To
2259 overcome this move perhaps =head 1= can be moved to the end of the
2260 buffer. An example of a hook that removes headings is before
2261 parsing is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01459.html][here]]. Note, this solution is compatible with
2262 /all/ export formats!
2263 2. The problem is simple when exporting to LaTeX, as the LaTeX
2264 compiler determines numbers. We can thus use
2265 =org-export-filter-headline-functions= to remove the offending
2266 headlines. One regexp-based solution that looks for the word
2267 =ignoreheading= is available on [[https://stackoverflow.com/questions/10295177/is-there-an-equivalent-of-org-modes-b-ignoreheading-for-non-beamer-documents][StackOverflow]] for both the legacy
2268 exporter Org v7 exporter and the current Org v8 exporter. Note,
2269 however, that this filter will only work with LaTeX (numbering and
2270 the table of content may break in other exporters). In the example
2271 above, this filer will work flawlessly in LaTeX, it will not work
2272 at all in HTML and it will fail to update section numbers, TOC and
2273 leave some auxiliary lines behind when exporting to plain text.
2274 3. Another solution that tries to recover the Org element
2275 representation is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01480.html][here]]. In the example above this filter
2276 will not remove =head 4= exporting to any backend, since verbatim
2277 strings do not retain the Org element representation. It will
2278 remove the extra heading line when exporting to plain text, but
2279 will also fail to update section numbers. It should be fairly
2280 simple to also make it work with HTML.
2282 *NOTE: another way to accomplish this behavior is to use the [[https://code.orgmode.org/bzg/org-mode/raw/master/contrib/lisp/ox-extra.el][=ox-extra.el=]] package:*
2283 To use this, add the following to your =.elisp= file:
2285 #+begin_src emacs-lisp
2286 (add-to-list 'load-path "path/to/contrib/lisp")
2288 (ox-extras-activate '(ignore-headlines))
2291 After this is added, then any headlines having an =:ignore:= tag will
2292 be omitted from the export, but their contents will be included in the
2295 *** Export Org to Org and handle includes.
2296 #+index: Export!handle includes
2297 N.B: this does not apply to the "new" export engine (>= 8.0) - the function
2298 =org-export-handle-include-files-recurse= is only available in earlier versions.
2299 There is probably a way to do the same thing in the "new" exporter but nobody
2300 has stepped up to the plate yet.
2302 Nick Dokos came up with this useful function:
2304 #+begin_src emacs-lisp
2305 (defun org-to-org-handle-includes ()
2306 "Copy the contents of the current buffer to OUTFILE,
2307 recursively processing #+INCLUDEs."
2308 (let* ((s (buffer-string))
2309 (fname (buffer-file-name))
2310 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
2314 (org-export-handle-include-files-recurse)
2317 (delete-region (point-min) (point-max))
2322 *** Specifying LaTeX commands to floating environments
2324 :CUSTOM_ID: latex-command-for-floats
2327 #+index: Export!LaTeX
2328 The keyword ~placement~ can be used to specify placement options to
2329 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2330 LaTeX export. Org passes along everything passed in options as long as
2331 there are no spaces. One can take advantage of this to pass other
2332 LaTeX commands and have their scope limited to the floating
2335 For example one can set the fontsize of a table different from the
2336 default normal size by putting something like =\footnotesize= right
2337 after the placement options. During LaTeX export using the
2338 ~#+ATTR_LaTeX:~ line below:
2341 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2344 exports the associated floating environment as shown in the following
2348 \begin{table}[<options>]\footnotesize
2353 It should be noted that this hack does not work for beamer export of
2354 tables since the =table= environment is not used. As an ugly
2355 workaround, one can use the following:
2358 ,#+LATEX: {\footnotesize
2359 ,#+ATTR_LaTeX: align=rr
2366 *** Styling code sections with CSS
2368 #+index: HTML!Styling code sections with CSS
2370 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2371 to HTML using =<pre>= tags, and assigned CSS classes by their content
2372 type. For example, Perl content will have an opening tag like
2373 =<pre class="src src-perl">=. You can use those classes to add styling
2374 to the output, such as here where a small language tag is added at the
2375 top of each kind of code box:
2378 (setq org-export-html-style
2379 "<style type=\"text/css\">
2380 <!--/*--><![CDATA[/*><!--*/
2381 .src { background-color: #F5FFF5; position: relative; overflow: visible; }
2382 .src:before { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2383 .src-sh:before { content: 'sh'; }
2384 .src-bash:before { content: 'sh'; }
2385 .src-R:before { content: 'R'; }
2386 .src-perl:before { content: 'Perl'; }
2387 .src-sql:before { content: 'SQL'; }
2388 .example { background-color: #FFF5F5; }
2393 Additionally, we use color to distinguish code output (the =.example=
2394 class) from input (all the =.src-*= classes).
2396 *** Where can I find nice themes for HTML export?
2398 You can find great looking HTML themes (CSS + JS) at
2399 https://github.com/fniessen/org-html-themes, currently:
2403 [[file:images/org-html-themes/bigblow.png]]
2405 - ReadTheOrg, a clone of Read The Docs.
2407 [[file:images/org-html-themes/readtheorg.png]]
2409 See https://www.youtube.com/watch?v=DnSGSiXYuOk for a demo of the Org
2412 *** Including external text fragments
2414 #+index: Export!including external text fragments
2416 I recently had to document some source code but could not modify the
2417 source files themselves. Here is a setup that lets you refer to
2418 fragments of external files, such that the fragments are inserted as
2419 source blocks in the current file during evaluation of the ~call~
2420 lines (thus during export as well).
2425 ,#+BEGIN_SRC emacs-lisp :results raw :var f="foo" :var s="Definition" :var e="\\. *$" :var b=()
2426 (defvar coqfiles nil)
2428 (defun fetchlines (file-path search-string &optional end before)
2429 "Searches for the SEARCH-STRING in FILE-PATH and returns the matching line.
2430 If the optional argument END is provided as a number, then this
2431 number of lines is printed. If END is a string, then it is a
2432 regular expression indicating the end of the expression to print.
2433 If END is omitted, then 10 lines are printed. If BEFORE is set,
2434 then one fewer line is printed (this is useful when END is a
2435 string matching the first line that should not be printed)."
2437 (insert-file-contents file-path nil nil nil t)
2438 (goto-char (point-min))
2440 (if (search-forward search-string nil t)
2442 (line-beginning-position)
2446 (line-end-position (if before (- end 1) end)))
2448 (let ((point (re-search-forward end nil t)))
2449 (if before (line-end-position 0) point)))
2450 (t (line-end-position 10)))
2451 (line-end-position 10))))))
2454 (fetchlines (concat coqfiles f ".v") s e b)
2458 ,#+BEGIN_SRC emacs-lisp :var text="" :results raw
2459 (concat "#+BEGIN_SRC coq\n" text "\n#+END_SRC")
2463 This is specialized for Coq files (hence the ~coq~ language in the
2464 ~wrap-coq~ function, the ~.v~ extension in the ~fetch~ function, and
2465 the default value for ~end~ matching the syntax ending definitions in
2466 Coq). To use it, you need to:
2467 - set the ~coqfiles~ variable to where your source files reside;
2468 - call the function using lines of the form
2470 ,#+call: fetchsrc(f="JsSyntax", s="Inductive expr :=", e="^ *$", b=1) :results drawer :post wrap-coq(text=*this*)
2472 In this example, we look inside the file ~JsSyntax.v~ in ~coqfiles~,
2473 search for a line matching ~Inductive expr :=~, and include the
2474 fragment until the first line consisting only of white space,
2475 excluded (as ~b=1~).
2477 I use drawers to store the results to avoid a bug leading to
2478 duplication during export when the code has already been evaluated in
2479 the buffer (see [[http://thread.gmane.org/gmane.emacs.orgmode/79520][this thread]] for a description of the problem). This
2480 has been fixed in recent versions of org-mode, so alternative
2481 approaches are possible.
2485 *** How do I preview LaTeX fragments when in a LaTeX source block?
2487 When editing =LaTeX= source blocks, you may want to preview LaTeX fragments
2488 just like in an Org-mode buffer. You can do this by using the usual
2489 keybinding =C-c C-x C-l= after loading this snipped:
2491 #+BEGIN_SRC emacs-lisp
2492 (define-key org-src-mode-map "\C-c\C-x\C-l" 'org-edit-preview-latex-fragment)
2494 (defun org-edit-preview-latex-fragment ()
2495 "Write latex fragment from source to parent buffer and preview it."
2497 (org-src-in-org-buffer (org-preview-latex-fragment)))
2500 Thanks to Sebastian Hofer for sharing this.
2502 * Hacking Org: Working with Org-mode and other Emacs Packages.
2503 ** How to ediff folded Org files
2504 A rather often quip among Org users is when looking at chages with
2505 ediff. Ediff tends to fold the Org buffers when comparing. This can
2506 be very inconvenient when trying to determine what changed. A recent
2507 discussion on the mailing list led to a [[http://article.gmane.org/gmane.emacs.orgmode/75222][neat solution]] from Ratish
2510 ** org-remember-anything
2512 #+index: Remember!Anything
2514 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2516 #+BEGIN_SRC emacs-lisp
2517 (defvar org-remember-anything
2518 '((name . "Org Remember")
2519 (candidates . (lambda () (mapcar 'car org-remember-templates)))
2520 (action . (lambda (name)
2521 (let* ((orig-template org-remember-templates)
2522 (org-remember-templates
2523 (list (assoc name orig-template))))
2524 (call-interactively 'org-remember))))))
2527 You can add it to your 'anything-sources' variable and open remember directly
2528 from anything. I imagine this would be more interesting for people with many
2529 remember templates, so that you are out of keys to assign those to.
2531 ** Org-mode and saveplace.el
2533 Fix a problem with =saveplace.el= putting you back in a folded position:
2535 #+begin_src emacs-lisp
2536 (add-hook 'org-mode-hook
2538 (when (outline-invisible-p)
2540 (outline-previous-visible-heading 1)
2541 (org-show-subtree)))))
2544 ** Using ido-mode for org-refile (and archiving via refile)
2546 First set up ido-mode, for example using:
2548 #+begin_src emacs-lisp
2549 ; use ido mode for completion
2550 (setq ido-everywhere t)
2551 (setq ido-enable-flex-matching t)
2552 (setq ido-max-directory-size 100000)
2553 (ido-mode (quote both))
2556 Now to enable it in org-mode, use the following:
2557 #+begin_src emacs-lisp
2558 (setq org-completion-use-ido t)
2559 (setq org-refile-use-outline-path nil)
2560 (setq org-refile-allow-creating-parent-nodes 'confirm)
2562 The last line enables the creation of nodes on the fly.
2564 If you refile into files that are not in your agenda file list, you can add them as target like this (replace file1\_done, etc with your files):
2565 #+begin_src emacs-lisp
2566 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2569 For refiling it is often not useful to include targets that have a DONE state. It's easy to remove them by using the verify-refile-target hook.
2570 #+begin_src emacs-lisp
2571 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2572 ; added check to only include headlines, e.g. line must have at least one child
2573 (defun my/verify-refile-target ()
2574 "Exclude todo keywords with a DONE state from refile targets"
2575 (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2576 (save-excursion (org-goto-first-child))
2578 (setq org-refile-target-verify-function 'my/verify-refile-target)
2580 Now when looking for a refile target, you can use the full power of ido to find them. Ctrl-R can be used to switch between different options that ido offers.
2582 ** Using ido-completing-read to find attachments
2584 #+index: Attachment!ido completion
2588 Org-attach is great for quickly linking files to a project. But if you
2589 use org-attach extensively you might find yourself wanting to browse
2590 all the files you've attached to org headlines. This is not easy to do
2591 manually, since the directories containing the files are not human
2592 readable (i.e., they are based on automatically generated ids). Here's
2593 some code to browse those files using ido (obviously, you need to be
2596 #+begin_src emacs-lisp
2597 (load-library "find-lisp")
2599 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2601 (defun my-ido-find-org-attach ()
2602 "Find files in org-attachment directory"
2604 (let* ((enable-recursive-minibuffers t)
2605 (files (find-lisp-find-files org-attach-directory "."))
2608 (cons (file-name-nondirectory x)
2612 (remove-duplicates (mapcar #'car file-assoc-list)
2614 (filename (ido-completing-read "Org attachments: " filename-list nil t))
2615 (longname (cdr (assoc filename file-assoc-list))))
2616 (ido-set-current-directory
2617 (if (file-directory-p longname)
2619 (file-name-directory longname)))
2620 (setq ido-exit 'refresh
2621 ido-text-init ido-text
2625 (add-hook 'ido-setup-hook 'ido-my-keys)
2627 (defun ido-my-keys ()
2628 "Add my keybindings for ido."
2629 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2632 To browse your org attachments using ido fuzzy matching and/or the
2633 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2636 ** Link to Gnus messages by Message-Id
2637 #+index: Link!Gnus message by Message-Id
2638 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2639 discussion about linking to Gnus messages without encoding the folder
2640 name in the link. The following code hooks in to the store-link
2641 function in Gnus to capture links by Message-Id when in nnml folders,
2642 and then provides a link type "mid" which can open this link. The
2643 =mde-org-gnus-open-message-link= function uses the
2644 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2645 scan. It will go through them, in order, asking each to locate the
2646 message and opening it from the first one that reports success.
2648 It has only been tested with a single nnml backend, so there may be
2649 bugs lurking here and there.
2651 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2654 #+begin_src emacs-lisp
2655 ;; Support for saving Gnus messages by Message-ID
2656 (defun mde-org-gnus-save-by-mid ()
2657 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2658 (when (eq major-mode 'gnus-article-mode)
2659 (gnus-article-show-summary))
2660 (let* ((group gnus-newsgroup-name)
2661 (method (gnus-find-method-for-group group)))
2662 (when (eq 'nnml (car method))
2663 (let* ((article (gnus-summary-article-number))
2664 (header (gnus-summary-article-header article))
2665 (from (mail-header-from header))
2668 (let ((mid (mail-header-id header)))
2669 (if (string-match "<\\(.*\\)>" mid)
2670 (match-string 1 mid)
2671 (error "Malformed message ID header %s" mid)))))
2672 (date (mail-header-date header))
2673 (subject (gnus-summary-subject-string)))
2674 (org-store-link-props :type "mid" :from from :subject subject
2675 :message-id message-id :group group
2676 :link (org-make-link "mid:" message-id))
2677 (apply 'org-store-link-props
2678 :description (org-email-link-description)
2679 org-store-link-plist)
2682 (defvar mde-mid-resolve-methods '()
2683 "List of methods to try when resolving message ID's. For Gnus,
2684 it is a cons of 'gnus and the select (type and name).")
2685 (setq mde-mid-resolve-methods
2688 (defvar mde-org-gnus-open-level 1
2689 "Level at which Gnus is started when opening a link")
2690 (defun mde-org-gnus-open-message-link (msgid)
2691 "Open a message link with Gnus"
2693 (require 'org-table)
2694 (catch 'method-found
2695 (message "[MID linker] Resolving %s" msgid)
2696 (dolist (method mde-mid-resolve-methods)
2698 ((and (eq (car method) 'gnus)
2699 (eq (cadr method) 'nnml))
2700 (funcall (cdr (assq 'gnus org-link-frame-setup))
2701 mde-org-gnus-open-level)
2702 (when gnus-other-frame-object
2703 (select-frame gnus-other-frame-object))
2704 (let* ((msg-info (nnml-find-group-number
2705 (concat "<" msgid ">")
2707 (group (and msg-info (car msg-info)))
2708 (message (and msg-info (cdr msg-info)))
2710 (if (gnus-methods-equal-p
2714 (gnus-group-full-name group (cdr method))))))
2716 (gnus-summary-read-group qname nil t)
2717 (gnus-summary-goto-article message nil t))
2718 (throw 'method-found t)))
2719 (t (error "Unknown link type"))))))
2721 (eval-after-load 'org-gnus
2723 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2724 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2727 ** Store link to a message when sending in Gnus
2728 #+index: Link!Store link to a message when sending in Gnus
2729 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2731 #+begin_src emacs-lisp
2732 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2733 "Send message with `message-send-and-exit' and store org link to message copy.
2734 If multiple groups appear in the Gcc header, the link refers to
2735 the copy in the last group."
2739 (message-narrow-to-headers)
2740 (let ((gcc (car (last
2741 (message-unquote-tokens
2742 (message-tokenize-header
2743 (mail-fetch-field "gcc" nil t) " ,")))))
2744 (buf (current-buffer))
2745 (message-kill-buffer-on-exit nil)
2746 id to from subject desc link newsgroup xarchive)
2747 (message-send-and-exit arg)
2749 ;; gcc group found ...
2751 (save-current-buffer
2752 (progn (set-buffer buf)
2753 (setq id (org-remove-angle-brackets
2754 (mail-fetch-field "Message-ID")))
2755 (setq to (mail-fetch-field "To"))
2756 (setq from (mail-fetch-field "From"))
2757 (setq subject (mail-fetch-field "Subject"))))
2758 (org-store-link-props :type "gnus" :from from :subject subject
2759 :message-id id :group gcc :to to)
2760 (setq desc (org-email-link-description))
2761 (setq link (org-gnus-article-link
2762 gcc newsgroup id xarchive))
2763 (setq org-stored-links
2764 (cons (list link desc) org-stored-links)))
2765 ;; no gcc group found ...
2766 (message "Can not create Org link: No Gcc header found."))))))
2768 (define-key message-mode-map [(control c) (control meta c)]
2769 'ulf-message-send-and-org-gnus-store-link)
2772 ** Link to visit a file and run occur
2773 #+index: Link!Visit a file and run occur
2774 Add the following bit of code to your startup (after loading org),
2775 and you can then use links like =occur:my-file.txt#regex= to open a
2776 file and run occur with the regex on it.
2778 #+BEGIN_SRC emacs-lisp
2779 (defun org-occur-open (uri)
2780 "Visit the file specified by URI, and run `occur' on the fragment
2781 \(anything after the first '#') in the uri."
2782 (let ((list (split-string uri "#")))
2783 (org-open-file (car list) t)
2784 (occur (mapconcat 'identity (cdr list) "#"))))
2785 (org-add-link-type "occur" 'org-occur-open)
2787 ** Send html messages and attachments with Wanderlust
2790 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2791 similar functionality for both Wanderlust and Gnus. The hack below is
2792 still somewhat different: It allows you to toggle sending of html
2793 messages within Wanderlust transparently. I.e. html markup of the
2794 message body is created right before sending starts.
2796 *** Send HTML message
2798 Putting the code below in your .emacs adds following four functions:
2800 - dmj/wl-send-html-message
2802 Function that does the job: Convert everything between "--text
2803 follows this line--" and first mime entity (read: attachment) or
2804 end of buffer into html markup using `org-export-region-as-html'
2805 and replaces original body with a multipart MIME entity with the
2806 plain text version of body and the html markup version. Thus a
2807 recipient that prefers html messages can see the html markup,
2808 recipients that prefer or depend on plain text can see the plain
2811 Cannot be called interactively: It is hooked into SEMI's
2812 `mime-edit-translate-hook' if message should be HTML message.
2814 - dmj/wl-send-html-message-draft-init
2816 Cannot be called interactively: It is hooked into WL's
2817 `wl-mail-setup-hook' and provides a buffer local variable to
2820 - dmj/wl-send-html-message-draft-maybe
2822 Cannot be called interactively: It is hooked into WL's
2823 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2824 `mime-edit-translate-hook' depending on whether HTML message is
2827 - dmj/wl-send-html-message-toggle
2829 Toggles sending of HTML message. If toggled on, the letters
2830 "HTML" appear in the mode line.
2832 Call it interactively! Or bind it to a key in `wl-draft-mode'.
2834 If you have to send HTML messages regularly you can set a global
2835 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2836 toggle on sending HTML message by default.
2838 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2839 Google's web front end. As you can see you have the whole markup of
2840 Org at your service: *bold*, /italics/, tables, lists...
2842 So even if you feel uncomfortable with sending HTML messages at least
2843 you send HTML that looks quite good.
2845 #+begin_src emacs-lisp
2846 (defun dmj/wl-send-html-message ()
2847 "Send message as html message.
2848 Convert body of message to html using
2849 `org-export-region-as-html'."
2852 (let (beg end html text)
2853 (goto-char (point-min))
2854 (re-search-forward "^--text follows this line--$")
2855 ;; move to beginning of next line
2856 (beginning-of-line 2)
2858 (if (not (re-search-forward "^--\\[\\[" nil t))
2859 (setq end (point-max))
2864 (setq text (buffer-substring-no-properties beg end))
2870 (when (re-search-backward "^-- \n" nil t)
2871 ;; preserve link breaks in signature
2872 (insert "\n#+BEGIN_VERSE\n")
2873 (goto-char (point-max))
2874 (insert "\n#+END_VERSE\n")
2876 (setq html (org-export-region-as-html
2877 (point-min) (point-max) t 'string))))
2878 (delete-region beg end)
2881 "--" "<<alternative>>-{\n"
2882 "--" "[[text/plain]]\n" text
2883 "--" "[[text/html]]\n" html
2884 "--" "}-<<alternative>>\n")))))
2886 (defun dmj/wl-send-html-message-toggle ()
2887 "Toggle sending of html message."
2889 (setq dmj/wl-send-html-message-toggled-p
2890 (if dmj/wl-send-html-message-toggled-p
2892 (message "Sending html message toggled %s"
2893 (if dmj/wl-send-html-message-toggled-p
2896 (defun dmj/wl-send-html-message-draft-init ()
2897 "Create buffer local settings for maybe sending html message."
2898 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2899 (setq dmj/wl-send-html-message-toggled-p nil))
2900 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2901 (add-to-list 'global-mode-string
2902 '(:eval (if (eq major-mode 'wl-draft-mode)
2903 dmj/wl-send-html-message-toggled-p))))
2905 (defun dmj/wl-send-html-message-maybe ()
2906 "Maybe send this message as html message.
2908 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2909 non-nil, add `dmj/wl-send-html-message' to
2910 `mime-edit-translate-hook'."
2911 (if dmj/wl-send-html-message-toggled-p
2912 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2913 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2915 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2916 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2917 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2920 *** Attach HTML of region or subtree
2922 Instead of sending a complete HTML message you might only send parts
2923 of an Org file as HTML for the poor souls who are plagued with
2924 non-proportional fonts in their mail program that messes up pretty
2927 This short function does the trick: It exports region or subtree to
2928 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2929 and clipboard. If a region is active, it uses the region, the
2930 complete subtree otherwise.
2932 #+begin_src emacs-lisp
2933 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2934 "Export region between BEG and END as html attachment.
2935 If BEG and END are not set, use current subtree. Region or
2936 subtree is exported to html without header and footer, prefixed
2937 with a mime entity string and pushed to clipboard and killring.
2938 When called with prefix, mime entity is not marked as
2940 (interactive "r\nP")
2942 (let* ((beg (if (region-active-p) (region-beginning)
2944 (org-back-to-heading)
2946 (end (if (region-active-p) (region-end)
2948 (org-end-of-subtree)
2950 (html (concat "--[[text/html"
2951 (if arg "" "\nContent-Disposition: attachment")
2953 (org-export-region-as-html beg end t 'string))))
2954 (when (fboundp 'x-set-selection)
2955 (ignore-errors (x-set-selection 'PRIMARY html))
2956 (ignore-errors (x-set-selection 'CLIPBOARD html)))
2957 (message "html export done, pushed to kill ring and clipboard"))))
2960 *** Adopting for Gnus
2962 The whole magic lies in the special strings that mark a HTML
2963 attachment. So you might just have to find out what these special
2964 strings are in message-mode and modify the functions accordingly.
2965 ** Add sunrise/sunset times to the agenda.
2966 #+index: Agenda!Diary s-expressions
2969 The diary package provides the function =diary-sunrise-sunset= which can be used
2970 in a diary s-expression in some agenda file like this:
2973 %%(diary-sunrise-sunset)
2976 Seb Vauban asked if it is possible to put sunrise and sunset in
2977 separate lines. Here is a hack to do that. It adds two functions (they
2978 have to be available before the agenda is shown, so I add them early
2979 in my org-config file which is sourced from .emacs, but you'll have to
2980 suit yourself here) that just parse the output of
2981 diary-sunrise-sunset, instead of doing the right thing which would be
2982 to take advantage of the data structures that diary/solar.el provides.
2983 In short, a hack - so perfectly suited for inclusion here :-)
2985 The functions (and latitude/longitude settings which you have to modify for
2986 your location) are as follows:
2988 #+begin_src emacs-lisp
2989 (setq calendar-latitude 48.2)
2990 (setq calendar-longitude 16.4)
2991 (setq calendar-location-name "Vienna, Austria")
2993 (autoload 'solar-sunrise-sunset "solar.el")
2994 (autoload 'solar-time-string "solar.el")
2995 (defun diary-sunrise ()
2996 "Local time of sunrise as a diary entry.
2997 The diary entry can contain `%s' which will be replaced with
2998 `calendar-location-name'."
2999 (let ((l (solar-sunrise-sunset date)))
3002 (if (string= entry "")
3004 (format entry (eval calendar-location-name))) " "
3005 (solar-time-string (caar l) nil)))))
3007 (defun diary-sunset ()
3008 "Local time of sunset as a diary entry.
3009 The diary entry can contain `%s' which will be replaced with
3010 `calendar-location-name'."
3011 (let ((l (solar-sunrise-sunset date)))
3014 (if (string= entry "")
3016 (format entry (eval calendar-location-name))) " "
3017 (solar-time-string (caadr l) nil)))))
3020 You also need to add a couple of diary s-expressions in one of your agenda
3024 %%(diary-sunrise)Sunrise in %s
3028 This will show sunrise with the location and sunset without it.
3030 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]].
3031 In comparison to the version posted on the mailing list, this one
3032 gets rid of the timezone information and can show the location.
3033 ** Add lunar phases to the agenda.
3034 #+index: Agenda!Diary s-expressions
3037 Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
3038 This can be used to display lunar phases in the agenda display with the
3041 #+begin_src emacs-lisp
3044 (org-no-warnings (defvar date))
3045 (defun org-lunar-phases ()
3046 "Show lunar phase in Agenda buffer."
3048 (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
3049 (phase (cl-find-if (lambda (phase) (equal (car phase) date))
3052 (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
3053 (substring (nth 1 phase) 0 5))))))
3056 Add the following line to an agenda file:
3061 %%(org-lunar-phases)
3064 This should display an entry on new moon, first/last quarter moon, and on full
3065 moon. You can customize the entries by customizing =lunar-phase-names=.
3067 E.g., to add Unicode symbols:
3069 #+begin_src emacs-lisp
3070 (setq lunar-phase-names
3071 '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
3072 "☽ First Quarter Moon"
3073 "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
3074 "☾ Last Quarter Moon"))
3077 Unicode 6 even provides symbols for the Moon with nice faces. But those
3078 symbols are currently barely supported in fonts.
3079 See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].
3081 ** Export BBDB contacts to org-contacts.el
3082 #+index: Address Book!BBDB to org-contacts
3083 Try this tool by Wes Hardaker:
3085 http://www.hardakers.net/code/bbdb-to-org-contacts/
3087 ** Calculating date differences - how to write a simple elisp function
3088 #+index: Timestamp!date calculations
3089 #+index: Elisp!technique
3091 Alexander Wingård asked how to calculate the number of days between a
3092 time stamp in his org file and today (see
3093 http://thread.gmane.org/gmane.emacs.orgmode/46881). Although the
3094 resulting answer is probably not of general interest, the method might
3095 be useful to a budding Elisp programmer.
3097 Alexander started from an already existing org function,
3098 =org-evaluate-time-range=. When this function is called in the context
3099 of a time range (two time stamps separated by "=--="), it calculates the
3100 number of days between the two dates and outputs the result in Emacs's
3101 echo area. What he wanted was a similar function that, when called from
3102 the context of a single time stamp, would calculate the number of days
3103 between the date in the time stamp and today. The result should go to
3104 the same place: Emacs's echo area.
3106 The solution presented in the mail thread is as follows:
3108 #+begin_src emacs-lisp
3109 (defun aw/org-evaluate-time-range (&optional to-buffer)
3111 (if (org-at-date-range-p t)
3112 (org-evaluate-time-range to-buffer)
3113 ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
3114 (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
3117 (goto-char (point-at-bol))
3118 (re-search-forward org-ts-regexp (point-at-eol) t)
3119 (if (not (org-at-timestamp-p t))
3120 (error "No timestamp here"))
3121 (goto-char (match-beginning 0))
3122 (org-insert-time-stamp (current-time) nil nil)
3124 (org-evaluate-time-range to-buffer)))))
3127 The function assumes that point is on some line with some time stamp
3128 (or a date range) in it. Note that =org-evaluate-time-range= does not care
3129 whether the first date is earlier than the second: it will always output
3130 the number of days between the earlier date and the later date.
3132 As stated before, the function itself is of limited interest (although
3133 it satisfied Alexander's need).The *method* used might be of wider
3134 interest however, so here is a short explanation.
3136 The idea is that we want =org-evaluate-time-range= to do all the
3137 heavy lifting, but that function requires that it be in a date-range
3138 context. So the function first checks whether it's in a date range
3139 context already: if so, it calls =org-evaluate-time-range= directly
3140 to do the work. The trick now is to arrange things so we can call this
3141 same function in the case where we do *not* have a date range
3142 context. In that case, we manufacture one: we create a temporary
3143 buffer, copy the line with the purported time stamp to the temp
3144 buffer, find the time stamp (signal an error if no time stamp is
3145 found) and insert a new time stamp with the current time before the
3146 existing time stamp, followed by "=--=": voilà, we now have a time range
3147 on which we can apply our old friend =org-evaluate-time-range= to
3148 produce the answer. Because of the above-mentioned property
3149 of =org-evaluate-time-range=, it does not matter if the existing
3150 time stamp is earlier or later than the current time: the correct
3151 number of days is output.
3153 Note that at the end of the call to =with-temp-buffer=, the temporary
3154 buffer goes away. It was just used as a scratch pad for the function
3155 to do some figuring.
3157 The idea of using a temp buffer as a scratch pad has wide
3158 applicability in Emacs programming. The rest of the work is knowing
3159 enough about facilities provided by Emacs (e.g. regexp searching) and
3160 by Org (e.g. checking for time stamps and generating a time stamp) so
3161 that you don't reinvent the wheel, and impedance-matching between the
3164 ** ibuffer and org files
3166 Neil Smithline posted this snippet to let you browse org files with
3169 #+BEGIN_SRC emacs-lisp
3172 (defun org-ibuffer ()
3173 "Open an `ibuffer' window showing only `org-mode' buffers."
3175 (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
3178 ** Enable org-mode links in other modes
3180 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
3182 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
3184 ** poporg.el: edit comments in org-mode
3186 [[https://github.com/QBobWatson/poporg/blob/master/poporg.el][poporg.el]] is a library by François Pinard which lets you edit comments
3187 and strings from your code using a separate org-mode buffer.
3189 ** Convert a .csv file to an Org-mode table
3191 Nicolas Richard has a [[http://article.gmane.org/gmane.emacs.orgmode/65456][nice recipe]] using the pcsv library ([[http://marmalade-repo.org/packages/pcsv][available]] from
3192 the Marmelade ELPA repository):
3194 #+BEGIN_SRC emacs-lisp
3195 (defun yf/lisp-table-to-org-table (table &optional function)
3196 "Convert a lisp table to `org-mode' syntax, applying FUNCTION to each of its elements.
3197 The elements should not have any more newlines in them after
3198 applying FUNCTION ; the default converts them to spaces. Return
3199 value is a string containg the unaligned `org-mode' table."
3200 (unless (functionp function)
3201 (setq function (lambda (x) (replace-regexp-in-string "\n" " " x))))
3202 (mapconcat (lambda (x) ; x is a line.
3203 (concat "| " (mapconcat function x " | ") " |"))
3206 (defun yf/csv-to-table (beg end)
3207 "Convert a csv file to an `org-mode' table."
3210 (insert (yf/lisp-table-to-org-table (pcsv-parse-region beg end)))
3211 (delete-region beg end)
3217 ~foldout.el~, which is part of Emacs, is a nice little companion for
3218 ~outline-mode~. With ~foldout.el~ one can narrow to a subtree and
3219 later unnarrow. ~foldout.el~ is useful for Org mode out of the box.
3221 There is one annoyance though (at least for me):
3222 ~foldout-zoom-subtree~ opens the drawers.
3224 This can be fixed e.g. by using the following slightly modified
3225 version of ~foldout-zoom-subtree~ which uses function ~org-show-entry~
3226 instead of ~outline-show-entry~.
3228 #+begin_src emacs-lisp
3229 (defun foldout-zoom-org-subtree (&optional exposure)
3230 "Same as `foldout-zoom-subtree' with often nicer zoom in Org mode."
3233 (((symbol-function #'outline-show-entry) (lambda () (org-show-entry))))
3234 (foldout-zoom-subtree exposure)))
3237 * Hacking Org: Working with Org-mode and External Programs.
3238 ** Use Org-mode with Screen [Andrew Hyatt]
3239 #+index: Link!to screen session
3240 "The general idea is that you start a task in which all the work will
3241 take place in a shell. This usually is not a leaf-task for me, but
3242 usually the parent of a leaf task. From a task in your org-file, M-x
3243 ash-org-screen will prompt for the name of a session. Give it a name,
3244 and it will insert a link. Open the link at any time to go the screen
3245 session containing your work!"
3247 http://article.gmane.org/gmane.emacs.orgmode/5276
3249 #+BEGIN_SRC emacs-lisp
3252 (defun ash-org-goto-screen (name)
3253 "Open the screen with the specified name in the window"
3254 (interactive "MScreen name: ")
3255 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
3256 (if (member screen-buffer-name
3257 (mapcar 'buffer-name (buffer-list)))
3258 (switch-to-buffer screen-buffer-name)
3259 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
3261 (defun ash-org-screen-buffer-name (name)
3262 "Returns the buffer name corresponding to the screen name given."
3263 (concat "*screen " name "*"))
3265 (defun ash-org-screen-helper (name arg)
3266 ;; Pick the name of the new buffer.
3267 (let ((term-ansi-buffer-name
3268 (generate-new-buffer-name
3269 (ash-org-screen-buffer-name name))))
3270 (setq term-ansi-buffer-name
3271 (term-ansi-make-term
3272 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
3273 (set-buffer term-ansi-buffer-name)
3276 (term-set-escape-char ?\C-x)
3277 term-ansi-buffer-name))
3279 (defun ash-org-screen (name)
3280 "Start a screen session with name"
3281 (interactive "MScreen name: ")
3283 (ash-org-screen-helper name "-S"))
3284 (insert-string (concat "[[screen:" name "]]")))
3286 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
3287 ;; \"%s\")") to org-link-abbrev-alist.
3290 ** Org Agenda + Appt + Zenity
3292 :CUSTOM_ID: org-agenda-appt-zenity
3295 #+index: Appointment!reminders
3296 #+index: Appt!Zenity
3298 <a name="agenda-appt-zenity"></a>
3300 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It makes sure your agenda
3301 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
3304 #+BEGIN_SRC emacs-lisp
3305 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3306 ; For org appointment reminders
3308 ;; Get appointments for today
3309 (defun my-org-agenda-to-appt ()
3311 (setq appt-time-msg-list nil)
3312 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
3313 (org-agenda-to-appt)))
3315 ;; Run once, activate and schedule refresh
3316 (my-org-agenda-to-appt)
3318 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
3321 (setq appt-message-warning-time 15)
3322 (setq appt-display-interval 5)
3324 ; Update appt each time agenda opened.
3325 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
3327 ; Setup zenify, we tell appt to use window, and replace default function
3328 (setq appt-display-format 'window)
3329 (setq appt-disp-window-function (function my-appt-disp-window))
3331 (defun my-appt-disp-window (min-to-app new-time msg)
3332 (save-window-excursion (shell-command (concat
3333 "/usr/bin/zenity --info --title='Appointment' --text='"
3334 msg "' &") nil nil)))
3337 ** Org and appointment notifications on Mac OS 10.8
3339 Sarah Bagby [[http://mid.gmane.org/EA76104A-9ACD-4141-8D33-2E4D810D9B5A@geol.ucsb.edu][posted some code]] on how to get appointments notifications on
3340 Mac OS 10.8 with [[https://github.com/alloy/terminal-notifier][terminal-notifier]].
3342 ** Org-Mode + gnome-osd
3343 #+index: Appointment!reminders
3344 #+index: Appt!gnome-osd
3345 Richard Riley uses gnome-osd in interaction with Org-Mode to display
3346 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
3348 ** txt2org convert text data to org-mode tables
3351 I often find it useful to generate Org-mode tables on the command line
3352 from tab-separated data. The following awk script makes this easy to
3353 do. Text data is read from STDIN on a pipe and any command line
3354 arguments are interpreted as rows at which to insert hlines.
3356 Here are two usage examples.
3357 1. running the following
3358 : $ cat <<EOF|~/src/config/bin/txt2org
3370 2. and the following (notice the command line argument)
3371 : $ cat <<EOF|~/src/config/bin/txt2org 1
3379 : | strings | numbers |
3380 : |---------+---------|
3386 Here is the script itself
3390 # Read tab separated data from STDIN and output an Org-mode table.
3392 # Optional command line arguments specify row numbers at which to
3396 for(i=1; i<ARGC; i++){
3397 hlines[ARGV[i]+1]=1; ARGV[i] = "-"; } }
3400 if(NF > max_nf){ max_nf = NF; };
3401 for(f=1; f<=NF; f++){
3402 if(length($f) > lengths[f]){ lengths[f] = length($f); };
3407 for(f=1; f<=max_nf; f++){
3408 for(i=0; i<(lengths[f] + 2); i++){ hline_str=hline_str "-"; }
3409 if( f != max_nf){ hline_str=hline_str "+"; }
3410 else { hline_str=hline_str "|"; } }
3412 for(r=1; r<=NR; r++){ # rows
3413 if(hlines[r] == 1){ print hline_str; }
3415 for(f=1; f<=max_nf; f++){ # columns
3416 cell=row[r][f]; padding=""
3417 for(i=0; i<(lengths[f] - length(cell)); i++){ padding=padding " "; }
3418 # for now just print everything right-aligned
3419 # if(cell ~ /[0-9.]/){ printf " %s%s |", cell, padding; }
3420 # else{ printf " %s%s |", padding, cell; }
3421 printf " %s%s |", padding, cell; }
3424 if(hlines[NR+1]){ print hline_str; } }
3428 #+index: Agenda!Views
3429 #+index: Agenda!and Remind (external program)
3432 http://article.gmane.org/gmane.emacs.orgmode/5073
3435 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
3436 command line calendaring program. Its features supersede the possibilities
3437 of orgmode in the area of date specifying, so that I want to use it
3438 combined with orgmode.
3440 Using the script below I'm able use remind and incorporate its output in my
3441 agenda views. The default of using 13 months look ahead is easily
3442 changed. It just happens I sometimes like to look a year into the
3446 ** Useful webjumps for conkeror
3447 #+index: Shortcuts!conkeror
3448 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
3449 your =~/.conkerorrc= file:
3452 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
3453 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
3456 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
3457 Org-mode mailing list.
3459 ** Use MathJax for HTML export without requiring JavaScript
3460 #+index: Export!MathJax
3461 As of 2010-08-14, MathJax is the default method used to export math to HTML.
3463 If you like the results but do not want JavaScript in the exported pages,
3464 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
3465 HTML file from the exported version. It can also embed all referenced fonts
3466 within the HTML file itself, so there are no dependencies to external files.
3468 The download archive contains an elisp file which integrates it into the Org
3469 export process (configurable per file with a "#+StaticMathJax:" line).
3471 Read README.org and the comments in org-static-mathjax.el for usage instructions.
3472 ** Search Org files using lgrep
3473 #+index: search!lgrep
3474 Matt Lundin suggests this:
3476 #+begin_src emacs-lisp
3477 (defun my-org-grep (search &optional context)
3478 "Search for word in org files.
3480 Prefix argument determines number of lines."
3481 (interactive "sSearch for: \nP")
3482 (let ((grep-find-ignored-files '("#*" ".#*"))
3483 (grep-template (concat "grep <X> -i -nH "
3485 (concat "-C" (number-to-string context)))
3487 (lgrep search "*org*" "/home/matt/org/")))
3489 (global-set-key (kbd "<f8>") 'my-org-grep)
3492 ** Automatic screenshot insertion
3493 #+index: Link!screenshot
3494 Suggested by Russell Adams
3496 #+begin_src emacs-lisp
3497 (defun my-org-screenshot ()
3498 "Take a screenshot into a time stamped unique-named file in the
3499 same directory as the org-buffer and insert a link to this file."
3504 (concat (buffer-file-name)
3506 (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
3507 (call-process "import" nil nil nil filename)
3508 (insert (concat "[[" filename "]]"))
3509 (org-display-inline-images))
3512 ** Capture invitations/appointments from MS Exchange emails
3513 #+index: Appointment!MS Exchange
3514 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
3515 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
3517 ** Audio/video file playback within org mode
3518 #+index: Link!audio/video
3519 Paul Sexton provided code that makes =file:= links to audio or video files
3520 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
3521 media player library. The user can pause, skip forward and backward in the
3522 track, and so on from without leaving Emacs. Links can also contain a time
3523 after a double colon -- when this is present, playback will begin at that
3524 position in the track.
3526 See the file [[file:code/elisp/org-player.el][org-player.el]]
3528 ** Under X11 Keep a window with the current agenda items at all time
3529 #+index: Agenda!dedicated window
3530 I struggle to keep (in emacs) a window with the agenda at all times.
3531 For a long time I have wanted a sticky window that keeps this
3532 information, and then use my window manager to place it and remove its
3533 decorations (I can also force its placement in the stack: top always,
3536 I wrote a small program in qt that simply monitors an HTML file and
3537 displays it. Nothing more. It does the work for me, and maybe somebody
3538 else will find it useful. It relies on exporting the agenda as HTML
3539 every time the org file is saved, and then this little program
3540 displays the html file. The window manager is responsible of removing
3541 decorations, making it sticky, and placing it in same place always.
3543 Here is a screenshot (see window to the bottom right). The decorations
3544 are removed by the window manager:
3546 http://turingmachine.org/hacking/org-mode/orgdisplay.png
3548 Here is the code. As I said, very, very simple, but maybe somebody will
3551 http://turingmachine.org/hacking/org-mode/
3555 ** Script (thru procmail) to output emails to an Org file
3556 #+index: Conversion!email to org file
3557 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
3559 : I've [...] created some procmail and shell glue that takes emails and
3560 : inserts them into an org-file so that I can capture stuff on the go using
3561 : the email program.
3563 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3565 ** Save File With Different Format for Headings (fileconversion)
3567 :CUSTOM_ID: fileconversion
3569 #+index: Conversion!fileconversion
3571 Using hooks and on the fly
3572 - When writing a buffer to the file: Replace the leading stars from
3573 headings with a file char.
3574 - When reading a file into the buffer: Replace the file chars with
3575 leading stars for headings.
3577 To change the file format just add or remove the keyword in the
3578 ~#+STARTUP:~ line in the Org buffer and save.
3580 Now you can also change to Fundamental mode to see how the file looks
3581 like on the level of the file, can go back to Org mode, reenter Org
3582 mode or change to any other major mode and the conversion gets done
3585 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
3587 :CUSTOM_ID: hidestarsfile
3589 #+index: Conversion!fileconversion hidestarsfile
3591 This is like "a cleaner outline view":
3592 https://orgmode.org/manual/Clean-view.html
3594 Example of the *file content* first with leading stars as usual and
3595 below without leading stars through ~#+STARTUP: odd hidestars
3599 ,#+STARTUP: odd hidestars
3611 ,#+STARTUP: odd hidestars hidestarsfile
3622 The latter is convenient for better human readability when an Org file,
3623 additionally to Emacs, is read with a file viewer or, for smaller edits,
3624 with an editor not capable of the Org file format.
3626 ~hidestarsfile~ is a hack and can not become part of the Org core:
3627 - An Org file with ~hidestarsfile~ can not contain list items with a
3628 star as bullet due to the syntax conflict at read time. Mark
3629 E. Shoulson suggested to use the non-breaking space which is now
3630 implemented in fileconversion as ~nbspstarsfile~ as an alternative
3631 for ~hidestarsfile~. Although I don't recommend it because an editor
3632 like typically e. g. Emacs may render the non-breaking space
3633 differently from the space ~0x20~.
3634 - An Org file with ~hidestarsfile~ can almost not be edited with an
3635 Org mode without added functionality of hidestarsfile as long as the
3636 file is not converted back.
3638 *** Headings in Markdown Format (markdownstarsfile)
3640 :CUSTOM_ID: markdownstarsfile
3642 #+index: Conversion!fileconversion markdownstarsfile
3644 Together with ~oddeven~ you can use ~markdownstarsfile~ to be readable
3645 or even basically editable with Markdown (does not make much sense
3646 with ~odd~, see ~org-convert-to-odd-levels~ and
3647 ~org-convert-to-oddeven-levels~ for how to convert).
3649 Example of the *file content*:
3652 ,#+STARTUP: oddeven markdownstarsfile
3654 1. first item of numbered list (same format in Org and Markdown)
3656 - first item of unordered list (same format in Org and Markdown)
3658 + first item of unordered list (same format in Org and Markdown)
3659 #### section level 4
3660 * first item of unordered list (same format in Org and Markdown)
3661 * avoid this item type to be compatible with Org hidestarsfile
3664 An Org file with ~markdownstarsfile~ can not contain code comment
3665 lines prefixed with ~#~, even not when within source blocks.
3669 :CUSTOM_ID: fileconversion-code
3671 #+index: Conversion!fileconversion emacs-lisp code
3673 #+BEGIN_SRC emacs-lisp
3674 ;; - fileconversion version 0.10
3675 ;; - DISCLAIMER: Make a backup of your Org files before trying
3676 ;; `f-org-fileconv-*'. It is recommended to use a version control
3677 ;; system like git and to review and commit the changes in the Org
3679 ;; - Supported "#+STARTUP:" formats: "hidestarsfile",
3680 ;; "nbspstarsfile", "markdownstarsfile".
3682 ;; Design summary: fileconversion is a round robin of two states linked by
3684 ;; - State `v-org-fileconv-level-org-p' is nil: The level is "file"
3686 ;; - Action `f-org-fileconv-decode': Replace file char with "*".
3687 ;; - State `v-org-fileconv-level-org-p' is non-nil: The level is "Org"
3689 ;; - Action `f-org-fileconv-encode': Replace "*" with file char.
3691 ;; Naming convention of prefix:
3692 ;; - f-[...]: "my function", instead of the unspecific prefix `my-*'.
3693 ;; - v-[...]: "my variable", instead of the unspecific prefix `my-*'.
3695 (defvar v-org-fileconv-level-org-p nil
3696 "Whether level of buffer is Org or only file.
3697 nil: level is file (encoded), non-nil: level is Org (decoded).")
3698 (make-variable-buffer-local 'v-org-fileconv-level-org-p)
3699 ;; Survive a change of major mode that does `kill-all-local-variables', e.
3700 ;; g. when reentering Org mode through "C-c C-c" on a #+STARTUP: line.
3701 (put 'v-org-fileconv-level-org-p 'permanent-local t)
3703 ;; * Callback `f-org-fileconv-org-mode-beg' before `org-mode'
3704 (defadvice org-mode (before org-mode-advice-before-fileconv)
3705 (f-org-fileconv-org-mode-beg))
3706 (ad-activate 'org-mode)
3707 (defun f-org-fileconv-org-mode-beg ()
3708 ;; - Reason to test `buffer-file-name': Only when converting really
3709 ;; from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3711 ;; - No `message' to not wipe a possible "File mode specification error:".
3712 ;; - `f-org-fileconv-decode' in org-mode-hook would be too late for
3713 ;; performance reasons, see
3714 ;; http://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00920.html
3715 (when (buffer-file-name) (f-org-fileconv-decode)))
3717 ;; * Callback `f-org-fileconv-org-mode-end' after `org-mode'
3718 (add-hook 'org-mode-hook 'f-org-fileconv-org-mode-end
3719 nil ; _Prepend_ to hook to have it first.
3720 nil) ; Hook addition global.
3721 (defun f-org-fileconv-org-mode-end ()
3722 ;; - Reason to test `buffer-file-name': only when converting really
3723 ;; from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3725 ;; - No `message' to not wipe a possible "File mode specification error:".
3726 (when (buffer-file-name)
3727 ;; - Adding this to `change-major-mode-hook' or "defadvice before" of
3728 ;; org-mode would be too early and already trigger during find-file.
3729 ;; - Argument 4: t to limit hook addition to buffer locally, this way
3730 ;; and as required the hook addition will disappear when the major
3731 ;; mode of the buffer changes.
3732 (add-hook 'change-major-mode-hook 'f-org-fileconv-encode nil t)
3733 (add-hook 'before-save-hook 'f-org-fileconv-encode nil t)
3734 (add-hook 'after-save-hook 'f-org-fileconv-decode nil t)))
3736 (defun f-org-fileconv-re ()
3737 "Check whether there is a #+STARTUP: line for fileconversion.
3738 If found then return the expressions required for the conversion."
3740 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3741 (let (re-list (count 0))
3742 (while (re-search-forward "^[ \t]*#\\+STARTUP:" nil t)
3743 ;; #+STARTUP: hidestarsfile
3744 (when (string-match-p "\\bhidestarsfile\\b" (thing-at-point 'line))
3746 ;; - Line starting with star for bold emphasis.
3747 ;; - Line of stars to underline section title in loosely quoted
3748 ;; ASCII style (star at end of line).
3749 (setq re-list '("\\(\\* \\)" ; common-re
3751 (setq count (1+ count)))
3752 ;; #+STARTUP: nbspstarsfile
3753 (when (string-match-p "\\bnbspstarsfile\\b" (thing-at-point 'line))
3754 (setq re-list '("\\(\\* \\)" ; common-re
3755 ?\xa0)) ; file-char non-breaking space
3756 (setq count (1+ count)))
3757 ;; #+STARTUP: markdownstarsfile
3758 (when (string-match-p "\\bmarkdownstarsfile\\b"
3759 (thing-at-point 'line))
3760 ;; Exclude e. g. "#STARTUP:".
3761 (setq re-list '("\\( \\)" ; common-re
3763 (setq count (1+ count))))
3764 (when (> count 1) (error "More than one fileconversion found."))
3767 (defun f-org-fileconv-decode ()
3768 "In headings replace file char with '*'."
3769 (let ((re-list (f-org-fileconv-re)))
3770 (when (and re-list (not v-org-fileconv-level-org-p))
3771 ;; No `save-excursion' to be able to keep point in case of error.
3772 (let* ((common-re (nth 0 re-list))
3773 (file-char (nth 1 re-list))
3774 (file-re (concat "^" (string file-char) "+" common-re))
3775 (org-re (concat "^\\*+" common-re))
3778 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3780 (when (re-search-forward org-re nil t)
3781 (goto-char (match-beginning 0))
3783 (error "Org fileconversion decode: Syntax conflict at point."))
3784 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3786 (with-silent-modifications
3787 (while (re-search-forward file-re nil t)
3788 (goto-char (match-beginning 0))
3789 ;; Faster than a lisp call of insert and delete on each single
3791 (setq len (- (match-beginning 1) (match-beginning 0)))
3792 (insert-char ?* len)
3796 ;; Notes for ediff when only one file has fileconversion:
3797 ;; - The changes to the buffer with fileconversion until here are
3798 ;; not regarded by `ediff-files' because the first call to diff is
3799 ;; made with the bare files directly. Only `ediff-update-diffs'
3800 ;; and `ediff-buffers' write the decoded buffers to temp files and
3801 ;; then call diff with them.
3802 ;; - Workarounds (choose one):
3803 ;; - After ediff-files first do a "!" (ediff-update-diffs) in the
3804 ;; "*Ediff Control Panel*".
3805 ;; - Instead of using `ediff-files' first open the files and then
3806 ;; run `ediff-buffers' (better for e. g. a script that takes two
3807 ;; files as arguments and uses "emacs --eval").
3809 ;; The level is Org most of all when no fileconversion is in effect.
3810 (setq v-org-fileconv-level-org-p t))
3812 (defun f-org-fileconv-encode ()
3813 "In headings replace '*' with file char."
3814 (let ((re-list (f-org-fileconv-re)))
3815 (when (and re-list v-org-fileconv-level-org-p)
3816 ;; No `save-excursion' to be able to keep point in case of error.
3817 (let* ((common-re (nth 0 re-list))
3818 (file-char (nth 1 re-list))
3819 (file-re (concat "^" (string file-char) "+" common-re))
3820 (org-re (concat "^\\*+" common-re))
3823 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3825 (when (re-search-forward file-re nil t)
3826 (goto-char (match-beginning 0))
3828 (error "Org fileconversion encode: Syntax conflict at point."))
3829 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3831 (with-silent-modifications
3832 (while (re-search-forward org-re nil t)
3833 (goto-char (match-beginning 0))
3834 ;; Faster than a lisp call of insert and delete on each single
3836 (setq len (- (match-beginning 1) (match-beginning 0)))
3837 (insert-char file-char len)
3840 (setq v-org-fileconv-level-org-p nil))))
3841 nil) ; For the hook.
3846 ** Meaningful diff for org files in a git repository
3847 #+index: git!diff org files
3848 Since most diff utilities are primarily meant for source code, it is
3849 difficult to read diffs of text files like ~.org~ files easily. If you
3850 version your org directory with a SCM like git you will know what I
3851 mean. However for git, there is a way around. You can use
3852 =gitattributes= to define a custom diff driver for org files. Then a
3853 regular expression can be used to configure how the diff driver
3854 recognises a "function".
3856 Put the following in your =<org_dir>/.gitattributes=.
3858 Then put the following lines in =<org_dir>/.git/config=
3860 : xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3862 This will let you see diffs for org files with each hunk identified by
3863 the unmodified headline closest to the changes. After the
3864 configuration a diff should look something like the example below.
3867 diff --git a/org-hacks.org b/org-hacks.org
3868 index a0672ea..92a08f7 100644
3871 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3873 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3875 +** Meaningful diff for org files in a git repository
3877 +Since most diff utilities are primarily meant for source code, it is
3878 +difficult to read diffs of text files like ~.org~ files easily. If you
3879 +version your org directory with a SCM like git you will know what I
3880 +mean. However for git, there is a way around. You can use
3881 +=gitattributes= to define a custom diff driver for org files. Then a
3882 +regular expression can be used to configure how the diff driver
3883 +recognises a "function".
3885 +Put the following in your =<org_dir>/.gitattributes=.
3887 +Then put the following lines in =<org_dir>/.git/config=
3889 +: xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3893 ** Cooking? Brewing?
3896 ** Opening devonthink links
3898 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3899 links from org-mode.
3901 ** Memacs - Org-mode collecting meta-data from the disk and cloud
3903 Karl Voit designed Memacs ([[https://en.wikipedia.org/wiki/Memex][Memex]] and Emacs) which is a collection of
3904 modules that are able to get meta-data from different kind of
3905 sources. Memacs then generates output files containing meta-data in
3906 Org-mode format. Those files a most likely integrated as ~*.org_archive~
3907 files in your agenda.
3909 This way, you can get a pretty decent overview of your (digital) life:
3910 - file name timestamps ([[https://en.wikipedia.org/wiki/Iso_date][ISO 8601]]; like "2013-10-11 Product Demonstration.odp")
3911 - emails (IMAP, POP, Maildir, mbox)
3912 - RSS feeds (blog updates, ... *lots* of possibilities there!)
3913 - version system commits (SVN, git)
3914 - calendar (iCal, CSV)
3915 - text messages from your phone (Android)
3916 - phone calls (Android)
3917 - photographs (EXIF)
3918 - bank accounts ([[http://easybank.at][easybank]])
3919 - usenet postings (slrn, mbox, ...)
3920 - XML (a sub-set of easy-to-parse XML files can be parsed with minimal
3923 General idea: you set up the module(s) you would like to use once and
3924 they are running in the background. As long as the data source does
3925 not change, you should not have to worry about the module again.
3927 It is hard to explain the vast amount of (small) benefits you get once
3928 you have set up your Memacs modules.
3930 There is [[http://arxiv.org/abs/1304.1332][a whitepaper which describes Memacs]] and its implications.
3932 Memacs is [[https://github.com/novoid/Memacs][hosted on github]] and is written in Python.
3934 You can use Memacs to write your own Memacs module: an example module
3935 demonstrates how to write modules with very low effort. Please
3936 consider a pull request on github so that other people can use your
3939 [[https://github.com/novoid/twitter-json_to_orgmode][Twitter JSON to Org-mode]] generates Memacs-like output files for
3940 [[https://blog.twitter.com/2012/your-twitter-archive][Twitter export archives]] (JSON) but is independent of Memacs.
3944 ** Cooking? Brewing?
3945 #+index: beer!brewing
3946 #+index: cooking!conversions
3947 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3949 It currently does metric/english conversion, and a few other tricks.
3950 Basically I just use calc’s units code. I think scaling recipes, or
3951 turning percentages into weights would be pretty easy.
3953 https://gitorious.org/org-cook/org-cook
3955 There is also, for those interested:
3957 https://gitorious.org/org-brew/org-brew
3959 for brewing beer. This is again, mostly just calc functions, including
3960 hydrometer correction, abv calculation, priming sugar for a given CO_2
3961 volume, etc. More integration with org-mode should be possible: for
3962 instance it would be nice to be able to use a lookup table (of ingredients)
3963 to calculate target original gravity, IBUs, etc.