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 *** Colorize clocking tasks with a block
25 :DIR: /home/stardiviner/Code/Emacs/worg/images/agenda/
28 Show Org Agenda tasks with heigh spacing based on clock time with ~org-agenda-log-mode~.
30 [[file:images/agenda/org-agenda-colorized-blocks.png]]
32 Here is original author's post https://emacs-china.org/t/org-agenda/8679.
34 Here is a hook function to use archive this effect:
36 #+begin_src emacs-lisp
37 ;; work with org-agenda dispatcher [c] "Today Clocked Tasks" to view today's clocked tasks.
38 (defun org-agenda-log-mode-colorize-block ()
39 "Set different line spacing based on clock time duration."
41 (let* ((colors (cl-case (alist-get 'background-mode (frame-parameters))
43 (list "#F6B1C3" "#FFFF9D" "#BEEB9F" "#ADD5F7"))
45 (list "#aa557f" "DarkGreen" "DarkSlateGray" "DarkSlateBlue"))))
49 (goto-char (point-min))
50 (while (setq pos (next-single-property-change (point) 'duration))
52 (when (and (not (equal pos (point-at-eol)))
53 (setq duration (org-get-at-bol 'duration)))
54 ;; larger duration bar height
55 (let ((line-height (if (< duration 15) 1.0 (+ 0.5 (/ duration 30))))
56 (ov (make-overlay (point-at-bol) (1+ (point-at-eol)))))
57 (overlay-put ov 'face `(:background ,(car colors) :foreground "black"))
58 (setq colors (cdr colors))
59 (overlay-put ov 'line-height line-height)
60 (overlay-put ov 'line-spacing (1- line-height))))))))
62 (add-hook 'org-agenda-finalize-hook #'org-agenda-log-mode-colorize-block)
65 *** Picking up a random task in the global TODO list
67 Tony day [[http://mid.gmane.org/m2zk19l1me.fsf@gmail.com][shared]] [[https://gist.github.com/4343164][this gist]] to pick up a
70 ** Building and Managing Org
71 *** Generating autoloads and Compiling Org without make
73 :CUSTOM_ID: compiling-org-without-make
76 #+index: Compilation!without make
78 Compilation is optional, but you _must_ update the autoloads file
79 each time you update org, even when you run org uncompiled!
81 Starting with Org 7.9 you'll find functions for creating the
82 autoload files and do byte-compilation in =mk/org-fixup.el=. When
83 you execute the commands below, your current directory must be where
84 org has been unpacked into, in other words the file =README= should
85 be found in your current directory and the directories =lisp= and
86 =etc= should be subdirectories of it. The command =emacs= should be
87 found in your =PATH= and start the Emacs version you are using. To
88 make just the autoloads file do:
89 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
90 To make the autoloads file and byte-compile org:
91 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
92 To make the autoloads file and byte-compile all of org again:
93 : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
94 If you are not using Git, you'll have to make fake version strings
95 first if =org-version.el= is not already available (if it is, you
96 could also edit the version strings there).
97 : emacs -batch -Q -L lisp -l ../mk/org-fixup \
98 : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
99 : (org-make-autoloads))'
101 POSIX shell for its quoting. Windows =CMD.exe= has quite different
102 quoting rules and this won't work, so your other option is to start
104 : emacs -Q -L lisp -l ../mk/org-fixup
105 then paste the following into the =*scratch*= buffer
106 #+BEGIN_SRC emacs-lisp
107 (let ((org-fake-release "7.9.1")
108 (org-fake-git-version "7.9.1-fake"))
109 (org-make-autoloads))
111 position the cursor after the closing paren and press =C-j= or =C-x
112 C-e= to evaluate the form. Of course you can replace
113 =org-make-autoloads= with =org-make-autoloads-compile= or even
114 =org-make-autoloads-compile-force= if you wish with both variants.
116 For *older org versions only* (that do not yet have
117 =mk/org-fixup.el=), you can use the definitions below. To use
118 this function, adjust the variables =my/org-lisp-directory= and
119 =my/org-compile-sources= to suit your needs. If you have
120 byte-compiled org, but want to run org uncompiled again, just remove
121 all =*.elc= files in the =lisp/= directory, set
122 =my/org-compile-sources= to =nil=.
124 #+BEGIN_SRC emacs-lisp
125 (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
126 "Directory where your org-mode files live.")
128 (defvar my/org-compile-sources t
129 "If `nil', never compile org-sources. `my/compile-org' will only create
130 the autoloads file `org-loaddefs.el' then. If `t', compile the sources, too.")
132 ;; Customize: (must end with a slash!)
133 (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")
136 (setq my/org-compile-sources t)
138 (defun my/compile-org(&optional directory)
139 "Generate autoloads file org-loaddefs.el. Optionally compile
140 all *.el files that come with org-mode."
142 (defun my/compile-org()
143 "Generate autoloads file org-loaddefs.el. Optionally compile
144 all *.el files that come with org-mode."
146 (let ((dirlisp (file-name-directory my/org-lisp-directory)))
147 (add-to-list 'load-path dirlisp)
149 (let ((generated-autoload-file (concat dirlisp "org-loaddefs.el")))
150 ;; create the org-loaddefs file
151 (update-directory-autoloads dirlisp)
152 (when my/org-compile-sources
153 ;; optionally byte-compile
154 (byte-recompile-directory dirlisp 0 'force)))))
158 #+index: Initialization!Reload
160 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
161 function to reload org files.
163 Normally you want to use the compiled files since they are faster.
164 If you update your org files you can easily reload them with
168 If you run into a bug and want to generate a useful backtrace you can
169 reload the source files instead of the compiled files with
173 and turn on the "Enter Debugger On Error" option. Redo the action
174 that generates the error and cut and paste the resulting backtrace.
175 To switch back to the compiled version just reload again with
179 *** Check for possibly problematic old link escapes
181 :CUSTOM_ID: check-old-link-escapes
184 Starting with version 7.5 Org uses [[https://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
185 and with a modified algorithm to determine which characters to escape
188 As a side effect this modified behaviour might break existing links if
189 they contain a sequence of characters that look like a percent escape
190 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
192 The function below can be used to perform a preliminary check for such
193 links in an Org mode file. It will run through all links in the file
194 and issue a warning if it finds a percent escape sequence which is not
195 in old Org's list of known percent escapes.
197 #+begin_src emacs-lisp
198 (defun dmaus/org-check-percent-escapes ()
199 "*Check buffer for possibly problematic old link escapes."
201 (when (eq major-mode 'org-mode)
202 (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
203 "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
204 (unless (boundp 'warning-suppress-types)
205 (setq warning-suppress-types nil))
208 (goto-char (point-min))
209 (while (re-search-forward org-any-link-re nil t)
210 (let ((end (match-end 0)))
211 (goto-char (match-beginning 0))
212 (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
213 (let ((escape (match-string-no-properties 0)))
214 (unless (member (upcase escape) old-escapes)
215 (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
222 ** Structure Movement and Editing
223 *** Go back to the previous top-level heading
225 #+BEGIN_SRC emacs-lisp
226 (defun org-back-to-top-level-heading ()
227 "Go back to the current top level heading."
229 (or (re-search-backward "^\* " nil t)
230 (goto-char (point-min))))
233 *** Go to a child of the current heading
235 :CUSTOM_ID: org-jump-to-child
237 #+index: Navigation!Heading
238 - [[http://langec.wordpress.com][Christoph Lange]]
240 =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).
242 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.
244 *** Go to a heading by its ID (=CUSTOM_ID= property)
246 :CUSTOM_ID: org-jump-to-id
248 #+index: Navigation!Heading
249 - [[http://langec.wordpress.com][Christoph Lange]]
251 =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.
253 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.
255 I noticed that =org-babel-ref-goto-headline-id= does something similar, so maybe some code could be shared among the two functions.
256 *** Show next/prev heading tidily
258 #+index: Navigation!Heading
260 These close the current heading and open the next/previous heading.
262 #+begin_src emacs-lisp
263 (defun ded/org-show-next-heading-tidily ()
264 "Show next entry, keeping other entries closed."
265 (if (save-excursion (end-of-line) (outline-invisible-p))
266 (progn (org-show-entry) (show-children))
267 (outline-next-heading)
268 (unless (and (bolp) (org-on-heading-p))
269 (org-up-heading-safe)
271 (error "Boundary reached"))
277 (defun ded/org-show-previous-heading-tidily ()
278 "Show previous entry, keeping other entries closed."
280 (outline-previous-heading)
281 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
284 (error "Boundary reached"))
290 (setq org-use-speed-commands t)
291 (add-to-list 'org-speed-commands-user
292 '("n" ded/org-show-next-heading-tidily))
293 (add-to-list 'org-speed-commands-user
294 '("p" ded/org-show-previous-heading-tidily))
297 *** Promote all items in subtree
298 #+index: Structure Editing!Promote
301 This function will promote all items in a subtree. Since I use
302 subtrees primarily to organize projects, the function is somewhat
303 unimaginatively called my-org-un-project:
305 #+begin_src emacs-lisp
306 (defun my-org-un-project ()
308 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
312 *** Turn a heading into an Org link
314 :CUSTOM_ID: heading-to-link
316 #+index: Structure Editing!Heading
317 #+index: Link!Turn a heading into a
320 #+begin_src emacs-lisp
321 (defun dmj:turn-headline-into-org-mode-link ()
322 "Replace word at point by an Org mode link."
324 (when (org-at-heading-p)
325 (let ((hl-text (nth 4 (org-heading-components))))
326 (unless (or (null hl-text)
327 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
329 (search-forward hl-text (point-at-eol))
332 (format "[[file:%s.org][%s]]"
333 (org-link-escape hl-text)
334 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
335 nil (- (point) (length hl-text)) (point))))))
338 *** Using M-up and M-down to transpose paragraphs
339 #+index: Structure Editing!paragraphs
341 From Paul Sexton: By default, if used within ordinary paragraphs in
342 org mode, =M-up= and =M-down= transpose *lines* (not sentences). The
343 following code makes these keys transpose paragraphs, keeping the
344 point at the start of the moved paragraph. Behavior in tables and
345 headings is unaffected. It would be easy to modify this to transpose
348 #+begin_src emacs-lisp
349 (defun org-transpose-paragraphs (arg)
351 (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
352 (thing-at-point 'sentence))
353 (transpose-paragraphs arg)
355 (re-search-forward "[[:graph:]]")
356 (goto-char (match-beginning 0))
359 (add-to-list 'org-metaup-hook
360 (lambda () (interactive) (org-transpose-paragraphs -1)))
361 (add-to-list 'org-metadown-hook
362 (lambda () (interactive) (org-transpose-paragraphs 1)))
364 *** Changelog support for org headers
365 #+index: Structure Editing!Heading
368 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
369 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
370 headline as the "current function" if you add a changelog entry from an org
373 #+BEGIN_SRC emacs-lisp
374 (defun org-log-current-defun ()
376 (org-back-to-heading)
377 (if (looking-at org-complex-heading-regexp)
380 (add-hook 'org-mode-hook
382 (make-variable-buffer-local 'add-log-current-defun-function)
383 (setq add-log-current-defun-function 'org-log-current-defun)))
386 *** Different org-cycle-level behavior
387 #+index: Cycling!behavior
390 In recent org versions, when your point (cursor) is at the end of an
391 empty header line (like after you first created the header), the TAB
392 key (=org-cycle=) has a special behavior: it cycles the headline through
393 all possible levels. However, I did not like the way it determined
394 "all possible levels," so I rewrote the whole function, along with a
395 couple of supporting functions.
397 The original function's definition of "all possible levels" was "every
398 level from 1 to one more than the initial level of the current
399 headline before you started cycling." My new definition is "every
400 level from 1 to one more than the previous headline's level." So, if
401 you have a headline at level 4 and you use ALT+RET to make a new
402 headline below it, it will cycle between levels 1 and 5, inclusive.
404 The main advantage of my custom =org-cycle-level= function is that it
405 is stateless: the next level in the cycle is determined entirely by
406 the contents of the buffer, and not what command you executed last.
407 This makes it more predictable, I hope.
409 #+BEGIN_SRC emacs-lisp
412 (defun org-point-at-end-of-empty-headline ()
413 "If point is at the end of an empty headline, return t, else nil."
414 (and (looking-at "[ \t]*$")
416 (beginning-of-line 1)
417 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
419 (defun org-level-increment ()
420 "Return the number of stars that will be added or removed at a
421 time to headlines when structure editing, based on the value of
422 `org-odd-levels-only'."
423 (if org-odd-levels-only 2 1))
425 (defvar org-previous-line-level-cached nil)
427 (defun org-recalculate-previous-line-level ()
428 "Same as `org-get-previous-line-level', but does not use cached
429 value. It does *set* the cached value, though."
430 (set 'org-previous-line-level-cached
431 (let ((current-level (org-current-level))
432 (prev-level (when (> (line-number-at-pos) 1)
435 (org-current-level)))))
436 (cond ((null current-level) nil) ; Before first headline
437 ((null prev-level) 0) ; At first headline
440 (defun org-get-previous-line-level ()
441 "Return the outline depth of the last headline before the
442 current line. Returns 0 for the first headline in the buffer, and
443 nil if before the first headline."
444 ;; This calculation is quite expensive, with all the regex searching
445 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
446 ;; the last value of this command.
447 (or (and (eq last-command 'org-cycle-level)
448 org-previous-line-level-cached)
449 (org-recalculate-previous-line-level)))
451 (defun org-cycle-level ()
453 (let ((org-adapt-indentation nil))
454 (when (org-point-at-end-of-empty-headline)
455 (setq this-command 'org-cycle-level) ;Only needed for caching
456 (let ((cur-level (org-current-level))
457 (prev-level (org-get-previous-line-level)))
459 ;; If first headline in file, promote to top-level.
461 (loop repeat (/ (- cur-level 1) (org-level-increment))
462 do (org-do-promote)))
463 ;; If same level as prev, demote one.
464 ((= prev-level cur-level)
466 ;; If parent is top-level, promote to top level if not already.
468 (loop repeat (/ (- cur-level 1) (org-level-increment))
469 do (org-do-promote)))
470 ;; If top-level, return to prev-level.
472 (loop repeat (/ (- prev-level 1) (org-level-increment))
474 ;; If less than prev-level, promote one.
475 ((< cur-level prev-level)
477 ;; If deeper than prev-level, promote until higher than
479 ((> cur-level prev-level)
480 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
481 do (org-do-promote))))
485 *** Count words in an Org buffer
486 # FIXME: Does not fit too well under Structure. Any idea where to put it?
487 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
489 #+begin_src emacs-lisp
490 (defun org-word-count (beg end
491 &optional count-latex-macro-args?
493 "Report the number of words in the Org mode buffer or selected region.
497 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
498 - hyperlinks (but does count words in hyperlink descriptions)
499 - tags, priorities, and TODO keywords in headers
500 - sections tagged as 'not for export'.
502 The text of footnote definitions is ignored, unless the optional argument
503 COUNT-FOOTNOTES? is non-nil.
505 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
506 includes LaTeX macro arguments (the material between {curly braces}).
507 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
511 (setf beg (point-min)
514 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
517 (while (< (point) end)
520 ((or (org-in-commented-line) (org-at-table-p))
522 ;; Ignore hyperlinks. But if link has a description, count
523 ;; the words within the description.
524 ((looking-at org-bracket-link-analytic-regexp)
525 (when (match-string-no-properties 5)
526 (let ((desc (match-string-no-properties 5)))
528 (incf wc (length (remove "" (org-split-string
530 (goto-char (match-end 0)))
531 ((looking-at org-any-link-re)
532 (goto-char (match-end 0)))
533 ;; Ignore source code blocks.
534 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
536 ;; Ignore inline source blocks, counting them as 1 word.
539 (looking-at org-babel-inline-src-block-regexp))
540 (goto-char (match-end 0))
542 ;; Count latex macros as 1 word, ignoring their arguments.
545 (looking-at latex-macro-regexp))
546 (goto-char (if count-latex-macro-args?
551 ((and (not count-footnotes?)
552 (or (org-footnote-at-definition-p)
553 (org-footnote-at-reference-p)))
556 (let ((contexts (org-context)))
558 ;; Ignore tags and TODO keywords, etc.
559 ((or (assoc :todo-keyword contexts)
560 (assoc :priority contexts)
561 (assoc :keyword contexts)
562 (assoc :checkbox contexts))
564 ;; Ignore sections marked with tags that are
565 ;; excluded from export.
566 ((assoc :tags contexts)
567 (if (intersection (org-get-tags-at) org-export-exclude-tags
569 (org-forward-same-level 1)
573 (re-search-forward "\\w+\\W*")))
574 (message (format "%d words in %s." wc
575 (if mark-active "region" "buffer")))))
578 *** Check for misplaced SCHEDULED and DEADLINE cookies
580 The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
581 below* the headline -- like this:
585 SCHEDULED: <2012-04-09 lun.>
588 This is what =org-scheduled= and =org-deadline= (and other similar
589 commands) do. And the manual explicitely tell people to stick to this
590 format (see the section "8.3.1 Inserting deadlines or schedules").
592 If you think you might have subtrees with misplaced =SCHEDULED= and
593 =DEADLINE= cookies, this command lets you check the current buffer:
595 #+begin_src emacs-lisp
596 (defun org-check-misformatted-subtree ()
597 "Check misformatted entries in the current buffer."
602 (when (and (move-beginning-of-line 2)
603 (not (looking-at org-heading-regexp)))
604 (if (or (and (org-get-scheduled-time (point))
605 (not (looking-at (concat "^.*" org-scheduled-regexp))))
606 (and (org-get-deadline-time (point))
607 (not (looking-at (concat "^.*" org-deadline-regexp)))))
608 (when (y-or-n-p "Fix this subtree? ")
609 (message "Call the function again when you're done fixing this subtree.")
611 (message "All subtrees checked."))))))
614 *** Sorting list by checkbox type
616 #+index: checkbox!sorting
618 You can use a custom function to sort list by checkbox type.
619 Here is a function suggested by Carsten:
621 #+BEGIN_SRC emacs-lisp
622 (defun org-sort-list-by-checkbox-type ()
623 "Sort list items according to Checkbox state."
628 (if (looking-at org-list-full-item-re)
629 (cdr (assoc (match-string 3)
630 '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
634 Use the function above directly on the list. If you want to use an
635 equivalent function after =C-c ^ f=, use this one instead:
637 #+BEGIN_SRC emacs-lisp
638 (defun org-sort-list-by-checkbox-type-1 ()
640 (if (looking-at org-list-full-item-re)
641 (cdr (assoc (match-string 3)
642 '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
646 *** Adding Licenses to org files
648 You can add pretty standard licenses, such as creative commons or gfdl
649 to org articles using =org-license.el=.
656 *** Align all tables in a file
658 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
660 #+begin_src emacs-lisp
661 (defun my-align-all-tables ()
663 (org-table-map-tables 'org-table-align 'quietly))
668 :CUSTOM_ID: transpose-table
670 #+index: Table!Calculation
672 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
673 see.) There are also other solutions:
675 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
676 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]]
678 - with org-babel and R: provided by Dan Davison in the mailing list (old
679 =#+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]]
681 - with field coordinates in formulas (=@#= and =$#=): see [[#field-coordinates-in-formulas-transpose-table][Worg]].
683 *** Manipulate hours/minutes/seconds in table formulas
684 #+index: Table!hours-minutes-seconds
685 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
686 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
687 "=d=" is any digit) as time values in Org-mode table formula. These
688 functions have now been wrapped up into a =with-time= macro which can
689 be used in table formula to translate table cell values to and from
690 numerical values for algebraic manipulation.
692 Here is the code implementing this macro.
693 #+begin_src emacs-lisp :results silent
694 (defun org-time-string-to-seconds (s)
695 "Convert a string HH:MM:SS to a number of seconds."
698 (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
699 (let ((hour (string-to-number (match-string 1 s)))
700 (min (string-to-number (match-string 2 s)))
701 (sec (string-to-number (match-string 3 s))))
702 (+ (* hour 3600) (* min 60) sec)))
704 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
705 (let ((min (string-to-number (match-string 1 s)))
706 (sec (string-to-number (match-string 2 s))))
708 ((stringp s) (string-to-number s))
711 (defun org-time-seconds-to-string (secs)
712 "Convert a number of seconds to a time string."
713 (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
714 ((>= secs 60) (format-seconds "%m:%.2s" secs))
715 (t (format-seconds "%s" secs))))
717 (defmacro with-time (time-output-p &rest exprs)
718 "Evaluate an org-table formula, converting all fields that look
719 like time data to integer seconds. If TIME-OUTPUT-P then return
720 the result as a time value."
722 (if time-output-p 'org-time-seconds-to-string 'identity)
730 (list 'with-time nil el)
731 (org-time-string-to-seconds el)))
736 Which allows the following forms of table manipulation such as adding
737 and subtracting time values.
738 : | Date | Start | Lunch | Back | End | Sum |
739 : |------------------+-------+-------+-------+-------+------|
740 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
741 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
743 and dividing time values by integers
744 : | time | miles | minutes/mile |
745 : |-------+-------+--------------|
746 : | 34:43 | 2.9 | 11:58 |
747 : | 32:15 | 2.77 | 11:38 |
748 : | 33:56 | 3.0 | 11:18 |
749 : | 52:22 | 4.62 | 11:20 |
750 : #+TBLFM: $3='(with-time t (/ $1 $2))
752 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
753 Elisp formulas) to compute time durations. For example:
755 : | Task 1 | Task 2 | Total |
756 : |--------+--------+---------|
757 : | 35:00 | 35:00 | 1:10:00 |
758 : #+TBLFM: @2$3=$1+$2;T
760 *** Dates computation
762 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of
763 dates stored in an org table.
765 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
769 : | Start Date | End Date | Duration |
770 : |------------+------------+----------|
771 : | 2004.08.07 | 2005.07.08 | 335 |
772 : #+TBLFM: $3=(date(<$2>)-date(<$1>))
774 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
775 above). The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
776 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
779 #+index: Table!Calculation
780 As with Times computation, the following code allows Computation with
781 Hex values in Org-mode tables using the =with-hex= macro.
783 Here is the code implementing this macro.
784 #+begin_src emacs-lisp
785 (defun org-hex-strip-lead (str)
786 (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
787 (substring str 2) str))
789 (defun org-hex-to-hex (int)
792 (defun org-hex-to-dec (str)
795 (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
799 (setf out (+ (* out 16)
800 (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
801 (coerce (match-string 1 str) 'list))
803 ((stringp str) (string-to-number str))
806 (defmacro with-hex (hex-output-p &rest exprs)
807 "Evaluate an org-table formula, converting all fields that look
808 like hexadecimal to decimal integers. If HEX-OUTPUT-P then
809 return the result as a hex value."
811 (if hex-output-p 'org-hex-to-hex 'identity)
818 (list 'with-hex nil el)
819 (org-hex-to-dec el)))
824 Which allows the following forms of table manipulation such as adding
825 and subtracting hex values.
826 | 0x10 | 0x0 | #ERROR | #ERROR |
827 | 0x20 | 0x1 | #ERROR | #ERROR |
828 | 0x30 | 0x2 | #ERROR | #ERROR |
829 | 0xf0 | 0xf | #ERROR | #ERROR |
830 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
832 *** Field coordinates in formulas (=@#= and =$#=)
834 :CUSTOM_ID: field-coordinates-in-formulas
836 #+index: Table!Field Coordinates
839 Following are some use cases that can be implemented with the “field
840 coordinates in formulas” described in the corresponding chapter in the
841 [[https://orgmode.org/manual/References.html#References][Org manual]].
843 **** Copy a column from a remote table into a column
845 :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
848 current column =$3= = remote column =$2=:
849 : #+TBLFM: $3 = remote(FOO, @@#$2)
851 **** Copy a row from a remote table transposed into a column
853 :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
856 current column =$1= = transposed remote row =@1=:
857 : #+TBLFM: $1 = remote(FOO, @$#$@#)
861 :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
866 This is more like a demonstration of using “field coordinates in formulas”
867 and is bound to be slow for large tables. See the discussion in the mailing
869 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
870 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
871 For more efficient solutions see
872 [[#transpose-table][Worg]].
874 To transpose this 4x7 table
877 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
878 : |------+------+------+------+------+------+------|
879 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
880 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
881 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
883 start with a 7x4 table without any horizontal line (to have filled
884 also the column header) and yet empty:
894 Then add the =TBLFM= line below. After recalculation this will end up with
897 : | year | min | avg | max |
898 : | 2004 | 401 | 402 | 403 |
899 : | 2005 | 501 | 502 | 503 |
900 : | 2006 | 601 | 602 | 603 |
901 : | 2007 | 701 | 702 | 703 |
902 : | 2008 | 801 | 802 | 803 |
903 : | 2009 | 901 | 902 | 903 |
904 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
906 The formula simply exchanges row and column numbers by taking
907 - the absolute remote row number =@$#= from the current column number =$#=
908 - the absolute remote column number =$@#= from the current row number =@#=
910 Formulas to be taken over from the remote table will have to be transformed
913 **** Dynamic variation of ranges
917 In this example all columns next to =quote= are calculated from the column
918 =quote= and show the average change of the time series =quote[year]=
919 during the period of the preceding =1=, =2=, =3= or =4= years:
921 : | year | quote | 1 a | 2 a | 3 a | 4 a |
922 : |------+-------+-------+-------+-------+-------|
923 : | 2005 | 10 | | | | |
924 : | 2006 | 12 | 0.200 | | | |
925 : | 2007 | 14 | 0.167 | 0.183 | | |
926 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
927 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
928 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
930 The important part of the formula without the field blanking is:
932 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
934 which is the Emacs Calc implementation of the equation
936 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
938 where /i/ is the current time and /a/ is the length of the preceding period.
940 *** Rearrange one or more field within the same row or column
942 :CUSTOM_ID: field-same-row-or-column
944 #+index: Table!Editing
948 **** Rearrange the column sequence in one row only
950 :CUSTOM_ID: column-sequence-in-row
952 #+index: Table!Editing
954 The functions below can be used to change the column sequence in one
955 row only, without affecting the other rows above and below like with
956 =M-<left>= or =M-<right>= (=org-table-move-column=). See also the
957 docstring of the functions for more explanations. The original table
958 that serves as the starting point for the examples:
961 : | e | 9 | 10 | 11 |
964 ***** Move current field in row
967 1) place point at "10" in original table
968 2) =M-x f-org-table-move-field-in-row-left=
969 3) point is at moved "10"
972 : | e | 10 | 9 | 11 |
977 1) place point at "9" in original table
978 2) =M-x f-org-table-move-field-in-row-right=
979 3) point is at moved "9"
982 : | e | 10 | 9 | 11 |
985 ***** Rotate rest of row (range from current field to end of row)
988 1) place point at @2$2 in original table
989 2) =M-x f-org-table-rotate-rest-of-row-left=
990 3) point is still at @2$2
993 : | e | 10 | 11 | 9 |
998 1) place point at @2$2 in original table
999 2) =M-x f-org-table-rotate-rest-of-row-right=
1000 3) point is still at @2$2
1003 : | e | 11 | 9 | 10 |
1006 ***** Open field in row (table size grows)
1008 This is just for completeness, interactively the same as typing =|
1011 1) place point at @2$2 in original table
1012 2) =M-x f-org-table-open-field-in-row-grow=
1013 3) point is still at @2$2
1015 : | a | b | c | d | |
1016 : | e | | 9 | 10 | 11 |
1017 : | f | g | h | i | |
1019 **** Rearrange the row sequence in one column only
1021 :CUSTOM_ID: row-sequence-in-column
1023 #+index: Table!Editing
1025 The functions below can be used to change the column sequence in one
1026 column only, without affecting the other columns left and right like
1027 with =M-<up>= or =M-<down>= (=org-table-move-row=). See also the
1028 docstring of the functions for more explanations. The original table
1029 that serves as the starting point for the examples:
1038 ***** Move current field in column
1041 1) place point at "10" in original table
1042 2) =M-x f-org-table-move-field-in-column-up=
1043 3) point is at moved "10"
1054 1) place point at "9" in original table
1055 2) =M-x f-org-table-move-field-in-column-down=
1056 3) point is at moved "9"
1065 ***** Rotate rest of column (range from current field to end of column)
1068 1) place point at @2$2 in original table
1069 2) =M-x f-org-table-rotate-rest-of-column-up=
1070 3) point is still at @2$2
1081 1) place point at @2$2 in original table
1082 2) =M-x f-org-table-rotate-rest-of-column-down=
1083 3) point is still at @2$2
1092 ***** Open field in column (table size grows)
1094 1) place point at @2$2 in original table
1095 2) =M-x f-org-table-open-field-in-column-grow=
1096 3) point is still at @2$2
1106 **** Key bindings for some of the functions
1108 I have this in an Org buffer to change temporarily to the desired
1109 behavior with =C-c C-c= on one of the three code snippets:
1112 : #+begin_src emacs-lisp :results silent
1113 : (org-defkey org-mode-map [(meta left)]
1114 : 'f-org-table-move-field-in-row-left)
1115 : (org-defkey org-mode-map [(meta right)]
1116 : 'f-org-table-move-field-in-row-right)
1117 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
1118 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
1122 : #+begin_src emacs-lisp :results silent
1123 : (org-defkey org-mode-map [(meta left)]
1124 : 'f-org-table-rotate-rest-of-row-left)
1125 : (org-defkey org-mode-map [(meta right)]
1126 : 'f-org-table-rotate-rest-of-row-right)
1127 : (org-defkey org-mode-map [(left)] 'org-table-previous-field)
1128 : (org-defkey org-mode-map [(right)] 'org-table-next-field)
1131 : - back to original:
1132 : #+begin_src emacs-lisp :results silent
1133 : (org-defkey org-mode-map [(meta left)] 'org-metaleft)
1134 : (org-defkey org-mode-map [(meta right)] 'org-metaright)
1135 : (org-defkey org-mode-map [(left)] 'backward-char)
1136 : (org-defkey org-mode-map [(right)] 'forward-char)
1143 : f-org-table-move-field-in-column-up
1144 : f-org-table-move-field-in-column-down
1145 : f-org-table-rotate-rest-of-column-up
1146 : f-org-table-rotate-rest-of-column-down
1148 are not yet implemented. They could be done similar to
1149 =f-org-table-open-field-in-column-grow=. A workaround without keeping
1150 horizontal separator lines is to interactively or programmatically
1153 1) Transpose the table, see
1154 [[#transpose-table][Org hacks]].
1155 2) Use =f-org-table-*-column-in-row-*=, see
1156 [[https://orgmode.org/worg/org-hacks.html#column-sequence-in-row][previous
1158 3) Transpose the table.
1160 The other functions:
1162 #+BEGIN_SRC emacs-lisp
1163 (defun f-org-table-move-field-in-row-left ()
1164 "Move current field in row to the left."
1166 (f-org-table-move-field-in-row 'left))
1167 (defun f-org-table-move-field-in-row-right ()
1168 "Move current field in row to the right."
1170 (f-org-table-move-field-in-row nil))
1172 (defun f-org-table-move-field-in-row (&optional left)
1173 "Move current field in row to the right.
1174 With arg LEFT, move to the left. For repeated invocation the
1175 point follows the moved field. Does not fix formulas."
1176 ;; Derived from `org-table-move-column'
1178 (if (not (org-at-table-p))
1179 (error "Not at a table"))
1180 (org-table-find-dataline)
1181 (org-table-check-inside-data-field)
1182 (let* ((col (org-table-current-column))
1183 (col1 (if left (1- col) col))
1184 ;; Current cursor position
1185 (colpos (if left (1- col) (1+ col))))
1186 (if (and left (= col 1))
1187 (error "Cannot move column further left"))
1188 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1189 (error "Cannot move column further right"))
1190 (org-table-goto-column col1 t)
1191 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1192 (replace-match "|\\2|\\1|"))
1193 (org-table-goto-column colpos)
1196 (defun f-org-table-rotate-rest-of-row-left ()
1197 "Rotate rest of row to the left."
1199 (f-org-table-rotate-rest-of-row 'left))
1200 (defun f-org-table-rotate-rest-of-row-right ()
1201 "Rotate rest of row to the right."
1203 (f-org-table-rotate-rest-of-row nil))
1205 (defun f-org-table-rotate-rest-of-row (&optional left)
1206 "Rotate rest of row to the right.
1207 With arg LEFT, rotate to the left. For both directions the
1208 boundaries of the rotation range are the current field and the
1209 field at the end of the row. For repeated invocation the point
1210 stays on the original current field. Does not fix formulas."
1211 ;; Derived from `org-table-move-column'
1213 (if (not (org-at-table-p))
1214 (error "Not at a table"))
1215 (org-table-find-dataline)
1216 (org-table-check-inside-data-field)
1217 (let ((col (org-table-current-column)))
1218 (org-table-goto-column col t)
1219 (and (looking-at (if left
1220 "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
1221 "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
1222 (replace-match "|\\2|\\1|"))
1223 (org-table-goto-column col)
1226 (defun f-org-table-open-field-in-row-grow ()
1227 "Open field in row, move fields to the right by growing table."
1233 (defun f-org-table-open-field-in-column-grow ()
1234 "Open field in column, move all fields downwards by growing table."
1236 (let ((col (org-table-current-column))
1238 ;; Cut all fields downwards in same column
1239 (goto-char (org-table-end))
1241 (while (org-at-table-hline-p) (forward-line -1))
1242 (org-table-goto-column col)
1243 (org-table-cut-region p (point))
1244 ;; Paste at one field below
1247 (org-table-goto-column col)
1248 (org-table-paste-rectangle)
1253 **** Reasons why this is not put into the Org core
1255 I consider this as only a hack for several reasons:
1257 - Generalization: The existing function =org-table-move-column= could
1258 be enhanced with additional optional parameters to incorporate these
1259 functionalities and could be used as the only function for better
1260 maintainability. Now it's only a copy/paste hack of several similar
1261 functions with simple modifications.
1262 - Bindings: Should be convenient for repetition like =M-<right>=.
1263 What should be bound where, what has to be left unbound?
1264 - Does not fix formulas. Could be resolved for field formulas but
1265 most probably not for column or range formulas and this can lead to
1266 confusion. AFAIK all table manipulations found in Org core fix
1268 - Completeness: Not all variations and combinations are covered yet
1269 - move, rotate with range to end, rotate with range to begin, rotate
1271 - left-right, up-down
1273 ** Capture and Remember
1274 *** Customize the size of the frame for remember
1275 #+index: Remember!frame
1276 #+index: Customization!remember
1277 (Note: this hack is likely out of date due to the development of
1280 # FIXME: gmane link?
1281 On emacs-orgmode, Ryan C. Thompson suggested this:
1284 I am using org-remember set to open a new frame when used,
1285 and the default frame size is much too large. To fix this, I have
1286 designed some advice and a custom variable to implement custom
1287 parameters for the remember frame:
1290 #+begin_src emacs-lisp
1291 (defcustom remember-frame-alist nil
1292 "Additional frame parameters for dedicated remember frame."
1296 (defadvice remember (around remember-frame-parameters activate)
1297 "Set some frame parameters for the remember frame."
1298 (let ((default-frame-alist (append remember-frame-alist
1299 default-frame-alist)))
1303 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1304 reasonable size for the frame.
1305 *** [[https://github.com/PhilHudson/org-capture-vars.el][User-defined capture template variables with prompt and completion list]]
1306 *** [[https://github.com/alphapapa/unpackaged.el#ensure-blank-lines-between-headings-and-before-contents][Ensure blank lines between headings and before contents]]
1308 *** [[#heading-to-link][Turn a heading into an org link]]
1309 *** Quickaccess to the link part of hyperlinks
1310 #+index: Link!Referent
1311 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1312 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1313 which is indeed kind of cumbersome.
1315 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1317 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1318 #+begin_src emacs-lisp
1320 (lambda (&optional arg)
1323 (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1327 #+begin_src emacs-lisp
1328 (defun my-org-extract-link ()
1329 "Extract the link location at point and put it on the killring."
1331 (when (org-in-regexp org-bracket-link-regexp 1)
1332 (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1335 They put the link destination on the killring and can be easily bound to a key.
1337 *** Insert link with HTML title as default description
1338 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1339 from HTML <title> tag and use it as a default link description. Here is a way to
1342 #+begin_src emacs-lisp
1343 (require 'mm-url) ; to include mm-url-decode-entities-string
1345 (defun my-org-insert-link ()
1346 "Insert org link where default description is set to html title."
1348 (let* ((url (read-string "URL: "))
1349 (title (get-html-title-from-url url)))
1350 (org-insert-link nil url title)))
1352 (defun get-html-title-from-url (url)
1353 "Return content in <title> tag."
1354 (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1356 (set-buffer download-buffer)
1357 (beginning-of-buffer)
1358 (setq x1 (search-forward "<title>"))
1359 (search-forward "</title>")
1360 (setq x2 (search-backward "<"))
1361 (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1364 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1366 ** Archiving Content in Org-Mode
1367 *** Preserve top level headings when archiving to a file
1368 #+index: Archiving!Preserve top level headings
1371 To preserve (somewhat) the integrity of your archive structure while
1372 archiving lower level items to a file, you can use the following
1375 #+begin_src emacs-lisp
1376 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1377 (let ((org-archive-location
1378 (if (save-excursion (org-back-to-heading)
1379 (> (org-outline-level) 1))
1380 (concat (car (split-string org-archive-location "::"))
1382 (car (org-get-outline-path)))
1383 org-archive-location)))
1387 Thus, if you have an outline structure such as...
1395 ...archiving "Subsubheading" to a new file will set the location in
1396 the new file to the top level heading:
1403 While this hack obviously destroys the outline hierarchy somewhat, it
1404 at least preserves the logic of level one groupings.
1406 A slightly more complex version of this hack will not only keep the
1407 archive organized by top-level headings, but will also preserve the
1408 tags found on those headings:
1410 #+begin_src emacs-lisp
1411 (defun my-org-inherited-no-file-tags ()
1412 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1413 (ltags (org-entry-get nil "TAGS")))
1416 (replace-regexp-in-string (concat tag ":") "" tags)))
1417 (append org-file-tags (when ltags (split-string ltags ":" t))))
1418 (if (string= ":" tags) nil tags)))
1420 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1421 (let ((tags (my-org-inherited-no-file-tags))
1422 (org-archive-location
1423 (if (save-excursion (org-back-to-heading)
1424 (> (org-outline-level) 1))
1425 (concat (car (split-string org-archive-location "::"))
1427 (car (org-get-outline-path)))
1428 org-archive-location)))
1430 (with-current-buffer (find-file-noselect (org-extract-archive-file))
1432 (while (org-up-heading-safe))
1433 (org-set-tags-to tags)))))
1436 *** Archive in a date tree
1437 #+index: Archiving!date tree
1438 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1440 (Make sure org-datetree.el is loaded for this to work.)
1442 #+begin_src emacs-lisp
1443 ;; (setq org-archive-location "%s_archive::date-tree")
1444 (defadvice org-archive-subtree
1445 (around org-archive-subtree-to-data-tree activate)
1446 "org-archive-subtree to date-tree"
1448 (string= "date-tree"
1449 (org-extract-archive-heading
1450 (org-get-local-archive-location)))
1451 (let* ((dct (decode-time (org-current-time)))
1455 (this-buffer (current-buffer))
1456 (location (org-get-local-archive-location))
1457 (afile (org-extract-archive-file location))
1458 (org-archive-location
1459 (format "%s::*** %04d-%02d-%02d %s" afile y m d
1460 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1461 (message "afile=%s" afile)
1463 (error "Invalid `org-archive-location'"))
1465 (switch-to-buffer (find-file-noselect afile))
1466 (org-datetree-find-year-create y)
1467 (org-datetree-find-month-create y m)
1468 (org-datetree-find-day-create y m d)
1470 (switch-to-buffer this-buffer))
1475 *** Add inherited tags to archived entries
1476 #+index: Archiving!Add inherited tags
1477 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1478 advise the function like this:
1481 (defadvice org-archive-subtree
1482 (before add-inherited-tags-before-org-archive-subtree activate)
1483 "add inherited tags before org-archive-subtree"
1484 (org-set-tags-to (org-get-tags-at)))
1487 ** Using and Managing Org-Metadata
1488 *** Remove redundant tags of headlines
1489 #+index: Tag!Remove redundant
1492 A small function that processes all headlines in current buffer and
1493 removes tags that are local to a headline and inherited by a parent
1494 headline or the #+FILETAGS: statement.
1496 #+BEGIN_SRC emacs-lisp
1497 (defun dmj/org-remove-redundant-tags ()
1498 "Remove redundant tags of headlines in current buffer.
1500 A tag is considered redundant if it is local to a headline and
1501 inherited by a parent headline."
1503 (when (eq major-mode 'org-mode)
1507 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1508 local inherited tag)
1509 (dolist (tag alltags)
1510 (if (get-text-property 0 'inherited tag)
1511 (push tag inherited) (push tag local)))
1513 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1517 *** Remove empty property drawers
1518 #+index: Drawer!Empty
1519 David Maus proposed this:
1521 #+begin_src emacs-lisp
1522 (defun dmj:org:remove-empty-propert-drawers ()
1523 "*Remove all empty property drawers in current file."
1525 (unless (eq major-mode 'org-mode)
1526 (error "You need to turn on Org mode for this function."))
1528 (goto-char (point-min))
1529 (while (re-search-forward ":PROPERTIES:" nil t)
1531 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1534 *** Group task list by a property
1535 #+index: Agenda!Group task list
1536 This advice allows you to group a task list in Org-Mode. To use it,
1537 set the variable =org-agenda-group-by-property= to the name of a
1538 property in the option list for a TODO or TAGS search. The resulting
1539 agenda view will group tasks by that property prior to searching.
1541 #+begin_src emacs-lisp
1542 (defvar org-agenda-group-by-property nil
1543 "Set this in org-mode agenda views to group tasks by property")
1545 (defun org-group-bucket-items (prop items)
1547 (dolist (item items)
1548 (let* ((marker (get-text-property 0 'org-marker item))
1549 (pvalue (org-entry-get marker prop t))
1550 (cell (assoc pvalue buckets)))
1552 (setcdr cell (cons item (cdr cell)))
1553 (setq buckets (cons (cons pvalue (list item))
1555 (setq buckets (mapcar (lambda (bucket)
1557 (reverse (cdr bucket))))
1559 (sort buckets (lambda (i1 i2)
1560 (string< (car i1) (car i2))))))
1562 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1563 (list &optional nosort))
1564 "Prepare bucketed agenda entry lists"
1565 (if org-agenda-group-by-property
1566 ;; bucketed, handle appropriately
1568 (dolist (bucket (org-group-bucket-items
1569 org-agenda-group-by-property
1571 (let ((header (concat "Property "
1572 org-agenda-group-by-property
1574 (or (car bucket) "<nil>") ":\n")))
1575 (add-text-properties 0 (1- (length header))
1576 (list 'face 'org-agenda-structure)
1580 ;; recursively process
1581 (let ((org-agenda-group-by-property nil))
1582 (org-finalize-agenda-entries
1583 (cdr bucket) nosort))
1585 (setq ad-return-value text))
1587 (ad-activate 'org-finalize-agenda-entries)
1589 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1592 Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1594 A small hook run when clocking out of a task that prompts for a note
1595 when the tag "=clockout_note=" is found in a headline. It uses the tag
1596 ("=clockout_note=") so inheritance can also be used...
1598 #+begin_src emacs-lisp
1599 (defun rgr/check-for-clock-out-note()
1602 (org-back-to-heading)
1603 (let ((tags (org-get-tags)))
1604 (and tags (message "tags: %s " tags)
1605 (when (member "clocknote" tags)
1608 (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1610 *** Dynamically adjust tag position
1611 #+index: Tag!position
1612 Here is a bit of code that allows you to have the tags always
1613 right-adjusted in the buffer.
1615 This is useful when you have bigger window than default window-size
1616 and you dislike the aesthetics of having the tag in the middle of the
1619 This hack solves the problem of adjusting it whenever you change the
1621 Before saving it will revert the file to having the tag position be
1622 left-adjusted so that if you track your files with version control,
1623 you won't run into artificial diffs just because the window-size
1626 *IMPORTANT*: This is probably slow on very big files.
1628 #+begin_src emacs-lisp
1629 (setq ba/org-adjust-tags-column t)
1631 (defun ba/org-adjust-tags-column-reset-tags ()
1632 "In org-mode buffers it will reset tag position according to
1635 (not (string= (buffer-name) "*Remember*"))
1636 (eql major-mode 'org-mode))
1637 (let ((b-m-p (buffer-modified-p)))
1640 (goto-char (point-min))
1641 (command-execute 'outline-next-visible-heading)
1642 ;; disable (message) that org-set-tags generates
1643 (flet ((message (&rest ignored) nil))
1645 (set-buffer-modified-p b-m-p))
1648 (defun ba/org-adjust-tags-column-now ()
1649 "Right-adjust `org-tags-column' value, then reset tag position."
1650 (set (make-local-variable 'org-tags-column)
1651 (- (- (window-width) (length org-ellipsis))))
1652 (ba/org-adjust-tags-column-reset-tags))
1654 (defun ba/org-adjust-tags-column-maybe ()
1655 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1656 (when ba/org-adjust-tags-column
1657 (ba/org-adjust-tags-column-now)))
1659 (defun ba/org-adjust-tags-column-before-save ()
1660 "Tags need to be left-adjusted when saving."
1661 (when ba/org-adjust-tags-column
1662 (setq org-tags-column 1)
1663 (ba/org-adjust-tags-column-reset-tags)))
1665 (defun ba/org-adjust-tags-column-after-save ()
1666 "Revert left-adjusted tag position done by before-save hook."
1667 (ba/org-adjust-tags-column-maybe)
1668 (set-buffer-modified-p nil))
1670 ; automatically align tags on right-hand side
1671 (add-hook 'window-configuration-change-hook
1672 'ba/org-adjust-tags-column-maybe)
1673 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1674 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1675 (add-hook 'org-agenda-mode-hook (lambda ()
1676 (setq org-agenda-tags-column (- (window-width)))))
1678 ; between invoking org-refile and displaying the prompt (which
1679 ; triggers window-configuration-change-hook) tags might adjust,
1680 ; which invalidates the org-refile cache
1681 (defadvice org-refile (around org-refile-disable-adjust-tags)
1682 "Disable dynamically adjusting tags"
1683 (let ((ba/org-adjust-tags-column nil))
1685 (ad-activate 'org-refile)
1687 *** Use an "attach" link type to open files without worrying about their location
1688 #+index: Link!Attach
1689 -- Darlan Cavalcante Moreira
1691 In the setup part in my org-files I put:
1694 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1697 Now I can use the "attach" link type, but org will ask me if I want to
1698 allow executing the elisp code. To avoid this you can even set
1699 org-confirm-elisp-link-function to nil (I don't like this because it allows
1700 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1705 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1707 This works very well.
1709 ** Org Agenda and Task Management
1710 *** Make it easier to set org-agenda-files from multiple directories
1711 #+index: Agenda!Files
1714 #+begin_src emacs-lisp
1715 (defun my-org-list-files (dirs ext)
1716 "Function to create list of org files in multiple subdirectories.
1717 This can be called to generate a list of files for
1718 org-agenda-files or org-refile-targets.
1720 DIRS is a list of directories.
1722 EXT is a list of the extensions of files to be included."
1723 (let ((dirs (if (listp dirs)
1726 (ext (if (listp ext)
1736 (file-expand-wildcards
1737 (concat (file-name-as-directory x) "*" y)))))
1742 (when (or (string-match "/.#" x)
1743 (string-match "#$" x))
1744 (setq files (delete x files))))
1748 (defvar my-org-agenda-directories '("~/org/")
1749 "List of directories containing org files.")
1750 (defvar my-org-agenda-extensions '(".org")
1751 "List of extensions of agenda files")
1753 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1754 (setq my-org-agenda-extensions '(".org" ".ref"))
1756 (defun my-org-set-agenda-files ()
1758 (setq org-agenda-files (my-org-list-files
1759 my-org-agenda-directories
1760 my-org-agenda-extensions)))
1762 (my-org-set-agenda-files)
1765 The code above will set your "default" agenda files to all files
1766 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1767 You can change these values by setting the variables
1768 my-org-agenda-extensions and my-org-agenda-directories. The function
1769 my-org-agenda-files-by-filetag uses these two variables to determine
1770 which files to search for filetags (i.e., the larger set from which
1771 the subset will be drawn).
1773 You can also easily use my-org-list-files to "mix and match"
1774 directories and extensions to generate different lists of agenda
1777 *** Restrict org-agenda-files by filetag
1779 :CUSTOM_ID: set-agenda-files-by-filetag
1781 #+index: Agenda!Files
1784 It is often helpful to limit yourself to a subset of your agenda
1785 files. For instance, at work, you might want to see only files related
1786 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1787 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
1788 commands]]. These solutions, however, require reapplying a filter each
1789 time you call the agenda or writing several new custom agenda commands
1790 for each context. Another solution is to use directories for different
1791 types of tasks and to change your agenda files with a function that
1792 sets org-agenda-files to the appropriate directory. But this relies on
1793 hard and static boundaries between files.
1795 The following functions allow for a more dynamic approach to selecting
1796 a subset of files based on filetags:
1798 #+begin_src emacs-lisp
1799 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1800 "Restrict org agenda files only to those containing filetag."
1802 (let* ((tagslist (my-org-get-all-filetags))
1804 (completing-read "Tag: "
1805 (mapcar 'car tagslist)))))
1806 (org-agenda-remove-restriction-lock 'noupdate)
1807 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1808 (setq org-agenda-overriding-restriction 'files)))
1810 (defun my-org-get-all-filetags ()
1811 "Get list of filetags from all default org-files."
1812 (let ((files org-agenda-files)
1814 (save-window-excursion
1815 (while (setq x (pop files))
1816 (set-buffer (find-file-noselect x))
1819 (let ((tagfiles (assoc y tagslist)))
1821 (setcdr tagfiles (cons x (cdr tagfiles)))
1822 (add-to-list 'tagslist (list y x)))))
1823 (my-org-get-filetags)))
1826 (defun my-org-get-filetags ()
1827 "Get list of filetags for current buffer"
1828 (let ((ftags org-file-tags)
1832 (org-no-properties x))
1836 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1837 with all filetags in your "normal" agenda files. When you select a
1838 tag, org-agenda-files will be restricted to only those files
1839 containing the filetag. To release the restriction, type C-c C-x >
1840 (org-agenda-remove-restriction-lock).
1842 *** Highlight the agenda line under cursor
1843 #+index: Agenda!Highlight
1844 This is useful to make sure what task you are operating on.
1846 #+BEGIN_SRC emacs-lisp
1847 (add-hook 'org-agenda-mode-hook (lambda () (hl-line-mode 1)))
1852 #+BEGIN_SRC emacs-lisp
1853 ;; hl-line seems to be only for emacs
1855 (add-hook 'org-agenda-mode-hook (lambda () (highline-mode 1)))
1857 ;; highline-mode does not work straightaway in tty mode.
1858 ;; I use a black background
1860 '(highline-face ((((type tty) (class color))
1861 (:background "white" :foreground "black")))))
1864 *** Split frame horizontally for agenda
1865 #+index: Agenda!frame
1866 If you would like to split the frame into two side-by-side windows when
1867 displaying the agenda, try this hack from Jan Rehders, which uses the
1868 `toggle-window-split' from
1870 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1872 #+BEGIN_SRC emacs-lisp
1873 ;; Patch org-mode to use vertical splitting
1874 (defadvice org-prepare-agenda (after org-fix-split)
1875 (toggle-window-split))
1876 (ad-activate 'org-prepare-agenda)
1879 *** Automatically add an appointment when clocking in a task
1880 #+index: Clock!Automatically add an appointment when clocking in a task
1881 #+index: Appointment!Automatically add an appointment when clocking in a task
1882 #+BEGIN_SRC emacs-lisp
1883 ;; Make sure you have a sensible value for `appt-message-warning-time'
1884 (defvar bzg-org-clock-in-appt-delay 100
1885 "Number of minutes for setting an appointment by clocking-in")
1888 This function let's you add an appointment for the current entry.
1889 This can be useful when you need a reminder.
1891 #+BEGIN_SRC emacs-lisp
1892 (defun bzg-org-clock-in-add-appt (&optional n)
1893 "Add an appointment for the Org entry at point in N minutes."
1896 (org-back-to-heading t)
1897 (looking-at org-complex-heading-regexp)
1898 (let* ((msg (match-string-no-properties 4))
1899 (ct-time (decode-time))
1900 (appt-min (+ (cadr ct-time)
1901 (or n bzg-org-clock-in-appt-delay)))
1902 (appt-time ; define the time for the appointment
1903 (progn (setf (cadr ct-time) appt-min) ct-time)))
1904 (appt-add (format-time-string
1905 "%H:%M" (apply 'encode-time appt-time)) msg)
1906 (if (interactive-p) (message "New appointment for %s" msg)))))
1909 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1912 #+BEGIN_SRC emacs-lisp
1913 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1914 "Add an appointment when clocking a task in."
1915 (bzg-org-clock-in-add-appt))
1918 You may also want to delete the associated appointment when clocking
1919 out. This function does this:
1921 #+BEGIN_SRC emacs-lisp
1922 (defun bzg-org-clock-out-delete-appt nil
1923 "When clocking out, delete any associated appointment."
1926 (org-back-to-heading t)
1927 (looking-at org-complex-heading-regexp)
1928 (let* ((msg (match-string-no-properties 4)))
1929 (setq appt-time-msg-list
1933 (if (not (string-match (regexp-quote msg)
1934 (cadr appt))) appt))
1935 appt-time-msg-list)))
1939 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1941 #+BEGIN_SRC emacs-lisp
1942 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1943 "Delete an appointment when clocking a task out."
1944 (bzg-org-clock-out-delete-appt))
1947 *IMPORTANT*: You can add appointment by clocking in in both an
1948 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1949 agenda buffer with the advice above will bring an error.
1951 *** Using external programs for appointments reminders
1952 #+index: Appointment!reminders
1953 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1955 *** Remove from agenda time grid lines that are in an appointment
1956 #+index: Agenda!time grid
1957 #+index: Appointment!Remove from agenda time grid lines
1958 The agenda shows lines for the time grid. Some people think that
1959 these lines are a distraction when there are appointments at those
1960 times. You can get rid of the lines which coincide exactly with the
1961 beginning of an appointment. Michael Ekstrand has written a piece of
1962 advice that also removes lines that are somewhere inside an
1965 #+begin_src emacs-lisp
1966 (defun org-time-to-minutes (time)
1967 "Convert an HHMM time to minutes"
1968 (+ (* (/ time 100) 60) (% time 100)))
1970 (defun org-time-from-minutes (minutes)
1971 "Convert a number of minutes to an HHMM time"
1972 (+ (* (/ minutes 60) 100) (% minutes 60)))
1974 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1975 (list ndays todayp))
1976 (if (member 'remove-match (car org-agenda-time-grid))
1977 (flet ((extract-window
1979 (let ((start (get-text-property 1 'time-of-day line))
1980 (dur (get-text-property 1 'duration line)))
1984 (org-time-from-minutes
1985 (+ dur (org-time-to-minutes start)))))
1988 (let* ((windows (delq nil (mapcar 'extract-window list)))
1989 (org-agenda-time-grid
1990 (list (car org-agenda-time-grid)
1991 (cadr org-agenda-time-grid)
1994 (find-if (lambda (w)
1997 (and (>= time (car w))
2000 (caddr org-agenda-time-grid)))))
2003 (ad-activate 'org-agenda-add-time-grid-maybe)
2005 *** Disable version control for Org mode agenda files
2006 #+index: Agenda!Files
2009 Even if you use Git to track your agenda files you might not need
2010 vc-mode to be enabled for these files.
2012 #+begin_src emacs-lisp
2013 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
2014 (defun dmj/disable-vc-for-agenda-files-hook ()
2015 "Disable vc-mode for Org agenda files."
2016 (if (and (fboundp 'org-agenda-file-p)
2017 (org-agenda-file-p (buffer-file-name)))
2018 (remove-hook 'find-file-hook 'vc-find-file-hook)
2019 (add-hook 'find-file-hook 'vc-find-file-hook)))
2022 *** Easy customization of TODO colors
2023 #+index: Customization!Todo keywords
2024 #+index: Todo keywords!Customization
2028 Here is some code I came up with some code to make it easier to
2029 customize the colors of various TODO keywords. As long as you just
2030 want a different color and nothing else, you can customize the
2031 variable org-todo-keyword-faces and use just a string color (i.e. a
2032 string of the color name) as the face, and then org-get-todo-face
2033 will convert the color to a face, inheriting everything else from
2034 the standard org-todo face.
2036 To demonstrate, I currently have org-todo-keyword-faces set to
2038 #+BEGIN_SRC emacs-lisp
2039 (("IN PROGRESS" . "dark orange")
2040 ("WAITING" . "red4")
2041 ("CANCELED" . "saddle brown"))
2044 Here's the code, in a form you can put in your =.emacs=
2046 #+BEGIN_SRC emacs-lisp
2047 (eval-after-load 'org-faces
2049 (defcustom org-todo-keyword-faces nil
2050 "Faces for specific TODO keywords.
2051 This is a list of cons cells, with TODO keywords in the car and
2052 faces in the cdr. The face can be a symbol, a color, or a
2053 property list of attributes, like (:foreground \"blue\" :weight
2054 bold :underline t)."
2059 (string :tag "Keyword")
2060 (choice color (sexp :tag "Face")))))))
2062 (eval-after-load 'org
2064 (defun org-get-todo-face-from-color (color)
2065 "Returns a specification for a face that inherits from org-todo
2066 face and has the given color as foreground. Returns nil if
2069 `(:inherit org-warning :foreground ,color)))
2071 (defun org-get-todo-face (kwd)
2072 "Get the right face for a TODO keyword KWD.
2073 If KWD is a number, get the corresponding match group."
2074 (if (numberp kwd) (setq kwd (match-string kwd)))
2075 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
2077 (org-get-todo-face-from-color face)
2079 (and (member kwd org-done-keywords) 'org-done)
2083 *** Add an effort estimate on the fly when clocking in
2084 #+index: Effort estimate!Add when clocking in
2085 #+index: Clock!Effort estimate
2086 You can use =org-clock-in-prepare-hook= to add an effort estimate.
2087 This way you can easily have a "tea-timer" for your tasks when they
2088 don't already have an effort estimate.
2090 #+begin_src emacs-lisp
2091 (add-hook 'org-clock-in-prepare-hook
2092 'my-org-mode-ask-effort)
2094 (defun my-org-mode-ask-effort ()
2095 "Ask for an effort estimate when clocking in."
2096 (unless (org-entry-get (point) "Effort")
2100 (org-entry-get-multivalued-property (point) "Effort"))))
2101 (unless (equal effort "")
2102 (org-set-property "Effort" effort)))))
2105 Or you can use a default effort for such a timer:
2107 #+begin_src emacs-lisp
2108 (add-hook 'org-clock-in-prepare-hook
2109 'my-org-mode-add-default-effort)
2111 (defvar org-clock-default-effort "1:00")
2113 (defun my-org-mode-add-default-effort ()
2114 "Add a default effort estimation."
2115 (unless (org-entry-get (point) "Effort")
2116 (org-set-property "Effort" org-clock-default-effort)))
2119 *** Use idle timer for automatic agenda views
2120 #+index: Agenda view!Refresh
2121 From John Wiegley's mailing list post (March 18, 2010):
2124 I have the following snippet in my .emacs file, which I find very
2125 useful. Basically what it does is that if I don't touch my Emacs for 5
2126 minutes, it displays the current agenda. This keeps my tasks "always
2127 in mind" whenever I come back to Emacs after doing something else,
2128 whereas before I had a tendency to forget that it was there.
2131 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
2133 #+begin_src emacs-lisp
2134 (defun jump-to-org-agenda ()
2136 (let ((buf (get-buffer "*Org Agenda*"))
2139 (if (setq wind (get-buffer-window buf))
2140 (select-window wind)
2141 (if (called-interactively-p)
2143 (select-window (display-buffer buf t t))
2144 (org-fit-window-to-buffer)
2145 ;; (org-agenda-redo)
2147 (with-selected-window (display-buffer buf)
2148 (org-fit-window-to-buffer)
2149 ;; (org-agenda-redo)
2151 (call-interactively 'org-agenda-list)))
2152 ;;(let ((buf (get-buffer "*Calendar*")))
2153 ;; (unless (get-buffer-window buf)
2154 ;; (org-agenda-goto-calendar)))
2157 (run-with-idle-timer 300 t 'jump-to-org-agenda)
2161 : [nil 0 300 0 t jump-to-org-agenda nil idle]
2163 *** Refresh the agenda view regularly
2164 #+index: Agenda view!Refresh
2165 Hack sent by Kiwon Um:
2167 #+begin_src emacs-lisp
2168 (defun kiwon/org-agenda-redo-in-other-window ()
2169 "Call org-agenda-redo function even in the non-agenda buffer."
2171 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
2173 (with-selected-window agenda-window (org-agenda-redo)))))
2174 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
2177 *** Reschedule agenda items to today with a single command
2178 #+index: Agenda!Reschedule
2179 This was suggested by Carsten in reply to David Abrahams:
2181 #+begin_example emacs-lisp
2182 (defun org-agenda-reschedule-to-today ()
2184 (flet ((org-read-date (&rest rest) (current-time)))
2185 (call-interactively 'org-agenda-schedule)))
2188 *** Mark subtree DONE along with all subheadings
2189 #+index: Subtree!subheadings
2190 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
2192 #+begin_src emacs-lisp
2193 (defun bh/mark-subtree-done ()
2196 (let ((limit (point)))
2198 (exchange-point-and-mark)
2199 (while (> (point) limit)
2201 (outline-previous-visible-heading 1))
2202 (org-todo "DONE"))))
2205 Then M-x bh/mark-subtree-done.
2207 *** Mark heading done when all checkboxes are checked.
2209 :CUSTOM_ID: mark-done-when-all-checkboxes-checked
2214 An item consists of a list with checkboxes. When all of the
2215 checkboxes are checked, the item should be considered complete and its
2216 TODO state should be automatically changed to DONE. The code below
2217 does that. This version is slightly enhanced over the one in the
2219 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
2220 reset the state back to TODO if a checkbox is unchecked.
2222 Note that the code requires that a checkbox statistics cookie (the [/]
2223 or [%] thingie in the headline - see the [[https://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
2224 manual) be present in order for it to work. Note also that it is too
2225 dumb to figure out whether the item has a TODO state in the first
2226 place: if there is a statistics cookie, a TODO/DONE state will be
2227 added willy-nilly any time that the statistics cookie is changed.
2229 #+begin_src emacs-lisp
2230 ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
2231 (eval-after-load 'org-list
2232 '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
2234 (defun ndk/checkbox-list-complete ()
2236 (org-back-to-heading t)
2237 (let ((beg (point)) end)
2241 (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
2243 (if (equal (match-string 1) "100%")
2244 ;; all done - do the state change
2247 (if (and (> (match-end 2) (match-beginning 2))
2248 (equal (match-string 2) (match-string 3)))
2250 (org-todo 'todo)))))))
2253 *** Links to custom agenda views
2255 :CUSTOM_ID: links-to-agenda-views
2257 #+index: Agenda view!Links to
2258 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
2260 If you have custom agenda commands defined to some key, say w, then
2261 the following will serve as a link to the custom agenda buffer.
2262 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
2264 Clicking on it will prompt if you want to execute the elisp code. If
2265 you would rather not have the prompt or would want to respond with a
2266 single letter, ~y~ or ~n~, take a look at the docstrings of the
2267 variables =org-confirm-elisp-link-function= and
2268 =org-confirm-elisp-link-not-regexp=. Please take special note of the
2269 security risk associated with completely disabling the prompting
2272 ** Exporting org files
2273 *** Ignoring headlines during export
2275 :CUSTOM_ID: ignoreheadline
2277 #+index: Export!ignore headlines
2278 Sometimes users want to ignore the headline text during export like in
2279 the Beamer exporter (=ox-beamer=). In the [[https://orgmode.org/manual/Beamer-export.html#Beamer-export][Beamer exporter]] one can use
2280 the tag =ignoreheading= to disable the export of a certain headline,
2281 whilst still retaining the content of the headline. We can imitate
2282 this feature in other export backends. Note that this is not a
2283 particularly easy problem, as the Org exporter creates a static
2284 representation of section numbers, table of contents etc.
2286 Consider the following document:
2288 ,* head 1 :noexport:
2289 ,* head 2 :ignoreheading:
2291 ,* =head 4= :ignoreheading:
2294 We want to remove heading 2 and 4.
2296 There are different strategies to accomplish this:
2297 1. The best option is to remove headings tagged with =ignoreheading=
2298 before export starts. This can be accomplished with the hook
2299 =org-export-before-parsing-hook= that runs before the buffer has
2300 been parsed. In the example above, however, =head 2= would not be
2301 exported as it becomes part of =head 1= which is not exporter. To
2302 overcome this move perhaps =head 1= can be moved to the end of the
2303 buffer. An example of a hook that removes headings is before
2304 parsing is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01459.html][here]]. Note, this solution is compatible with
2305 /all/ export formats!
2306 2. The problem is simple when exporting to LaTeX, as the LaTeX
2307 compiler determines numbers. We can thus use
2308 =org-export-filter-headline-functions= to remove the offending
2309 headlines. One regexp-based solution that looks for the word
2310 =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
2311 exporter Org v7 exporter and the current Org v8 exporter. Note,
2312 however, that this filter will only work with LaTeX (numbering and
2313 the table of content may break in other exporters). In the example
2314 above, this filer will work flawlessly in LaTeX, it will not work
2315 at all in HTML and it will fail to update section numbers, TOC and
2316 leave some auxiliary lines behind when exporting to plain text.
2317 3. Another solution that tries to recover the Org element
2318 representation is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01480.html][here]]. In the example above this filter
2319 will not remove =head 4= exporting to any backend, since verbatim
2320 strings do not retain the Org element representation. It will
2321 remove the extra heading line when exporting to plain text, but
2322 will also fail to update section numbers. It should be fairly
2323 simple to also make it work with HTML.
2325 *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:*
2326 To use this, add the following to your =.elisp= file:
2328 #+begin_src emacs-lisp
2329 (add-to-list 'load-path "path/to/contrib/lisp")
2331 (ox-extras-activate '(ignore-headlines))
2334 After this is added, then any headlines having an =:ignore:= tag will
2335 be omitted from the export, but their contents will be included in the
2338 *** Export Org to Org and handle includes.
2339 #+index: Export!handle includes
2340 N.B: this does not apply to the "new" export engine (>= 8.0) - the function
2341 =org-export-handle-include-files-recurse= is only available in earlier versions.
2342 There is probably a way to do the same thing in the "new" exporter but nobody
2343 has stepped up to the plate yet.
2345 Nick Dokos came up with this useful function:
2347 #+begin_src emacs-lisp
2348 (defun org-to-org-handle-includes ()
2349 "Copy the contents of the current buffer to OUTFILE,
2350 recursively processing #+INCLUDEs."
2351 (let* ((s (buffer-string))
2352 (fname (buffer-file-name))
2353 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
2357 (org-export-handle-include-files-recurse)
2360 (delete-region (point-min) (point-max))
2365 *** Specifying LaTeX commands to floating environments
2367 :CUSTOM_ID: latex-command-for-floats
2370 #+index: Export!LaTeX
2371 The keyword ~placement~ can be used to specify placement options to
2372 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2373 LaTeX export. Org passes along everything passed in options as long as
2374 there are no spaces. One can take advantage of this to pass other
2375 LaTeX commands and have their scope limited to the floating
2378 For example one can set the fontsize of a table different from the
2379 default normal size by putting something like =\footnotesize= right
2380 after the placement options. During LaTeX export using the
2381 ~#+ATTR_LaTeX:~ line below:
2384 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2387 exports the associated floating environment as shown in the following
2391 \begin{table}[<options>]\footnotesize
2396 It should be noted that this hack does not work for beamer export of
2397 tables since the =table= environment is not used. As an ugly
2398 workaround, one can use the following:
2401 ,#+LATEX: {\footnotesize
2402 ,#+ATTR_LaTeX: align=rr
2409 *** Styling code sections with CSS
2411 #+index: HTML!Styling code sections with CSS
2413 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2414 to HTML using =<pre>= tags, and assigned CSS classes by their content
2415 type. For example, Perl content will have an opening tag like
2416 =<pre class="src src-perl">=. You can use those classes to add styling
2417 to the output, such as here where a small language tag is added at the
2418 top of each kind of code box:
2421 (setq org-export-html-style
2422 "<style type=\"text/css\">
2423 <!--/*--><![CDATA[/*><!--*/
2424 .src { background-color: #F5FFF5; position: relative; overflow: visible; }
2425 .src:before { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2426 .src-sh:before { content: 'sh'; }
2427 .src-bash:before { content: 'sh'; }
2428 .src-R:before { content: 'R'; }
2429 .src-perl:before { content: 'Perl'; }
2430 .src-sql:before { content: 'SQL'; }
2431 .example { background-color: #FFF5F5; }
2436 Additionally, we use color to distinguish code output (the =.example=
2437 class) from input (all the =.src-*= classes).
2439 *** Where can I find nice themes for HTML export?
2441 You can find great looking HTML themes (CSS + JS) at
2442 https://github.com/fniessen/org-html-themes, currently:
2446 [[file:images/org-html-themes/bigblow.png]]
2448 - ReadTheOrg, a clone of Read The Docs.
2450 [[file:images/org-html-themes/readtheorg.png]]
2452 See https://www.youtube.com/watch?v=DnSGSiXYuOk for a demo of the Org
2455 *** Including external text fragments
2457 #+index: Export!including external text fragments
2459 I recently had to document some source code but could not modify the
2460 source files themselves. Here is a setup that lets you refer to
2461 fragments of external files, such that the fragments are inserted as
2462 source blocks in the current file during evaluation of the ~call~
2463 lines (thus during export as well).
2468 ,#+BEGIN_SRC emacs-lisp :results raw :var f="foo" :var s="Definition" :var e="\\. *$" :var b=()
2469 (defvar coqfiles nil)
2471 (defun fetchlines (file-path search-string &optional end before)
2472 "Searches for the SEARCH-STRING in FILE-PATH and returns the matching line.
2473 If the optional argument END is provided as a number, then this
2474 number of lines is printed. If END is a string, then it is a
2475 regular expression indicating the end of the expression to print.
2476 If END is omitted, then 10 lines are printed. If BEFORE is set,
2477 then one fewer line is printed (this is useful when END is a
2478 string matching the first line that should not be printed)."
2480 (insert-file-contents file-path nil nil nil t)
2481 (goto-char (point-min))
2483 (if (search-forward search-string nil t)
2485 (line-beginning-position)
2489 (line-end-position (if before (- end 1) end)))
2491 (let ((point (re-search-forward end nil t)))
2492 (if before (line-end-position 0) point)))
2493 (t (line-end-position 10)))
2494 (line-end-position 10))))))
2497 (fetchlines (concat coqfiles f ".v") s e b)
2501 ,#+BEGIN_SRC emacs-lisp :var text="" :results raw
2502 (concat "#+BEGIN_SRC coq\n" text "\n#+END_SRC")
2506 This is specialized for Coq files (hence the ~coq~ language in the
2507 ~wrap-coq~ function, the ~.v~ extension in the ~fetch~ function, and
2508 the default value for ~end~ matching the syntax ending definitions in
2509 Coq). To use it, you need to:
2510 - set the ~coqfiles~ variable to where your source files reside;
2511 - call the function using lines of the form
2513 ,#+call: fetchsrc(f="JsSyntax", s="Inductive expr :=", e="^ *$", b=1) :results drawer :post wrap-coq(text=*this*)
2515 In this example, we look inside the file ~JsSyntax.v~ in ~coqfiles~,
2516 search for a line matching ~Inductive expr :=~, and include the
2517 fragment until the first line consisting only of white space,
2518 excluded (as ~b=1~).
2520 I use drawers to store the results to avoid a bug leading to
2521 duplication during export when the code has already been evaluated in
2522 the buffer (see [[http://thread.gmane.org/gmane.emacs.orgmode/79520][this thread]] for a description of the problem). This
2523 has been fixed in recent versions of org-mode, so alternative
2524 approaches are possible.
2528 *** How do I preview LaTeX fragments when in a LaTeX source block?
2530 When editing =LaTeX= source blocks, you may want to preview LaTeX fragments
2531 just like in an Org-mode buffer. You can do this by using the usual
2532 keybinding =C-c C-x C-l= after loading this snipped:
2534 #+BEGIN_SRC emacs-lisp
2535 (define-key org-src-mode-map "\C-c\C-x\C-l" 'org-edit-preview-latex-fragment)
2537 (defun org-edit-preview-latex-fragment ()
2538 "Write latex fragment from source to parent buffer and preview it."
2540 (org-src-in-org-buffer (org-preview-latex-fragment)))
2543 Thanks to Sebastian Hofer for sharing this.
2545 * Hacking Org: Working with Org-mode and other Emacs Packages.
2546 ** How to ediff folded Org files
2547 A rather often quip among Org users is when looking at chages with
2548 ediff. Ediff tends to fold the Org buffers when comparing. This can
2549 be very inconvenient when trying to determine what changed. A recent
2550 discussion on the mailing list led to a [[http://article.gmane.org/gmane.emacs.orgmode/75222][neat solution]] from Ratish
2553 ** org-remember-anything
2555 #+index: Remember!Anything
2557 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2559 #+BEGIN_SRC emacs-lisp
2560 (defvar org-remember-anything
2561 '((name . "Org Remember")
2562 (candidates . (lambda () (mapcar 'car org-remember-templates)))
2563 (action . (lambda (name)
2564 (let* ((orig-template org-remember-templates)
2565 (org-remember-templates
2566 (list (assoc name orig-template))))
2567 (call-interactively 'org-remember))))))
2570 You can add it to your 'anything-sources' variable and open remember directly
2571 from anything. I imagine this would be more interesting for people with many
2572 remember templates, so that you are out of keys to assign those to.
2574 ** Org-mode and saveplace.el
2576 Fix a problem with =saveplace.el= putting you back in a folded position:
2578 #+begin_src emacs-lisp
2579 (add-hook 'org-mode-hook
2581 (when (outline-invisible-p)
2583 (outline-previous-visible-heading 1)
2584 (org-show-subtree)))))
2587 ** Using ido-mode for org-refile (and archiving via refile)
2589 First set up ido-mode, for example using:
2591 #+begin_src emacs-lisp
2592 ; use ido mode for completion
2593 (setq ido-everywhere t)
2594 (setq ido-enable-flex-matching t)
2595 (setq ido-max-directory-size 100000)
2596 (ido-mode (quote both))
2599 Now to enable it in org-mode, use the following:
2600 #+begin_src emacs-lisp
2601 (setq org-completion-use-ido t)
2602 (setq org-refile-use-outline-path nil)
2603 (setq org-refile-allow-creating-parent-nodes 'confirm)
2605 The last line enables the creation of nodes on the fly.
2607 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):
2608 #+begin_src emacs-lisp
2609 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2612 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.
2613 #+begin_src emacs-lisp
2614 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2615 ; added check to only include headlines, e.g. line must have at least one child
2616 (defun my/verify-refile-target ()
2617 "Exclude todo keywords with a DONE state from refile targets"
2618 (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2619 (save-excursion (org-goto-first-child))
2621 (setq org-refile-target-verify-function 'my/verify-refile-target)
2623 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.
2625 ** Using ido-completing-read to find attachments
2627 #+index: Attachment!ido completion
2631 Org-attach is great for quickly linking files to a project. But if you
2632 use org-attach extensively you might find yourself wanting to browse
2633 all the files you've attached to org headlines. This is not easy to do
2634 manually, since the directories containing the files are not human
2635 readable (i.e., they are based on automatically generated ids). Here's
2636 some code to browse those files using ido (obviously, you need to be
2639 #+begin_src emacs-lisp
2640 (load-library "find-lisp")
2642 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2644 (defun my-ido-find-org-attach ()
2645 "Find files in org-attachment directory"
2647 (let* ((enable-recursive-minibuffers t)
2648 (files (find-lisp-find-files org-attach-directory "."))
2651 (cons (file-name-nondirectory x)
2655 (remove-duplicates (mapcar #'car file-assoc-list)
2657 (filename (ido-completing-read "Org attachments: " filename-list nil t))
2658 (longname (cdr (assoc filename file-assoc-list))))
2659 (ido-set-current-directory
2660 (if (file-directory-p longname)
2662 (file-name-directory longname)))
2663 (setq ido-exit 'refresh
2664 ido-text-init ido-text
2668 (add-hook 'ido-setup-hook 'ido-my-keys)
2670 (defun ido-my-keys ()
2671 "Add my keybindings for ido."
2672 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2675 To browse your org attachments using ido fuzzy matching and/or the
2676 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2679 ** Link to Gnus messages by Message-Id
2680 #+index: Link!Gnus message by Message-Id
2681 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2682 discussion about linking to Gnus messages without encoding the folder
2683 name in the link. The following code hooks in to the store-link
2684 function in Gnus to capture links by Message-Id when in nnml folders,
2685 and then provides a link type "mid" which can open this link. The
2686 =mde-org-gnus-open-message-link= function uses the
2687 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2688 scan. It will go through them, in order, asking each to locate the
2689 message and opening it from the first one that reports success.
2691 It has only been tested with a single nnml backend, so there may be
2692 bugs lurking here and there.
2694 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2697 #+begin_src emacs-lisp
2698 ;; Support for saving Gnus messages by Message-ID
2699 (defun mde-org-gnus-save-by-mid ()
2700 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2701 (when (eq major-mode 'gnus-article-mode)
2702 (gnus-article-show-summary))
2703 (let* ((group gnus-newsgroup-name)
2704 (method (gnus-find-method-for-group group)))
2705 (when (eq 'nnml (car method))
2706 (let* ((article (gnus-summary-article-number))
2707 (header (gnus-summary-article-header article))
2708 (from (mail-header-from header))
2711 (let ((mid (mail-header-id header)))
2712 (if (string-match "<\\(.*\\)>" mid)
2713 (match-string 1 mid)
2714 (error "Malformed message ID header %s" mid)))))
2715 (date (mail-header-date header))
2716 (subject (gnus-summary-subject-string)))
2717 (org-store-link-props :type "mid" :from from :subject subject
2718 :message-id message-id :group group
2719 :link (org-make-link "mid:" message-id))
2720 (apply 'org-store-link-props
2721 :description (org-email-link-description)
2722 org-store-link-plist)
2725 (defvar mde-mid-resolve-methods '()
2726 "List of methods to try when resolving message ID's. For Gnus,
2727 it is a cons of 'gnus and the select (type and name).")
2728 (setq mde-mid-resolve-methods
2731 (defvar mde-org-gnus-open-level 1
2732 "Level at which Gnus is started when opening a link")
2733 (defun mde-org-gnus-open-message-link (msgid)
2734 "Open a message link with Gnus"
2736 (require 'org-table)
2737 (catch 'method-found
2738 (message "[MID linker] Resolving %s" msgid)
2739 (dolist (method mde-mid-resolve-methods)
2741 ((and (eq (car method) 'gnus)
2742 (eq (cadr method) 'nnml))
2743 (funcall (cdr (assq 'gnus org-link-frame-setup))
2744 mde-org-gnus-open-level)
2745 (when gnus-other-frame-object
2746 (select-frame gnus-other-frame-object))
2747 (let* ((msg-info (nnml-find-group-number
2748 (concat "<" msgid ">")
2750 (group (and msg-info (car msg-info)))
2751 (message (and msg-info (cdr msg-info)))
2753 (if (gnus-methods-equal-p
2757 (gnus-group-full-name group (cdr method))))))
2759 (gnus-summary-read-group qname nil t)
2760 (gnus-summary-goto-article message nil t))
2761 (throw 'method-found t)))
2762 (t (error "Unknown link type"))))))
2764 (eval-after-load 'org-gnus
2766 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2767 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2770 ** Store link to a message when sending in Gnus
2771 #+index: Link!Store link to a message when sending in Gnus
2772 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2774 #+begin_src emacs-lisp
2775 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2776 "Send message with `message-send-and-exit' and store org link to message copy.
2777 If multiple groups appear in the Gcc header, the link refers to
2778 the copy in the last group."
2782 (message-narrow-to-headers)
2783 (let ((gcc (car (last
2784 (message-unquote-tokens
2785 (message-tokenize-header
2786 (mail-fetch-field "gcc" nil t) " ,")))))
2787 (buf (current-buffer))
2788 (message-kill-buffer-on-exit nil)
2789 id to from subject desc link newsgroup xarchive)
2790 (message-send-and-exit arg)
2792 ;; gcc group found ...
2794 (save-current-buffer
2795 (progn (set-buffer buf)
2796 (setq id (org-remove-angle-brackets
2797 (mail-fetch-field "Message-ID")))
2798 (setq to (mail-fetch-field "To"))
2799 (setq from (mail-fetch-field "From"))
2800 (setq subject (mail-fetch-field "Subject"))))
2801 (org-store-link-props :type "gnus" :from from :subject subject
2802 :message-id id :group gcc :to to)
2803 (setq desc (org-email-link-description))
2804 (setq link (org-gnus-article-link
2805 gcc newsgroup id xarchive))
2806 (setq org-stored-links
2807 (cons (list link desc) org-stored-links)))
2808 ;; no gcc group found ...
2809 (message "Can not create Org link: No Gcc header found."))))))
2811 (define-key message-mode-map [(control c) (control meta c)]
2812 'ulf-message-send-and-org-gnus-store-link)
2815 ** Link to visit a file and run occur
2816 #+index: Link!Visit a file and run occur
2817 Add the following bit of code to your startup (after loading org),
2818 and you can then use links like =occur:my-file.txt#regex= to open a
2819 file and run occur with the regex on it.
2821 #+BEGIN_SRC emacs-lisp
2822 (defun org-occur-open (uri)
2823 "Visit the file specified by URI, and run `occur' on the fragment
2824 \(anything after the first '#') in the uri."
2825 (let ((list (split-string uri "#")))
2826 (org-open-file (car list) t)
2827 (occur (mapconcat 'identity (cdr list) "#"))))
2828 (org-add-link-type "occur" 'org-occur-open)
2830 ** Send html messages and attachments with Wanderlust
2833 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2834 similar functionality for both Wanderlust and Gnus. The hack below is
2835 still somewhat different: It allows you to toggle sending of html
2836 messages within Wanderlust transparently. I.e. html markup of the
2837 message body is created right before sending starts.
2839 *** Send HTML message
2841 Putting the code below in your .emacs adds following four functions:
2843 - dmj/wl-send-html-message
2845 Function that does the job: Convert everything between "--text
2846 follows this line--" and first mime entity (read: attachment) or
2847 end of buffer into html markup using `org-export-region-as-html'
2848 and replaces original body with a multipart MIME entity with the
2849 plain text version of body and the html markup version. Thus a
2850 recipient that prefers html messages can see the html markup,
2851 recipients that prefer or depend on plain text can see the plain
2854 Cannot be called interactively: It is hooked into SEMI's
2855 `mime-edit-translate-hook' if message should be HTML message.
2857 - dmj/wl-send-html-message-draft-init
2859 Cannot be called interactively: It is hooked into WL's
2860 `wl-mail-setup-hook' and provides a buffer local variable to
2863 - dmj/wl-send-html-message-draft-maybe
2865 Cannot be called interactively: It is hooked into WL's
2866 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2867 `mime-edit-translate-hook' depending on whether HTML message is
2870 - dmj/wl-send-html-message-toggle
2872 Toggles sending of HTML message. If toggled on, the letters
2873 "HTML" appear in the mode line.
2875 Call it interactively! Or bind it to a key in `wl-draft-mode'.
2877 If you have to send HTML messages regularly you can set a global
2878 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2879 toggle on sending HTML message by default.
2881 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2882 Google's web front end. As you can see you have the whole markup of
2883 Org at your service: *bold*, /italics/, tables, lists...
2885 So even if you feel uncomfortable with sending HTML messages at least
2886 you send HTML that looks quite good.
2888 #+begin_src emacs-lisp
2889 (defun dmj/wl-send-html-message ()
2890 "Send message as html message.
2891 Convert body of message to html using
2892 `org-export-region-as-html'."
2895 (let (beg end html text)
2896 (goto-char (point-min))
2897 (re-search-forward "^--text follows this line--$")
2898 ;; move to beginning of next line
2899 (beginning-of-line 2)
2901 (if (not (re-search-forward "^--\\[\\[" nil t))
2902 (setq end (point-max))
2907 (setq text (buffer-substring-no-properties beg end))
2913 (when (re-search-backward "^-- \n" nil t)
2914 ;; preserve link breaks in signature
2915 (insert "\n#+BEGIN_VERSE\n")
2916 (goto-char (point-max))
2917 (insert "\n#+END_VERSE\n")
2919 (setq html (org-export-region-as-html
2920 (point-min) (point-max) t 'string))))
2921 (delete-region beg end)
2924 "--" "<<alternative>>-{\n"
2925 "--" "[[text/plain]]\n" text
2926 "--" "[[text/html]]\n" html
2927 "--" "}-<<alternative>>\n")))))
2929 (defun dmj/wl-send-html-message-toggle ()
2930 "Toggle sending of html message."
2932 (setq dmj/wl-send-html-message-toggled-p
2933 (if dmj/wl-send-html-message-toggled-p
2935 (message "Sending html message toggled %s"
2936 (if dmj/wl-send-html-message-toggled-p
2939 (defun dmj/wl-send-html-message-draft-init ()
2940 "Create buffer local settings for maybe sending html message."
2941 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2942 (setq dmj/wl-send-html-message-toggled-p nil))
2943 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2944 (add-to-list 'global-mode-string
2945 '(:eval (if (eq major-mode 'wl-draft-mode)
2946 dmj/wl-send-html-message-toggled-p))))
2948 (defun dmj/wl-send-html-message-maybe ()
2949 "Maybe send this message as html message.
2951 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2952 non-nil, add `dmj/wl-send-html-message' to
2953 `mime-edit-translate-hook'."
2954 (if dmj/wl-send-html-message-toggled-p
2955 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2956 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2958 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2959 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2960 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2963 *** Attach HTML of region or subtree
2965 Instead of sending a complete HTML message you might only send parts
2966 of an Org file as HTML for the poor souls who are plagued with
2967 non-proportional fonts in their mail program that messes up pretty
2970 This short function does the trick: It exports region or subtree to
2971 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2972 and clipboard. If a region is active, it uses the region, the
2973 complete subtree otherwise.
2975 #+begin_src emacs-lisp
2976 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2977 "Export region between BEG and END as html attachment.
2978 If BEG and END are not set, use current subtree. Region or
2979 subtree is exported to html without header and footer, prefixed
2980 with a mime entity string and pushed to clipboard and killring.
2981 When called with prefix, mime entity is not marked as
2983 (interactive "r\nP")
2985 (let* ((beg (if (region-active-p) (region-beginning)
2987 (org-back-to-heading)
2989 (end (if (region-active-p) (region-end)
2991 (org-end-of-subtree)
2993 (html (concat "--[[text/html"
2994 (if arg "" "\nContent-Disposition: attachment")
2996 (org-export-region-as-html beg end t 'string))))
2997 (when (fboundp 'x-set-selection)
2998 (ignore-errors (x-set-selection 'PRIMARY html))
2999 (ignore-errors (x-set-selection 'CLIPBOARD html)))
3000 (message "html export done, pushed to kill ring and clipboard"))))
3003 *** Adopting for Gnus
3005 The whole magic lies in the special strings that mark a HTML
3006 attachment. So you might just have to find out what these special
3007 strings are in message-mode and modify the functions accordingly.
3008 ** Add sunrise/sunset times to the agenda.
3009 #+index: Agenda!Diary s-expressions
3012 The diary package provides the function =diary-sunrise-sunset= which can be used
3013 in a diary s-expression in some agenda file like this:
3016 %%(diary-sunrise-sunset)
3019 Seb Vauban asked if it is possible to put sunrise and sunset in
3020 separate lines. Here is a hack to do that. It adds two functions (they
3021 have to be available before the agenda is shown, so I add them early
3022 in my org-config file which is sourced from .emacs, but you'll have to
3023 suit yourself here) that just parse the output of
3024 diary-sunrise-sunset, instead of doing the right thing which would be
3025 to take advantage of the data structures that diary/solar.el provides.
3026 In short, a hack - so perfectly suited for inclusion here :-)
3028 The functions (and latitude/longitude settings which you have to modify for
3029 your location) are as follows:
3031 #+begin_src emacs-lisp
3032 (setq calendar-latitude 48.2)
3033 (setq calendar-longitude 16.4)
3034 (setq calendar-location-name "Vienna, Austria")
3036 (autoload 'solar-sunrise-sunset "solar.el")
3037 (autoload 'solar-time-string "solar.el")
3038 (defun diary-sunrise ()
3039 "Local time of sunrise as a diary entry.
3040 The diary entry can contain `%s' which will be replaced with
3041 `calendar-location-name'."
3042 (let ((l (solar-sunrise-sunset date)))
3045 (if (string= entry "")
3047 (format entry (eval calendar-location-name))) " "
3048 (solar-time-string (caar l) nil)))))
3050 (defun diary-sunset ()
3051 "Local time of sunset as a diary entry.
3052 The diary entry can contain `%s' which will be replaced with
3053 `calendar-location-name'."
3054 (let ((l (solar-sunrise-sunset date)))
3057 (if (string= entry "")
3059 (format entry (eval calendar-location-name))) " "
3060 (solar-time-string (caadr l) nil)))))
3063 You also need to add a couple of diary s-expressions in one of your agenda
3067 %%(diary-sunrise)Sunrise in %s
3071 This will show sunrise with the location and sunset without it.
3073 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]].
3074 In comparison to the version posted on the mailing list, this one
3075 gets rid of the timezone information and can show the location.
3076 ** Add lunar phases to the agenda.
3077 #+index: Agenda!Diary s-expressions
3080 Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
3081 This can be used to display lunar phases in the agenda display with the
3084 #+begin_src emacs-lisp
3087 (org-no-warnings (defvar date))
3088 (defun org-lunar-phases ()
3089 "Show lunar phase in Agenda buffer."
3091 (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
3092 (phase (cl-find-if (lambda (phase) (equal (car phase) date))
3095 (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
3096 (substring (nth 1 phase) 0 5))))))
3099 Add the following line to an agenda file:
3104 %%(org-lunar-phases)
3107 This should display an entry on new moon, first/last quarter moon, and on full
3108 moon. You can customize the entries by customizing =lunar-phase-names=.
3110 E.g., to add Unicode symbols:
3112 #+begin_src emacs-lisp
3113 (setq lunar-phase-names
3114 '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
3115 "☽ First Quarter Moon"
3116 "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
3117 "☾ Last Quarter Moon"))
3120 Unicode 6 even provides symbols for the Moon with nice faces. But those
3121 symbols are currently barely supported in fonts.
3122 See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].
3124 ** Export BBDB contacts to org-contacts.el
3125 #+index: Address Book!BBDB to org-contacts
3126 Try this tool by Wes Hardaker:
3128 http://www.hardakers.net/code/bbdb-to-org-contacts/
3130 ** Calculating date differences - how to write a simple elisp function
3131 #+index: Timestamp!date calculations
3132 #+index: Elisp!technique
3134 Alexander Wingård asked how to calculate the number of days between a
3135 time stamp in his org file and today (see
3136 http://thread.gmane.org/gmane.emacs.orgmode/46881). Although the
3137 resulting answer is probably not of general interest, the method might
3138 be useful to a budding Elisp programmer.
3140 Alexander started from an already existing org function,
3141 =org-evaluate-time-range=. When this function is called in the context
3142 of a time range (two time stamps separated by "=--="), it calculates the
3143 number of days between the two dates and outputs the result in Emacs's
3144 echo area. What he wanted was a similar function that, when called from
3145 the context of a single time stamp, would calculate the number of days
3146 between the date in the time stamp and today. The result should go to
3147 the same place: Emacs's echo area.
3149 The solution presented in the mail thread is as follows:
3151 #+begin_src emacs-lisp
3152 (defun aw/org-evaluate-time-range (&optional to-buffer)
3154 (if (org-at-date-range-p t)
3155 (org-evaluate-time-range to-buffer)
3156 ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
3157 (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
3160 (goto-char (point-at-bol))
3161 (re-search-forward org-ts-regexp (point-at-eol) t)
3162 (if (not (org-at-timestamp-p t))
3163 (error "No timestamp here"))
3164 (goto-char (match-beginning 0))
3165 (org-insert-time-stamp (current-time) nil nil)
3167 (org-evaluate-time-range to-buffer)))))
3170 The function assumes that point is on some line with some time stamp
3171 (or a date range) in it. Note that =org-evaluate-time-range= does not care
3172 whether the first date is earlier than the second: it will always output
3173 the number of days between the earlier date and the later date.
3175 As stated before, the function itself is of limited interest (although
3176 it satisfied Alexander's need).The *method* used might be of wider
3177 interest however, so here is a short explanation.
3179 The idea is that we want =org-evaluate-time-range= to do all the
3180 heavy lifting, but that function requires that it be in a date-range
3181 context. So the function first checks whether it's in a date range
3182 context already: if so, it calls =org-evaluate-time-range= directly
3183 to do the work. The trick now is to arrange things so we can call this
3184 same function in the case where we do *not* have a date range
3185 context. In that case, we manufacture one: we create a temporary
3186 buffer, copy the line with the purported time stamp to the temp
3187 buffer, find the time stamp (signal an error if no time stamp is
3188 found) and insert a new time stamp with the current time before the
3189 existing time stamp, followed by "=--=": voilà, we now have a time range
3190 on which we can apply our old friend =org-evaluate-time-range= to
3191 produce the answer. Because of the above-mentioned property
3192 of =org-evaluate-time-range=, it does not matter if the existing
3193 time stamp is earlier or later than the current time: the correct
3194 number of days is output.
3196 Note that at the end of the call to =with-temp-buffer=, the temporary
3197 buffer goes away. It was just used as a scratch pad for the function
3198 to do some figuring.
3200 The idea of using a temp buffer as a scratch pad has wide
3201 applicability in Emacs programming. The rest of the work is knowing
3202 enough about facilities provided by Emacs (e.g. regexp searching) and
3203 by Org (e.g. checking for time stamps and generating a time stamp) so
3204 that you don't reinvent the wheel, and impedance-matching between the
3207 ** ibuffer and org files
3209 Neil Smithline posted this snippet to let you browse org files with
3212 #+BEGIN_SRC emacs-lisp
3215 (defun org-ibuffer ()
3216 "Open an `ibuffer' window showing only `org-mode' buffers."
3218 (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
3221 ** Enable org-mode links in other modes
3223 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
3225 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
3227 ** poporg.el: edit comments in org-mode
3229 [[https://github.com/QBobWatson/poporg/blob/master/poporg.el][poporg.el]] is a library by François Pinard which lets you edit comments
3230 and strings from your code using a separate org-mode buffer.
3232 ** Convert a .csv file to an Org-mode table
3234 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
3235 the Marmelade ELPA repository):
3237 #+BEGIN_SRC emacs-lisp
3238 (defun yf/lisp-table-to-org-table (table &optional function)
3239 "Convert a lisp table to `org-mode' syntax, applying FUNCTION to each of its elements.
3240 The elements should not have any more newlines in them after
3241 applying FUNCTION ; the default converts them to spaces. Return
3242 value is a string containg the unaligned `org-mode' table."
3243 (unless (functionp function)
3244 (setq function (lambda (x) (replace-regexp-in-string "\n" " " x))))
3245 (mapconcat (lambda (x) ; x is a line.
3246 (concat "| " (mapconcat function x " | ") " |"))
3249 (defun yf/csv-to-table (beg end)
3250 "Convert a csv file to an `org-mode' table."
3253 (insert (yf/lisp-table-to-org-table (pcsv-parse-region beg end)))
3254 (delete-region beg end)
3260 ~foldout.el~, which is part of Emacs, is a nice little companion for
3261 ~outline-mode~. With ~foldout.el~ one can narrow to a subtree and
3262 later unnarrow. ~foldout.el~ is useful for Org mode out of the box.
3264 There is one annoyance though (at least for me):
3265 ~foldout-zoom-subtree~ opens the drawers.
3267 This can be fixed e.g. by using the following slightly modified
3268 version of ~foldout-zoom-subtree~ which uses function ~org-show-entry~
3269 instead of ~outline-show-entry~.
3271 #+begin_src emacs-lisp
3272 (defun foldout-zoom-org-subtree (&optional exposure)
3273 "Same as `foldout-zoom-subtree' with often nicer zoom in Org mode."
3276 (((symbol-function #'outline-show-entry) (lambda () (org-show-entry))))
3277 (foldout-zoom-subtree exposure)))
3280 * Hacking Org: Working with Org-mode and External Programs.
3281 ** Use Org-mode with Screen [Andrew Hyatt]
3282 #+index: Link!to screen session
3283 "The general idea is that you start a task in which all the work will
3284 take place in a shell. This usually is not a leaf-task for me, but
3285 usually the parent of a leaf task. From a task in your org-file, M-x
3286 ash-org-screen will prompt for the name of a session. Give it a name,
3287 and it will insert a link. Open the link at any time to go the screen
3288 session containing your work!"
3290 http://article.gmane.org/gmane.emacs.orgmode/5276
3292 #+BEGIN_SRC emacs-lisp
3295 (defun ash-org-goto-screen (name)
3296 "Open the screen with the specified name in the window"
3297 (interactive "MScreen name: ")
3298 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
3299 (if (member screen-buffer-name
3300 (mapcar 'buffer-name (buffer-list)))
3301 (switch-to-buffer screen-buffer-name)
3302 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
3304 (defun ash-org-screen-buffer-name (name)
3305 "Returns the buffer name corresponding to the screen name given."
3306 (concat "*screen " name "*"))
3308 (defun ash-org-screen-helper (name arg)
3309 ;; Pick the name of the new buffer.
3310 (let ((term-ansi-buffer-name
3311 (generate-new-buffer-name
3312 (ash-org-screen-buffer-name name))))
3313 (setq term-ansi-buffer-name
3314 (term-ansi-make-term
3315 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
3316 (set-buffer term-ansi-buffer-name)
3319 (term-set-escape-char ?\C-x)
3320 term-ansi-buffer-name))
3322 (defun ash-org-screen (name)
3323 "Start a screen session with name"
3324 (interactive "MScreen name: ")
3326 (ash-org-screen-helper name "-S"))
3327 (insert-string (concat "[[screen:" name "]]")))
3329 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
3330 ;; \"%s\")") to org-link-abbrev-alist.
3333 ** Org Agenda + Appt + Zenity
3335 :CUSTOM_ID: org-agenda-appt-zenity
3338 #+index: Appointment!reminders
3339 #+index: Appt!Zenity
3341 <a name="agenda-appt-zenity"></a>
3343 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It makes sure your agenda
3344 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
3347 #+BEGIN_SRC emacs-lisp
3348 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3349 ; For org appointment reminders
3351 ;; Get appointments for today
3352 (defun my-org-agenda-to-appt ()
3354 (setq appt-time-msg-list nil)
3355 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
3356 (org-agenda-to-appt)))
3358 ;; Run once, activate and schedule refresh
3359 (my-org-agenda-to-appt)
3361 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
3364 (setq appt-message-warning-time 15)
3365 (setq appt-display-interval 5)
3367 ; Update appt each time agenda opened.
3368 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
3370 ; Setup zenify, we tell appt to use window, and replace default function
3371 (setq appt-display-format 'window)
3372 (setq appt-disp-window-function (function my-appt-disp-window))
3374 (defun my-appt-disp-window (min-to-app new-time msg)
3375 (save-window-excursion (shell-command (concat
3376 "/usr/bin/zenity --info --title='Appointment' --text='"
3377 msg "' &") nil nil)))
3380 ** Org and appointment notifications on Mac OS 10.8
3382 Sarah Bagby [[http://mid.gmane.org/EA76104A-9ACD-4141-8D33-2E4D810D9B5A@geol.ucsb.edu][posted some code]] on how to get appointments notifications on
3383 Mac OS 10.8 with [[https://github.com/alloy/terminal-notifier][terminal-notifier]].
3385 ** Org-Mode + gnome-osd
3386 #+index: Appointment!reminders
3387 #+index: Appt!gnome-osd
3388 Richard Riley uses gnome-osd in interaction with Org-Mode to display
3389 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
3391 ** txt2org convert text data to org-mode tables
3394 I often find it useful to generate Org-mode tables on the command line
3395 from tab-separated data. The following awk script makes this easy to
3396 do. Text data is read from STDIN on a pipe and any command line
3397 arguments are interpreted as rows at which to insert hlines.
3399 Here are two usage examples.
3400 1. running the following
3401 : $ cat <<EOF|~/src/config/bin/txt2org
3413 2. and the following (notice the command line argument)
3414 : $ cat <<EOF|~/src/config/bin/txt2org 1
3422 : | strings | numbers |
3423 : |---------+---------|
3429 Here is the script itself
3433 # Read tab separated data from STDIN and output an Org-mode table.
3435 # Optional command line arguments specify row numbers at which to
3439 for(i=1; i<ARGC; i++){
3440 hlines[ARGV[i]+1]=1; ARGV[i] = "-"; } }
3443 if(NF > max_nf){ max_nf = NF; };
3444 for(f=1; f<=NF; f++){
3445 if(length($f) > lengths[f]){ lengths[f] = length($f); };
3450 for(f=1; f<=max_nf; f++){
3451 for(i=0; i<(lengths[f] + 2); i++){ hline_str=hline_str "-"; }
3452 if( f != max_nf){ hline_str=hline_str "+"; }
3453 else { hline_str=hline_str "|"; } }
3455 for(r=1; r<=NR; r++){ # rows
3456 if(hlines[r] == 1){ print hline_str; }
3458 for(f=1; f<=max_nf; f++){ # columns
3459 cell=row[r][f]; padding=""
3460 for(i=0; i<(lengths[f] - length(cell)); i++){ padding=padding " "; }
3461 # for now just print everything right-aligned
3462 # if(cell ~ /[0-9.]/){ printf " %s%s |", cell, padding; }
3463 # else{ printf " %s%s |", padding, cell; }
3464 printf " %s%s |", padding, cell; }
3467 if(hlines[NR+1]){ print hline_str; } }
3471 #+index: Agenda!Views
3472 #+index: Agenda!and Remind (external program)
3475 http://article.gmane.org/gmane.emacs.orgmode/5073
3478 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
3479 command line calendaring program. Its features supersede the possibilities
3480 of orgmode in the area of date specifying, so that I want to use it
3481 combined with orgmode.
3483 Using the script below I'm able use remind and incorporate its output in my
3484 agenda views. The default of using 13 months look ahead is easily
3485 changed. It just happens I sometimes like to look a year into the
3489 ** Useful webjumps for conkeror
3490 #+index: Shortcuts!conkeror
3491 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
3492 your =~/.conkerorrc= file:
3495 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
3496 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
3499 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
3500 Org-mode mailing list.
3502 ** Use MathJax for HTML export without requiring JavaScript
3503 #+index: Export!MathJax
3504 As of 2010-08-14, MathJax is the default method used to export math to HTML.
3506 If you like the results but do not want JavaScript in the exported pages,
3507 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
3508 HTML file from the exported version. It can also embed all referenced fonts
3509 within the HTML file itself, so there are no dependencies to external files.
3511 The download archive contains an elisp file which integrates it into the Org
3512 export process (configurable per file with a "#+StaticMathJax:" line).
3514 Read README.org and the comments in org-static-mathjax.el for usage instructions.
3515 ** Search Org files using lgrep
3516 #+index: search!lgrep
3517 Matt Lundin suggests this:
3519 #+begin_src emacs-lisp
3520 (defun my-org-grep (search &optional context)
3521 "Search for word in org files.
3523 Prefix argument determines number of lines."
3524 (interactive "sSearch for: \nP")
3525 (let ((grep-find-ignored-files '("#*" ".#*"))
3526 (grep-template (concat "grep <X> -i -nH "
3528 (concat "-C" (number-to-string context)))
3530 (lgrep search "*org*" "/home/matt/org/")))
3532 (global-set-key (kbd "<f8>") 'my-org-grep)
3535 ** Automatic screenshot insertion
3536 #+index: Link!screenshot
3537 Suggested by Russell Adams
3539 #+begin_src emacs-lisp
3540 (defun my-org-screenshot ()
3541 "Take a screenshot into a time stamped unique-named file in the
3542 same directory as the org-buffer and insert a link to this file."
3547 (concat (buffer-file-name)
3549 (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
3550 (call-process "import" nil nil nil filename)
3551 (insert (concat "[[" filename "]]"))
3552 (org-display-inline-images))
3555 ** Capture invitations/appointments from MS Exchange emails
3556 #+index: Appointment!MS Exchange
3557 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
3558 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
3560 ** Audio/video file playback within org mode
3561 #+index: Link!audio/video
3562 Paul Sexton provided code that makes =file:= links to audio or video files
3563 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
3564 media player library. The user can pause, skip forward and backward in the
3565 track, and so on from without leaving Emacs. Links can also contain a time
3566 after a double colon -- when this is present, playback will begin at that
3567 position in the track.
3569 See the file [[file:code/elisp/org-player.el][org-player.el]]
3571 ** Under X11 Keep a window with the current agenda items at all time
3572 #+index: Agenda!dedicated window
3573 I struggle to keep (in emacs) a window with the agenda at all times.
3574 For a long time I have wanted a sticky window that keeps this
3575 information, and then use my window manager to place it and remove its
3576 decorations (I can also force its placement in the stack: top always,
3579 I wrote a small program in qt that simply monitors an HTML file and
3580 displays it. Nothing more. It does the work for me, and maybe somebody
3581 else will find it useful. It relies on exporting the agenda as HTML
3582 every time the org file is saved, and then this little program
3583 displays the html file. The window manager is responsible of removing
3584 decorations, making it sticky, and placing it in same place always.
3586 Here is a screenshot (see window to the bottom right). The decorations
3587 are removed by the window manager:
3589 http://turingmachine.org/hacking/org-mode/orgdisplay.png
3591 Here is the code. As I said, very, very simple, but maybe somebody will
3594 http://turingmachine.org/hacking/org-mode/
3598 ** Script (thru procmail) to output emails to an Org file
3599 #+index: Conversion!email to org file
3600 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
3602 : I've [...] created some procmail and shell glue that takes emails and
3603 : inserts them into an org-file so that I can capture stuff on the go using
3604 : the email program.
3606 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3608 ** Save File With Different Format for Headings (fileconversion)
3610 :CUSTOM_ID: fileconversion
3612 #+index: Conversion!fileconversion
3614 Using hooks and on the fly
3615 - When writing a buffer to the file: Replace the leading stars from
3616 headings with a file char.
3617 - When reading a file into the buffer: Replace the file chars with
3618 leading stars for headings.
3620 To change the file format just add or remove the keyword in the
3621 ~#+STARTUP:~ line in the Org buffer and save.
3623 Now you can also change to Fundamental mode to see how the file looks
3624 like on the level of the file, can go back to Org mode, reenter Org
3625 mode or change to any other major mode and the conversion gets done
3628 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
3630 :CUSTOM_ID: hidestarsfile
3632 #+index: Conversion!fileconversion hidestarsfile
3634 This is like "a cleaner outline view":
3635 https://orgmode.org/manual/Clean-view.html
3637 Example of the *file content* first with leading stars as usual and
3638 below without leading stars through ~#+STARTUP: odd hidestars
3642 ,#+STARTUP: odd hidestars
3654 ,#+STARTUP: odd hidestars hidestarsfile
3665 The latter is convenient for better human readability when an Org file,
3666 additionally to Emacs, is read with a file viewer or, for smaller edits,
3667 with an editor not capable of the Org file format.
3669 ~hidestarsfile~ is a hack and can not become part of the Org core:
3670 - An Org file with ~hidestarsfile~ can not contain list items with a
3671 star as bullet due to the syntax conflict at read time. Mark
3672 E. Shoulson suggested to use the non-breaking space which is now
3673 implemented in fileconversion as ~nbspstarsfile~ as an alternative
3674 for ~hidestarsfile~. Although I don't recommend it because an editor
3675 like typically e. g. Emacs may render the non-breaking space
3676 differently from the space ~0x20~.
3677 - An Org file with ~hidestarsfile~ can almost not be edited with an
3678 Org mode without added functionality of hidestarsfile as long as the
3679 file is not converted back.
3681 *** Headings in Markdown Format (markdownstarsfile)
3683 :CUSTOM_ID: markdownstarsfile
3685 #+index: Conversion!fileconversion markdownstarsfile
3687 Together with ~oddeven~ you can use ~markdownstarsfile~ to be readable
3688 or even basically editable with Markdown (does not make much sense
3689 with ~odd~, see ~org-convert-to-odd-levels~ and
3690 ~org-convert-to-oddeven-levels~ for how to convert).
3692 Example of the *file content*:
3695 ,#+STARTUP: oddeven markdownstarsfile
3697 1. first item of numbered list (same format in Org and Markdown)
3699 - first item of unordered list (same format in Org and Markdown)
3701 + first item of unordered list (same format in Org and Markdown)
3702 #### section level 4
3703 * first item of unordered list (same format in Org and Markdown)
3704 * avoid this item type to be compatible with Org hidestarsfile
3707 An Org file with ~markdownstarsfile~ can not contain code comment
3708 lines prefixed with ~#~, even not when within source blocks.
3712 :CUSTOM_ID: fileconversion-code
3714 #+index: Conversion!fileconversion emacs-lisp code
3716 #+BEGIN_SRC emacs-lisp
3717 ;; - fileconversion version 0.10
3718 ;; - DISCLAIMER: Make a backup of your Org files before trying
3719 ;; `f-org-fileconv-*'. It is recommended to use a version control
3720 ;; system like git and to review and commit the changes in the Org
3722 ;; - Supported "#+STARTUP:" formats: "hidestarsfile",
3723 ;; "nbspstarsfile", "markdownstarsfile".
3725 ;; Design summary: fileconversion is a round robin of two states linked by
3727 ;; - State `v-org-fileconv-level-org-p' is nil: The level is "file"
3729 ;; - Action `f-org-fileconv-decode': Replace file char with "*".
3730 ;; - State `v-org-fileconv-level-org-p' is non-nil: The level is "Org"
3732 ;; - Action `f-org-fileconv-encode': Replace "*" with file char.
3734 ;; Naming convention of prefix:
3735 ;; - f-[...]: "my function", instead of the unspecific prefix `my-*'.
3736 ;; - v-[...]: "my variable", instead of the unspecific prefix `my-*'.
3738 (defvar v-org-fileconv-level-org-p nil
3739 "Whether level of buffer is Org or only file.
3740 nil: level is file (encoded), non-nil: level is Org (decoded).")
3741 (make-variable-buffer-local 'v-org-fileconv-level-org-p)
3742 ;; Survive a change of major mode that does `kill-all-local-variables', e.
3743 ;; g. when reentering Org mode through "C-c C-c" on a #+STARTUP: line.
3744 (put 'v-org-fileconv-level-org-p 'permanent-local t)
3746 ;; * Callback `f-org-fileconv-org-mode-beg' before `org-mode'
3747 (defadvice org-mode (before org-mode-advice-before-fileconv)
3748 (f-org-fileconv-org-mode-beg))
3749 (ad-activate 'org-mode)
3750 (defun f-org-fileconv-org-mode-beg ()
3751 ;; - Reason to test `buffer-file-name': Only when converting really
3752 ;; from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3754 ;; - No `message' to not wipe a possible "File mode specification error:".
3755 ;; - `f-org-fileconv-decode' in org-mode-hook would be too late for
3756 ;; performance reasons, see
3757 ;; http://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00920.html
3758 (when (buffer-file-name) (f-org-fileconv-decode)))
3760 ;; * Callback `f-org-fileconv-org-mode-end' after `org-mode'
3761 (add-hook 'org-mode-hook 'f-org-fileconv-org-mode-end
3762 nil ; _Prepend_ to hook to have it first.
3763 nil) ; Hook addition global.
3764 (defun f-org-fileconv-org-mode-end ()
3765 ;; - Reason to test `buffer-file-name': only when converting really
3766 ;; from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3768 ;; - No `message' to not wipe a possible "File mode specification error:".
3769 (when (buffer-file-name)
3770 ;; - Adding this to `change-major-mode-hook' or "defadvice before" of
3771 ;; org-mode would be too early and already trigger during find-file.
3772 ;; - Argument 4: t to limit hook addition to buffer locally, this way
3773 ;; and as required the hook addition will disappear when the major
3774 ;; mode of the buffer changes.
3775 (add-hook 'change-major-mode-hook 'f-org-fileconv-encode nil t)
3776 (add-hook 'before-save-hook 'f-org-fileconv-encode nil t)
3777 (add-hook 'after-save-hook 'f-org-fileconv-decode nil t)))
3779 (defun f-org-fileconv-re ()
3780 "Check whether there is a #+STARTUP: line for fileconversion.
3781 If found then return the expressions required for the conversion."
3783 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3784 (let (re-list (count 0))
3785 (while (re-search-forward "^[ \t]*#\\+STARTUP:" nil t)
3786 ;; #+STARTUP: hidestarsfile
3787 (when (string-match-p "\\bhidestarsfile\\b" (thing-at-point 'line))
3789 ;; - Line starting with star for bold emphasis.
3790 ;; - Line of stars to underline section title in loosely quoted
3791 ;; ASCII style (star at end of line).
3792 (setq re-list '("\\(\\* \\)" ; common-re
3794 (setq count (1+ count)))
3795 ;; #+STARTUP: nbspstarsfile
3796 (when (string-match-p "\\bnbspstarsfile\\b" (thing-at-point 'line))
3797 (setq re-list '("\\(\\* \\)" ; common-re
3798 ?\xa0)) ; file-char non-breaking space
3799 (setq count (1+ count)))
3800 ;; #+STARTUP: markdownstarsfile
3801 (when (string-match-p "\\bmarkdownstarsfile\\b"
3802 (thing-at-point 'line))
3803 ;; Exclude e. g. "#STARTUP:".
3804 (setq re-list '("\\( \\)" ; common-re
3806 (setq count (1+ count))))
3807 (when (> count 1) (error "More than one fileconversion found."))
3810 (defun f-org-fileconv-decode ()
3811 "In headings replace file char with '*'."
3812 (let ((re-list (f-org-fileconv-re)))
3813 (when (and re-list (not v-org-fileconv-level-org-p))
3814 ;; No `save-excursion' to be able to keep point in case of error.
3815 (let* ((common-re (nth 0 re-list))
3816 (file-char (nth 1 re-list))
3817 (file-re (concat "^" (string file-char) "+" common-re))
3818 (org-re (concat "^\\*+" common-re))
3821 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3823 (when (re-search-forward org-re nil t)
3824 (goto-char (match-beginning 0))
3826 (error "Org fileconversion decode: Syntax conflict at point."))
3827 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3829 (with-silent-modifications
3830 (while (re-search-forward file-re nil t)
3831 (goto-char (match-beginning 0))
3832 ;; Faster than a lisp call of insert and delete on each single
3834 (setq len (- (match-beginning 1) (match-beginning 0)))
3835 (insert-char ?* len)
3839 ;; Notes for ediff when only one file has fileconversion:
3840 ;; - The changes to the buffer with fileconversion until here are
3841 ;; not regarded by `ediff-files' because the first call to diff is
3842 ;; made with the bare files directly. Only `ediff-update-diffs'
3843 ;; and `ediff-buffers' write the decoded buffers to temp files and
3844 ;; then call diff with them.
3845 ;; - Workarounds (choose one):
3846 ;; - After ediff-files first do a "!" (ediff-update-diffs) in the
3847 ;; "*Ediff Control Panel*".
3848 ;; - Instead of using `ediff-files' first open the files and then
3849 ;; run `ediff-buffers' (better for e. g. a script that takes two
3850 ;; files as arguments and uses "emacs --eval").
3852 ;; The level is Org most of all when no fileconversion is in effect.
3853 (setq v-org-fileconv-level-org-p t))
3855 (defun f-org-fileconv-encode ()
3856 "In headings replace '*' with file char."
3857 (let ((re-list (f-org-fileconv-re)))
3858 (when (and re-list v-org-fileconv-level-org-p)
3859 ;; No `save-excursion' to be able to keep point in case of error.
3860 (let* ((common-re (nth 0 re-list))
3861 (file-char (nth 1 re-list))
3862 (file-re (concat "^" (string file-char) "+" common-re))
3863 (org-re (concat "^\\*+" common-re))
3866 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3868 (when (re-search-forward file-re nil t)
3869 (goto-char (match-beginning 0))
3871 (error "Org fileconversion encode: Syntax conflict at point."))
3872 (goto-char (point-min)) ; `beginning-of-buffer' is not allowed.
3874 (with-silent-modifications
3875 (while (re-search-forward org-re nil t)
3876 (goto-char (match-beginning 0))
3877 ;; Faster than a lisp call of insert and delete on each single
3879 (setq len (- (match-beginning 1) (match-beginning 0)))
3880 (insert-char file-char len)
3883 (setq v-org-fileconv-level-org-p nil))))
3884 nil) ; For the hook.
3889 ** Meaningful diff for org files in a git repository
3890 #+index: git!diff org files
3891 Since most diff utilities are primarily meant for source code, it is
3892 difficult to read diffs of text files like ~.org~ files easily. If you
3893 version your org directory with a SCM like git you will know what I
3894 mean. However for git, there is a way around. You can use
3895 =gitattributes= to define a custom diff driver for org files. Then a
3896 regular expression can be used to configure how the diff driver
3897 recognises a "function".
3899 Put the following in your =<org_dir>/.gitattributes=.
3901 Then put the following lines in =<org_dir>/.git/config=
3903 : xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3905 This will let you see diffs for org files with each hunk identified by
3906 the unmodified headline closest to the changes. After the
3907 configuration a diff should look something like the example below.
3910 diff --git a/org-hacks.org b/org-hacks.org
3911 index a0672ea..92a08f7 100644
3914 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3916 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3918 +** Meaningful diff for org files in a git repository
3920 +Since most diff utilities are primarily meant for source code, it is
3921 +difficult to read diffs of text files like ~.org~ files easily. If you
3922 +version your org directory with a SCM like git you will know what I
3923 +mean. However for git, there is a way around. You can use
3924 +=gitattributes= to define a custom diff driver for org files. Then a
3925 +regular expression can be used to configure how the diff driver
3926 +recognises a "function".
3928 +Put the following in your =<org_dir>/.gitattributes=.
3930 +Then put the following lines in =<org_dir>/.git/config=
3932 +: xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3936 ** Cooking? Brewing?
3939 ** Opening devonthink links
3941 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3942 links from org-mode.
3944 ** Memacs - Org-mode collecting meta-data from the disk and cloud
3946 Karl Voit designed Memacs ([[https://en.wikipedia.org/wiki/Memex][Memex]] and Emacs) which is a collection of
3947 modules that are able to get meta-data from different kind of
3948 sources. Memacs then generates output files containing meta-data in
3949 Org-mode format. Those files a most likely integrated as ~*.org_archive~
3950 files in your agenda.
3952 This way, you can get a pretty decent overview of your (digital) life:
3953 - file name timestamps ([[https://en.wikipedia.org/wiki/Iso_date][ISO 8601]]; like "2013-10-11 Product Demonstration.odp")
3954 - emails (IMAP, POP, Maildir, mbox)
3955 - RSS feeds (blog updates, ... *lots* of possibilities there!)
3956 - version system commits (SVN, git)
3957 - calendar (iCal, CSV)
3958 - text messages from your phone (Android)
3959 - phone calls (Android)
3960 - photographs (EXIF)
3961 - bank accounts ([[http://easybank.at][easybank]])
3962 - usenet postings (slrn, mbox, ...)
3963 - XML (a sub-set of easy-to-parse XML files can be parsed with minimal
3966 General idea: you set up the module(s) you would like to use once and
3967 they are running in the background. As long as the data source does
3968 not change, you should not have to worry about the module again.
3970 It is hard to explain the vast amount of (small) benefits you get once
3971 you have set up your Memacs modules.
3973 There is [[http://arxiv.org/abs/1304.1332][a whitepaper which describes Memacs]] and its implications.
3975 Memacs is [[https://github.com/novoid/Memacs][hosted on github]] and is written in Python.
3977 You can use Memacs to write your own Memacs module: an example module
3978 demonstrates how to write modules with very low effort. Please
3979 consider a pull request on github so that other people can use your
3982 [[https://github.com/novoid/twitter-json_to_orgmode][Twitter JSON to Org-mode]] generates Memacs-like output files for
3983 [[https://blog.twitter.com/2012/your-twitter-archive][Twitter export archives]] (JSON) but is independent of Memacs.
3987 ** Cooking? Brewing?
3988 #+index: beer!brewing
3989 #+index: cooking!conversions
3990 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3992 It currently does metric/english conversion, and a few other tricks.
3993 Basically I just use calc’s units code. I think scaling recipes, or
3994 turning percentages into weights would be pretty easy.
3996 https://gitorious.org/org-cook/org-cook
3998 There is also, for those interested:
4000 https://gitorious.org/org-brew/org-brew
4002 for brewing beer. This is again, mostly just calc functions, including
4003 hydrometer correction, abv calculation, priming sugar for a given CO_2
4004 volume, etc. More integration with org-mode should be possible: for
4005 instance it would be nice to be able to use a lookup table (of ingredients)
4006 to calculate target original gravity, IBUs, etc.