Advice not sending multiple patches in one single email.
[Worg.git] / org-hacks.org
blobdadca2c50c8615bea2326f10850ab6daa0e19d79
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
6 #+AUTHOR:     Worg people
7 #+EMAIL:      mdl AT imapmail DOT org
8 #+LANGUAGE:   en
9 #+PRIORITIES: A C B
10 #+CATEGORY:   worg
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
18 workaround. Go crazy.
20 * Hacking Org: Working within Org-mode.
21 ** Building and Managing Org
22 *** Compiling Org without make
23 :PROPERTIES:
24 :CUSTOM_ID: compiling-org-without-make
25 :END:
27 This file is the result of  [[http://article.gmane.org/gmane.emacs.orgmode/15264][one of our discussions]] on the mailing list.
28 Enhancements welcome.
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.")
41 ;; Customize:
42 (setq my/org-lisp-directory "~/.emacs.d/org/lisp")
44 ;; Customize:
45 (setq  my/org-compile-sources t)
47 (defun my/compile-org(&optional directory)
48   "Compile all *.el files that come with org-mode."
49   (interactive)
50   (setq directory (concat
51                         (file-truename
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
59     (require 'autoload)
60     (setq esf/org-install-file (concat directory "org-install.el"))
61     (find-file esf/org-install-file)
62     (erase-buffer)
63     (mapc (lambda (x)
64             (generate-file-autoloads x))
65           list-of-org-files)
66     (insert "\n(provide (quote org-install))\n")
67     (save-buffer)
68     (kill-buffer)
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)))))
76 #+END_SRC
77 *** Reload Org
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
85 : M-x org-reload
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
90 : C-u M-x org-reload
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
96 : M-x org-reload
98 *** Check for possibly problematic old link escapes
99 :PROPERTIES:
100 :CUSTOM_ID: check-old-link-escapes
101 :END:
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
105 and how.
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."
119     (interactive)
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))
125         (widen)
126         (show-all)
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"
135                         escape
136                         (buffer-name)
137                         (- (point) 3)))))
138             (goto-char end))))))
139 #+end_src
141 ** Structure Movement and Editing 
142 *** Show next/prev heading tidily
143 - Dan Davison
144   These close the current heading and open the next/previous heading.
146 #+begin_src emacs-lisp
147 (defun ded/org-show-next-heading-tidily ()
148   "Show next entry, keeping other entries closed."
149   (if (save-excursion (end-of-line) (outline-invisible-p))
150       (progn (org-show-entry) (show-children))
151     (outline-next-heading)
152     (unless (and (bolp) (org-on-heading-p))
153       (org-up-heading-safe)
154       (hide-subtree)
155       (error "Boundary reached"))
156     (org-overview)
157     (org-reveal t)
158     (org-show-entry)
159     (show-children)))
161 (defun ded/org-show-previous-heading-tidily ()
162   "Show previous entry, keeping other entries closed."
163   (let ((pos (point)))
164     (outline-previous-heading)
165     (unless (and (< (point) pos) (bolp) (org-on-heading-p))
166       (goto-char pos)
167       (hide-subtree)
168       (error "Boundary reached"))
169     (org-overview)
170     (org-reveal t)
171     (org-show-entry)
172     (show-children)))
174 (setq org-use-speed-commands t)
175 (add-to-list 'org-speed-commands-user
176              '("n" ded/org-show-next-heading-tidily))
177 (add-to-list 'org-speed-commands-user
178              '("p" ded/org-show-previous-heading-tidily))
179 #+end_src
181 *** Promote all items in subtree
182 - Matt Lundin
184 This function will promote all items in a subtree. Since I use
185 subtrees primarily to organize projects, the function is somewhat
186 unimaginatively called my-org-un-project:
188 #+begin_src emacs-lisp
189 (defun my-org-un-project ()
190   (interactive)
191   (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
192   (org-cycle t))
193 #+end_src
195 *** Turn a heading into an Org link
196     :PROPERTIES:
197     :CUSTOM_ID: heading-to-link
198     :END:
200 From David Maus:
202 #+begin_src emacs-lisp
203   (defun dmj:turn-headline-into-org-mode-link ()
204     "Replace word at point by an Org mode link."
205     (interactive)
206     (when (org-at-heading-p)
207       (let ((hl-text (nth 4 (org-heading-components))))
208         (unless (or (null hl-text)
209                     (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
210           (beginning-of-line)
211           (search-forward hl-text (point-at-eol))
212           (replace-string
213            hl-text
214            (format "[[file:%s.org][%s]]"
215                    (org-link-escape hl-text)
216                    (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
217            nil (- (point) (length hl-text)) (point))))))
218 #+end_src
220 *** Using M-up and M-down to transpose paragraphs
222 From Paul Sexton: By default, if used within ordinary paragraphs in
223 org mode, =M-up= and =M-down= transpose *lines* (not sentences).  The
224 following code makes these keys transpose paragraphs, keeping the
225 point at the start of the moved paragraph. Behavior in tables and
226 headings is unaffected. It would be easy to modify this to transpose
227 sentences.
229 #+begin_src emacs-lisp
230 (defun org-transpose-paragraphs (arg)
231  (interactive)
232  (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
233             (thing-at-point 'sentence))
234    (transpose-paragraphs arg)
235    (backward-paragraph)
236    (re-search-forward "[[:graph:]]")
237    (goto-char (match-beginning 0))
238    t))
240 (add-to-list 'org-metaup-hook 
241  (lambda () (interactive) (org-transpose-paragraphs -1)))
242 (add-to-list 'org-metadown-hook 
243  (lambda () (interactive) (org-transpose-paragraphs 1)))
244 #+end_src
245 *** Changelog support for org headers
246 -- James TD Smith
248 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
249 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
250 headline as the "current function" if you add a changelog entry from an org
251 buffer.
253 #+BEGIN_SRC emacs-lisp
254   (defun org-log-current-defun ()
255     (save-excursion
256       (org-back-to-heading)
257       (if (looking-at org-complex-heading-regexp)
258           (match-string 4))))
260   (add-hook 'org-mode-hook
261             (lambda ()
262               (make-variable-buffer-local 'add-log-current-defun-function)
263               (setq add-log-current-defun-function 'org-log-current-defun)))
264 #+END_SRC
266 *** Different org-cycle-level behavior
267 -- Ryan Thompson
269 In recent org versions, when your point (cursor) is at the end of an
270 empty header line (like after you first created the header), the TAB
271 key (=org-cycle=) has a special behavior: it cycles the headline through
272 all possible levels. However, I did not like the way it determined
273 "all possible levels," so I rewrote the whole function, along with a
274 couple of supporting functions.
276 The original function's definition of "all possible levels" was "every
277 level from 1 to one more than the initial level of the current
278 headline before you started cycling." My new definition is "every
279 level from 1 to one more than the previous headline's level." So, if
280 you have a headline at level 4 and you use ALT+RET to make a new
281 headline below it, it will cycle between levels 1 and 5, inclusive.
283 The main advantage of my custom =org-cycle-level= function is that it
284 is stateless: the next level in the cycle is determined entirely by
285 the contents of the buffer, and not what command you executed last.
286 This makes it more predictable, I hope.
288 #+BEGIN_SRC emacs-lisp
289 (require 'cl)
291 (defun org-point-at-end-of-empty-headline ()
292   "If point is at the end of an empty headline, return t, else nil."
293   (and (looking-at "[ \t]*$")
294        (save-excursion
295          (beginning-of-line 1)
296          (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
298 (defun org-level-increment ()
299   "Return the number of stars that will be added or removed at a
300 time to headlines when structure editing, based on the value of
301 `org-odd-levels-only'."
302   (if org-odd-levels-only 2 1))
304 (defvar org-previous-line-level-cached nil)
306 (defun org-recalculate-previous-line-level ()
307   "Same as `org-get-previous-line-level', but does not use cached
308 value. It does *set* the cached value, though."
309   (set 'org-previous-line-level-cached
310        (let ((current-level (org-current-level))
311              (prev-level (when (> (line-number-at-pos) 1)
312                            (save-excursion
313                              (previous-line)
314                              (org-current-level)))))
315          (cond ((null current-level) nil) ; Before first headline
316                ((null prev-level) 0)      ; At first headline
317                (prev-level)))))
319 (defun org-get-previous-line-level ()
320   "Return the outline depth of the last headline before the
321 current line. Returns 0 for the first headline in the buffer, and
322 nil if before the first headline."
323   ;; This calculation is quite expensive, with all the regex searching
324   ;; and stuff. Since org-cycle-level won't change lines, we can reuse
325   ;; the last value of this command.
326   (or (and (eq last-command 'org-cycle-level)
327            org-previous-line-level-cached)
328       (org-recalculate-previous-line-level)))
330 (defun org-cycle-level ()
331   (interactive)
332   (let ((org-adapt-indentation nil))
333     (when (org-point-at-end-of-empty-headline)
334       (setq this-command 'org-cycle-level) ;Only needed for caching
335       (let ((cur-level (org-current-level))
336             (prev-level (org-get-previous-line-level)))
337         (cond
338          ;; If first headline in file, promote to top-level.
339          ((= prev-level 0)
340           (loop repeat (/ (- cur-level 1) (org-level-increment))
341                 do (org-do-promote)))
342          ;; If same level as prev, demote one.
343          ((= prev-level cur-level)
344           (org-do-demote))
345          ;; If parent is top-level, promote to top level if not already.
346          ((= prev-level 1)
347           (loop repeat (/ (- cur-level 1) (org-level-increment))
348                 do (org-do-promote)))
349          ;; If top-level, return to prev-level.
350          ((= cur-level 1)
351           (loop repeat (/ (- prev-level 1) (org-level-increment))
352                 do (org-do-demote)))
353          ;; If less than prev-level, promote one.
354          ((< cur-level prev-level)
355           (org-do-promote))
356          ;; If deeper than prev-level, promote until higher than
357          ;; prev-level.
358          ((> cur-level prev-level)
359           (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
360                 do (org-do-promote))))
361         t))))
362 #+END_SRC
364 *** Count words in an Org buffer
365 #FIXME: Does not fit too well under Structure. Any idea where to put it?
366 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
368 #+begin_src emacs-lisp
369 (defun org-word-count (beg end
370                            &optional count-latex-macro-args?
371                            count-footnotes?)
372   "Report the number of words in the Org mode buffer or selected region.
373 Ignores:
374 - comments
375 - tables
376 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
377 - hyperlinks (but does count words in hyperlink descriptions)
378 - tags, priorities, and TODO keywords in headers
379 - sections tagged as 'not for export'.
381 The text of footnote definitions is ignored, unless the optional argument
382 COUNT-FOOTNOTES? is non-nil.
384 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
385 includes LaTeX macro arguments (the material between {curly braces}).
386 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
387 of its arguments."
388   (interactive "r")
389   (unless mark-active
390     (setf beg (point-min)
391           end (point-max)))
392   (let ((wc 0)
393         (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
394     (save-excursion
395       (goto-char beg)
396       (while (< (point) end)
397         (cond
398          ;; Ignore comments.
399          ((or (org-in-commented-line) (org-at-table-p))
400           nil)
401          ;; Ignore hyperlinks. But if link has a description, count
402          ;; the words within the description.
403          ((looking-at org-bracket-link-analytic-regexp)
404           (when (match-string-no-properties 5)
405             (let ((desc (match-string-no-properties 5)))
406               (save-match-data
407                 (incf wc (length (remove "" (org-split-string
408                                              desc "\\W")))))))
409           (goto-char (match-end 0)))
410          ((looking-at org-any-link-re)
411           (goto-char (match-end 0)))
412          ;; Ignore source code blocks.
413          ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
414           nil)
415          ;; Ignore inline source blocks, counting them as 1 word.
416          ((save-excursion
417             (backward-char)
418             (looking-at org-babel-inline-src-block-regexp))
419           (goto-char (match-end 0))
420           (setf wc (+ 2 wc)))
421          ;; Count latex macros as 1 word, ignoring their arguments.
422          ((save-excursion
423             (backward-char)
424             (looking-at latex-macro-regexp))
425           (goto-char (if count-latex-macro-args?
426                          (match-beginning 2)
427                        (match-end 0)))
428           (setf wc (+ 2 wc)))
429          ;; Ignore footnotes.
430          ((and (not count-footnotes?)
431                (or (org-footnote-at-definition-p)
432                    (org-footnote-at-reference-p)))
433           nil)
434          (t
435           (let ((contexts (org-context)))
436             (cond
437              ;; Ignore tags and TODO keywords, etc.
438              ((or (assoc :todo-keyword contexts)
439                   (assoc :priority contexts)
440                   (assoc :keyword contexts)
441                   (assoc :checkbox contexts))
442               nil)
443              ;; Ignore sections marked with tags that are
444              ;; excluded from export.
445              ((assoc :tags contexts)
446               (if (intersection (org-get-tags-at) org-export-exclude-tags
447                                 :test 'equal)
448                   (org-forward-same-level 1)
449                 nil))
450              (t
451               (incf wc))))))
452         (re-search-forward "\\w+\\W*")))
453     (message (format "%d words in %s." wc
454                      (if mark-active "region" "buffer")))))
455 #+end_src
457 ** Org Table
458 *** Transpose tables (Juan Pechiar)
460 This function by Juan Pechiar will transpose a table:
462 #+begin_src emacs-lisp
463 (defun org-transpose-table-at-point ()
464   "Transpose orgmode table at point, eliminate hlines"
465   (interactive)
466   (let ((contents
467          (apply #'mapcar* #'list
468                 ;; remove 'hline from list
469                 (remove-if-not 'listp
470                                ;; signals error if not table
471                                (org-table-to-lisp)))))
472     (delete-region (org-table-begin) (org-table-end))
473     (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) "  |\n" ))
474                        contents ""))
475     (org-table-align)))
476 #+end_src
478 So a table like
480 : | 1 | 2 | 4 | 5 |
481 : |---+---+---+---|
482 : | a | b | c | d |
483 : | e | f | g | h |
485 will be transposed as
487 : | 1 | a | e |
488 : | 2 | b | f |
489 : | 4 | c | g |
490 : | 5 | d | h |
492 (Note that horizontal lines disappeared.)
494 *** Manipulate hours/minutes/seconds in table formulas
496 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
497 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
498 "=d=" is any digit) as time values in Org-mode table formula.  These
499 functions have now been wrapped up into a =with-time= macro which can
500 be used in table formula to translate table cell values to and from
501 numerical values for algebraic manipulation.
503 Here is the code implementing this macro.
504 #+begin_src emacs-lisp :results silent
505   (defun org-time-string-to-seconds (s)
506     "Convert a string HH:MM:SS to a number of seconds."
507     (cond
508      ((and (stringp s)
509            (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
510       (let ((hour (string-to-number (match-string 1 s)))
511             (min (string-to-number (match-string 2 s)))
512             (sec (string-to-number (match-string 3 s))))
513         (+ (* hour 3600) (* min 60) sec)))
514      ((and (stringp s)
515            (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
516       (let ((min (string-to-number (match-string 1 s)))
517             (sec (string-to-number (match-string 2 s))))
518         (+ (* min 60) sec)))
519      ((stringp s) (string-to-number s))
520      (t s)))
522   (defun org-time-seconds-to-string (secs)
523     "Convert a number of seconds to a time string."
524     (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
525           ((>= secs 60) (format-seconds "%m:%.2s" secs))
526           (t (format-seconds "%s" secs))))
528   (defmacro with-time (time-output-p &rest exprs)
529     "Evaluate an org-table formula, converting all fields that look
530   like time data to integer seconds.  If TIME-OUTPUT-P then return
531   the result as a time value."
532     (list
533      (if time-output-p 'org-time-seconds-to-string 'identity)
534      (cons 'progn
535            (mapcar
536             (lambda (expr)
537               `,(cons (car expr)
538                       (mapcar
539                        (lambda (el)
540                          (if (listp el)
541                              (list 'with-time nil el)
542                            (org-time-string-to-seconds el)))
543                        (cdr expr))))
544             `,@exprs))))
545 #+end_src
547 Which allows the following forms of table manipulation such as adding
548 and subtracting time values.
549 : | Date             | Start | Lunch |  Back |   End |  Sum |
550 : |------------------+-------+-------+-------+-------+------|
551 : | [2011-03-01 Tue] |  8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
552 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
554 and dividing time values by integers
555 : |  time | miles | minutes/mile |
556 : |-------+-------+--------------|
557 : | 34:43 |   2.9 |        11:58 |
558 : | 32:15 |  2.77 |        11:38 |
559 : | 33:56 |   3.0 |        11:18 |
560 : | 52:22 |  4.62 |        11:20 |
561 : #+TBLFM: $3='(with-time t (/ $1 $2))
563 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
564 Elisp formulas) to compute time durations.  For example:
566 : | Task 1 | Task 2 |   Total |
567 : |--------+--------+---------|
568 : |  35:00 |  35:00 | 1:10:00 |
569 : #+TBLFM: @2$3=$1+$2;T
571 *** Dates computation
573 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of 
574 dates stored in an org table.
576 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
578 Try the following:
580 | Start Date |   End Date | Duration |
581 |------------+------------+----------|
582 | 2004.08.07 | 2005.07.08 |      335 |
583 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
585 See [[http://thread.gmane.org/gmane.emacs.orgmode/7741][this thread]] as well as [[http://article.gmane.org/gmane.emacs.orgmode/7753][this post]] (which is really a followup on the
586 above).  The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
587 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
589 *** Hex computation
591 As with Times computation, the following code allows Computation with
592 Hex values in Org-mode tables using the =with-hex= macro.
594 Here is the code implementing this macro.
595 #+begin_src emacs-lisp
596   (defun org-hex-strip-lead (str)
597     (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
598         (substring str 2) str))
600   (defun org-hex-to-hex (int)
601     (format "0x%x" int))
603   (defun org-hex-to-dec (str)
604     (cond
605      ((and (stringp str)
606            (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
607       (let ((out 0))
608         (mapc
609          (lambda (ch)
610            (setf out (+ (* out 16)
611                         (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
612          (coerce (match-string 1 str) 'list))
613         out))
614      ((stringp str) (string-to-number str))
615      (t str)))
617   (defmacro with-hex (hex-output-p &rest exprs)
618     "Evaluate an org-table formula, converting all fields that look
619       like hexadecimal to decimal integers.  If HEX-OUTPUT-P then
620       return the result as a hex value."
621     (list
622      (if hex-output-p 'org-hex-to-hex 'identity)
623      (cons 'progn
624            (mapcar
625             (lambda (expr)
626               `,(cons (car expr)
627                       (mapcar (lambda (el)
628                                 (if (listp el)
629                                     (list 'with-hex nil el)
630                                   (org-hex-to-dec el)))
631                               (cdr expr))))
632             `,@exprs))))
633 #+end_src
635 Which allows the following forms of table manipulation such as adding
636 and subtracting hex values.
637 | 0x10 | 0x0 | 0x10 |  16 |
638 | 0x20 | 0x1 | 0x21 |  33 |
639 | 0x30 | 0x2 | 0x32 |  50 |
640 | 0xf0 | 0xf | 0xff | 255 |
641 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
643 *** Field coordinates in formulas (=@#= and =$#=)
645 -- Michael Brand
647 Following are some use cases that can be implemented with the
648 _field coordinates in formulas_ described in the corresponding
649 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
651 **** Copy a column from a remote table into a column
653 current column =$3= = remote column =$2=:
654 : #+TBLFM: $3 = remote(FOO, @@#$2)
656 **** Copy a row from a remote table transposed into a column
658 current column =$1= = transposed remote row =@1=:
659 : #+TBLFM: $1 = remote(FOO, @$#$@#)
661 **** Transpose a table
663 -- Michael Brand
665 This is more like a demonstration of using _field coordinates in formulas_
666 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel.  The efficient
667 and simple solution for this with the help of org-babel and Emacs Lisp has
668 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
670 To transpose this 4x7 table
672 : #+TBLNAME: FOO
673 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
674 : |------+------+------+------+------+------+------|
675 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
676 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
677 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
679 start with a 7x4 table without any horizontal line (to have filled
680 also the column header) and yet empty:
682 : |   |   |   |   |
683 : |   |   |   |   |
684 : |   |   |   |   |
685 : |   |   |   |   |
686 : |   |   |   |   |
687 : |   |   |   |   |
688 : |   |   |   |   |
690 Then add the =TBLFM= below with the same formula repeated for each column.
691 After recalculation this will end up with the transposed copy:
693 : | year | min | avg | max |
694 : | 2004 | 401 | 402 | 403 |
695 : | 2005 | 501 | 502 | 503 |
696 : | 2006 | 601 | 602 | 603 |
697 : | 2007 | 701 | 702 | 703 |
698 : | 2008 | 801 | 802 | 803 |
699 : | 2009 | 901 | 902 | 903 |
700 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
702 The formulas simply exchange row and column numbers by taking
703 - the absolute remote row number =@$#= from the current column number =$#=
704 - the absolute remote column number =$@#= from the current row number =@#=
706 Possible field formulas from the remote table will have to be transferred
707 manually.  Since there are no row formulas yet there is no need to transfer
708 column formulas to row formulas or vice versa.
710 **** Dynamic variation of ranges
712 -- Michael Brand
714 In this example all columns next to =quote= are calculated from the column
715 =quote= and show the average change of the time series =quote[year]=
716 during the period of the preceding =1=, =2=, =3= or =4= years:
718 : | year | quote |   1 a |   2 a |   3 a |   4 a |
719 : |------+-------+-------+-------+-------+-------|
720 : | 2005 |    10 |       |       |       |       |
721 : | 2006 |    12 | 0.200 |       |       |       |
722 : | 2007 |    14 | 0.167 | 0.183 |       |       |
723 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
724 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
725 : #+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
727 The formula is the same for each column =$3= through =$6=.  This can easily
728 be seen with the great formula editor invoked by C-c ' on the
729 table. The important part of the formula without the field blanking is:
731 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
733 which is the Emacs Calc implementation of the equation
735 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
737 where /i/ is the current time and /a/ is the length of the preceding period.
739 ** Capture and Remember
740 *** Customize the size of the frame for remember
741 (Note: this hack is likely out of date due to the development of
742 [[org-capture]].)
744 #FIXME: gmane link?
745 On emacs-orgmode, Ryan C. Thompson suggested this:
747 #+begin_quote
748 I am using org-remember set to open a new frame when used,
749 and the default frame size is much too large. To fix this, I have
750 designed some advice and a custom variable to implement custom
751 parameters for the remember frame:
752 #+end_quote
754 #+begin_src emacs-lisp
755 (defcustom remember-frame-alist nil
756   "Additional frame parameters for dedicated remember frame."
757   :type 'alist
758   :group 'remember)
760 (defadvice remember (around remember-frame-parameters activate)
761   "Set some frame parameters for the remember frame."
762   (let ((default-frame-alist (append remember-frame-alist
763                                      default-frame-alist)))
764     ad-do-it))
765 #+end_src
767 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
768 reasonable size for the frame.
769 ** Handling Links
770 *** [[#heading-to-link][Turn a heading into an org link]] 
771 *** Quickaccess to the link part of hyperlinks
772 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
773 of an org hyperling other than to use `C-c C-l C-a C-k C-g', 
774 which is indeed kind of cumbersome.
776 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
778 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
779 #+begin_src emacs-lisp
780 (fset 'getlink
781       (lambda (&optional arg) 
782         "Keyboard macro." 
783         (interactive "p") 
784         (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
785 #+end_src
787 or a function: 
788 #+begin_src emacs-lisp
789 (defun my-org-extract-link ()
790   "Extract the link location at point and put it on the killring."
791   (interactive)
792   (when (org-in-regexp org-bracket-link-regexp 1)
793     (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
794 #+end_src
796 They put the link destination on the killring and can be easily bound to a key.
798 ** Archiving Content in Org-Mode
799 *** Preserve top level headings when archiving to a file
800 - Matt Lundin
802 To preserve (somewhat) the integrity of your archive structure while
803 archiving lower level items to a file, you can use the following
804 defadvice:
806 #+begin_src emacs-lisp
807 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
808   (let ((org-archive-location
809          (if (save-excursion (org-back-to-heading)
810                              (> (org-outline-level) 1))
811              (concat (car (split-string org-archive-location "::"))
812                      "::* "
813                      (car (org-get-outline-path)))
814            org-archive-location)))
815     ad-do-it))
816 #+end_src
818 Thus, if you have an outline structure such as...
820 #+begin_src org
821 ,* Heading
822 ,** Subheading
823 ,*** Subsubheading
824 #+end_src
826 ...archiving "Subsubheading" to a new file will set the location in
827 the new file to the top level heading:
829 #+begin_src org
830 ,* Heading
831 ,** Subsubheading
832 #+end_src
834 While this hack obviously destroys the outline hierarchy somewhat, it
835 at least preserves the logic of level one groupings.
837 A slightly more complex version of this hack will not only keep the
838 archive organized by top-level headings, but will also preserve the
839 tags found on those headings:
841 #+begin_src emacs-lisp
842   (defun my-org-inherited-no-file-tags ()
843     (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
844           (ltags (org-entry-get nil "TAGS")))
845       (mapc (lambda (tag)
846               (setq tags
847                     (replace-regexp-in-string (concat tag ":") "" tags)))
848             (append org-file-tags (when ltags (split-string ltags ":" t))))
849       (if (string= ":" tags) nil tags)))
851   (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
852     (let ((tags (my-org-inherited-no-file-tags))
853           (org-archive-location
854            (if (save-excursion (org-back-to-heading)
855                                (> (org-outline-level) 1))
856                (concat (car (split-string org-archive-location "::"))
857                        "::* "
858                        (car (org-get-outline-path)))
859              org-archive-location)))
860       ad-do-it
861       (with-current-buffer (find-file-noselect (org-extract-archive-file))
862         (save-excursion
863           (while (org-up-heading-safe))
864           (org-set-tags-to tags)))))
865 #+end_src
867 *** Archive in a date tree
869 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
871 (Make sure org-datetree.el is loaded for this to work.)
873 #+begin_src emacs-lisp
874 ;; (setq org-archive-location "%s_archive::date-tree")
875 (defadvice org-archive-subtree
876   (around org-archive-subtree-to-data-tree activate)
877   "org-archive-subtree to date-tree"
878   (if
879       (string= "date-tree"
880                (org-extract-archive-heading
881                 (org-get-local-archive-location)))
882       (let* ((dct (decode-time (org-current-time)))
883              (y (nth 5 dct))
884              (m (nth 4 dct))
885              (d (nth 3 dct))
886              (this-buffer (current-buffer))
887              (location (org-get-local-archive-location))
888              (afile (org-extract-archive-file location))
889              (org-archive-location
890               (format "%s::*** %04d-%02d-%02d %s" afile y m d
891                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
892         (message "afile=%s" afile)
893         (unless afile
894           (error "Invalid `org-archive-location'"))
895         (save-excursion
896           (switch-to-buffer (find-file-noselect afile))
897           (org-datetree-find-year-create y)
898           (org-datetree-find-month-create y m)
899           (org-datetree-find-day-create y m d)
900           (widen)
901           (switch-to-buffer this-buffer))
902         ad-do-it)
903     ad-do-it))
904 #+end_src
906 *** Add inherited tags to archived entries
908 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
909 advise the function like this:
911 #+begin_example
912 (defadvice org-archive-subtree
913   (before add-inherited-tags-before-org-archive-subtree activate)
914     "add inherited tags before org-archive-subtree"
915     (org-set-tags-to (org-get-tags-at)))
916 #+end_example
918 ** Using and Managing Org-Metadata
919 *** Remove redundant tags of headlines
920 -- David Maus
922 A small function that processes all headlines in current buffer and
923 removes tags that are local to a headline and inherited by a parent
924 headline or the #+FILETAGS: statement.
926 #+BEGIN_SRC emacs-lisp
927   (defun dmj/org-remove-redundant-tags ()
928     "Remove redundant tags of headlines in current buffer.
930   A tag is considered redundant if it is local to a headline and
931   inherited by a parent headline."
932     (interactive)
933     (when (eq major-mode 'org-mode)
934       (save-excursion
935         (org-map-entries
936          '(lambda ()
937             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
938                   local inherited tag)
939               (dolist (tag alltags)
940                 (if (get-text-property 0 'inherited tag)
941                     (push tag inherited) (push tag local)))
942               (dolist (tag local)
943                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
944          t nil))))
945 #+END_SRC
947 *** Remove empty property drawers
949 David Maus proposed this:
951 #+begin_src emacs-lisp
952 (defun dmj:org:remove-empty-propert-drawers ()
953   "*Remove all empty property drawers in current file."
954   (interactive)
955   (unless (eq major-mode 'org-mode)
956     (error "You need to turn on Org mode for this function."))
957   (save-excursion
958     (goto-char (point-min))
959     (while (re-search-forward ":PROPERTIES:" nil t)
960       (save-excursion
961         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
962 #+end_src
964 *** Group task list by a property
966 This advice allows you to group a task list in Org-Mode.  To use it,
967 set the variable =org-agenda-group-by-property= to the name of a
968 property in the option list for a TODO or TAGS search.  The resulting
969 agenda view will group tasks by that property prior to searching.
971 #+begin_src emacs-lisp
972 (defvar org-agenda-group-by-property nil
973   "Set this in org-mode agenda views to group tasks by property")
975 (defun org-group-bucket-items (prop items)
976   (let ((buckets ()))
977     (dolist (item items)
978       (let* ((marker (get-text-property 0 'org-marker item))
979              (pvalue (org-entry-get marker prop t))
980              (cell (assoc pvalue buckets)))
981         (if cell
982             (setcdr cell (cons item (cdr cell)))
983           (setq buckets (cons (cons pvalue (list item))
984                               buckets)))))
985     (setq buckets (mapcar (lambda (bucket)
986                             (cons (car bucket)
987                                   (reverse (cdr bucket))))
988                           buckets))
989     (sort buckets (lambda (i1 i2)
990                     (string< (car i1) (car i2))))))
992 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
993                                                (list &optional nosort))
994   "Prepare bucketed agenda entry lists"
995   (if org-agenda-group-by-property
996       ;; bucketed, handle appropriately
997       (let ((text ""))
998         (dolist (bucket (org-group-bucket-items
999                          org-agenda-group-by-property
1000                          list))
1001           (let ((header (concat "Property "
1002                                 org-agenda-group-by-property
1003                                 " is "
1004                                 (or (car bucket) "<nil>") ":\n")))
1005             (add-text-properties 0 (1- (length header))
1006                                  (list 'face 'org-agenda-structure)
1007                                  header)
1008             (setq text
1009                   (concat text header
1010                           ;; recursively process
1011                           (let ((org-agenda-group-by-property nil))
1012                             (org-finalize-agenda-entries
1013                              (cdr bucket) nosort))
1014                           "\n\n"))))
1015         (setq ad-return-value text))
1016     ad-do-it))
1017 (ad-activate 'org-finalize-agenda-entries)
1018 #+end_src
1019 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1020     Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1022 A small hook run when clocking out of a task that prompts for a note
1023 when the tag "=clockout_note=" is found in a headline. It uses the tag
1024 ("=clockout_note=") so inheritance can also be used...
1026 #+begin_src emacs-lisp
1027   (defun rgr/check-for-clock-out-note()
1028         (interactive)
1029         (save-excursion
1030           (org-back-to-heading)
1031           (let ((tags (org-get-tags)))
1032             (and tags (message "tags: %s " tags)
1033                  (when (member "clocknote" tags)
1034                    (org-add-note))))))
1036   (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1037 #+end_src
1038 *** Dynamically adjust tag position
1039 Here is a bit of code that allows you to have the tags always
1040 right-adjusted in the buffer.
1042 This is useful when you have bigger window than default window-size
1043 and you dislike the aesthetics of having the tag in the middle of the
1044 line.
1046 This hack solves the problem of adjusting it whenever you change the
1047 window size.
1048 Before saving it will revert the file to having the tag position be
1049 left-adjusted so that if you track your files with version control,
1050 you won't run into artificial diffs just because the window-size
1051 changed.
1053 *IMPORTANT*: This is probably slow on very big files.
1055 #+begin_src emacs-lisp
1056 (setq ba/org-adjust-tags-column t)
1058 (defun ba/org-adjust-tags-column-reset-tags ()
1059   "In org-mode buffers it will reset tag position according to
1060 `org-tags-column'."
1061   (when (and
1062          (not (string= (buffer-name) "*Remember*"))
1063          (eql major-mode 'org-mode))
1064     (let ((b-m-p (buffer-modified-p)))
1065       (condition-case nil
1066           (save-excursion
1067             (goto-char (point-min))
1068             (command-execute 'outline-next-visible-heading)
1069             ;; disable (message) that org-set-tags generates
1070             (flet ((message (&rest ignored) nil))
1071               (org-set-tags 1 t))
1072             (set-buffer-modified-p b-m-p))
1073         (error nil)))))
1075 (defun ba/org-adjust-tags-column-now ()
1076   "Right-adjust `org-tags-column' value, then reset tag position."
1077   (set (make-local-variable 'org-tags-column)
1078        (- (- (window-width) (length org-ellipsis))))
1079   (ba/org-adjust-tags-column-reset-tags))
1081 (defun ba/org-adjust-tags-column-maybe ()
1082   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1083   (when ba/org-adjust-tags-column
1084     (ba/org-adjust-tags-column-now)))
1086 (defun ba/org-adjust-tags-column-before-save ()
1087   "Tags need to be left-adjusted when saving."
1088   (when ba/org-adjust-tags-column
1089      (setq org-tags-column 1)
1090      (ba/org-adjust-tags-column-reset-tags)))
1092 (defun ba/org-adjust-tags-column-after-save ()
1093   "Revert left-adjusted tag position done by before-save hook."
1094   (ba/org-adjust-tags-column-maybe)
1095   (set-buffer-modified-p nil))
1097 ; automatically align tags on right-hand side
1098 (add-hook 'window-configuration-change-hook
1099           'ba/org-adjust-tags-column-maybe)
1100 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1101 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1102 (add-hook 'org-agenda-mode-hook '(lambda ()
1103                                   (setq org-agenda-tags-column (- (window-width)))))
1105 ; between invoking org-refile and displaying the prompt (which
1106 ; triggers window-configuration-change-hook) tags might adjust,
1107 ; which invalidates the org-refile cache
1108 (defadvice org-refile (around org-refile-disable-adjust-tags)
1109   "Disable dynamically adjusting tags"
1110   (let ((ba/org-adjust-tags-column nil))
1111     ad-do-it))
1112 (ad-activate 'org-refile)
1113 #+end_src
1114 *** Use an "attach" link type to open files without worrying about their location
1116 -- Darlan Cavalcante Moreira
1118 In the setup part in my org-files I put:
1120 #+begin_src org
1121   ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1122 #+end_src org
1124 Now I can use the "attach" link type, but org will ask me if I want to
1125 allow executing the elisp code.  To avoid this you can even set
1126 org-confirm-elisp-link-function to nil (I don't like this because it allows
1127 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1128 appropriately.
1130 In my case I use
1132 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1134 This works very well.
1136 ** Org Agenda and Task Management
1137 *** Make it easier to set org-agenda-files from multiple directories
1138 - Matt Lundin
1140 #+begin_src emacs-lisp
1141 (defun my-org-list-files (dirs ext)
1142   "Function to create list of org files in multiple subdirectories.
1143 This can be called to generate a list of files for
1144 org-agenda-files or org-refile-targets.
1146 DIRS is a list of directories.
1148 EXT is a list of the extensions of files to be included."
1149   (let ((dirs (if (listp dirs)
1150                   dirs
1151                 (list dirs)))
1152         (ext (if (listp ext)
1153                  ext
1154                (list ext)))
1155         files)
1156     (mapc
1157      (lambda (x)
1158        (mapc
1159         (lambda (y)
1160           (setq files
1161                 (append files
1162                         (file-expand-wildcards
1163                          (concat (file-name-as-directory x) "*" y)))))
1164         ext))
1165      dirs)
1166     (mapc
1167      (lambda (x)
1168        (when (or (string-match "/.#" x)
1169                  (string-match "#$" x))
1170          (setq files (delete x files))))
1171      files)
1172     files))
1174 (defvar my-org-agenda-directories '("~/org/")
1175   "List of directories containing org files.")
1176 (defvar my-org-agenda-extensions '(".org")
1177   "List of extensions of agenda files")
1179 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1180 (setq my-org-agenda-extensions '(".org" ".ref"))
1182 (defun my-org-set-agenda-files ()
1183   (interactive)
1184   (setq org-agenda-files (my-org-list-files
1185                           my-org-agenda-directories
1186                           my-org-agenda-extensions)))
1188 (my-org-set-agenda-files)
1189 #+end_src
1191 The code above will set your "default" agenda files to all files
1192 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1193 You can change these values by setting the variables
1194 my-org-agenda-extensions and my-org-agenda-directories. The function
1195 my-org-agenda-files-by-filetag uses these two variables to determine
1196 which files to search for filetags (i.e., the larger set from which
1197 the subset will be drawn).
1199 You can also easily use my-org-list-files to "mix and match"
1200 directories and extensions to generate different lists of agenda
1201 files.
1203 *** Restrict org-agenda-files by filetag
1204   :PROPERTIES:
1205   :CUSTOM_ID: set-agenda-files-by-filetag
1206   :END:
1207 - Matt Lundin
1209 It is often helpful to limit yourself to a subset of your agenda
1210 files. For instance, at work, you might want to see only files related
1211 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1212 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
1213 commands]]. These solutions, however, require reapplying a filter each
1214 time you call the agenda or writing several new custom agenda commands
1215 for each context. Another solution is to use directories for different
1216 types of tasks and to change your agenda files with a function that
1217 sets org-agenda-files to the appropriate directory. But this relies on
1218 hard and static boundaries between files.
1220 The following functions allow for a more dynamic approach to selecting
1221 a subset of files based on filetags:
1223 #+begin_src emacs-lisp
1224 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1225   "Restrict org agenda files only to those containing filetag."
1226   (interactive)
1227   (let* ((tagslist (my-org-get-all-filetags))
1228          (ftag (or tag
1229                    (completing-read "Tag: "
1230                                     (mapcar 'car tagslist)))))
1231     (org-agenda-remove-restriction-lock 'noupdate)
1232     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1233     (setq org-agenda-overriding-restriction 'files)))
1235 (defun my-org-get-all-filetags ()
1236   "Get list of filetags from all default org-files."
1237   (let ((files org-agenda-files)
1238         tagslist x)
1239     (save-window-excursion
1240       (while (setq x (pop files))
1241         (set-buffer (find-file-noselect x))
1242         (mapc
1243          (lambda (y)
1244            (let ((tagfiles (assoc y tagslist)))
1245              (if tagfiles
1246                  (setcdr tagfiles (cons x (cdr tagfiles)))
1247                (add-to-list 'tagslist (list y x)))))
1248          (my-org-get-filetags)))
1249       tagslist)))
1251 (defun my-org-get-filetags ()
1252   "Get list of filetags for current buffer"
1253   (let ((ftags org-file-tags)
1254         x)
1255     (mapcar
1256      (lambda (x)
1257        (org-substring-no-properties x))
1258      ftags)))
1259 #+end_src
1261 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1262 with all filetags in your "normal" agenda files. When you select a
1263 tag, org-agenda-files will be restricted to only those files
1264 containing the filetag. To release the restriction, type C-c C-x >
1265 (org-agenda-remove-restriction-lock).
1267 *** Highlight the agenda line under cursor
1269 This is useful to make sure what task you are operating on.
1271 #+BEGIN_SRC emacs-lisp
1272 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1273 #+END_SRC
1275 Under XEmacs:
1277 #+BEGIN_SRC emacs-lisp
1278 ;; hl-line seems to be only for emacs
1279 (require 'highline)
1280 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1282 ;; highline-mode does not work straightaway in tty mode.
1283 ;; I use a black background
1284 (custom-set-faces
1285   '(highline-face ((((type tty) (class color))
1286                     (:background "white" :foreground "black")))))
1287 #+END_SRC
1289 *** Split horizontally for agenda
1291 If you would like to split the frame into two side-by-side windows when
1292 displaying the agenda, try this hack from Jan Rehders, which uses the
1293 `toggle-window-split' from
1295 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1297 #+BEGIN_SRC emacs-lisp
1298 ;; Patch org-mode to use vertical splitting
1299 (defadvice org-prepare-agenda (after org-fix-split)
1300   (toggle-window-split))
1301 (ad-activate 'org-prepare-agenda)
1302 #+END_SRC
1304 *** Automatically add an appointment when clocking in a task
1306 #+BEGIN_SRC emacs-lisp
1307 ;; Make sure you have a sensible value for `appt-message-warning-time'
1308 (defvar bzg-org-clock-in-appt-delay 100
1309   "Number of minutes for setting an appointment by clocking-in")
1310 #+END_SRC
1312 This function let's you add an appointment for the current entry.
1313 This can be useful when you need a reminder.
1315 #+BEGIN_SRC emacs-lisp
1316 (defun bzg-org-clock-in-add-appt (&optional n)
1317   "Add an appointment for the Org entry at point in N minutes."
1318   (interactive)
1319   (save-excursion
1320     (org-back-to-heading t)
1321     (looking-at org-complex-heading-regexp)
1322     (let* ((msg (match-string-no-properties 4))
1323            (ct-time (decode-time))
1324            (appt-min (+ (cadr ct-time)
1325                         (or n bzg-org-clock-in-appt-delay)))
1326            (appt-time ; define the time for the appointment
1327             (progn (setf (cadr ct-time) appt-min) ct-time)))
1328       (appt-add (format-time-string
1329                  "%H:%M" (apply 'encode-time appt-time)) msg)
1330       (if (interactive-p) (message "New appointment for %s" msg)))))
1331 #+END_SRC
1333 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1334 add an appointment:
1336 #+BEGIN_SRC emacs-lisp
1337 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1338   "Add an appointment when clocking a task in."
1339   (bzg-org-clock-in-add-appt))
1340 #+END_SRC
1342 You may also want to delete the associated appointment when clocking
1343 out.  This function does this:
1345 #+BEGIN_SRC emacs-lisp
1346 (defun bzg-org-clock-out-delete-appt nil
1347   "When clocking out, delete any associated appointment."
1348   (interactive)
1349   (save-excursion
1350     (org-back-to-heading t)
1351     (looking-at org-complex-heading-regexp)
1352     (let* ((msg (match-string-no-properties 4)))
1353       (setq appt-time-msg-list
1354             (delete nil
1355                     (mapcar
1356                      (lambda (appt)
1357                        (if (not (string-match (regexp-quote msg)
1358                                               (cadr appt))) appt))
1359                      appt-time-msg-list)))
1360       (appt-check))))
1361 #+END_SRC
1363 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1365 #+BEGIN_SRC emacs-lisp
1366 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1367   "Delete an appointment when clocking a task out."
1368   (bzg-org-clock-out-delete-appt))
1369 #+END_SRC
1371 *IMPORTANT*: You can add appointment by clocking in in both an
1372 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
1373 agenda buffer with the advice above will bring an error.
1375 *** Remove time grid lines that are in an appointment
1377 The agenda shows lines for the time grid.  Some people think that
1378 these lines are a distraction when there are appointments at those
1379 times.  You can get rid of the lines which coincide exactly with the
1380 beginning of an appointment.  Michael Ekstrand has written a piece of
1381 advice that also removes lines that are somewhere inside an
1382 appointment:
1384 #+begin_src emacs-lisp
1385 (defun org-time-to-minutes (time)
1386   "Convert an HHMM time to minutes"
1387   (+ (* (/ time 100) 60) (% time 100)))
1389 (defun org-time-from-minutes (minutes)
1390   "Convert a number of minutes to an HHMM time"
1391   (+ (* (/ minutes 60) 100) (% minutes 60)))
1393 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1394                                                   (list ndays todayp))
1395   (if (member 'remove-match (car org-agenda-time-grid))
1396       (flet ((extract-window
1397               (line)
1398               (let ((start (get-text-property 1 'time-of-day line))
1399                     (dur (get-text-property 1 'duration line)))
1400                 (cond
1401                  ((and start dur)
1402                   (cons start
1403                         (org-time-from-minutes
1404                          (+ dur (org-time-to-minutes start)))))
1405                  (start start)
1406                  (t nil)))))
1407         (let* ((windows (delq nil (mapcar 'extract-window list)))
1408                (org-agenda-time-grid
1409                 (list (car org-agenda-time-grid)
1410                       (cadr org-agenda-time-grid)
1411                       (remove-if
1412                        (lambda (time)
1413                          (find-if (lambda (w)
1414                                     (if (numberp w)
1415                                         (equal w time)
1416                                       (and (>= time (car w))
1417                                            (< time (cdr w)))))
1418                                   windows))
1419                        (caddr org-agenda-time-grid)))))
1420           ad-do-it))
1421     ad-do-it))
1422 (ad-activate 'org-agenda-add-time-grid-maybe)
1423 #+end_src
1424 *** Disable vc for Org mode agenda files
1425 -- David Maus
1427 Even if you use Git to track your agenda files you might not need
1428 vc-mode to be enabled for these files.
1430 #+begin_src emacs-lisp
1431 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1432 (defun dmj/disable-vc-for-agenda-files-hook ()
1433   "Disable vc-mode for Org agenda files."
1434   (if (and (fboundp 'org-agenda-file-p)
1435            (org-agenda-file-p (buffer-file-name)))
1436       (remove-hook 'find-file-hook 'vc-find-file-hook)
1437     (add-hook 'find-file-hook 'vc-find-file-hook)))
1438 #+end_src
1440 *** Easy customization of TODO colors
1441 -- Ryan C. Thompson
1443 Here is some code I came up with some code to make it easier to
1444 customize the colors of various TODO keywords. As long as you just
1445 want a different color and nothing else, you can customize the
1446 variable org-todo-keyword-faces and use just a string color (i.e. a
1447 string of the color name) as the face, and then org-get-todo-face
1448 will convert the color to a face, inheriting everything else from
1449 the standard org-todo face.
1451 To demonstrate, I currently have org-todo-keyword-faces set to
1453 #+BEGIN_SRC emacs-lisp
1454 (("IN PROGRESS" . "dark orange")
1455  ("WAITING" . "red4")
1456  ("CANCELED" . "saddle brown"))
1457 #+END_SRC
1459   Here's the code, in a form you can put in your =.emacs=
1461 #+BEGIN_SRC emacs-lisp
1462 (eval-after-load 'org-faces
1463  '(progn
1464     (defcustom org-todo-keyword-faces nil
1465       "Faces for specific TODO keywords.
1466 This is a list of cons cells, with TODO keywords in the car and
1467 faces in the cdr.  The face can be a symbol, a color, or a
1468 property list of attributes, like (:foreground \"blue\" :weight
1469 bold :underline t)."
1470       :group 'org-faces
1471       :group 'org-todo
1472       :type '(repeat
1473               (cons
1474                (string :tag "Keyword")
1475                (choice color (sexp :tag "Face")))))))
1477 (eval-after-load 'org
1478  '(progn
1479     (defun org-get-todo-face-from-color (color)
1480       "Returns a specification for a face that inherits from org-todo
1481  face and has the given color as foreground. Returns nil if
1482  color is nil."
1483       (when color
1484         `(:inherit org-warning :foreground ,color)))
1486     (defun org-get-todo-face (kwd)
1487       "Get the right face for a TODO keyword KWD.
1488 If KWD is a number, get the corresponding match group."
1489       (if (numberp kwd) (setq kwd (match-string kwd)))
1490       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1491             (if (stringp face)
1492                 (org-get-todo-face-from-color face)
1493               face))
1494           (and (member kwd org-done-keywords) 'org-done)
1495           'org-todo))))
1496 #+END_SRC
1498 *** Add an effort estimate on the fly when clocking in
1500 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1501 This way you can easily have a "tea-timer" for your tasks when they
1502 don't already have an effort estimate.
1504 #+begin_src emacs-lisp
1505 (add-hook 'org-clock-in-prepare-hook
1506           'my-org-mode-ask-effort)
1508 (defun my-org-mode-ask-effort ()
1509   "Ask for an effort estimate when clocking in."
1510   (unless (org-entry-get (point) "Effort")
1511     (let ((effort
1512            (completing-read
1513             "Effort: "
1514             (org-entry-get-multivalued-property (point) "Effort"))))
1515       (unless (equal effort "")
1516         (org-set-property "Effort" effort)))))
1517 #+end_src
1519 Or you can use a default effort for such a timer:
1521 #+begin_src emacs-lisp
1522 (add-hook 'org-clock-in-prepare-hook
1523           'my-org-mode-add-default-effort)
1525 (defvar org-clock-default-effort "1:00")
1527 (defun my-org-mode-add-default-effort ()
1528   "Add a default effort estimation."
1529   (unless (org-entry-get (point) "Effort")
1530     (org-set-property "Effort" org-clock-default-effort)))
1531 #+end_src
1533 *** Refresh the agenda view regurally
1535 Hack sent by Kiwon Um:
1537 #+begin_src emacs-lisp
1538 (defun kiwon/org-agenda-redo-in-other-window ()
1539   "Call org-agenda-redo function even in the non-agenda buffer."
1540   (interactive)
1541   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1542     (when agenda-window
1543       (with-selected-window agenda-window (org-agenda-redo)))))
1544 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1545 #+end_src
1547 *** Reschedule agenda items to today with a single command
1549 This was suggested by Carsten in reply to David Abrahams:
1551 #+begin_example emacs-lisp
1552 (defun org-agenda-reschedule-to-today ()
1553   (interactive)
1554   (flet ((org-read-date (&rest rest) (current-time)))
1555     (call-interactively 'org-agenda-schedule)))
1556 #+end_example
1558 *** Mark subtree DONE along with all subheadings
1560 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
1562 #+begin_src emacs-lisp
1563 (defun bh/mark-subtree-done ()
1564   (interactive)
1565   (org-mark-subtree)
1566   (let ((limit (point)))
1567     (save-excursion
1568       (exchange-point-and-mark)
1569       (while (> (point) limit)
1570         (org-todo "DONE")
1571         (outline-previous-visible-heading 1))
1572       (org-todo "DONE"))))
1573 #+end_src
1575 Then M-x bh/mark-subtree-done.
1577 ** Exporting org files
1578 *** Export Org to Org and handle includes.
1580 Nick Dokos came up with this useful function:
1582 #+begin_src emacs-lisp
1583 (defun org-to-org-handle-includes ()
1584   "Copy the contents of the current buffer to OUTFILE,
1585 recursively processing #+INCLUDEs."
1586   (let* ((s (buffer-string))
1587          (fname (buffer-file-name))
1588          (ofname (format "%s.I.org" (file-name-sans-extension fname))))
1589     (setq result
1590           (with-temp-buffer
1591             (insert s)
1592             (org-export-handle-include-files-recurse)
1593             (buffer-string)))
1594     (find-file ofname)
1595     (delete-region (point-min) (point-max))
1596     (insert result)
1597     (save-buffer)))
1598 #+end_src
1600 *** Specifying LaTeX commands to floating environments
1601     :PROPERTIES:
1602     :CUSTOM_ID: latex-command-for-floats
1603     :END:
1605 The keyword ~placement~ can be used to specify placement options to
1606 floating environments (like =\begin{figure}= and =\begin{table}=}) in
1607 LaTeX export. Org passes along everything passed in options as long as
1608 there are no spaces. One can take advantage of this to pass other
1609 LaTeX commands and have their scope limited to the floating
1610 environment.
1612 For example one can set the fontsize of a table different from the
1613 default normal size by putting something like =\footnotesize= right
1614 after the placement options. During LaTeX export using the
1615 ~#+ATTR_LaTeX:~ line below:
1617 #+begin_src org
1618   ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
1619 #+end_src
1621 exports the associated floating environment as shown in the following
1622 block.
1624 #+begin_src latex
1625 \begin{table}[<options>]\footnotesize
1627 \end{table}
1628 #+end_src
1630 It should be noted that this hack does not work for beamer export of
1631 tables since the =table= environment is not used. As an ugly
1632 workaround, one can use the following:
1634 #+begin_src org
1635   ,#+LATEX: {\footnotesize
1636   ,#+ATTR_LaTeX: align=rr
1637   ,| some | table |
1638   ,|------+-------|
1639   ,| ..   | ..    |
1640   ,#+LATEX: }
1641 #+end_src
1643 *** Styling code sections with CSS
1645 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
1646 to HTML using =<pre>= tags, and assigned CSS classes by their content
1647 type.  For example, Perl content will have an opening tag like
1648 =<pre class="src src-perl">=.  You can use those classes to add styling
1649 to the output, such as here where a small language tag is added at the
1650 top of each kind of code box:
1652 #+begin_src lisp
1653 (setq org-export-html-style
1654  "<style type=\"text/css\">
1655     <!--/*--><![CDATA[/*><!--*/
1656       .src             { background-color: #F5FFF5; position: relative; overflow: visible; }
1657       .src:before      { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
1658       .src-sh:before   { content: 'sh'; }
1659       .src-bash:before { content: 'sh'; }
1660       .src-R:before    { content: 'R'; }
1661       .src-perl:before { content: 'Perl'; }
1662       .src-sql:before  { content: 'SQL'; }
1663       .example         { background-color: #FFF5F5; }
1664     /*]]>*/-->
1665  </style>")
1666 #+end_src
1668 Additionally, we use color to distinguish code output (the =.example=
1669 class) from input (all the =.src-*= classes).
1671 * Hacking Org: Working with Org-mode and other Emacs Packages.
1672 ** org-remember-anything
1674 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1676 #+BEGIN_SRC emacs-lisp
1677 (defvar org-remember-anything
1678   '((name . "Org Remember")
1679     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1680     (action . (lambda (name)
1681                 (let* ((orig-template org-remember-templates)
1682                        (org-remember-templates
1683                         (list (assoc name orig-template))))
1684                   (call-interactively 'org-remember))))))
1685 #+END_SRC
1687 You can add it to your 'anything-sources' variable and open remember directly
1688 from anything. I imagine this would be more interesting for people with many
1689 remember templates, so that you are out of keys to assign those to.
1691 ** Org-mode and saveplace.el
1693 Fix a problem with saveplace.el putting you back in a folded position:
1695 #+begin_src emacs-lisp
1696 (add-hook 'org-mode-hook
1697           (lambda ()
1698             (when (outline-invisible-p)
1699               (save-excursion
1700                 (outline-previous-visible-heading 1)
1701                 (org-show-subtree)))))
1702 #+end_src
1704 ** Using ido-completing-read to find attachments
1705 -- Matt Lundin.
1707 Org-attach is great for quickly linking files to a project. But if you
1708 use org-attach extensively you might find yourself wanting to browse
1709 all the files you've attached to org headlines. This is not easy to do
1710 manually, since the directories containing the files are not human
1711 readable (i.e., they are based on automatically generated ids). Here's
1712 some code to browse those files using ido (obviously, you need to be
1713 using ido):
1715 #+begin_src emacs-lisp
1716 (load-library "find-lisp")
1718 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1720 (defun my-ido-find-org-attach ()
1721   "Find files in org-attachment directory"
1722   (interactive)
1723   (let* ((enable-recursive-minibuffers t)
1724          (files (find-lisp-find-files org-attach-directory "."))
1725          (file-assoc-list
1726           (mapcar (lambda (x)
1727                     (cons (file-name-nondirectory x)
1728                           x))
1729                   files))
1730          (filename-list
1731           (remove-duplicates (mapcar #'car file-assoc-list)
1732                              :test #'string=))
1733          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1734          (longname (cdr (assoc filename file-assoc-list))))
1735     (ido-set-current-directory
1736      (if (file-directory-p longname)
1737          longname
1738        (file-name-directory longname)))
1739     (setq ido-exit 'refresh
1740           ido-text-init ido-text
1741           ido-rotate-temp t)
1742     (exit-minibuffer)))
1744 (add-hook 'ido-setup-hook 'ido-my-keys)
1746 (defun ido-my-keys ()
1747   "Add my keybindings for ido."
1748   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1749 #+end_src
1751 To browse your org attachments using ido fuzzy matching and/or the
1752 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1753 press =C-;=.
1755 ** Use idle timer for automatic agenda views
1757 From John Wiegley's mailing list post (March 18, 2010):
1759 #+begin_quote
1760 I have the following snippet in my .emacs file, which I find very
1761 useful. Basically what it does is that if I don't touch my Emacs for 5
1762 minutes, it displays the current agenda. This keeps my tasks "always
1763 in mind" whenever I come back to Emacs after doing something else,
1764 whereas before I had a tendency to forget that it was there.
1765 #+end_quote
1767   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1769 #+begin_src emacs-lisp
1770 (defun jump-to-org-agenda ()
1771   (interactive)
1772   (let ((buf (get-buffer "*Org Agenda*"))
1773         wind)
1774     (if buf
1775         (if (setq wind (get-buffer-window buf))
1776             (select-window wind)
1777           (if (called-interactively-p)
1778               (progn
1779                 (select-window (display-buffer buf t t))
1780                 (org-fit-window-to-buffer)
1781                 ;; (org-agenda-redo)
1782                 )
1783             (with-selected-window (display-buffer buf)
1784               (org-fit-window-to-buffer)
1785               ;; (org-agenda-redo)
1786               )))
1787       (call-interactively 'org-agenda-list)))
1788   ;;(let ((buf (get-buffer "*Calendar*")))
1789   ;;  (unless (get-buffer-window buf)
1790   ;;    (org-agenda-goto-calendar)))
1791   )
1793 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1794 #+end_src
1796 #+results:
1797 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1799 ** Link to Gnus messages by Message-Id
1801 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1802 discussion about linking to Gnus messages without encoding the folder
1803 name in the link.  The following code hooks in to the store-link
1804 function in Gnus to capture links by Message-Id when in nnml folders,
1805 and then provides a link type "mid" which can open this link.  The
1806 =mde-org-gnus-open-message-link= function uses the
1807 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1808 scan.  It will go through them, in order, asking each to locate the
1809 message and opening it from the first one that reports success.
1811 It has only been tested with a single nnml backend, so there may be
1812 bugs lurking here and there.
1814 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1815 article]].
1817 #+begin_src emacs-lisp
1818 ;; Support for saving Gnus messages by Message-ID
1819 (defun mde-org-gnus-save-by-mid ()
1820   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1821     (when (eq major-mode 'gnus-article-mode)
1822       (gnus-article-show-summary))
1823     (let* ((group gnus-newsgroup-name)
1824            (method (gnus-find-method-for-group group)))
1825       (when (eq 'nnml (car method))
1826         (let* ((article (gnus-summary-article-number))
1827                (header (gnus-summary-article-header article))
1828                (from (mail-header-from header))
1829                (message-id
1830                 (save-match-data
1831                   (let ((mid (mail-header-id header)))
1832                     (if (string-match "<\\(.*\\)>" mid)
1833                         (match-string 1 mid)
1834                       (error "Malformed message ID header %s" mid)))))
1835                (date (mail-header-date header))
1836                (subject (gnus-summary-subject-string)))
1837           (org-store-link-props :type "mid" :from from :subject subject
1838                                 :message-id message-id :group group
1839                                 :link (org-make-link "mid:" message-id))
1840           (apply 'org-store-link-props
1841                  :description (org-email-link-description)
1842                  org-store-link-plist)
1843           t)))))
1845 (defvar mde-mid-resolve-methods '()
1846   "List of methods to try when resolving message ID's.  For Gnus,
1847 it is a cons of 'gnus and the select (type and name).")
1848 (setq mde-mid-resolve-methods
1849       '((gnus nnml "")))
1851 (defvar mde-org-gnus-open-level 1
1852   "Level at which Gnus is started when opening a link")
1853 (defun mde-org-gnus-open-message-link (msgid)
1854   "Open a message link with Gnus"
1855   (require 'gnus)
1856   (require 'org-table)
1857   (catch 'method-found
1858     (message "[MID linker] Resolving %s" msgid)
1859     (dolist (method mde-mid-resolve-methods)
1860       (cond
1861        ((and (eq (car method) 'gnus)
1862              (eq (cadr method) 'nnml))
1863         (funcall (cdr (assq 'gnus org-link-frame-setup))
1864                  mde-org-gnus-open-level)
1865         (when gnus-other-frame-object
1866           (select-frame gnus-other-frame-object))
1867         (let* ((msg-info (nnml-find-group-number
1868                           (concat "<" msgid ">")
1869                           (cdr method)))
1870                (group (and msg-info (car msg-info)))
1871                (message (and msg-info (cdr msg-info)))
1872                (qname (and group
1873                            (if (gnus-methods-equal-p
1874                                 (cdr method)
1875                                 gnus-select-method)
1876                                group
1877                              (gnus-group-full-name group (cdr method))))))
1878           (when msg-info
1879             (gnus-summary-read-group qname nil t)
1880             (gnus-summary-goto-article message nil t))
1881           (throw 'method-found t)))
1882        (t (error "Unknown link type"))))))
1884 (eval-after-load 'org-gnus
1885   '(progn
1886      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1887      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1888 #+end_src
1890 ** Store link upon sending a message in Gnus
1892 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1894 #+begin_src emacs-lisp
1895 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1896   "Send message with `message-send-and-exit' and store org link to message copy.
1897 If multiple groups appear in the Gcc header, the link refers to
1898 the copy in the last group."
1899   (interactive "P")
1900     (save-excursion
1901       (save-restriction
1902         (message-narrow-to-headers)
1903         (let ((gcc (car (last
1904                          (message-unquote-tokens
1905                           (message-tokenize-header
1906                            (mail-fetch-field "gcc" nil t) " ,")))))
1907               (buf (current-buffer))
1908               (message-kill-buffer-on-exit nil)
1909               id to from subject desc link newsgroup xarchive)
1910         (message-send-and-exit arg)
1911         (or
1912          ;; gcc group found ...
1913          (and gcc
1914               (save-current-buffer
1915                 (progn (set-buffer buf)
1916                        (setq id (org-remove-angle-brackets
1917                                  (mail-fetch-field "Message-ID")))
1918                        (setq to (mail-fetch-field "To"))
1919                        (setq from (mail-fetch-field "From"))
1920                        (setq subject (mail-fetch-field "Subject"))))
1921               (org-store-link-props :type "gnus" :from from :subject subject
1922                                     :message-id id :group gcc :to to)
1923               (setq desc (org-email-link-description))
1924               (setq link (org-gnus-article-link
1925                           gcc newsgroup id xarchive))
1926               (setq org-stored-links
1927                     (cons (list link desc) org-stored-links)))
1928          ;; no gcc group found ...
1929          (message "Can not create Org link: No Gcc header found."))))))
1931 (define-key message-mode-map [(control c) (control meta c)]
1932   'ulf-message-send-and-org-gnus-store-link)
1933 #+end_src
1935 ** Send html messages and attachments with Wanderlust
1936   -- David Maus
1938 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1939 similar functionality for both Wanderlust and Gnus.  The hack below is
1940 still somewhat different: It allows you to toggle sending of html
1941 messages within Wanderlust transparently.  I.e. html markup of the
1942 message body is created right before sending starts.
1944 *** Send HTML message
1946 Putting the code below in your .emacs adds following four functions:
1948 - dmj/wl-send-html-message
1950   Function that does the job: Convert everything between "--text
1951   follows this line--" and first mime entity (read: attachment) or
1952   end of buffer into html markup using `org-export-region-as-html'
1953   and replaces original body with a multipart MIME entity with the
1954   plain text version of body and the html markup version.  Thus a
1955   recipient that prefers html messages can see the html markup,
1956   recipients that prefer or depend on plain text can see the plain
1957   text.
1959   Cannot be called interactively: It is hooked into SEMI's
1960   `mime-edit-translate-hook' if message should be HTML message.
1962 - dmj/wl-send-html-message-draft-init
1964   Cannot be called interactively: It is hooked into WL's
1965   `wl-mail-setup-hook' and provides a buffer local variable to
1966   toggle.
1968 - dmj/wl-send-html-message-draft-maybe
1970   Cannot be called interactively: It is hooked into WL's
1971   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1972   `mime-edit-translate-hook' depending on whether HTML message is
1973   toggled on or off
1975 - dmj/wl-send-html-message-toggle
1977   Toggles sending of HTML message.  If toggled on, the letters
1978   "HTML" appear in the mode line.
1980   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1982 If you have to send HTML messages regularly you can set a global
1983 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1984 toggle on sending HTML message by default.
1986 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1987 Google's web front end.  As you can see you have the whole markup of
1988 Org at your service: *bold*, /italics/, tables, lists...
1990 So even if you feel uncomfortable with sending HTML messages at least
1991 you send HTML that looks quite good.
1993 #+begin_src emacs-lisp
1994 (defun dmj/wl-send-html-message ()
1995   "Send message as html message.
1996 Convert body of message to html using
1997   `org-export-region-as-html'."
1998   (require 'org)
1999   (save-excursion
2000     (let (beg end html text)
2001       (goto-char (point-min))
2002       (re-search-forward "^--text follows this line--$")
2003       ;; move to beginning of next line
2004       (beginning-of-line 2)
2005       (setq beg (point))
2006       (if (not (re-search-forward "^--\\[\\[" nil t))
2007           (setq end (point-max))
2008         ;; line up
2009         (end-of-line 0)
2010         (setq end (point)))
2011       ;; grab body
2012       (setq text (buffer-substring-no-properties beg end))
2013       ;; convert to html
2014       (with-temp-buffer
2015         (org-mode)
2016         (insert text)
2017         ;; handle signature
2018         (when (re-search-backward "^-- \n" nil t)
2019           ;; preserve link breaks in signature
2020           (insert "\n#+BEGIN_VERSE\n")
2021           (goto-char (point-max))
2022           (insert "\n#+END_VERSE\n")
2023           ;; grab html
2024           (setq html (org-export-region-as-html
2025                       (point-min) (point-max) t 'string))))
2026       (delete-region beg end)
2027       (insert
2028        (concat
2029         "--" "<<alternative>>-{\n"
2030         "--" "[[text/plain]]\n" text
2031         "--" "[[text/html]]\n"  html
2032         "--" "}-<<alternative>>\n")))))
2034 (defun dmj/wl-send-html-message-toggle ()
2035   "Toggle sending of html message."
2036   (interactive)
2037   (setq dmj/wl-send-html-message-toggled-p
2038         (if dmj/wl-send-html-message-toggled-p
2039             nil "HTML"))
2040   (message "Sending html message toggled %s"
2041            (if dmj/wl-send-html-message-toggled-p
2042                "on" "off")))
2044 (defun dmj/wl-send-html-message-draft-init ()
2045   "Create buffer local settings for maybe sending html message."
2046   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2047     (setq dmj/wl-send-html-message-toggled-p nil))
2048   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2049   (add-to-list 'global-mode-string
2050                '(:eval (if (eq major-mode 'wl-draft-mode)
2051                            dmj/wl-send-html-message-toggled-p))))
2053 (defun dmj/wl-send-html-message-maybe ()
2054   "Maybe send this message as html message.
2056 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2057 non-nil, add `dmj/wl-send-html-message' to
2058 `mime-edit-translate-hook'."
2059   (if dmj/wl-send-html-message-toggled-p
2060       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2061     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2063 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2064 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2065 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2066 #+end_src
2068 *** Attach HTML of region or subtree
2070 Instead of sending a complete HTML message you might only send parts
2071 of an Org file as HTML for the poor souls who are plagued with
2072 non-proportional fonts in their mail program that messes up pretty
2073 ASCII tables.
2075 This short function does the trick: It exports region or subtree to
2076 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2077 and clipboard.  If a region is active, it uses the region, the
2078 complete subtree otherwise.
2080 #+begin_src emacs-lisp
2081 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2082   "Export region between BEG and END as html attachment.
2083 If BEG and END are not set, use current subtree.  Region or
2084 subtree is exported to html without header and footer, prefixed
2085 with a mime entity string and pushed to clipboard and killring.
2086 When called with prefix, mime entity is not marked as
2087 attachment."
2088   (interactive "r\nP")
2089   (save-excursion
2090     (let* ((beg (if (region-active-p) (region-beginning)
2091                   (progn
2092                     (org-back-to-heading)
2093                     (point))))
2094            (end (if (region-active-p) (region-end)
2095                   (progn
2096                     (org-end-of-subtree)
2097                     (point))))
2098            (html (concat "--[[text/html"
2099                          (if arg "" "\nContent-Disposition: attachment")
2100                          "]]\n"
2101                          (org-export-region-as-html beg end t 'string))))
2102       (when (fboundp 'x-set-selection)
2103         (ignore-errors (x-set-selection 'PRIMARY html))
2104         (ignore-errors (x-set-selection 'CLIPBOARD html)))
2105       (message "html export done, pushed to kill ring and clipboard"))))
2106 #+end_src
2108 *** Adopting for Gnus
2110 The whole magic lies in the special strings that mark a HTML
2111 attachment.  So you might just have to find out what these special
2112 strings are in message-mode and modify the functions accordingly.
2113 ** Add sunrise/sunset times to the agenda.
2114   -- Nick Dokos
2116 The diary package provides the function =diary-sunrise-sunset= which can be used
2117 in a diary s-expression in some agenda file like this:
2119 #+begin_src org-mode
2120 %%(diary-sunrise-sunset)
2121 #+end_src
2123 Seb Vauban asked if it is possible to put sunrise and sunset in
2124 separate lines. Here is a hack to do that. It adds two functions (they
2125 have to be available before the agenda is shown, so I add them early
2126 in my org-config file which is sourced from .emacs, but you'll have to
2127 suit yourself here) that just parse the output of
2128 diary-sunrise-sunset, instead of doing the right thing which would be
2129 to take advantage of the data structures that diary/solar.el provides.
2130 In short, a hack - so perfectly suited for inclusion here :-)
2132 The functions (and latitude/longitude settings which you have to modify for
2133 your location) are as follows:
2135 #+begin_src emacs-lisp
2136 (setq calendar-latitude 40.3)
2137 (setq calendar-longitude -71.0)
2138 (defun diary-sunrise ()
2139   (let ((dss (diary-sunrise-sunset)))
2140     (with-temp-buffer
2141       (insert dss)
2142       (goto-char (point-min))
2143       (while (re-search-forward " ([^)]*)" nil t)
2144         (replace-match "" nil nil))
2145       (goto-char (point-min))
2146       (search-forward ",")
2147       (buffer-substring (point-min) (match-beginning 0)))))
2149 (defun diary-sunset ()
2150   (let ((dss (diary-sunrise-sunset))
2151         start end)
2152     (with-temp-buffer
2153       (insert dss)
2154       (goto-char (point-min))
2155       (while (re-search-forward " ([^)]*)" nil t)
2156         (replace-match "" nil nil))
2157       (goto-char (point-min))
2158       (search-forward ", ")
2159       (setq start (match-end 0))
2160       (search-forward " at")
2161       (setq end (match-beginning 0))
2162       (goto-char start)
2163       (capitalize-word 1)
2164       (buffer-substring start end))))
2165 #+end_src
2167 You also need to add a couple of diary s-expressions in one of your agenda
2168 files:
2170 #+begin_src org-mode
2171 %%(diary-sunrise)
2172 %%(diary-sunset)
2173 #+end_src
2175 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]].
2176 In comparison to the version posted on the mailing list, this one
2177 gets rid of the timezone information.
2178 ** Export BBDB contacts to org-contacts.el
2180 Try this tool by Wes Hardaker:
2182 http://www.hardakers.net/code/bbdb-to-org-contacts/
2184 * Hacking Org: Working with Org-mode and External Programs.
2188 : I've [...] created some procmail and shell glue that takes emails and
2189 : inserts them into an org-file so that I can capture stuff on the go using
2190 : the email program.
2192 That's [[http://tychoish.com/code/org-mail/][here]].
2194 ** Use Org-mode with Screen [Andrew Hyatt]
2196 "The general idea is that you start a task in which all the work will
2197 take place in a shell.  This usually is not a leaf-task for me, but
2198 usually the parent of a leaf task.  From a task in your org-file, M-x
2199 ash-org-screen will prompt for the name of a session.  Give it a name,
2200 and it will insert a link.  Open the link at any time to go the screen
2201 session containing your work!"
2203 http://article.gmane.org/gmane.emacs.orgmode/5276
2205 #+BEGIN_SRC emacs-lisp
2206 (require 'term)
2208 (defun ash-org-goto-screen (name)
2209   "Open the screen with the specified name in the window"
2210   (interactive "MScreen name: ")
2211   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2212     (if (member screen-buffer-name
2213                 (mapcar 'buffer-name (buffer-list)))
2214         (switch-to-buffer screen-buffer-name)
2215       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2217 (defun ash-org-screen-buffer-name (name)
2218   "Returns the buffer name corresponding to the screen name given."
2219   (concat "*screen " name "*"))
2221 (defun ash-org-screen-helper (name arg)
2222   ;; Pick the name of the new buffer.
2223   (let ((term-ansi-buffer-name
2224          (generate-new-buffer-name
2225           (ash-org-screen-buffer-name name))))
2226     (setq term-ansi-buffer-name
2227           (term-ansi-make-term
2228            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2229     (set-buffer term-ansi-buffer-name)
2230     (term-mode)
2231     (term-char-mode)
2232     (term-set-escape-char ?\C-x)
2233     term-ansi-buffer-name))
2235 (defun ash-org-screen (name)
2236   "Start a screen session with name"
2237   (interactive "MScreen name: ")
2238   (save-excursion
2239     (ash-org-screen-helper name "-S"))
2240   (insert-string (concat "[[screen:" name "]]")))
2242 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2243 ;; \"%s\")") to org-link-abbrev-alist.
2244 #+END_SRC
2246 ** Org Agenda + Appt + Zenity
2247 #+BEGIN_HTML
2248 <a name="agenda-appt-zenity"></a>
2249 #+END_HTML
2250 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It makes sure your agenda
2251 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2252 popup window.
2254 #+BEGIN_SRC emacs-lisp
2255 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2256 ; For org appointment reminders
2258 ;; Get appointments for today
2259 (defun my-org-agenda-to-appt ()
2260   (interactive)
2261   (setq appt-time-msg-list nil)
2262   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
2263         (org-agenda-to-appt)))
2265 ;; Run once, activate and schedule refresh
2266 (my-org-agenda-to-appt)
2267 (appt-activate t)
2268 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2270 ; 5 minute warnings
2271 (setq appt-message-warning-time 15)
2272 (setq appt-display-interval 5)
2274 ; Update appt each time agenda opened.
2275 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2277 ; Setup zenify, we tell appt to use window, and replace default function
2278 (setq appt-display-format 'window)
2279 (setq appt-disp-window-function (function my-appt-disp-window))
2281 (defun my-appt-disp-window (min-to-app new-time msg)
2282   (save-window-excursion (shell-command (concat
2283     "/usr/bin/zenity --info --title='Appointment' --text='"
2284     msg "' &") nil nil)))
2285 #+END_SRC
2287 ** Org-Mode + gnome-osd
2289 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2290 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2292 ** remind2org
2294 From Detlef Steuer
2296 http://article.gmane.org/gmane.emacs.orgmode/5073
2298 #+BEGIN_QUOTE
2299 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2300 command line calendaring program. Its features superseed the possibilities
2301 of orgmode in the area of date specifying, so that I want to use it
2302 combined with orgmode.
2304 Using the script below I'm able use remind and incorporate its output in my
2305 agenda views.  The default of using 13 months look ahead is easily
2306 changed. It just happens I sometimes like to look a year into the
2307 future. :-)
2308 #+END_QUOTE
2310 ** Useful webjumps for conkeror
2312 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2313 your =~/.conkerorrc= file:
2315 #+begin_example
2316 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2317 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2318 #+end_example
2320 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2321 Org-mode mailing list.
2323 ** Use MathJax for HTML export without requiring JavaScript
2324 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2326 If you like the results but do not want JavaScript in the exported pages,
2327 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2328 HTML file from the exported version. It can also embed all referenced fonts
2329 within the HTML file itself, so there are no dependencies to external files.
2331 The download archive contains an elisp file which integrates it into the Org
2332 export process (configurable per file with a "#+StaticMathJax:" line).
2334 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2335 ** Search Org files using lgrep
2337 Matt Lundin suggests this:
2339 #+begin_src emacs-lisp
2340   (defun my-org-grep (search &optional context)
2341     "Search for word in org files.
2343 Prefix argument determines number of lines."
2344     (interactive "sSearch for: \nP")
2345     (let ((grep-find-ignored-files '("#*" ".#*"))
2346           (grep-template (concat "grep <X> -i -nH "
2347                                  (when context
2348                                    (concat "-C" (number-to-string context)))
2349                                  " -e <R> <F>")))
2350       (lgrep search "*org*" "/home/matt/org/")))
2352   (global-set-key (kbd "<f8>") 'my-org-grep)
2353 #+end_src
2355 ** Automatic screenshot insertion
2357 Suggested by Russell Adams
2359 #+begin_src emacs-lisp
2360   (defun my-org-screenshot ()
2361     "Take a screenshot into a time stamped unique-named file in the
2362   same directory as the org-buffer and insert a link to this file."
2363     (interactive)
2364     (setq filename
2365           (concat
2366            (make-temp-name
2367             (concat (buffer-file-name)
2368                     "_"
2369                     (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
2370     (call-process "import" nil nil nil filename)
2371     (insert (concat "[[" filename "]]"))
2372     (org-display-inline-images))
2373 #+end_src
2375 ** Capture invitations/appointments from MS Exchange emails
2377 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this.  Please check
2378 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
2380 ** Audio/video file playback within org mode
2382 Paul Sexton provided code that makes =file:= links to audio or video files
2383 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
2384 media player library. The user can pause, skip forward and backward in the
2385 track, and so on from without leaving Emacs. Links can also contain a time
2386 after a double colon -- when this is present, playback will begin at that
2387 position in the track.
2389 See the file [[file:code/elisp/org-player.el][org-player.el]]
2391 ** Under X11 Keep a window with the current agenda items at all time
2393 I struggle to keep (in emacs) a window with the agenda at all times.
2394 For a long time I have wanted a sticky window that keeps this
2395 information, and then use my window manager to place it and remove its
2396 decorations (I can also force its placement in the stack: top always,
2397 for example).
2399 I wrote a small program in qt that simply monitors an HTML file and
2400 displays it. Nothing more. It does the work for me, and maybe somebody
2401 else will find it useful. It relies on exporting the agenda as HTML
2402 every time the org file is saved, and then this little program
2403 displays the html file. The window manager is responsible of removing
2404 decorations, making it sticky, and placing it in same place always.
2406 Here is a screenshot (see window to the bottom right). The decorations
2407 are removed by the window manager:
2409 http://turingmachine.org/hacking/org-mode/orgdisplay.png
2411 Here is the code. As I said, very, very simple, but maybe somebody will
2412 find if useful.
2414 http://turingmachine.org/hacking/org-mode/
2416 --daniel german
2418 ** Script (thru procmail) to output emails to an Org file
2420 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
2421 * Musings
2423 ** Cooking?  Brewing?
2425 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
2427 It currently does metric/english conversion, and a few other tricks.
2428 Basically I just use calc’s units code.  I think scaling recipes, or
2429 turning percentages into weights would be pretty easy.
2431   https://gitorious.org/org-cook/org-cook
2433 There is also, for those interested:
2435   https://gitorious.org/org-brew/org-brew
2437 for brewing beer. This is again, mostly just calc functions, including
2438 hydrometer correction, abv calculation, priming sugar for a given CO_2
2439 volume, etc. More integration with org-mode should be possible: for
2440 instance it would be nice to be able to use a lookup table (of ingredients)
2441 to calculate target original gravity, IBUs, etc.