1 #+OPTIONS: H:3 num:nil toc:t \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate
3 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
4 #+TAGS: Write(w) Update(u) Fix(f) Check(c)
5 #+TITLE: Org ad hoc code, quick hacks and workarounds
7 #+EMAIL: mdl AT imapmail DOT org
12 # This file is the default header for new Org files in Worg. Feel free
13 # to tailor it to your needs.
15 [[file:index.org][{Back to Worg's index}]]
17 This page is for ad hoc bits of code. Feel free to add quick hacks and
20 * Hacking Org: Working within Org-mode.
21 ** Building and Managing Org
22 *** Compiling Org without make
24 :CUSTOM_ID: compiling-org-without-make
27 This file is the result of [[http://article.gmane.org/gmane.emacs.orgmode/15264][one of our discussions]] on the mailing list.
30 To use this function, adjust the variables =my/org-lisp-directory= and
31 =my/org-compile-sources= to suite your needs.
33 #+BEGIN_SRC emacs-lisp
34 (defvar my/org-lisp-directory "~/.emacs.d/org/lisp"
35 "Directory where your org-mode files live.")
37 (defvar my/org-compile-sources t
38 "If `nil', never compile org-sources. `my/compile-org' will only create
39 the autoloads file `org-install.el' then. If `t', compile the sources, too.")
42 (setq my/org-lisp-directory "~/.emacs.d/org/lisp")
45 (setq my/org-compile-sources t)
47 (defun my/compile-org(&optional directory)
48 "Compile all *.el files that come with org-mode."
50 (setq directory (concat
52 (or directory my/org-lisp-directory)) "/"))
54 (add-to-list 'load-path directory)
56 (let ((list-of-org-files (file-expand-wildcards (concat directory "*.el"))))
58 ;; create the org-install file
60 (setq esf/org-install-file (concat directory "org-install.el"))
61 (find-file esf/org-install-file)
64 (generate-file-autoloads x))
66 (insert "\n(provide (quote org-install))\n")
69 (byte-compile-file esf/org-install-file t)
71 (dolist (f list-of-org-files)
72 (if (file-exists-p (concat f "c")) ; delete compiled files
73 (delete-file (concat f "c")))
74 (if my/org-compile-sources ; Compile, if `my/org-compile-sources' is t
75 (byte-compile-file f)))))
79 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
80 function to reload org files.
82 Normally you want to use the compiled files since they are faster.
83 If you update your org files you can easily reload them with
87 If you run into a bug and want to generate a useful backtrace you can
88 reload the source files instead of the compiled files with
92 and turn on the "Enter Debugger On Error" option. Redo the action
93 that generates the error and cut and paste the resulting backtrace.
94 To switch back to the compiled version just reload again with
98 *** Check for possibly problematic old link escapes
100 :CUSTOM_ID: check-old-link-escapes
103 Starting with version 7.5 Org uses [[http://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
104 and with a modified algorithm to determine which characters to escape
107 As a side effect this modified behaviour might break existing links if
108 they contain a sequence of characters that look like a percent escape
109 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
111 The function below can be used to perform a preliminary check for such
112 links in an Org mode file. It will run through all links in the file
113 and issue a warning if it finds a percent escape sequence which is not
114 in old Org's list of known percent escapes.
116 #+begin_src emacs-lisp
117 (defun dmaus/org-check-percent-escapes ()
118 "*Check buffer for possibly problematic old link escapes."
120 (when (eq major-mode 'org-mode)
121 (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
122 "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
123 (unless (boundp 'warning-suppress-types)
124 (setq warning-suppress-types nil))
127 (goto-char (point-min))
128 (while (re-search-forward org-any-link-re nil t)
129 (let ((end (match-end 0)))
130 (goto-char (match-beginning 0))
131 (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
132 (let ((escape (match-string-no-properties 0)))
133 (unless (member (upcase escape) old-escapes)
134 (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
141 ** Enhancing the Org experience
143 Speed commands are described [[http://orgmode.org/manual/Speed-keys.html#Speed-keys][here]] in the manual. Add your own speed
145 *** Show next/prev heading tidily
147 These close the current heading and open the next/previous heading.
149 #+begin_src emacs-lisp
150 (defun ded/org-show-next-heading-tidily ()
151 "Show next entry, keeping other entries closed."
152 (if (save-excursion (end-of-line) (outline-invisible-p))
153 (progn (org-show-entry) (show-children))
154 (outline-next-heading)
155 (unless (and (bolp) (org-on-heading-p))
156 (org-up-heading-safe)
158 (error "Boundary reached"))
164 (defun ded/org-show-previous-heading-tidily ()
165 "Show previous entry, keeping other entries closed."
167 (outline-previous-heading)
168 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
171 (error "Boundary reached"))
177 (setq org-use-speed-commands t)
178 (add-to-list 'org-speed-commands-user
179 '("n" ded/org-show-next-heading-tidily))
180 (add-to-list 'org-speed-commands-user
181 '("p" ded/org-show-previous-heading-tidily))
184 *** Changelog support for org headers
187 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
188 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
189 headline as the "current function" if you add a changelog entry from an org
192 #+BEGIN_SRC emacs-lisp
193 (defun org-log-current-defun ()
195 (org-back-to-heading)
196 (if (looking-at org-complex-heading-regexp)
199 (add-hook 'org-mode-hook
201 (make-variable-buffer-local 'add-log-current-defun-function)
202 (setq add-log-current-defun-function 'org-log-current-defun)))
205 *** Different org-cycle-level behavior
208 In recent org versions, when your point (cursor) is at the end of an
209 empty header line (like after you first created the header), the TAB
210 key (=org-cycle=) has a special behavior: it cycles the headline through
211 all possible levels. However, I did not like the way it determined
212 "all possible levels," so I rewrote the whole function, along with a
213 couple of supporting functions.
215 The original function's definition of "all possible levels" was "every
216 level from 1 to one more than the initial level of the current
217 headline before you started cycling." My new definition is "every
218 level from 1 to one more than the previous headline's level." So, if
219 you have a headline at level 4 and you use ALT+RET to make a new
220 headline below it, it will cycle between levels 1 and 5, inclusive.
222 The main advantage of my custom =org-cycle-level= function is that it
223 is stateless: the next level in the cycle is determined entirely by
224 the contents of the buffer, and not what command you executed last.
225 This makes it more predictable, I hope.
227 #+BEGIN_SRC emacs-lisp
230 (defun org-point-at-end-of-empty-headline ()
231 "If point is at the end of an empty headline, return t, else nil."
232 (and (looking-at "[ \t]*$")
234 (beginning-of-line 1)
235 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
237 (defun org-level-increment ()
238 "Return the number of stars that will be added or removed at a
239 time to headlines when structure editing, based on the value of
240 `org-odd-levels-only'."
241 (if org-odd-levels-only 2 1))
243 (defvar org-previous-line-level-cached nil)
245 (defun org-recalculate-previous-line-level ()
246 "Same as `org-get-previous-line-level', but does not use cached
247 value. It does *set* the cached value, though."
248 (set 'org-previous-line-level-cached
249 (let ((current-level (org-current-level))
250 (prev-level (when (> (line-number-at-pos) 1)
253 (org-current-level)))))
254 (cond ((null current-level) nil) ; Before first headline
255 ((null prev-level) 0) ; At first headline
258 (defun org-get-previous-line-level ()
259 "Return the outline depth of the last headline before the
260 current line. Returns 0 for the first headline in the buffer, and
261 nil if before the first headline."
262 ;; This calculation is quite expensive, with all the regex searching
263 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
264 ;; the last value of this command.
265 (or (and (eq last-command 'org-cycle-level)
266 org-previous-line-level-cached)
267 (org-recalculate-previous-line-level)))
269 (defun org-cycle-level ()
271 (let ((org-adapt-indentation nil))
272 (when (org-point-at-end-of-empty-headline)
273 (setq this-command 'org-cycle-level) ;Only needed for caching
274 (let ((cur-level (org-current-level))
275 (prev-level (org-get-previous-line-level)))
277 ;; If first headline in file, promote to top-level.
279 (loop repeat (/ (- cur-level 1) (org-level-increment))
280 do (org-do-promote)))
281 ;; If same level as prev, demote one.
282 ((= prev-level cur-level)
284 ;; If parent is top-level, promote to top level if not already.
286 (loop repeat (/ (- cur-level 1) (org-level-increment))
287 do (org-do-promote)))
288 ;; If top-level, return to prev-level.
290 (loop repeat (/ (- prev-level 1) (org-level-increment))
292 ;; If less than prev-level, promote one.
293 ((< cur-level prev-level)
295 ;; If deeper than prev-level, promote until higher than
297 ((> cur-level prev-level)
298 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
299 do (org-do-promote))))
304 **** Transpose tables (Juan Pechiar)
306 This function by Juan Pechiar will transpose a table:
308 #+begin_src emacs-lisp
309 (defun org-transpose-table-at-point ()
310 "Transpose orgmode table at point, eliminate hlines"
313 (apply #'mapcar* #'list
314 ;; remove 'hline from list
315 (remove-if-not 'listp
316 ;; signals error if not table
317 (org-table-to-lisp)))))
318 (delete-region (org-table-begin) (org-table-end))
319 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
331 will be transposed as
338 (Note that horizontal lines disappeared.)
340 *** Times computation
341 **** Manipulate hours/minutes/seconds in table formulas
343 Martin Halder [[http://article.gmane.org/gmane.emacs.orgmode/39487][wanted]] to "generate a simple table with time format "hh:mm"
344 and auto calculate daily sum". He [[http://article.gmane.org/gmane.emacs.orgmode/39519][ended up]] with these functions, which can
347 #+begin_src emacs-lisp
349 (if (string-match org-timer-re arg)
350 (org-timer-hms-to-secs arg)
351 (org-timer-hms-to-secs (concat arg ":00"))))
356 m (/ s 60) s (- s (* 60 m))
357 h (/ m 60) m (- m (* 60 h)))
358 (format "%d:%02d" h m)))
362 (setq s (/ (* s 10000) 3600)
364 m (/ s 100) s (- s (* 100 m))
365 h (/ m 100) m (- m (* 100 h)))
366 (format "%d.%02d" h m)))
369 Using this function, you can create a table like this one:
371 : | Date | Start | Lunch | Back | End | Sum | Ind |
372 : |------------------+-------+-------+-------+-------+------+------|
373 : | [2011-03-01 Tue] | 8:00 | 12:00 | 12:30 | 18:15 | 9:45 | 9.75 |
374 : #+TBLFM: $6='(my-hms (+ (- (my-sec $5) (my-sec $4)) (- (my-sec $3) (my-sec $2))))::$7='(my-ihms (+ (- (my-sec $5) (my-sec $4)) (- (my-sec $3) (my-sec $2))))
376 **** Subtracting durations in seconds
378 #+begin_src emacs-lisp
379 (defun org-hh:mm:ss-string-to-seconds (s)
380 "Convert a string HH:MM:SS to a number of seconds."
381 (when (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s)
382 (let ((hour (string-to-number (match-string 1 s)))
383 (min (string-to-number (match-string 2 s)))
384 (sec (string-to-number (match-string 3 s))))
385 (+ (* hour 3600) (* min 60) sec))))
387 (defun org-subtract-hh:mm:ss-time (t1 t2)
388 "Substract two hh:mm:ss time values."
389 (let* ((sec (- (org-hh:mm:ss-string-to-seconds t2)
390 (org-hh:mm:ss-string-to-seconds t1)))
391 (hour (floor (/ sec 3600)))
392 (min (floor (/ (- sec (* 3600 hour)) 60)))
393 (secs (round (- sec (* 3600 hour) (* 60 min)))))
394 (format "%.2d:%.2d:%.2d" hour min secs)))
397 With these function, you can subtract durations in a table like this:
399 : | Part | Begin | End | Duration |
400 : |-------+----------+----------+----------|
401 : | One | 00:00:00 | 00:01:11 | 00:01:11 |
402 : | Two | 00:01:12 | 00:02:00 | 00:00:48 |
403 : | Three | 00:02:05 | 00:16:06 | 00:14:01 |
404 : #+TBLFM: $4='(org-subtract-hh:mm:ss-time $2 $3)
406 *** Dates computation
408 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
410 I have a table in org which stores the date, I'm wondering if there is
411 any function to calculate the duration? For example:
413 | Start Date | End Date | Duration |
414 |------------+------------+----------|
415 | 2004.08.07 | 2005.07.08 | |
417 I tried to use B&-C&, but failed ...
419 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
423 | Start Date | End Date | Duration |
424 |------------+------------+----------|
425 | 2004.08.07 | 2005.07.08 | 335 |
426 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
430 http://thread.gmane.org/gmane.emacs.orgmode/7741
432 as well as this post (which is really a followup on the
435 http://article.gmane.org/gmane.emacs.orgmode/7753
437 The problem that this last article pointed out was solved
440 http://article.gmane.org/gmane.emacs.orgmode/8001
442 and Chris Randle's original musings are at
444 http://article.gmane.org/gmane.emacs.orgmode/6536/
446 *** Field coordinates in formulas (=@#= and =$#=)
450 Following are some use cases that can be implemented with the
451 _field coordinates in formulas_ described in the corresponding
452 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
454 **** Copy a column from a remote table into a column
456 current column =$3= = remote column =$2=:
457 : #+TBLFM: $3 = remote(FOO, @@#$2)
459 **** Copy a row from a remote table transposed into a column
461 current column =$1= = transposed remote row =@1=:
462 : #+TBLFM: $1 = remote(FOO, @$#$@#)
464 **** Transpose a table
468 This is more like a demonstration of using _field coordinates in formulas_
469 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel. The efficient
470 and simple solution for this with the help of org-babel and Emacs Lisp has
471 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
473 To transpose this 4x7 table
476 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
477 : |------+------+------+------+------+------+------|
478 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
479 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
480 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
482 start with a 7x4 table without any horizontal line (to have filled
483 also the column header) and yet empty:
493 Then add the =TBLFM= below with the same formula repeated for each column.
494 After recalculation this will end up with the transposed copy:
496 : | year | min | avg | max |
497 : | 2004 | 401 | 402 | 403 |
498 : | 2005 | 501 | 502 | 503 |
499 : | 2006 | 601 | 602 | 603 |
500 : | 2007 | 701 | 702 | 703 |
501 : | 2008 | 801 | 802 | 803 |
502 : | 2009 | 901 | 902 | 903 |
503 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
505 The formulas simply exchange row and column numbers by taking
506 - the absolute remote row number =@$#= from the current column number =$#=
507 - the absolute remote column number =$@#= from the current row number =@#=
509 Possible field formulas from the remote table will have to be transferred
510 manually. Since there are no row formulas yet there is no need to transfer
511 column formulas to row formulas or vice versa.
513 **** Dynamic variation of ranges
517 In this example all columns next to =quote= are calculated from the column
518 =quote= and show the average change of the time series =quote[year]=
519 during the period of the preceding =1=, =2=, =3= or =4= years:
521 : | year | quote | 1 a | 2 a | 3 a | 4 a |
522 : |------+-------+-------+-------+-------+-------|
523 : | 2005 | 10 | | | | |
524 : | 2006 | 12 | 0.200 | | | |
525 : | 2007 | 14 | 0.167 | 0.183 | | |
526 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
527 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
528 : #+TBLFM: $3=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$4=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$5=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$6=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3
530 The formula is the same for each column =$3= through =$6=. This can easily
531 be seen with the great formula editor invoked by C-c ' on the
532 table. The important part of the formula without the field blanking is:
534 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
536 which is the Emacs Calc implementation of the equation
538 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
540 where /i/ is the current time and /a/ is the length of the preceding period.
542 *** Customize the size of the frame for remember
543 (Note: this hack is likely out of date due to the development of
547 On emacs-orgmode, Ryan C. Thompson suggested this:
550 I am using org-remember set to open a new frame when used,
551 and the default frame size is much too large. To fix this, I have
552 designed some advice and a custom variable to implement custom
553 parameters for the remember frame:
556 #+begin_src emacs-lisp
557 (defcustom remember-frame-alist nil
558 "Additional frame parameters for dedicated remember frame."
562 (defadvice remember (around remember-frame-parameters activate)
563 "Set some frame parameters for the remember frame."
564 (let ((default-frame-alist (append remember-frame-alist
565 default-frame-alist)))
569 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
570 reasonable size for the frame.
571 *** Promote all items in subtree
574 This function will promote all items in a subtree. Since I use
575 subtrees primarily to organize projects, the function is somewhat
576 unimaginatively called my-org-un-project:
578 #+begin_src emacs-lisp
579 (defun my-org-un-project ()
581 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
585 *** Turn a heading into an Org link
589 #+begin_src emacs-lisp
590 (defun dmj:turn-headline-into-org-mode-link ()
591 "Replace word at point by an Org mode link."
593 (when (org-at-heading-p)
594 (let ((hl-text (nth 4 (org-heading-components))))
595 (unless (or (null hl-text)
596 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
598 (search-forward hl-text (point-at-eol))
601 (format "[[file:%s.org][%s]]"
602 (org-link-escape hl-text)
603 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
604 nil (- (point) (length hl-text)) (point))))))
607 *** Count words in an Org buffer
609 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
611 #+begin_src emacs-lisp
612 (defun org-word-count (beg end
613 &optional count-latex-macro-args?
615 "Report the number of words in the Org mode buffer or selected region.
619 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
620 - hyperlinks (but does count words in hyperlink descriptions)
621 - tags, priorities, and TODO keywords in headers
622 - sections tagged as 'not for export'.
624 The text of footnote definitions is ignored, unless the optional argument
625 COUNT-FOOTNOTES? is non-nil.
627 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
628 includes LaTeX macro arguments (the material between {curly braces}).
629 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
633 (setf beg (point-min)
636 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
639 (while (< (point) end)
642 ((or (org-in-commented-line) (org-at-table-p))
644 ;; Ignore hyperlinks. But if link has a description, count
645 ;; the words within the description.
646 ((looking-at org-bracket-link-analytic-regexp)
647 (when (match-string-no-properties 5)
648 (let ((desc (match-string-no-properties 5)))
650 (incf wc (length (remove "" (org-split-string
652 (goto-char (match-end 0)))
653 ((looking-at org-any-link-re)
654 (goto-char (match-end 0)))
655 ;; Ignore source code blocks.
656 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
658 ;; Ignore inline source blocks, counting them as 1 word.
661 (looking-at org-babel-inline-src-block-regexp))
662 (goto-char (match-end 0))
664 ;; Count latex macros as 1 word, ignoring their arguments.
667 (looking-at latex-macro-regexp))
668 (goto-char (if count-latex-macro-args?
673 ((and (not count-footnotes?)
674 (or (org-footnote-at-definition-p)
675 (org-footnote-at-reference-p)))
678 (let ((contexts (org-context)))
680 ;; Ignore tags and TODO keywords, etc.
681 ((or (assoc :todo-keyword contexts)
682 (assoc :priority contexts)
683 (assoc :keyword contexts)
684 (assoc :checkbox contexts))
686 ;; Ignore sections marked with tags that are
687 ;; excluded from export.
688 ((assoc :tags contexts)
689 (if (intersection (org-get-tags-at) org-export-exclude-tags
691 (org-forward-same-level 1)
695 (re-search-forward "\\w+\\W*")))
696 (message (format "%d words in %s." wc
697 (if mark-active "region" "buffer")))))
700 ** Archiving Content in Org-Mode
701 *** Preserve top level headings when archiving to a file
704 To preserve (somewhat) the integrity of your archive structure while
705 archiving lower level items to a file, you can use the following
708 #+begin_src emacs-lisp
709 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
710 (let ((org-archive-location
711 (if (save-excursion (org-back-to-heading)
712 (> (org-outline-level) 1))
713 (concat (car (split-string org-archive-location "::"))
715 (car (org-get-outline-path)))
716 org-archive-location)))
720 Thus, if you have an outline structure such as...
728 ...archiving "Subsubheading" to a new file will set the location in
729 the new file to the top level heading:
736 While this hack obviously destroys the outline hierarchy somewhat, it
737 at least preserves the logic of level one groupings.
739 A slightly more complex version of this hack will not only keep the
740 archive organized by top-level headings, but will also preserve the
741 tags found on those headings:
743 #+begin_src emacs-lisp
744 (defun my-org-inherited-no-file-tags ()
745 (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
746 (ltags (org-entry-get nil "TAGS")))
749 (replace-regexp-in-string (concat tag ":") "" tags)))
750 (append org-file-tags (when ltags (split-string ltags ":" t))))
751 (if (string= ":" tags) nil tags)))
753 (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
754 (let ((tags (my-org-inherited-no-file-tags))
755 (org-archive-location
756 (if (save-excursion (org-back-to-heading)
757 (> (org-outline-level) 1))
758 (concat (car (split-string org-archive-location "::"))
760 (car (org-get-outline-path)))
761 org-archive-location)))
763 (with-current-buffer (find-file-noselect (org-extract-archive-file))
767 (when (= 1 (org-up-heading-safe))
769 (org-set-tags-to tags)))))
772 *** Archive in a date tree
774 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
776 (Make sure org-datetree.el is loaded for this to work.)
778 #+begin_src emacs-lisp
779 ;; (setq org-archive-location "%s_archive::date-tree")
780 (defadvice org-archive-subtree
781 (around org-archive-subtree-to-data-tree activate)
782 "org-archive-subtree to date-tree"
785 (org-extract-archive-heading
786 (org-get-local-archive-location)))
787 (let* ((dct (decode-time (org-current-time)))
791 (this-buffer (current-buffer))
792 (location (org-get-local-archive-location))
793 (afile (org-extract-archive-file location))
794 (org-archive-location
795 (format "%s::*** %04d-%02d-%02d %s" afile y m d
796 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
797 (message "afile=%s" afile)
799 (error "Invalid `org-archive-location'"))
801 (switch-to-buffer (find-file-noselect afile))
802 (org-datetree-find-year-create y)
803 (org-datetree-find-month-create y m)
804 (org-datetree-find-day-create y m d)
806 (switch-to-buffer this-buffer))
811 *** Add inherited tags to archived entries
813 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
814 advise the function like this:
817 (defadvice org-archive-subtree
818 (before add-inherited-tags-before-org-archive-subtree activate)
819 "add inherited tags before org-archive-subtree"
820 (org-set-tags-to (org-get-tags-at)))
823 ** Using and Managing Org-Metadata
824 *** Remove redundant tags of headlines
827 A small function that processes all headlines in current buffer and
828 removes tags that are local to a headline and inherited by a parent
829 headline or the #+FILETAGS: statement.
831 #+BEGIN_SRC emacs-lisp
832 (defun dmj/org-remove-redundant-tags ()
833 "Remove redundant tags of headlines in current buffer.
835 A tag is considered redundant if it is local to a headline and
836 inherited by a parent headline."
838 (when (eq major-mode 'org-mode)
842 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
844 (dolist (tag alltags)
845 (if (get-text-property 0 'inherited tag)
846 (push tag inherited) (push tag local)))
848 (if (member tag inherited) (org-toggle-tag tag 'off)))))
852 *** Remove empty property drawers
854 David Maus proposed this:
856 #+begin_src emacs-lisp
857 (defun dmj:org:remove-empty-propert-drawers ()
858 "*Remove all empty property drawers in current file."
860 (unless (eq major-mode 'org-mode)
861 (error "You need to turn on Org mode for this function."))
863 (goto-char (point-min))
864 (while (re-search-forward ":PROPERTIES:" nil t)
866 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
869 *** Group task list by a property
871 This advice allows you to group a task list in Org-Mode. To use it,
872 set the variable =org-agenda-group-by-property= to the name of a
873 property in the option list for a TODO or TAGS search. The resulting
874 agenda view will group tasks by that property prior to searching.
876 #+begin_src emacs-lisp
877 (defvar org-agenda-group-by-property nil
878 "Set this in org-mode agenda views to group tasks by property")
880 (defun org-group-bucket-items (prop items)
883 (let* ((marker (get-text-property 0 'org-marker item))
884 (pvalue (org-entry-get marker prop t))
885 (cell (assoc pvalue buckets)))
887 (setcdr cell (cons item (cdr cell)))
888 (setq buckets (cons (cons pvalue (list item))
890 (setq buckets (mapcar (lambda (bucket)
892 (reverse (cdr bucket))))
894 (sort buckets (lambda (i1 i2)
895 (string< (car i1) (car i2))))))
897 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
898 (list &optional nosort))
899 "Prepare bucketed agenda entry lists"
900 (if org-agenda-group-by-property
901 ;; bucketed, handle appropriately
903 (dolist (bucket (org-group-bucket-items
904 org-agenda-group-by-property
906 (let ((header (concat "Property "
907 org-agenda-group-by-property
909 (or (car bucket) "<nil>") ":\n")))
910 (add-text-properties 0 (1- (length header))
911 (list 'face 'org-agenda-structure)
915 ;; recursively process
916 (let ((org-agenda-group-by-property nil))
917 (org-finalize-agenda-entries
918 (cdr bucket) nosort))
920 (setq ad-return-value text))
922 (ad-activate 'org-finalize-agenda-entries)
924 *** Dynamically adjust tag position
925 Here is a bit of code that allows you to have the tags always
926 right-adjusted in the buffer.
928 This is useful when you have bigger window than default window-size
929 and you dislike the aesthetics of having the tag in the middle of the
932 This hack solves the problem of adjusting it whenever you change the
934 Before saving it will revert the file to having the tag position be
935 left-adjusted so that if you track your files with version control,
936 you won't run into artificial diffs just because the window-size
939 *IMPORTANT*: This is probably slow on very big files.
941 #+begin_src emacs-lisp
942 (setq ba/org-adjust-tags-column t)
944 (defun ba/org-adjust-tags-column-reset-tags ()
945 "In org-mode buffers it will reset tag position according to
948 (not (string= (buffer-name) "*Remember*"))
949 (eql major-mode 'org-mode))
950 (let ((b-m-p (buffer-modified-p)))
953 (goto-char (point-min))
954 (command-execute 'outline-next-visible-heading)
955 ;; disable (message) that org-set-tags generates
956 (flet ((message (&rest ignored) nil))
958 (set-buffer-modified-p b-m-p))
961 (defun ba/org-adjust-tags-column-now ()
962 "Right-adjust `org-tags-column' value, then reset tag position."
963 (set (make-local-variable 'org-tags-column)
964 (- (- (window-width) (length org-ellipsis))))
965 (ba/org-adjust-tags-column-reset-tags))
967 (defun ba/org-adjust-tags-column-maybe ()
968 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
969 (when ba/org-adjust-tags-column
970 (ba/org-adjust-tags-column-now)))
972 (defun ba/org-adjust-tags-column-before-save ()
973 "Tags need to be left-adjusted when saving."
974 (when ba/org-adjust-tags-column
975 (setq org-tags-column 1)
976 (ba/org-adjust-tags-column-reset-tags)))
978 (defun ba/org-adjust-tags-column-after-save ()
979 "Revert left-adjusted tag position done by before-save hook."
980 (ba/org-adjust-tags-column-maybe)
981 (set-buffer-modified-p nil))
983 ; automatically align tags on right-hand side
984 (add-hook 'window-configuration-change-hook
985 'ba/org-adjust-tags-column-maybe)
986 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
987 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
988 (add-hook 'org-agenda-mode-hook '(lambda ()
989 (setq org-agenda-tags-column (- (window-width)))))
991 ; between invoking org-refile and displaying the prompt (which
992 ; triggers window-configuration-change-hook) tags might adjust,
993 ; which invalidates the org-refile cache
994 (defadvice org-refile (around org-refile-disable-adjust-tags)
995 "Disable dynamically adjusting tags"
996 (let ((ba/org-adjust-tags-column nil))
998 (ad-activate 'org-refile)
1000 ** Org Agenda and Task Management
1001 *** Make it easier to set org-agenda-files from multiple directories
1004 #+begin_src emacs-lisp
1005 (defun my-org-list-files (dirs ext)
1006 "Function to create list of org files in multiple subdirectories.
1007 This can be called to generate a list of files for
1008 org-agenda-files or org-refile-targets.
1010 DIRS is a list of directories.
1012 EXT is a list of the extensions of files to be included."
1013 (let ((dirs (if (listp dirs)
1016 (ext (if (listp ext)
1026 (file-expand-wildcards
1027 (concat (file-name-as-directory x) "*" y)))))
1032 (when (or (string-match "/.#" x)
1033 (string-match "#$" x))
1034 (setq files (delete x files))))
1038 (defvar my-org-agenda-directories '("~/org/")
1039 "List of directories containing org files.")
1040 (defvar my-org-agenda-extensions '(".org")
1041 "List of extensions of agenda files")
1043 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1044 (setq my-org-agenda-extensions '(".org" ".ref"))
1046 (defun my-org-set-agenda-files ()
1048 (setq org-agenda-files (my-org-list-files
1049 my-org-agenda-directories
1050 my-org-agenda-extensions)))
1052 (my-org-set-agenda-files)
1055 The code above will set your "default" agenda files to all files
1056 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1057 You can change these values by setting the variables
1058 my-org-agenda-extensions and my-org-agenda-directories. The function
1059 my-org-agenda-files-by-filetag uses these two variables to determine
1060 which files to search for filetags (i.e., the larger set from which
1061 the subset will be drawn).
1063 You can also easily use my-org-list-files to "mix and match"
1064 directories and extensions to generate different lists of agenda
1067 *** Restrict org-agenda-files by filetag
1069 :CUSTOM_ID: set-agenda-files-by-filetag
1073 It is often helpful to limit yourself to a subset of your agenda
1074 files. For instance, at work, you might want to see only files related
1075 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1076 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
1077 commands]]. These solutions, however, require reapplying a filter each
1078 time you call the agenda or writing several new custom agenda commands
1079 for each context. Another solution is to use directories for different
1080 types of tasks and to change your agenda files with a function that
1081 sets org-agenda-files to the appropriate directory. But this relies on
1082 hard and static boundaries between files.
1084 The following functions allow for a more dynamic approach to selecting
1085 a subset of files based on filetags:
1087 #+begin_src emacs-lisp
1088 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1089 "Restrict org agenda files only to those containing filetag."
1091 (let* ((tagslist (my-org-get-all-filetags))
1093 (completing-read "Tag: "
1094 (mapcar 'car tagslist)))))
1095 (org-agenda-remove-restriction-lock 'noupdate)
1096 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1097 (setq org-agenda-overriding-restriction 'files)))
1099 (defun my-org-get-all-filetags ()
1100 "Get list of filetags from all default org-files."
1101 (let ((files org-agenda-files)
1103 (save-window-excursion
1104 (while (setq x (pop files))
1105 (set-buffer (find-file-noselect x))
1108 (let ((tagfiles (assoc y tagslist)))
1110 (setcdr tagfiles (cons x (cdr tagfiles)))
1111 (add-to-list 'tagslist (list y x)))))
1112 (my-org-get-filetags)))
1115 (defun my-org-get-filetags ()
1116 "Get list of filetags for current buffer"
1117 (let ((ftags org-file-tags)
1121 (org-substring-no-properties x))
1125 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1126 with all filetags in your "normal" agenda files. When you select a
1127 tag, org-agenda-files will be restricted to only those files
1128 containing the filetag. To release the restriction, type C-c C-x >
1129 (org-agenda-remove-restriction-lock).
1131 *** Highlight the agenda line under cursor
1133 This is useful to make sure what task you are operating on.
1135 #+BEGIN_SRC emacs-lisp
1136 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1137 #+END_SRC emacs-lisp
1141 #+BEGIN_SRC emacs-lisp
1142 ;; hl-line seems to be only for emacs
1144 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1146 ;; highline-mode does not work straightaway in tty mode.
1147 ;; I use a black background
1149 '(highline-face ((((type tty) (class color))
1150 (:background "white" :foreground "black")))))
1151 #+END_SRC emacs-lisp
1153 *** Split horizontally for agenda
1155 If you would like to split the frame into two side-by-side windows when
1156 displaying the agenda, try this hack from Jan Rehders, which uses the
1157 `toggle-window-split' from
1159 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1161 #+BEGIN_SRC emacs-lisp
1162 ;; Patch org-mode to use vertical splitting
1163 (defadvice org-prepare-agenda (after org-fix-split)
1164 (toggle-window-split))
1165 (ad-activate 'org-prepare-agenda)
1168 *** Automatically add an appointment when clocking in a task
1170 #+BEGIN_SRC emacs-lisp
1171 ;; Make sure you have a sensible value for `appt-message-warning-time'
1172 (defvar bzg-org-clock-in-appt-delay 100
1173 "Number of minutes for setting an appointment by clocking-in")
1176 This function let's you add an appointment for the current entry.
1177 This can be useful when you need a reminder.
1179 #+BEGIN_SRC emacs-lisp
1180 (defun bzg-org-clock-in-add-appt (&optional n)
1181 "Add an appointment for the Org entry at point in N minutes."
1184 (org-back-to-heading t)
1185 (looking-at org-complex-heading-regexp)
1186 (let* ((msg (match-string-no-properties 4))
1187 (ct-time (decode-time))
1188 (appt-min (+ (cadr ct-time)
1189 (or n bzg-org-clock-in-appt-delay)))
1190 (appt-time ; define the time for the appointment
1191 (progn (setf (cadr ct-time) appt-min) ct-time)))
1192 (appt-add (format-time-string
1193 "%H:%M" (apply 'encode-time appt-time)) msg)
1194 (if (interactive-p) (message "New appointment for %s" msg)))))
1197 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1200 #+BEGIN_SRC emacs-lisp
1201 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1202 "Add an appointment when clocking a task in."
1203 (bzg-org-clock-in-add-appt))
1206 You may also want to delete the associated appointment when clocking
1207 out. This function does this:
1209 #+BEGIN_SRC emacs-lisp
1210 (defun bzg-org-clock-out-delete-appt nil
1211 "When clocking out, delete any associated appointment."
1214 (org-back-to-heading t)
1215 (looking-at org-complex-heading-regexp)
1216 (let* ((msg (match-string-no-properties 4)))
1217 (setq appt-time-msg-list
1221 (if (not (string-match (regexp-quote msg)
1222 (cadr appt))) appt))
1223 appt-time-msg-list)))
1227 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1229 #+BEGIN_SRC emacs-lisp
1230 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1231 "Delete an appointment when clocking a task out."
1232 (bzg-org-clock-out-delete-appt))
1235 *IMPORTANT*: You can add appointment by clocking in in both an
1236 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1237 agenda buffer with the advice above will bring an error.
1239 *** Remove time grid lines that are in an appointment
1241 The agenda shows lines for the time grid. Some people think that
1242 these lines are a distraction when there are appointments at those
1243 times. You can get rid of the lines which coincide exactly with the
1244 beginning of an appointment. Michael Ekstrand has written a piece of
1245 advice that also removes lines that are somewhere inside an
1248 #+begin_src emacs-lisp
1249 (defun org-time-to-minutes (time)
1250 "Convert an HHMM time to minutes"
1251 (+ (* (/ time 100) 60) (% time 100)))
1253 (defun org-time-from-minutes (minutes)
1254 "Convert a number of minutes to an HHMM time"
1255 (+ (* (/ minutes 60) 100) (% minutes 60)))
1257 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1258 (list ndays todayp))
1259 (if (member 'remove-match (car org-agenda-time-grid))
1260 (flet ((extract-window
1262 (let ((start (get-text-property 1 'time-of-day line))
1263 (dur (get-text-property 1 'duration line)))
1267 (org-time-from-minutes
1268 (+ dur (org-time-to-minutes start)))))
1271 (let* ((windows (delq nil (mapcar 'extract-window list)))
1272 (org-agenda-time-grid
1273 (list (car org-agenda-time-grid)
1274 (cadr org-agenda-time-grid)
1277 (find-if (lambda (w)
1280 (and (>= time (car w))
1283 (caddr org-agenda-time-grid)))))
1286 (ad-activate 'org-agenda-add-time-grid-maybe)
1288 *** Disable vc for Org mode agenda files
1291 Even if you use Git to track your agenda files you might not need
1292 vc-mode to be enabled for these files.
1294 #+begin_src emacs-lisp
1295 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1296 (defun dmj/disable-vc-for-agenda-files-hook ()
1297 "Disable vc-mode for Org agenda files."
1298 (if (and (fboundp 'org-agenda-file-p)
1299 (org-agenda-file-p (buffer-file-name)))
1300 (remove-hook 'find-file-hook 'vc-find-file-hook)
1301 (add-hook 'find-file-hook 'vc-find-file-hook)))
1304 *** Easy customization of TODO colors
1307 Here is some code I came up with some code to make it easier to
1308 customize the colors of various TODO keywords. As long as you just
1309 want a different color and nothing else, you can customize the
1310 variable org-todo-keyword-faces and use just a string color (i.e. a
1311 string of the color name) as the face, and then org-get-todo-face
1312 will convert the color to a face, inheriting everything else from
1313 the standard org-todo face.
1315 To demonstrate, I currently have org-todo-keyword-faces set to
1317 #+BEGIN_SRC emacs-lisp
1318 (("IN PROGRESS" . "dark orange")
1319 ("WAITING" . "red4")
1320 ("CANCELED" . "saddle brown"))
1321 #+END_SRC emacs-lisp
1323 Here's the code, in a form you can put in your =.emacs=
1325 #+BEGIN_SRC emacs-lisp
1326 (eval-after-load 'org-faces
1328 (defcustom org-todo-keyword-faces nil
1329 "Faces for specific TODO keywords.
1330 This is a list of cons cells, with TODO keywords in the car and
1331 faces in the cdr. The face can be a symbol, a color, or a
1332 property list of attributes, like (:foreground \"blue\" :weight
1333 bold :underline t)."
1338 (string :tag "Keyword")
1339 (choice color (sexp :tag "Face")))))))
1341 (eval-after-load 'org
1343 (defun org-get-todo-face-from-color (color)
1344 "Returns a specification for a face that inherits from org-todo
1345 face and has the given color as foreground. Returns nil if
1348 `(:inherit org-warning :foreground ,color)))
1350 (defun org-get-todo-face (kwd)
1351 "Get the right face for a TODO keyword KWD.
1352 If KWD is a number, get the corresponding match group."
1353 (if (numberp kwd) (setq kwd (match-string kwd)))
1354 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1356 (org-get-todo-face-from-color face)
1358 (and (member kwd org-done-keywords) 'org-done)
1360 #+END_SRC emacs-lisp
1362 *** Add an effort estimate on the fly when clocking in
1364 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1365 This way you can easily have a "tea-timer" for your tasks when they
1366 don't already have an effort estimate.
1368 #+begin_src emacs-lisp
1369 (add-hook 'org-clock-in-prepare-hook
1370 'my-org-mode-ask-effort)
1372 (defun my-org-mode-ask-effort ()
1373 "Ask for an effort estimate when clocking in."
1374 (unless (org-entry-get (point) "Effort")
1378 (org-entry-get-multivalued-property (point) "Effort"))))
1379 (unless (equal effort "")
1380 (org-set-property "Effort" effort)))))
1383 Or you can use a default effort for such a timer:
1385 #+begin_src emacs-lisp
1386 (add-hook 'org-clock-in-prepare-hook
1387 'my-org-mode-add-default-effort)
1389 (defvar org-clock-default-effort "1:00")
1391 (defun my-org-mode-add-default-effort ()
1392 "Add a default effort estimation."
1393 (unless (org-entry-get (point) "Effort")
1394 (org-set-property "Effort" org-clock-default-effort)))
1397 *** Refresh the agenda view regurally
1399 Hack sent by Kiwon Um:
1401 #+begin_src emacs-lisp
1402 (defun kiwon/org-agenda-redo-in-other-window ()
1403 "Call org-agenda-redo function even in the non-agenda buffer."
1405 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1407 (with-selected-window agenda-window (org-agenda-redo)))))
1408 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1411 *** Reschedule agenda items to today with a single command
1413 This was suggested by Carsten in reply to David Abrahams:
1415 #+begin_example emacs-lisp
1416 (defun org-agenda-reschedule-to-today ()
1418 (flet ((org-read-date (&rest rest) (current-time)))
1419 (call-interactively 'org-agenda-schedule)))
1422 * Hacking Org: Working with Org-mode and other Emacs Packages.
1423 ** org-remember-anything
1425 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1427 #+BEGIN_SRC emacs-lisp
1428 (defvar org-remember-anything
1429 '((name . "Org Remember")
1430 (candidates . (lambda () (mapcar 'car org-remember-templates)))
1431 (action . (lambda (name)
1432 (let* ((orig-template org-remember-templates)
1433 (org-remember-templates
1434 (list (assoc name orig-template))))
1435 (call-interactively 'org-remember))))))
1438 You can add it to your 'anything-sources' variable and open remember directly
1439 from anything. I imagine this would be more interesting for people with many
1440 remember templatesm, so that you are out of keys to assign those to. You should
1441 get something like this:
1443 [[file:images/thumbs/org-remember-anything.png]]
1445 ** Org-mode and saveplace.el
1447 Fix a problem with saveplace.el putting you back in a folded position:
1449 #+begin_src emacs-lisp
1450 (add-hook 'org-mode-hook
1452 (when (outline-invisible-p)
1454 (outline-previous-visible-heading 1)
1455 (org-show-subtree)))))
1458 ** Using ido-completing-read to find attachments
1461 Org-attach is great for quickly linking files to a project. But if you
1462 use org-attach extensively you might find yourself wanting to browse
1463 all the files you've attached to org headlines. This is not easy to do
1464 manually, since the directories containing the files are not human
1465 readable (i.e., they are based on automatically generated ids). Here's
1466 some code to browse those files using ido (obviously, you need to be
1469 #+begin_src emacs-lisp
1470 (load-library "find-lisp")
1472 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1474 (defun my-ido-find-org-attach ()
1475 "Find files in org-attachment directory"
1477 (let* ((enable-recursive-minibuffers t)
1478 (files (find-lisp-find-files org-attach-directory "."))
1481 (cons (file-name-nondirectory x)
1485 (remove-duplicates (mapcar #'car file-assoc-list)
1487 (filename (ido-completing-read "Org attachments: " filename-list nil t))
1488 (longname (cdr (assoc filename file-assoc-list))))
1489 (ido-set-current-directory
1490 (if (file-directory-p longname)
1492 (file-name-directory longname)))
1493 (setq ido-exit 'refresh
1494 ido-text-init ido-text
1498 (add-hook 'ido-setup-hook 'ido-my-keys)
1500 (defun ido-my-keys ()
1501 "Add my keybindings for ido."
1502 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1505 To browse your org attachments using ido fuzzy matching and/or the
1506 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1509 ** Use idle timer for automatic agenda views
1511 From John Wiegley's mailing list post (March 18, 2010):
1514 I have the following snippet in my .emacs file, which I find very
1515 useful. Basically what it does is that if I don't touch my Emacs for 5
1516 minutes, it displays the current agenda. This keeps my tasks "always
1517 in mind" whenever I come back to Emacs after doing something else,
1518 whereas before I had a tendency to forget that it was there.
1521 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1523 #+begin_src emacs-lisp
1524 (defun jump-to-org-agenda ()
1526 (let ((buf (get-buffer "*Org Agenda*"))
1529 (if (setq wind (get-buffer-window buf))
1530 (select-window wind)
1531 (if (called-interactively-p)
1533 (select-window (display-buffer buf t t))
1534 (org-fit-window-to-buffer)
1535 ;; (org-agenda-redo)
1537 (with-selected-window (display-buffer buf)
1538 (org-fit-window-to-buffer)
1539 ;; (org-agenda-redo)
1541 (call-interactively 'org-agenda-list)))
1542 ;;(let ((buf (get-buffer "*Calendar*")))
1543 ;; (unless (get-buffer-window buf)
1544 ;; (org-agenda-goto-calendar)))
1547 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1551 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1553 ** Link to Gnus messages by Message-Id
1555 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1556 discussion about linking to Gnus messages without encoding the folder
1557 name in the link. The following code hooks in to the store-link
1558 function in Gnus to capture links by Message-Id when in nnml folders,
1559 and then provides a link type "mid" which can open this link. The
1560 =mde-org-gnus-open-message-link= function uses the
1561 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1562 scan. It will go through them, in order, asking each to locate the
1563 message and opening it from the first one that reports success.
1565 It has only been tested with a single nnml backend, so there may be
1566 bugs lurking here and there.
1568 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1571 #+begin_src emacs-lisp
1572 ;; Support for saving Gnus messages by Message-ID
1573 (defun mde-org-gnus-save-by-mid ()
1574 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1575 (when (eq major-mode 'gnus-article-mode)
1576 (gnus-article-show-summary))
1577 (let* ((group gnus-newsgroup-name)
1578 (method (gnus-find-method-for-group group)))
1579 (when (eq 'nnml (car method))
1580 (let* ((article (gnus-summary-article-number))
1581 (header (gnus-summary-article-header article))
1582 (from (mail-header-from header))
1585 (let ((mid (mail-header-id header)))
1586 (if (string-match "<\\(.*\\)>" mid)
1587 (match-string 1 mid)
1588 (error "Malformed message ID header %s" mid)))))
1589 (date (mail-header-date header))
1590 (subject (gnus-summary-subject-string)))
1591 (org-store-link-props :type "mid" :from from :subject subject
1592 :message-id message-id :group group
1593 :link (org-make-link "mid:" message-id))
1594 (apply 'org-store-link-props
1595 :description (org-email-link-description)
1596 org-store-link-plist)
1599 (defvar mde-mid-resolve-methods '()
1600 "List of methods to try when resolving message ID's. For Gnus,
1601 it is a cons of 'gnus and the select (type and name).")
1602 (setq mde-mid-resolve-methods
1605 (defvar mde-org-gnus-open-level 1
1606 "Level at which Gnus is started when opening a link")
1607 (defun mde-org-gnus-open-message-link (msgid)
1608 "Open a message link with Gnus"
1610 (require 'org-table)
1611 (catch 'method-found
1612 (message "[MID linker] Resolving %s" msgid)
1613 (dolist (method mde-mid-resolve-methods)
1615 ((and (eq (car method) 'gnus)
1616 (eq (cadr method) 'nnml))
1617 (funcall (cdr (assq 'gnus org-link-frame-setup))
1618 mde-org-gnus-open-level)
1619 (when gnus-other-frame-object
1620 (select-frame gnus-other-frame-object))
1621 (let* ((msg-info (nnml-find-group-number
1622 (concat "<" msgid ">")
1624 (group (and msg-info (car msg-info)))
1625 (message (and msg-info (cdr msg-info)))
1627 (if (gnus-methods-equal-p
1631 (gnus-group-full-name group (cdr method))))))
1633 (gnus-summary-read-group qname nil t)
1634 (gnus-summary-goto-article message nil t))
1635 (throw 'method-found t)))
1636 (t (error "Unknown link type"))))))
1638 (eval-after-load 'org-gnus
1640 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1641 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1644 ** Store link upon sending a message in Gnus
1646 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1648 #+begin_src emacs-lisp
1649 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1650 "Send message with `message-send-and-exit' and store org link to message copy.
1651 If multiple groups appear in the Gcc header, the link refers to
1652 the copy in the last group."
1656 (message-narrow-to-headers)
1657 (let ((gcc (car (last
1658 (message-unquote-tokens
1659 (message-tokenize-header
1660 (mail-fetch-field "gcc" nil t) " ,")))))
1661 (buf (current-buffer))
1662 (message-kill-buffer-on-exit nil)
1663 id to from subject desc link newsgroup xarchive)
1664 (message-send-and-exit arg)
1666 ;; gcc group found ...
1668 (save-current-buffer
1669 (progn (set-buffer buf)
1670 (setq id (org-remove-angle-brackets
1671 (mail-fetch-field "Message-ID")))
1672 (setq to (mail-fetch-field "To"))
1673 (setq from (mail-fetch-field "From"))
1674 (setq subject (mail-fetch-field "Subject"))))
1675 (org-store-link-props :type "gnus" :from from :subject subject
1676 :message-id id :group gcc :to to)
1677 (setq desc (org-email-link-description))
1678 (setq link (org-gnus-article-link
1679 gcc newsgroup id xarchive))
1680 (setq org-stored-links
1681 (cons (list link desc) org-stored-links)))
1682 ;; no gcc group found ...
1683 (message "Can not create Org link: No Gcc header found."))))))
1685 (define-key message-mode-map [(control c) (control meta c)]
1686 'ulf-message-send-and-org-gnus-store-link)
1689 ** Send html messages and attachments with Wanderlust
1692 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1693 similar functionality for both Wanderlust and Gnus. The hack below is
1694 still somewhat different: It allows you to toggle sending of html
1695 messages within Wanderlust transparently. I.e. html markup of the
1696 message body is created right before sending starts.
1698 *** Send HTML message
1700 Putting the code below in your .emacs adds following four functions:
1702 - dmj/wl-send-html-message
1704 Function that does the job: Convert everything between "--text
1705 follows this line--" and first mime entity (read: attachment) or
1706 end of buffer into html markup using `org-export-region-as-html'
1707 and replaces original body with a multipart MIME entity with the
1708 plain text version of body and the html markup version. Thus a
1709 recipient that prefers html messages can see the html markup,
1710 recipients that prefer or depend on plain text can see the plain
1713 Cannot be called interactively: It is hooked into SEMI's
1714 `mime-edit-translate-hook' if message should be HTML message.
1716 - dmj/wl-send-html-message-draft-init
1718 Cannot be called interactively: It is hooked into WL's
1719 `wl-mail-setup-hook' and provides a buffer local variable to
1722 - dmj/wl-send-html-message-draft-maybe
1724 Cannot be called interactively: It is hooked into WL's
1725 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1726 `mime-edit-translate-hook' depending on whether HTML message is
1729 - dmj/wl-send-html-message-toggle
1731 Toggles sending of HTML message. If toggled on, the letters
1732 "HTML" appear in the mode line.
1734 Call it interactively! Or bind it to a key in `wl-draft-mode'.
1736 If you have to send HTML messages regularly you can set a global
1737 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1738 toggle on sending HTML message by default.
1740 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1741 Google's web front end. As you can see you have the whole markup of
1742 Org at your service: *bold*, /italics/, tables, lists...
1744 So even if you feel uncomfortable with sending HTML messages at least
1745 you send HTML that looks quite good.
1747 #+begin_src emacs-lisp
1748 (defun dmj/wl-send-html-message ()
1749 "Send message as html message.
1750 Convert body of message to html using
1751 `org-export-region-as-html'."
1754 (let (beg end html text)
1755 (goto-char (point-min))
1756 (re-search-forward "^--text follows this line--$")
1757 ;; move to beginning of next line
1758 (beginning-of-line 2)
1760 (if (not (re-search-forward "^--\\[\\[" nil t))
1761 (setq end (point-max))
1766 (setq text (buffer-substring-no-properties beg end))
1772 (when (re-search-backward "^-- \n" nil t)
1773 ;; preserve link breaks in signature
1774 (insert "\n#+BEGIN_VERSE\n")
1775 (goto-char (point-max))
1776 (insert "\n#+END_VERSE\n")
1778 (setq html (org-export-region-as-html
1779 (point-min) (point-max) t 'string))))
1780 (delete-region beg end)
1783 "--" "<<alternative>>-{\n"
1784 "--" "[[text/plain]]\n" text
1785 "--" "[[text/html]]\n" html
1786 "--" "}-<<alternative>>\n")))))
1788 (defun dmj/wl-send-html-message-toggle ()
1789 "Toggle sending of html message."
1791 (setq dmj/wl-send-html-message-toggled-p
1792 (if dmj/wl-send-html-message-toggled-p
1794 (message "Sending html message toggled %s"
1795 (if dmj/wl-send-html-message-toggled-p
1798 (defun dmj/wl-send-html-message-draft-init ()
1799 "Create buffer local settings for maybe sending html message."
1800 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1801 (setq dmj/wl-send-html-message-toggled-p nil))
1802 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1803 (add-to-list 'global-mode-string
1804 '(:eval (if (eq major-mode 'wl-draft-mode)
1805 dmj/wl-send-html-message-toggled-p))))
1807 (defun dmj/wl-send-html-message-maybe ()
1808 "Maybe send this message as html message.
1810 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1811 non-nil, add `dmj/wl-send-html-message' to
1812 `mime-edit-translate-hook'."
1813 (if dmj/wl-send-html-message-toggled-p
1814 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1815 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1817 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1818 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1819 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1822 *** Attach HTML of region or subtree
1824 Instead of sending a complete HTML message you might only send parts
1825 of an Org file as HTML for the poor souls who are plagued with
1826 non-proportional fonts in their mail program that messes up pretty
1829 This short function does the trick: It exports region or subtree to
1830 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1831 and clipboard. If a region is active, it uses the region, the
1832 complete subtree otherwise.
1834 #+begin_src emacs-lisp
1835 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1836 "Export region between BEG and END as html attachment.
1837 If BEG and END are not set, use current subtree. Region or
1838 subtree is exported to html without header and footer, prefixed
1839 with a mime entity string and pushed to clipboard and killring.
1840 When called with prefix, mime entity is not marked as
1842 (interactive "r\nP")
1844 (let* ((beg (if (region-active-p) (region-beginning)
1846 (org-back-to-heading)
1848 (end (if (region-active-p) (region-end)
1850 (org-end-of-subtree)
1852 (html (concat "--[[text/html"
1853 (if arg "" "\nContent-Disposition: attachment")
1855 (org-export-region-as-html beg end t 'string))))
1856 (when (fboundp 'x-set-selection)
1857 (ignore-errors (x-set-selection 'PRIMARY html))
1858 (ignore-errors (x-set-selection 'CLIPBOARD html)))
1859 (message "html export done, pushed to kill ring and clipboard"))))
1862 *** Adopting for Gnus
1864 The whole magic lies in the special strings that mark a HTML
1865 attachment. So you might just have to find out what these special
1866 strings are in message-mode and modify the functions accordingly.
1867 ** Add sunrise/sunset times to the agenda.
1870 The diary package provides the function =diary-sunrise-sunset= which can be used
1871 in a diary s-expression in some agenda file like this:
1873 #+begin_src org-mode
1874 %%(diary-sunrise-sunset)
1877 Seb Vauban asked if it is possible to put sunrise and sunset in
1878 separate lines. Here is a hack to do that. It adds two functions (they
1879 have to be available before the agenda is shown, so I add them early
1880 in my org-config file which is sourced from .emacs, but you'll have to
1881 suit yourself here) that just parse the output of
1882 diary-sunrise-sunset, instead of doing the right thing which would be
1883 to take advantage of the data structures that diary/solar.el provides.
1884 In short, a hack - so perfectly suited for inclusion here :-)
1886 The functions (and latitude/longitude settings which you have to modify for
1887 your location) are as follows:
1889 #+begin_src emacs-lisp
1890 (setq calendar-latitude 40.3)
1891 (setq calendar-longitude -71.0)
1892 (defun diary-sunrise ()
1893 (let ((dss (diary-sunrise-sunset)))
1896 (goto-char (point-min))
1897 (while (re-search-forward " ([^)]*)" nil t)
1898 (replace-match "" nil nil))
1899 (goto-char (point-min))
1900 (search-forward ",")
1901 (buffer-substring (point-min) (match-beginning 0)))))
1903 (defun diary-sunset ()
1904 (let ((dss (diary-sunrise-sunset))
1908 (goto-char (point-min))
1909 (while (re-search-forward " ([^)]*)" nil t)
1910 (replace-match "" nil nil))
1911 (goto-char (point-min))
1912 (search-forward ", ")
1913 (setq start (match-end 0))
1914 (search-forward " at")
1915 (setq end (match-beginning 0))
1918 (buffer-substring start end))))
1921 You also need to add a couple of diary s-expressions in one of your agenda
1924 #+begin_src org-mode
1929 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]].
1930 In comparison to the version posted on the mailing list, this one
1931 gets rid of the timezone information.
1932 * Hacking Org: Working with Org-mode and External Programs.
1933 ** Use Org-mode with Screen [Andrew Hyatt]
1935 "The general idea is that you start a task in which all the work will
1936 take place in a shell. This usually is not a leaf-task for me, but
1937 usually the parent of a leaf task. From a task in your org-file, M-x
1938 ash-org-screen will prompt for the name of a session. Give it a name,
1939 and it will insert a link. Open the link at any time to go the screen
1940 session containing your work!"
1942 http://article.gmane.org/gmane.emacs.orgmode/5276
1944 #+BEGIN_SRC emacs-lisp
1947 (defun ash-org-goto-screen (name)
1948 "Open the screen with the specified name in the window"
1949 (interactive "MScreen name: ")
1950 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1951 (if (member screen-buffer-name
1952 (mapcar 'buffer-name (buffer-list)))
1953 (switch-to-buffer screen-buffer-name)
1954 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1956 (defun ash-org-screen-buffer-name (name)
1957 "Returns the buffer name corresponding to the screen name given."
1958 (concat "*screen " name "*"))
1960 (defun ash-org-screen-helper (name arg)
1961 ;; Pick the name of the new buffer.
1962 (let ((term-ansi-buffer-name
1963 (generate-new-buffer-name
1964 (ash-org-screen-buffer-name name))))
1965 (setq term-ansi-buffer-name
1966 (term-ansi-make-term
1967 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1968 (set-buffer term-ansi-buffer-name)
1971 (term-set-escape-char ?\C-x)
1972 term-ansi-buffer-name))
1974 (defun ash-org-screen (name)
1975 "Start a screen session with name"
1976 (interactive "MScreen name: ")
1978 (ash-org-screen-helper name "-S"))
1979 (insert-string (concat "[[screen:" name "]]")))
1981 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1982 ;; \"%s\")") to org-link-abbrev-alist.
1985 ** Org Agenda + Appt + Zenity
1987 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It make sure your agenda
1988 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1991 #+BEGIN_SRC emacs-lisp
1992 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1993 ; For org appointment reminders
1995 ;; Get appointments for today
1996 (defun my-org-agenda-to-appt ()
1998 (setq appt-time-msg-list nil)
1999 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
2000 (org-agenda-to-appt)))
2002 ;; Run once, activate and schedule refresh
2003 (my-org-agenda-to-appt)
2005 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2008 (setq appt-message-warning-time 15)
2009 (setq appt-display-interval 5)
2011 ; Update appt each time agenda opened.
2012 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2014 ; Setup zenify, we tell appt to use window, and replace default function
2015 (setq appt-display-format 'window)
2016 (setq appt-disp-window-function (function my-appt-disp-window))
2018 (defun my-appt-disp-window (min-to-app new-time msg)
2019 (save-window-excursion (shell-command (concat
2020 "/usr/bin/zenity --info --title='Appointment' --text='"
2021 msg "' &") nil nil)))
2024 ** Org-Mode + gnome-osd
2026 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2027 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2033 http://article.gmane.org/gmane.emacs.orgmode/5073
2036 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2037 command line calendaring program. Its features superseed the possibilities
2038 of orgmode in the area of date specifying, so that I want to use it
2039 combined with orgmode.
2041 Using the script below I'm able use remind and incorporate its output in my
2042 agenda views. The default of using 13 months look ahead is easily
2043 changed. It just happens I sometimes like to look a year into the
2047 ** Useful webjumps for conkeror
2049 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2050 your =~/.conkerorrc= file:
2053 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2054 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2057 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2058 Org-mode mailing list.
2060 ** Use MathJax for HTML export without requiring JavaScript
2061 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2063 If you like the results but do not want JavaScript in the exported pages,
2064 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2065 HTML file from the exported version. It can also embed all referenced fonts
2066 within the HTML file itself, so there are no dependencies to external files.
2068 The download archive contains an elisp file which integrates it into the Org
2069 export process (configurable per file with a "#+StaticMathJax:" line).
2071 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2072 ** Search Org files using lgrep
2074 Matt Lundin suggests this:
2076 #+begin_src emacs-lisp
2077 (defun my-org-grep (search &optional context)
2078 "Search for word in org files.
2080 Prefix argument determines number of lines."
2081 (interactive "sSearch for: \nP")
2082 (let ((grep-find-ignored-files '("#*" ".#*"))
2083 (grep-template (concat "grep <X> -i -nH "
2085 (concat "-C" (number-to-string context)))
2087 (lgrep search "*org*" "/home/matt/org/")))
2089 (global-set-key (kbd "<f8>") 'my-org-grep)
2092 ** Automatic screenshot insertion
2094 Suggested by Jonathan Bisson:
2096 #+begin_src emacs-lisp
2097 (defun my-screenshot ()
2098 "Take a screenshot into a unique-named file in the current buffer file
2099 directory and insert a link to this file."
2104 (file-name-directory (buffer-file-name))) ".jpg"))
2105 (call-process "import" nil nil nil filename)
2106 (insert (concat "[[" filename "]]"))
2107 (org-display-inline-images))
2110 ** Capture invitations/appointments from MS Exchange emails
2112 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
2113 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]