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 esage
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"
137 (- (point) 3))))))))))
140 ** Enhancing the Org experience.
142 Speed commands are described [[http://orgmode.org/manual/Speed-keys.html#Speed-keys][here]] in the manual. Add your own speed
144 *** Show next/prev heading tidily
146 These close the current heading and open the next/previous heading.
148 #+begin_src emacs-lisp
149 (defun ded/org-show-next-heading-tidily ()
150 "Show next entry, keeping other entries closed."
151 (if (save-excursion (end-of-line) (outline-invisible-p))
152 (progn (org-show-entry) (show-children))
153 (outline-next-heading)
154 (unless (and (bolp) (org-on-heading-p))
155 (org-up-heading-safe)
157 (error "Boundary reached"))
163 (defun ded/org-show-previous-heading-tidily ()
164 "Show previous entry, keeping other entries closed."
166 (outline-previous-heading)
167 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
170 (error "Boundary reached"))
176 (setq org-use-speed-commands t)
177 (add-to-list 'org-speed-commands-user
178 '("n" ded/org-show-next-heading-tidily))
179 (add-to-list 'org-speed-commands-user
180 '("p" ded/org-show-previous-heading-tidily))
183 *** Changelog support for org headers
186 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
187 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
188 headline as the "current function" if you add a changelog entry from an org
191 #+BEGIN_SRC emacs-lisp
192 (defun org-log-current-defun ()
194 (org-back-to-heading)
195 (if (looking-at org-complex-heading-regexp)
198 (add-hook 'org-mode-hook
200 (make-variable-buffer-local 'add-log-current-defun-function)
201 (setq add-log-current-defun-function 'org-log-current-defun)))
204 *** Different org-cycle-level behavior
207 In recent org versions, when your point (cursor) is at the end of an
208 empty header line (like after you first created the header), the TAB
209 key (=org-cycle=) has a special behavior: it cycles the headline through
210 all possible levels. However, I did not like the way it determined
211 "all possible levels," so I rewrote the whole function, along with a
212 couple of supporting functions.
214 The original function's definition of "all possible levels" was "every
215 level from 1 to one more than the initial level of the current
216 headline before you started cycling." My new definition is "every
217 level from 1 to one more than the previous headline's level." So, if
218 you have a headline at level 4 and you use ALT+RET to make a new
219 headline below it, it will cycle between levels 1 and 5, inclusive.
221 The main advantage of my custom =org-cycle-level= function is that it
222 is stateless: the next level in the cycle is determined entirely by
223 the contents of the buffer, and not what command you executed last.
224 This makes it more predictable, I hope.
226 #+BEGIN_SRC emacs-lisp
229 (defun org-point-at-end-of-empty-headline ()
230 "If point is at the end of an empty headline, return t, else nil."
231 (and (looking-at "[ \t]*$")
233 (beginning-of-line 1)
234 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
236 (defun org-level-increment ()
237 "Return the number of stars that will be added or removed at a
238 time to headlines when structure editing, based on the value of
239 `org-odd-levels-only'."
240 (if org-odd-levels-only 2 1))
242 (defvar org-previous-line-level-cached nil)
244 (defun org-recalculate-previous-line-level ()
245 "Same as `org-get-previous-line-level', but does not use cached
246 value. It does *set* the cached value, though."
247 (set 'org-previous-line-level-cached
248 (let ((current-level (org-current-level))
249 (prev-level (when (> (line-number-at-pos) 1)
252 (org-current-level)))))
253 (cond ((null current-level) nil) ; Before first headline
254 ((null prev-level) 0) ; At first headline
257 (defun org-get-previous-line-level ()
258 "Return the outline depth of the last headline before the
259 current line. Returns 0 for the first headline in the buffer, and
260 nil if before the first headline."
261 ;; This calculation is quite expensive, with all the regex searching
262 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
263 ;; the last value of this command.
264 (or (and (eq last-command 'org-cycle-level)
265 org-previous-line-level-cached)
266 (org-recalculate-previous-line-level)))
268 (defun org-cycle-level ()
270 (let ((org-adapt-indentation nil))
271 (when (org-point-at-end-of-empty-headline)
272 (setq this-command 'org-cycle-level) ;Only needed for caching
273 (let ((cur-level (org-current-level))
274 (prev-level (org-get-previous-line-level)))
276 ;; If first headline in file, promote to top-level.
278 (loop repeat (/ (- cur-level 1) (org-level-increment))
279 do (org-do-promote)))
280 ;; If same level as prev, demote one.
281 ((= prev-level cur-level)
283 ;; If parent is top-level, promote to top level if not already.
285 (loop repeat (/ (- cur-level 1) (org-level-increment))
286 do (org-do-promote)))
287 ;; If top-level, return to prev-level.
289 (loop repeat (/ (- prev-level 1) (org-level-increment))
291 ;; If less than prev-level, promote one.
292 ((< cur-level prev-level)
294 ;; If deeper than prev-level, promote until higher than
296 ((> cur-level prev-level)
297 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
298 do (org-do-promote))))
303 **** Transpose tables (Juan Pechiar)
305 This function by Juan Pechiar will transpose a table:
307 #+begin_src emacs-lisp
308 (defun org-transpose-table-at-point ()
309 "Transpose orgmode table at point, eliminate hlines"
312 (apply #'mapcar* #'list
313 ;; remove 'hline from list
314 (remove-if-not 'listp
315 ;; signals error if not table
316 (org-table-to-lisp)))))
317 (delete-region (org-table-begin) (org-table-end))
318 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
330 will be transposed as
337 (Note that horizontal lines disappeared.)
339 *** Dates computation
341 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
343 I have a table in org which stores the date, I'm wondering if there is
344 any function to calculate the duration? For example:
346 | Start Date | End Date | Duration |
347 |------------+------------+----------|
348 | 2004.08.07 | 2005.07.08 | |
350 I tried to use B&-C&, but failed ...
352 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
356 | Start Date | End Date | Duration |
357 |------------+------------+----------|
358 | 2004.08.07 | 2005.07.08 | 335 |
359 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
363 http://thread.gmane.org/gmane.emacs.orgmode/7741
365 as well as this post (which is really a followup on the
368 http://article.gmane.org/gmane.emacs.orgmode/7753
370 The problem that this last article pointed out was solved
373 http://article.gmane.org/gmane.emacs.orgmode/8001
375 and Chris Randle's original musings are at
377 http://article.gmane.org/gmane.emacs.orgmode/6536/
379 *** Field coordinates in formulas (=@#= and =$#=)
383 Following are some use cases that can be implemented with the
384 _field coordinates in formulas_ described in the corresponding
385 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
387 **** Copy a column from a remote table into a column
389 current column =$3= = remote column =$2=:
390 : #+TBLFM: $3 = remote(FOO, @@#$2)
392 **** Copy a row from a remote table transposed into a column
394 current column =$1= = transposed remote row =@1=:
395 : #+TBLFM: $1 = remote(FOO, @$#$@#)
397 **** Transpose a table
401 This is more like a demonstration of using _field coordinates in formulas_
402 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel. The efficient
403 and simple solution for this with the help of org-babel and Emacs Lisp has
404 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
406 To transpose this 4x7 table
409 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
410 : |------+------+------+------+------+------+------|
411 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
412 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
413 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
415 start with a 7x4 table without any horizontal line (to have filled
416 also the column header) and yet empty:
426 Then add the =TBLFM= below with the same formula repeated for each column.
427 After recalculation this will end up with the transposed copy:
429 : | year | min | avg | max |
430 : | 2004 | 401 | 402 | 403 |
431 : | 2005 | 501 | 502 | 503 |
432 : | 2006 | 601 | 602 | 603 |
433 : | 2007 | 701 | 702 | 703 |
434 : | 2008 | 801 | 802 | 803 |
435 : | 2009 | 901 | 902 | 903 |
436 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
438 The formulas simply exchange row and column numbers by taking
439 - the absolute remote row number =@$#= from the current column number =$#=
440 - the absolute remote column number =$@#= from the current row number =@#=
442 Possible field formulas from the remote table will have to be transferred
443 manually. Since there are no row formulas yet there is no need to transfer
444 column formulas to row formulas or vice versa.
446 **** Dynamic variation of ranges
450 In this example all columns next to =quote= are calculated from the column
451 =quote= and show the average change of the time series =quote[year]=
452 during the period of the preceding =1=, =2=, =3= or =4= years:
454 : | year | quote | 1 a | 2 a | 3 a | 4 a |
455 : |------+-------+-------+-------+-------+-------|
456 : | 2005 | 10 | | | | |
457 : | 2006 | 12 | 0.200 | | | |
458 : | 2007 | 14 | 0.167 | 0.183 | | |
459 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
460 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
461 : #+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
463 The formula is the same for each column =$3= through =$6=. This can easily
464 be seen with the great formula editor invoked by C-c ' on the
465 table. The important part of the formula without the field blanking is:
467 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
469 which is the Emacs Calc implementation of the equation
471 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
473 where /i/ is the current time and /a/ is the length of the preceding period.
475 *** Customize the size of the frame for remember
476 (Note: this hack is likely out of date due to the development of
480 On emacs-orgmode, Ryan C. Thompson suggested this:
483 I am using org-remember set to open a new frame when used,
484 and the default frame size is much too large. To fix this, I have
485 designed some advice and a custom variable to implement custom
486 parameters for the remember frame:
489 #+begin_src emacs-lisp
490 (defcustom remember-frame-alist nil
491 "Additional frame parameters for dedicated remember frame."
495 (defadvice remember (around remember-frame-parameters activate)
496 "Set some frame parameters for the remember frame."
497 (let ((default-frame-alist (append remember-frame-alist
498 default-frame-alist)))
502 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
503 reasonable size for the frame.
504 *** Promote all items in subtree
507 This function will promote all items in a subtree. Since I use
508 subtrees primarily to organize projects, the function is somewhat
509 unimaginatively called my-org-un-project:
511 #+begin_src emacs-lisp
512 (defun my-org-un-project ()
514 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
518 *** Turn a heading into an Org link
522 #+begin_src emacs-lisp
523 (defun dmj:turn-headline-into-org-mode-link ()
524 "Replace word at point by an Org mode link."
526 (when (org-at-heading-p)
527 (let ((hl-text (nth 4 (org-heading-components))))
528 (unless (or (null hl-text)
529 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
531 (search-forward hl-text (point-at-eol))
534 (format "[[file:%s.org][%s]]"
535 (org-link-escape hl-text)
536 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
537 nil (- (point) (length hl-text)) (point))))))
540 *** Count words in an Org buffer
542 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
544 #+begin_src emacs-lisp
545 (defun org-word-count (beg end
546 &optional count-latex-macro-args?
548 "Report the number of words in the Org mode buffer or selected region.
552 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
553 - hyperlinks (but does count words in hyperlink descriptions)
554 - tags, priorities, and TODO keywords in headers
555 - sections tagged as 'not for export'.
557 The text of footnote definitions is ignored, unless the optional argument
558 COUNT-FOOTNOTES? is non-nil.
560 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
561 includes LaTeX macro arguments (the material between {curly braces}).
562 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
566 (setf beg (point-min)
569 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
572 (while (< (point) end)
575 ((or (org-in-commented-line) (org-at-table-p))
577 ;; Ignore hyperlinks. But if link has a description, count
578 ;; the words within the description.
579 ((looking-at org-bracket-link-analytic-regexp)
580 (when (match-string-no-properties 5)
581 (let ((desc (match-string-no-properties 5)))
583 (incf wc (length (remove "" (org-split-string
585 (goto-char (match-end 0)))
586 ((looking-at org-any-link-re)
587 (goto-char (match-end 0)))
588 ;; Ignore source code blocks.
589 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
591 ;; Ignore inline source blocks, counting them as 1 word.
594 (looking-at org-babel-inline-src-block-regexp))
595 (goto-char (match-end 0))
597 ;; Count latex macros as 1 word, ignoring their arguments.
600 (looking-at latex-macro-regexp))
601 (goto-char (if count-latex-macro-args?
606 ((and (not count-footnotes?)
607 (or (org-footnote-at-definition-p)
608 (org-footnote-at-reference-p)))
611 (let ((contexts (org-context)))
613 ;; Ignore tags and TODO keywords, etc.
614 ((or (assoc :todo-keyword contexts)
615 (assoc :priority contexts)
616 (assoc :keyword contexts)
617 (assoc :checkbox contexts))
619 ;; Ignore sections marked with tags that are
620 ;; excluded from export.
621 ((assoc :tags contexts)
622 (if (intersection (org-get-tags-at) org-export-exclude-tags
624 (org-forward-same-level 1)
628 (re-search-forward "\\w+\\W*")))
629 (message (format "%d words in %s." wc
630 (if mark-active "region" "buffer")))))
633 ** Archiving Content in Org-Mode
634 *** Preserve top level headings when archiving to a file
637 To preserve (somewhat) the integrity of your archive structure while
638 archiving lower level items to a file, you can use the following
641 #+begin_src emacs-lisp
642 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
643 (let ((org-archive-location
644 (if (save-excursion (org-back-to-heading)
645 (> (org-outline-level) 1))
646 (concat (car (split-string org-archive-location "::"))
648 (car (org-get-outline-path)))
649 org-archive-location)))
653 Thus, if you have an outline structure such as...
661 ...archiving "Subsubheading" to a new file will set the location in
662 the new file to the top level heading:
669 While this hack obviously destroys the outline hierarchy somewhat, it
670 at least preserves the logic of level one groupings.
672 *** Archive in a date tree
674 Posted to Org-mode mailing list by Osamu Okano
677 #+begin_src emacs-lisp
678 ;; (setq org-archive-location "%s_archive::date-tree")
679 (defadvice org-archive-subtree
680 (around org-archive-subtree-to-data-tree activate)
681 "org-archive-subtree to date-tree"
684 (org-extract-archive-heading
685 (org-get-local-archive-location)))
686 (let* ((dct (decode-time (org-current-time)))
690 (this-buffer (current-buffer))
691 (location (org-get-local-archive-location))
692 (afile (org-extract-archive-file location))
693 (org-archive-location
694 (format "%s::*** %04d-%02d-%02d %s" afile y m d
695 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
696 (message "afile=%s" afile)
698 (error "Invalid `org-archive-location'"))
700 (switch-to-buffer (find-file-noselect afile))
701 (org-datetree-find-year-create y)
702 (org-datetree-find-month-create y m)
703 (org-datetree-find-day-create y m d)
705 (switch-to-buffer this-buffer))
710 *** Add inherited tags to archived entries
712 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
713 advise the function like this:
716 (defadvice org-archive-subtree
717 (before add-inherited-tags-before-org-archive-subtree activate)
718 "add inherited tags before org-archive-subtree"
719 (org-set-tags-to (org-get-tags-at)))
722 ** Using and Managing Org-Metadata
723 *** Remove redundant tags of headlines
726 A small function that processes all headlines in current buffer and
727 removes tags that are local to a headline and inherited by a parent
728 headline or the #+FILETAGS: statement.
730 #+BEGIN_SRC emacs-lisp
731 (defun dmj/org-remove-redundant-tags ()
732 "Remove redundant tags of headlines in current buffer.
734 A tag is considered redundant if it is local to a headline and
735 inherited by a parent headline."
737 (when (eq major-mode 'org-mode)
741 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
743 (dolist (tag alltags)
744 (if (get-text-property 0 'inherited tag)
745 (push tag inherited) (push tag local)))
747 (if (member tag inherited) (org-toggle-tag tag 'off)))))
751 *** Remove empty property drawers
753 David Maus proposed this:
755 #+begin_src emacs-lisp
756 (defun dmj:org:remove-empty-propert-drawers ()
757 "*Remove all empty property drawers in current file."
759 (unless (eq major-mode 'org-mode)
760 (error "You need to turn on Org mode for this function."))
762 (goto-char (point-min))
763 (while (re-search-forward ":PROPERTIES:" nil t)
765 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
768 *** Group task list by a property
770 This advice allows you to group a task list in Org-Mode. To use it,
771 set the variable =org-agenda-group-by-property= to the name of a
772 property in the option list for a TODO or TAGS search. The resulting
773 agenda view will group tasks by that property prior to searching.
775 #+begin_src emacs-lisp
776 (defvar org-agenda-group-by-property nil
777 "Set this in org-mode agenda views to group tasks by property")
779 (defun org-group-bucket-items (prop items)
782 (let* ((marker (get-text-property 0 'org-marker item))
783 (pvalue (org-entry-get marker prop t))
784 (cell (assoc pvalue buckets)))
786 (setcdr cell (cons item (cdr cell)))
787 (setq buckets (cons (cons pvalue (list item))
789 (setq buckets (mapcar (lambda (bucket)
791 (reverse (cdr bucket))))
793 (sort buckets (lambda (i1 i2)
794 (string< (car i1) (car i2))))))
796 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
797 (list &optional nosort))
798 "Prepare bucketed agenda entry lists"
799 (if org-agenda-group-by-property
800 ;; bucketed, handle appropriately
802 (dolist (bucket (org-group-bucket-items
803 org-agenda-group-by-property
805 (let ((header (concat "Property "
806 org-agenda-group-by-property
808 (or (car bucket) "<nil>") ":\n")))
809 (add-text-properties 0 (1- (length header))
810 (list 'face 'org-agenda-structure)
814 ;; recursively process
815 (let ((org-agenda-group-by-property nil))
816 (org-finalize-agenda-entries
817 (cdr bucket) nosort))
819 (setq ad-return-value text))
821 (ad-activate 'org-finalize-agenda-entries)
823 *** Dynamically adjust tag position
824 Here is a bit of code that allows you to have the tags always
825 right-adjusted in the buffer.
827 This is useful when you have bigger window than default window-size
828 and you dislike the aesthetics of having the tag in the middle of the
831 This hack solves the problem of adjusting it whenever you change the
833 Before saving it will revert the file to having the tag position be
834 left-adjusted so that if you track your files with version control,
835 you won't run into artificial diffs just because the window-size
838 *IMPORTANT*: This is probably slow on very big files.
840 #+begin_src emacs-lisp
841 (setq ba/org-adjust-tags-column t)
843 (defun ba/org-adjust-tags-column-reset-tags ()
844 "In org-mode buffers it will reset tag position according to
847 (not (string= (buffer-name) "*Remember*"))
848 (eql major-mode 'org-mode))
849 (let ((b-m-p (buffer-modified-p)))
852 (goto-char (point-min))
853 (command-execute 'outline-next-visible-heading)
854 ;; disable (message) that org-set-tags generates
855 (flet ((message (&rest ignored) nil))
857 (set-buffer-modified-p b-m-p))
860 (defun ba/org-adjust-tags-column-now ()
861 "Right-adjust `org-tags-column' value, then reset tag position."
862 (set (make-local-variable 'org-tags-column)
863 (- (- (window-width) (length org-ellipsis))))
864 (ba/org-adjust-tags-column-reset-tags))
866 (defun ba/org-adjust-tags-column-maybe ()
867 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
868 (when ba/org-adjust-tags-column
869 (ba/org-adjust-tags-column-now)))
871 (defun ba/org-adjust-tags-column-before-save ()
872 "Tags need to be left-adjusted when saving."
873 (when ba/org-adjust-tags-column
874 (setq org-tags-column 1)
875 (ba/org-adjust-tags-column-reset-tags)))
877 (defun ba/org-adjust-tags-column-after-save ()
878 "Revert left-adjusted tag position done by before-save hook."
879 (ba/org-adjust-tags-column-maybe)
880 (set-buffer-modified-p nil))
882 ; automatically align tags on right-hand side
883 (add-hook 'window-configuration-change-hook
884 'ba/org-adjust-tags-column-maybe)
885 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
886 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
887 (add-hook 'org-agenda-mode-hook '(lambda ()
888 (setq org-agenda-tags-column (- (window-width)))))
890 ; between invoking org-refile and displaying the prompt (which
891 ; triggers window-configuration-change-hook) tags might adjust,
892 ; which invalidates the org-refile cache
893 (defadvice org-refile (around org-refile-disable-adjust-tags)
894 "Disable dynamically adjusting tags"
895 (let ((ba/org-adjust-tags-column nil))
897 (ad-activate 'org-refile)
899 ** Org Agenda and Task Management
900 *** Make it easier to set org-agenda-files from multiple directories
903 #+begin_src emacs-lisp
904 (defun my-org-list-files (dirs ext)
905 "Function to create list of org files in multiple subdirectories.
906 This can be called to generate a list of files for
907 org-agenda-files or org-refile-targets.
909 DIRS is a list of directories.
911 EXT is a list of the extensions of files to be included."
912 (let ((dirs (if (listp dirs)
925 (file-expand-wildcards
926 (concat (file-name-as-directory x) "*" y)))))
931 (when (or (string-match "/.#" x)
932 (string-match "#$" x))
933 (setq files (delete x files))))
937 (defvar my-org-agenda-directories '("~/org/")
938 "List of directories containing org files.")
939 (defvar my-org-agenda-extensions '(".org")
940 "List of extensions of agenda files")
942 (setq my-org-agenda-directories '("~/org/" "~/work/"))
943 (setq my-org-agenda-extensions '(".org" ".ref"))
945 (defun my-org-set-agenda-files ()
947 (setq org-agenda-files (my-org-list-files
948 my-org-agenda-directories
949 my-org-agenda-extensions)))
951 (my-org-set-agenda-files)
954 The code above will set your "default" agenda files to all files
955 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
956 You can change these values by setting the variables
957 my-org-agenda-extensions and my-org-agenda-directories. The function
958 my-org-agenda-files-by-filetag uses these two variables to determine
959 which files to search for filetags (i.e., the larger set from which
960 the subset will be drawn).
962 You can also easily use my-org-list-files to "mix and match"
963 directories and extensions to generate different lists of agenda
966 *** Restrict org-agenda-files by filetag
968 :CUSTOM_ID: set-agenda-files-by-filetag
972 It is often helpful to limit yourself to a subset of your agenda
973 files. For instance, at work, you might want to see only files related
974 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
975 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
976 commands]]. These solutions, however, require reapplying a filter each
977 time you call the agenda or writing several new custom agenda commands
978 for each context. Another solution is to use directories for different
979 types of tasks and to change your agenda files with a function that
980 sets org-agenda-files to the appropriate directory. But this relies on
981 hard and static boundaries between files.
983 The following functions allow for a more dynamic approach to selecting
984 a subset of files based on filetags:
986 #+begin_src emacs-lisp
987 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
988 "Restrict org agenda files only to those containing filetag."
990 (let* ((tagslist (my-org-get-all-filetags))
992 (completing-read "Tag: "
993 (mapcar 'car tagslist)))))
994 (org-agenda-remove-restriction-lock 'noupdate)
995 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
996 (setq org-agenda-overriding-restriction 'files)))
998 (defun my-org-get-all-filetags ()
999 "Get list of filetags from all default org-files."
1000 (let ((files org-agenda-files)
1002 (save-window-excursion
1003 (while (setq x (pop files))
1004 (set-buffer (find-file-noselect x))
1007 (let ((tagfiles (assoc y tagslist)))
1009 (setcdr tagfiles (cons x (cdr tagfiles)))
1010 (add-to-list 'tagslist (list y x)))))
1011 (my-org-get-filetags)))
1014 (defun my-org-get-filetags ()
1015 "Get list of filetags for current buffer"
1016 (let ((ftags org-file-tags)
1020 (org-substring-no-properties x))
1024 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1025 with all filetags in your "normal" agenda files. When you select a
1026 tag, org-agenda-files will be restricted to only those files
1027 containing the filetag. To release the restriction, type C-c C-x >
1028 (org-agenda-remove-restriction-lock).
1030 *** Highlight the agenda line under cursor
1032 This is useful to make sure what task you are operating on.
1034 #+BEGIN_SRC emacs-lisp
1035 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1036 #+END_SRC emacs-lisp
1040 #+BEGIN_SRC emacs-lisp
1041 ;; hl-line seems to be only for emacs
1043 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1045 ;; highline-mode does not work straightaway in tty mode.
1046 ;; I use a black background
1048 '(highline-face ((((type tty) (class color))
1049 (:background "white" :foreground "black")))))
1050 #+END_SRC emacs-lisp
1052 *** Split horizontally for agenda
1054 If you would like to split the frame into two side-by-side windows when
1055 displaying the agenda, try this hack from Jan Rehders, which uses the
1056 `toggle-window-split' from
1058 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1060 #+BEGIN_SRC emacs-lisp
1061 ;; Patch org-mode to use vertical splitting
1062 (defadvice org-prepare-agenda (after org-fix-split)
1063 (toggle-window-split))
1064 (ad-activate 'org-prepare-agenda)
1067 *** Automatically add an appointment when clocking in a task
1069 #+BEGIN_SRC emacs-lisp
1070 ;; Make sure you have a sensible value for `appt-message-warning-time'
1071 (defvar bzg-org-clock-in-appt-delay 100
1072 "Number of minutes for setting an appointment by clocking-in")
1075 This function let's you add an appointment for the current entry.
1076 This can be useful when you need a reminder.
1078 #+BEGIN_SRC emacs-lisp
1079 (defun bzg-org-clock-in-add-appt (&optional n)
1080 "Add an appointment for the Org entry at point in N minutes."
1083 (org-back-to-heading t)
1084 (looking-at org-complex-heading-regexp)
1085 (let* ((msg (match-string-no-properties 4))
1086 (ct-time (decode-time))
1087 (appt-min (+ (cadr ct-time)
1088 (or n bzg-org-clock-in-appt-delay)))
1089 (appt-time ; define the time for the appointment
1090 (progn (setf (cadr ct-time) appt-min) ct-time)))
1091 (appt-add (format-time-string
1092 "%H:%M" (apply 'encode-time appt-time)) msg)
1093 (if (interactive-p) (message "New appointment for %s" msg)))))
1096 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1099 #+BEGIN_SRC emacs-lisp
1100 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1101 "Add an appointment when clocking a task in."
1102 (bzg-org-clock-in-add-appt))
1105 You may also want to delete the associated appointment when clocking
1106 out. This function does this:
1108 #+BEGIN_SRC emacs-lisp
1109 (defun bzg-org-clock-out-delete-appt nil
1110 "When clocking out, delete any associated appointment."
1113 (org-back-to-heading t)
1114 (looking-at org-complex-heading-regexp)
1115 (let* ((msg (match-string-no-properties 4)))
1116 (setq appt-time-msg-list
1120 (if (not (string-match (regexp-quote msg)
1121 (cadr appt))) appt))
1122 appt-time-msg-list)))
1126 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1128 #+BEGIN_SRC emacs-lisp
1129 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1130 "Delete an appointment when clocking a task out."
1131 (bzg-org-clock-out-delete-appt))
1134 *IMPORTANT*: You can add appointment by clocking in in both an
1135 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1136 agenda buffer with the advice above will bring an error.
1138 *** Remove time grid lines that are in an appointment
1140 The agenda shows lines for the time grid. Some people think that
1141 these lines are a distraction when there are appointments at those
1142 times. You can get rid of the lines which coincide exactly with the
1143 beginning of an appointment. Michael Ekstrand has written a piece of
1144 advice that also removes lines that are somewhere inside an
1147 #+begin_src emacs-lisp
1148 (defun org-time-to-minutes (time)
1149 "Convert an HHMM time to minutes"
1150 (+ (* (/ time 100) 60) (% time 100)))
1152 (defun org-time-from-minutes (minutes)
1153 "Convert a number of minutes to an HHMM time"
1154 (+ (* (/ minutes 60) 100) (% minutes 60)))
1156 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1157 (list ndays todayp))
1158 (if (member 'remove-match (car org-agenda-time-grid))
1159 (flet ((extract-window
1161 (let ((start (get-text-property 1 'time-of-day line))
1162 (dur (get-text-property 1 'duration line)))
1166 (org-time-from-minutes
1167 (+ dur (org-time-to-minutes start)))))
1170 (let* ((windows (delq nil (mapcar 'extract-window list)))
1171 (org-agenda-time-grid
1172 (list (car org-agenda-time-grid)
1173 (cadr org-agenda-time-grid)
1176 (find-if (lambda (w)
1179 (and (>= time (car w))
1182 (caddr org-agenda-time-grid)))))
1185 (ad-activate 'org-agenda-add-time-grid-maybe)
1187 *** Disable vc for Org mode agenda files
1190 Even if you use Git to track your agenda files you might not need
1191 vc-mode to be enabled for these files.
1193 #+begin_src emacs-lisp
1194 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1195 (defun dmj/disable-vc-for-agenda-files-hook ()
1196 "Disable vc-mode for Org agenda files."
1197 (if (and (fboundp 'org-agenda-file-p)
1198 (org-agenda-file-p (buffer-file-name)))
1199 (remove-hook 'find-file-hook 'vc-find-file-hook)
1200 (add-hook 'find-file-hook 'vc-find-file-hook)))
1203 *** Easy customization of TODO colors
1206 Here is some code I came up with some code to make it easier to
1207 customize the colors of various TODO keywords. As long as you just
1208 want a different color and nothing else, you can customize the
1209 variable org-todo-keyword-faces and use just a string color (i.e. a
1210 string of the color name) as the face, and then org-get-todo-face
1211 will convert the color to a face, inheriting everything else from
1212 the standard org-todo face.
1214 To demonstrate, I currently have org-todo-keyword-faces set to
1216 #+BEGIN_SRC emacs-lisp
1217 (("IN PROGRESS" . "dark orange")
1218 ("WAITING" . "red4")
1219 ("CANCELED" . "saddle brown"))
1220 #+END_SRC emacs-lisp
1222 Here's the code, in a form you can put in your =.emacs=
1224 #+BEGIN_SRC emacs-lisp
1225 (eval-after-load 'org-faces
1227 (defcustom org-todo-keyword-faces nil
1228 "Faces for specific TODO keywords.
1229 This is a list of cons cells, with TODO keywords in the car and
1230 faces in the cdr. The face can be a symbol, a color, or a
1231 property list of attributes, like (:foreground \"blue\" :weight
1232 bold :underline t)."
1237 (string :tag "Keyword")
1238 (choice color (sexp :tag "Face")))))))
1240 (eval-after-load 'org
1242 (defun org-get-todo-face-from-color (color)
1243 "Returns a specification for a face that inherits from org-todo
1244 face and has the given color as foreground. Returns nil if
1247 `(:inherit org-warning :foreground ,color)))
1249 (defun org-get-todo-face (kwd)
1250 "Get the right face for a TODO keyword KWD.
1251 If KWD is a number, get the corresponding match group."
1252 (if (numberp kwd) (setq kwd (match-string kwd)))
1253 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1255 (org-get-todo-face-from-color face)
1257 (and (member kwd org-done-keywords) 'org-done)
1259 #+END_SRC emacs-lisp
1261 *** Add an effort estimate on the fly when clocking in
1263 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1264 This way you can easily have a "tea-timer" for your tasks when they
1265 don't already have an effort estimate.
1267 #+begin_src emacs-lisp
1268 (add-hook 'org-clock-in-prepare-hook
1269 'my-org-mode-ask-effort)
1271 (defun my-org-mode-ask-effort ()
1272 "Ask for an effort estimate when clocking in."
1273 (unless (org-entry-get (point) "Effort")
1277 (org-entry-get-multivalued-property (point) "Effort"))))
1278 (unless (equal effort "")
1279 (org-set-property "Effort" effort)))))
1282 Or you can use a default effort for such a timer:
1284 #+begin_src emacs-lisp
1285 (add-hook 'org-clock-in-prepare-hook
1286 'my-org-mode-add-default-effort)
1288 (defvar org-clock-default-effort "1:00")
1290 (defun my-org-mode-add-default-effort ()
1291 "Add a default effort estimation."
1292 (unless (org-entry-get (point) "Effort")
1293 (org-set-property "Effort" org-clock-default-effort)))
1296 *** Refresh the agenda view regurally
1298 Hack sent by Kiwon Um:
1300 #+begin_src emacs-lisp
1301 (defun kiwon/org-agenda-redo-in-other-window ()
1302 "Call org-agenda-redo function even in the non-agenda buffer."
1304 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1306 (with-selected-window agenda-window (org-agenda-redo)))))
1307 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1310 *** Reschedule agenda items to today with a single command
1312 This was suggested by Carsten in reply to David Abrahams:
1314 #+begin_example emacs-lisp
1315 (defun org-agenda-reschedule-to-today ()
1317 (flet ((org-read-date (&rest rest) (current-time)))
1318 (call-interactively 'org-agenda-schedule)))
1321 * Hacking Org: Working with Org-mode and other Emacs Packages.
1322 ** org-remember-anything
1324 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1326 #+BEGIN_SRC emacs-lisp
1327 (defvar org-remember-anything
1328 '((name . "Org Remember")
1329 (candidates . (lambda () (mapcar 'car org-remember-templates)))
1330 (action . (lambda (name)
1331 (let* ((orig-template org-remember-templates)
1332 (org-remember-templates
1333 (list (assoc name orig-template))))
1334 (call-interactively 'org-remember))))))
1337 You can add it to your 'anything-sources' variable and open remember directly
1338 from anything. I imagine this would be more interesting for people with many
1339 remember templatesm, so that you are out of keys to assign those to. You should
1340 get something like this:
1342 [[file:images/thumbs/org-remember-anything.png]]
1344 ** Org-mode and saveplace.el
1346 Fix a problem with saveplace.el putting you back in a folded position:
1348 #+begin_src emacs-lisp
1349 (add-hook 'org-mode-hook
1351 (when (outline-invisible-p)
1353 (outline-previous-visible-heading 1)
1354 (org-show-subtree)))))
1357 ** Using ido-completing-read to find attachments
1360 Org-attach is great for quickly linking files to a project. But if you
1361 use org-attach extensively you might find yourself wanting to browse
1362 all the files you've attached to org headlines. This is not easy to do
1363 manually, since the directories containing the files are not human
1364 readable (i.e., they are based on automatically generated ids). Here's
1365 some code to browse those files using ido (obviously, you need to be
1368 #+begin_src emacs-lisp
1369 (load-library "find-lisp")
1371 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1373 (defun my-ido-find-org-attach ()
1374 "Find files in org-attachment directory"
1376 (let* ((enable-recursive-minibuffers t)
1377 (files (find-lisp-find-files org-attach-directory "."))
1380 (cons (file-name-nondirectory x)
1384 (remove-duplicates (mapcar #'car file-assoc-list)
1386 (filename (ido-completing-read "Org attachments: " filename-list nil t))
1387 (longname (cdr (assoc filename file-assoc-list))))
1388 (ido-set-current-directory
1389 (if (file-directory-p longname)
1391 (file-name-directory longname)))
1392 (setq ido-exit 'refresh
1393 ido-text-init ido-text
1397 (add-hook 'ido-setup-hook 'ido-my-keys)
1399 (defun ido-my-keys ()
1400 "Add my keybindings for ido."
1401 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1404 To browse your org attachments using ido fuzzy matching and/or the
1405 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1408 ** Use idle timer for automatic agenda views
1410 From John Wiegley's mailing list post (March 18, 2010):
1413 I have the following snippet in my .emacs file, which I find very
1414 useful. Basically what it does is that if I don't touch my Emacs for 5
1415 minutes, it displays the current agenda. This keeps my tasks "always
1416 in mind" whenever I come back to Emacs after doing something else,
1417 whereas before I had a tendency to forget that it was there.
1420 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1422 #+begin_src emacs-lisp
1423 (defun jump-to-org-agenda ()
1425 (let ((buf (get-buffer "*Org Agenda*"))
1428 (if (setq wind (get-buffer-window buf))
1429 (select-window wind)
1430 (if (called-interactively-p)
1432 (select-window (display-buffer buf t t))
1433 (org-fit-window-to-buffer)
1434 ;; (org-agenda-redo)
1436 (with-selected-window (display-buffer buf)
1437 (org-fit-window-to-buffer)
1438 ;; (org-agenda-redo)
1440 (call-interactively 'org-agenda-list)))
1441 ;;(let ((buf (get-buffer "*Calendar*")))
1442 ;; (unless (get-buffer-window buf)
1443 ;; (org-agenda-goto-calendar)))
1446 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1450 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1452 ** Link to Gnus messages by Message-Id
1454 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1455 discussion about linking to Gnus messages without encoding the folder
1456 name in the link. The following code hooks in to the store-link
1457 function in Gnus to capture links by Message-Id when in nnml folders,
1458 and then provides a link type "mid" which can open this link. The
1459 =mde-org-gnus-open-message-link= function uses the
1460 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1461 scan. It will go through them, in order, asking each to locate the
1462 message and opening it from the first one that reports success.
1464 It has only been tested with a single nnml backend, so there may be
1465 bugs lurking here and there.
1467 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1470 #+begin_src emacs-lisp
1471 ;; Support for saving Gnus messages by Message-ID
1472 (defun mde-org-gnus-save-by-mid ()
1473 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1474 (when (eq major-mode 'gnus-article-mode)
1475 (gnus-article-show-summary))
1476 (let* ((group gnus-newsgroup-name)
1477 (method (gnus-find-method-for-group group)))
1478 (when (eq 'nnml (car method))
1479 (let* ((article (gnus-summary-article-number))
1480 (header (gnus-summary-article-header article))
1481 (from (mail-header-from header))
1484 (let ((mid (mail-header-id header)))
1485 (if (string-match "<\\(.*\\)>" mid)
1486 (match-string 1 mid)
1487 (error "Malformed message ID header %s" mid)))))
1488 (date (mail-header-date header))
1489 (subject (gnus-summary-subject-string)))
1490 (org-store-link-props :type "mid" :from from :subject subject
1491 :message-id message-id :group group
1492 :link (org-make-link "mid:" message-id))
1493 (apply 'org-store-link-props
1494 :description (org-email-link-description)
1495 org-store-link-plist)
1498 (defvar mde-mid-resolve-methods '()
1499 "List of methods to try when resolving message ID's. For Gnus,
1500 it is a cons of 'gnus and the select (type and name).")
1501 (setq mde-mid-resolve-methods
1504 (defvar mde-org-gnus-open-level 1
1505 "Level at which Gnus is started when opening a link")
1506 (defun mde-org-gnus-open-message-link (msgid)
1507 "Open a message link with Gnus"
1509 (require 'org-table)
1510 (catch 'method-found
1511 (message "[MID linker] Resolving %s" msgid)
1512 (dolist (method mde-mid-resolve-methods)
1514 ((and (eq (car method) 'gnus)
1515 (eq (cadr method) 'nnml))
1516 (funcall (cdr (assq 'gnus org-link-frame-setup))
1517 mde-org-gnus-open-level)
1518 (when gnus-other-frame-object
1519 (select-frame gnus-other-frame-object))
1520 (let* ((msg-info (nnml-find-group-number
1521 (concat "<" msgid ">")
1523 (group (and msg-info (car msg-info)))
1524 (message (and msg-info (cdr msg-info)))
1526 (if (gnus-methods-equal-p
1530 (gnus-group-full-name group (cdr method))))))
1532 (gnus-summary-read-group qname nil t)
1533 (gnus-summary-goto-article message nil t))
1534 (throw 'method-found t)))
1535 (t (error "Unknown link type"))))))
1537 (eval-after-load 'org-gnus
1539 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1540 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1543 ** Store link upon sending a message in Gnus
1545 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1547 #+begin_src emacs-lisp
1548 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1549 "Send message with `message-send-and-exit' and store org link to message copy.
1550 If multiple groups appear in the Gcc header, the link refers to
1551 the copy in the last group."
1555 (message-narrow-to-headers)
1556 (let ((gcc (car (last
1557 (message-unquote-tokens
1558 (message-tokenize-header
1559 (mail-fetch-field "gcc" nil t) " ,")))))
1560 (buf (current-buffer))
1561 (message-kill-buffer-on-exit nil)
1562 id to from subject desc link newsgroup xarchive)
1563 (message-send-and-exit arg)
1565 ;; gcc group found ...
1567 (save-current-buffer
1568 (progn (set-buffer buf)
1569 (setq id (org-remove-angle-brackets
1570 (mail-fetch-field "Message-ID")))
1571 (setq to (mail-fetch-field "To"))
1572 (setq from (mail-fetch-field "From"))
1573 (setq subject (mail-fetch-field "Subject"))))
1574 (org-store-link-props :type "gnus" :from from :subject subject
1575 :message-id id :group gcc :to to)
1576 (setq desc (org-email-link-description))
1577 (setq link (org-gnus-article-link
1578 gcc newsgroup id xarchive))
1579 (setq org-stored-links
1580 (cons (list link desc) org-stored-links)))
1581 ;; no gcc group found ...
1582 (message "Can not create Org link: No Gcc header found."))))))
1584 (define-key message-mode-map [(control c) (control meta c)]
1585 'ulf-message-send-and-org-gnus-store-link)
1588 ** Send html messages and attachments with Wanderlust
1591 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1592 similar functionality for both Wanderlust and Gnus. The hack below is
1593 still somewhat different: It allows you to toggle sending of html
1594 messages within Wanderlust transparently. I.e. html markup of the
1595 message body is created right before sending starts.
1597 *** Send HTML message
1599 Putting the code below in your .emacs adds following four functions:
1601 - dmj/wl-send-html-message
1603 Function that does the job: Convert everything between "--text
1604 follows this line--" and first mime entity (read: attachment) or
1605 end of buffer into html markup using `org-export-region-as-html'
1606 and replaces original body with a multipart MIME entity with the
1607 plain text version of body and the html markup version. Thus a
1608 recipient that prefers html messages can see the html markup,
1609 recipients that prefer or depend on plain text can see the plain
1612 Cannot be called interactively: It is hooked into SEMI's
1613 `mime-edit-translate-hook' if message should be HTML message.
1615 - dmj/wl-send-html-message-draft-init
1617 Cannot be called interactively: It is hooked into WL's
1618 `wl-mail-setup-hook' and provides a buffer local variable to
1621 - dmj/wl-send-html-message-draft-maybe
1623 Cannot be called interactively: It is hooked into WL's
1624 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1625 `mime-edit-translate-hook' depending on whether HTML message is
1628 - dmj/wl-send-html-message-toggle
1630 Toggles sending of HTML message. If toggled on, the letters
1631 "HTML" appear in the mode line.
1633 Call it interactively! Or bind it to a key in `wl-draft-mode'.
1635 If you have to send HTML messages regularly you can set a global
1636 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1637 toggle on sending HTML message by default.
1639 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1640 Google's web front end. As you can see you have the whole markup of
1641 Org at your service: *bold*, /italics/, tables, lists...
1643 So even if you feel uncomfortable with sending HTML messages at least
1644 you send HTML that looks quite good.
1646 #+begin_src emacs-lisp
1647 (defun dmj/wl-send-html-message ()
1648 "Send message as html message.
1649 Convert body of message to html using
1650 `org-export-region-as-html'."
1653 (let (beg end html text)
1654 (goto-char (point-min))
1655 (re-search-forward "^--text follows this line--$")
1656 ;; move to beginning of next line
1657 (beginning-of-line 2)
1659 (if (not (re-search-forward "^--\\[\\[" nil t))
1660 (setq end (point-max))
1665 (setq text (buffer-substring-no-properties beg end))
1671 (when (re-search-backward "^-- \n" nil t)
1672 ;; preserve link breaks in signature
1673 (insert "\n#+BEGIN_VERSE\n")
1674 (goto-char (point-max))
1675 (insert "\n#+END_VERSE\n")
1677 (setq html (org-export-region-as-html
1678 (point-min) (point-max) t 'string))))
1679 (delete-region beg end)
1682 "--" "<<alternative>>-{\n"
1683 "--" "[[text/plain]]\n" text
1684 "--" "[[text/html]]\n" html
1685 "--" "}-<<alternative>>\n")))))
1687 (defun dmj/wl-send-html-message-toggle ()
1688 "Toggle sending of html message."
1690 (setq dmj/wl-send-html-message-toggled-p
1691 (if dmj/wl-send-html-message-toggled-p
1693 (message "Sending html message toggled %s"
1694 (if dmj/wl-send-html-message-toggled-p
1697 (defun dmj/wl-send-html-message-draft-init ()
1698 "Create buffer local settings for maybe sending html message."
1699 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1700 (setq dmj/wl-send-html-message-toggled-p nil))
1701 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1702 (add-to-list 'global-mode-string
1703 '(:eval (if (eq major-mode 'wl-draft-mode)
1704 dmj/wl-send-html-message-toggled-p))))
1706 (defun dmj/wl-send-html-message-maybe ()
1707 "Maybe send this message as html message.
1709 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1710 non-nil, add `dmj/wl-send-html-message' to
1711 `mime-edit-translate-hook'."
1712 (if dmj/wl-send-html-message-toggled-p
1713 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1714 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1716 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1717 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1718 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1721 *** Attach HTML of region or subtree
1723 Instead of sending a complete HTML message you might only send parts
1724 of an Org file as HTML for the poor souls who are plagued with
1725 non-proportional fonts in their mail program that messes up pretty
1728 This short function does the trick: It exports region or subtree to
1729 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1730 and clipboard. If a region is active, it uses the region, the
1731 complete subtree otherwise.
1733 #+begin_src emacs-lisp
1734 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1735 "Export region between BEG and END as html attachment.
1736 If BEG and END are not set, use current subtree. Region or
1737 subtree is exported to html without header and footer, prefixed
1738 with a mime entity string and pushed to clipboard and killring.
1739 When called with prefix, mime entity is not marked as
1741 (interactive "r\nP")
1743 (let* ((beg (if (region-active-p) (region-beginning)
1745 (org-back-to-heading)
1747 (end (if (region-active-p) (region-end)
1749 (org-end-of-subtree)
1751 (html (concat "--[[text/html"
1752 (if arg "" "\nContent-Disposition: attachment")
1754 (org-export-region-as-html beg end t 'string))))
1755 (when (fboundp 'x-set-selection)
1756 (ignore-errors (x-set-selection 'PRIMARY html))
1757 (ignore-errors (x-set-selection 'CLIPBOARD html)))
1758 (message "html export done, pushed to kill ring and clipboard"))))
1761 *** Adopting for Gnus
1763 The whole magic lies in the special strings that mark a HTML
1764 attachment. So you might just have to find out what these special
1765 strings are in message-mode and modify the functions accordingly.
1766 * Hacking Org: Working with Org-mode and External Programs.
1767 ** Use Org-mode with Screen [Andrew Hyatt]
1769 "The general idea is that you start a task in which all the work will
1770 take place in a shell. This usually is not a leaf-task for me, but
1771 usually the parent of a leaf task. From a task in your org-file, M-x
1772 ash-org-screen will prompt for the name of a session. Give it a name,
1773 and it will insert a link. Open the link at any time to go the screen
1774 session containing your work!"
1776 http://article.gmane.org/gmane.emacs.orgmode/5276
1778 #+BEGIN_SRC emacs-lisp
1781 (defun ash-org-goto-screen (name)
1782 "Open the screen with the specified name in the window"
1783 (interactive "MScreen name: ")
1784 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1785 (if (member screen-buffer-name
1786 (mapcar 'buffer-name (buffer-list)))
1787 (switch-to-buffer screen-buffer-name)
1788 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1790 (defun ash-org-screen-buffer-name (name)
1791 "Returns the buffer name corresponding to the screen name given."
1792 (concat "*screen " name "*"))
1794 (defun ash-org-screen-helper (name arg)
1795 ;; Pick the name of the new buffer.
1796 (let ((term-ansi-buffer-name
1797 (generate-new-buffer-name
1798 (ash-org-screen-buffer-name name))))
1799 (setq term-ansi-buffer-name
1800 (term-ansi-make-term
1801 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1802 (set-buffer term-ansi-buffer-name)
1805 (term-set-escape-char ?\C-x)
1806 term-ansi-buffer-name))
1808 (defun ash-org-screen (name)
1809 "Start a screen session with name"
1810 (interactive "MScreen name: ")
1812 (ash-org-screen-helper name "-S"))
1813 (insert-string (concat "[[screen:" name "]]")))
1815 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1816 ;; \"%s\")") to org-link-abbrev-alist.
1819 ** Org Agenda + Appt + Zenity
1821 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It make sure your agenda
1822 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1825 #+BEGIN_SRC emacs-lisp
1826 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1827 ; For org appointment reminders
1829 ;; Get appointments for today
1830 (defun my-org-agenda-to-appt ()
1832 (setq appt-time-msg-list nil)
1833 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
1834 (org-agenda-to-appt)))
1836 ;; Run once, activate and schedule refresh
1837 (my-org-agenda-to-appt)
1839 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
1842 (setq appt-message-warning-time 15)
1843 (setq appt-display-interval 5)
1845 ; Update appt each time agenda opened.
1846 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
1848 ; Setup zenify, we tell appt to use window, and replace default function
1849 (setq appt-display-format 'window)
1850 (setq appt-disp-window-function (function my-appt-disp-window))
1852 (defun my-appt-disp-window (min-to-app new-time msg)
1853 (save-window-excursion (shell-command (concat
1854 "/usr/bin/zenity --info --title='Appointment' --text='"
1855 msg "' &") nil nil)))
1858 ** Org-Mode + gnome-osd
1860 Richard Riley uses gnome-osd in interaction with Org-Mode to display
1861 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
1867 http://article.gmane.org/gmane.emacs.orgmode/5073
1870 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
1871 command line calendaring program. Its features superseed the possibilities
1872 of orgmode in the area of date specifying, so that I want to use it
1873 combined with orgmode.
1875 Using the script below I'm able use remind and incorporate its output in my
1876 agenda views. The default of using 13 months look ahead is easily
1877 changed. It just happens I sometimes like to look a year into the
1881 ** Useful webjumps for conkeror
1883 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
1884 your =~/.conkerorrc= file:
1887 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
1888 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
1891 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
1892 Org-mode mailing list.
1894 ** Use MathJax for HTML export without requiring JavaScript
1895 As of 2010-08-14, MathJax is the default method used to export math to HTML.
1897 If you like the results but do not want JavaScript in the exported pages,
1898 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
1899 HTML file from the exported version. It can also embed all referenced fonts
1900 within the HTML file itself, so there are no dependencies to external files.
1902 The download archive contains an elisp file which integrates it into the Org
1903 export process (configurable per file with a "#+StaticMathJax:" line).
1905 Read README.org and the comments in org-static-mathjax.el for usage instructions.
1906 ** Search Org files using lgrep
1908 Matt Lundi suggests this:
1910 #+begin_src emacs-lisp
1911 (defun my-org-grep (search &optional context)
1912 "Search for word in org files.
1914 Prefix argument determines number of lines."
1915 (interactive "sSearch for: \nP")
1916 (let ((grep-find-ignored-files '("#*" ".#*"))
1917 (grep-template (concat "grep <X> -i -nH "
1919 (concat "-C" (number-to-string context)))
1921 (lgrep search "*org*" "/home/matt/org/")))
1923 (global-set-key (kbd "<f8>") 'my-org-grep)
1926 ** Automatic screenshot insertion
1928 Suggested by Jonathan Bisson:
1930 #+begin_src emacs-lisp
1931 (defun my-screenshot ()
1932 "Take a screenshot into a unique-named file in the current buffer file
1933 directory and insert a link to this file."
1938 (file-name-directory (buffer-file-name))) ".jpg"))
1939 (call-process "import" nil nil nil filename)
1940 (insert (concat "[[" filename "]]"))
1941 (org-display-inline-images))