Rephrase the link to MobileOrg for Android
[Worg.git] / org-hacks.org
blob75f18f13868c2b4e15c7f85b83d18fa21bedde92
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 table
459     :PROPERTIES:
460     :CUSTOM_ID: transpose-table
461     :END:
463 This function by Juan Pechiar will transpose a table:
465 #+begin_src emacs-lisp
466 (defun org-transpose-table-at-point ()
467   "Transpose orgmode table at point, eliminate hlines"
468   (interactive)
469   (let ((contents
470          (apply #'mapcar* #'list
471                 ;; remove 'hline from list
472                 (remove-if-not 'listp
473                                ;; signals error if not table
474                                (org-table-to-lisp)))))
475     (delete-region (org-table-begin) (org-table-end))
476     (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) "  |\n" ))
477                        contents ""))
478     (org-table-align)))
479 #+end_src
481 So a table like
483 : | 1 | 2 | 4 | 5 |
484 : |---+---+---+---|
485 : | a | b | c | d |
486 : | e | f | g | h |
488 will be transposed as
490 : | 1 | a | e |
491 : | 2 | b | f |
492 : | 4 | c | g |
493 : | 5 | d | h |
495 (Note that horizontal lines disappeared.)
497 There are also other solutions:
498 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
499   list, see
500   [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][gmane]]
501   or
502   [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00239.html][gnu]]
503 - with org-babel and R: provided by Dan Davison in the mailing list (old
504   =#+TBLR:= syntax), see
505   [[http://thread.gmane.org/gmane.emacs.orgmode/10159/focus=10159][gmane]]
506   or
507   [[http://lists.gnu.org/archive/html/emacs-orgmode/2008-12/msg00454.html][gnu]]
508 - with field coordinates in formulas (=@#= and =$#=): see
509   [[file:org-hacks.org::#field-coordinates-in-formulas-transpose-table][Worg]].
511 *** Manipulate hours/minutes/seconds in table formulas
513 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
514 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
515 "=d=" is any digit) as time values in Org-mode table formula.  These
516 functions have now been wrapped up into a =with-time= macro which can
517 be used in table formula to translate table cell values to and from
518 numerical values for algebraic manipulation.
520 Here is the code implementing this macro.
521 #+begin_src emacs-lisp :results silent
522   (defun org-time-string-to-seconds (s)
523     "Convert a string HH:MM:SS to a number of seconds."
524     (cond
525      ((and (stringp s)
526            (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
527       (let ((hour (string-to-number (match-string 1 s)))
528             (min (string-to-number (match-string 2 s)))
529             (sec (string-to-number (match-string 3 s))))
530         (+ (* hour 3600) (* min 60) sec)))
531      ((and (stringp s)
532            (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
533       (let ((min (string-to-number (match-string 1 s)))
534             (sec (string-to-number (match-string 2 s))))
535         (+ (* min 60) sec)))
536      ((stringp s) (string-to-number s))
537      (t s)))
539   (defun org-time-seconds-to-string (secs)
540     "Convert a number of seconds to a time string."
541     (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
542           ((>= secs 60) (format-seconds "%m:%.2s" secs))
543           (t (format-seconds "%s" secs))))
545   (defmacro with-time (time-output-p &rest exprs)
546     "Evaluate an org-table formula, converting all fields that look
547   like time data to integer seconds.  If TIME-OUTPUT-P then return
548   the result as a time value."
549     (list
550      (if time-output-p 'org-time-seconds-to-string 'identity)
551      (cons 'progn
552            (mapcar
553             (lambda (expr)
554               `,(cons (car expr)
555                       (mapcar
556                        (lambda (el)
557                          (if (listp el)
558                              (list 'with-time nil el)
559                            (org-time-string-to-seconds el)))
560                        (cdr expr))))
561             `,@exprs))))
562 #+end_src
564 Which allows the following forms of table manipulation such as adding
565 and subtracting time values.
566 : | Date             | Start | Lunch |  Back |   End |  Sum |
567 : |------------------+-------+-------+-------+-------+------|
568 : | [2011-03-01 Tue] |  8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
569 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
571 and dividing time values by integers
572 : |  time | miles | minutes/mile |
573 : |-------+-------+--------------|
574 : | 34:43 |   2.9 |        11:58 |
575 : | 32:15 |  2.77 |        11:38 |
576 : | 33:56 |   3.0 |        11:18 |
577 : | 52:22 |  4.62 |        11:20 |
578 : #+TBLFM: $3='(with-time t (/ $1 $2))
580 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
581 Elisp formulas) to compute time durations.  For example:
583 : | Task 1 | Task 2 |   Total |
584 : |--------+--------+---------|
585 : |  35:00 |  35:00 | 1:10:00 |
586 : #+TBLFM: @2$3=$1+$2;T
588 *** Dates computation
590 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of 
591 dates stored in an org table.
593 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
595 Try the following:
597 | Start Date |   End Date | Duration |
598 |------------+------------+----------|
599 | 2004.08.07 | 2005.07.08 |      335 |
600 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
602 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
603 above).  The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
604 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
606 *** Hex computation
608 As with Times computation, the following code allows Computation with
609 Hex values in Org-mode tables using the =with-hex= macro.
611 Here is the code implementing this macro.
612 #+begin_src emacs-lisp
613   (defun org-hex-strip-lead (str)
614     (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
615         (substring str 2) str))
617   (defun org-hex-to-hex (int)
618     (format "0x%x" int))
620   (defun org-hex-to-dec (str)
621     (cond
622      ((and (stringp str)
623            (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
624       (let ((out 0))
625         (mapc
626          (lambda (ch)
627            (setf out (+ (* out 16)
628                         (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
629          (coerce (match-string 1 str) 'list))
630         out))
631      ((stringp str) (string-to-number str))
632      (t str)))
634   (defmacro with-hex (hex-output-p &rest exprs)
635     "Evaluate an org-table formula, converting all fields that look
636       like hexadecimal to decimal integers.  If HEX-OUTPUT-P then
637       return the result as a hex value."
638     (list
639      (if hex-output-p 'org-hex-to-hex 'identity)
640      (cons 'progn
641            (mapcar
642             (lambda (expr)
643               `,(cons (car expr)
644                       (mapcar (lambda (el)
645                                 (if (listp el)
646                                     (list 'with-hex nil el)
647                                   (org-hex-to-dec el)))
648                               (cdr expr))))
649             `,@exprs))))
650 #+end_src
652 Which allows the following forms of table manipulation such as adding
653 and subtracting hex values.
654 | 0x10 | 0x0 | 0x10 |  16 |
655 | 0x20 | 0x1 | 0x21 |  33 |
656 | 0x30 | 0x2 | 0x32 |  50 |
657 | 0xf0 | 0xf | 0xff | 255 |
658 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
660 *** Field coordinates in formulas (=@#= and =$#=)
661     :PROPERTIES:
662     :CUSTOM_ID: field-coordinates-in-formulas
663     :END:
665 -- Michael Brand
667 Following are some use cases that can be implemented with the “field
668 coordinates in formulas” described in the corresponding chapter in the
669 [[http://orgmode.org/manual/References.html#References][Org manual]].
671 **** Copy a column from a remote table into a column
672      :PROPERTIES:
673      :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
674      :END:
676 current column =$3= = remote column =$2=:
677 : #+TBLFM: $3 = remote(FOO, @@#$2)
679 **** Copy a row from a remote table transposed into a column
680      :PROPERTIES:
681      :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
682      :END:
684 current column =$1= = transposed remote row =@1=:
685 : #+TBLFM: $1 = remote(FOO, @$#$@#)
687 **** Transpose table
688      :PROPERTIES:
689      :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
690      :END:
692 -- Michael Brand
694 This is more like a demonstration of using “field coordinates in formulas”
695 and is bound to be slow for large tables. See the discussion in the mailing
696 list on
697 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
698 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
699 For more efficient solutions see
700 [[file:org-hacks.org::#transpose-table][Worg]].
702 To transpose this 4x7 table
704 : #+TBLNAME: FOO
705 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
706 : |------+------+------+------+------+------+------|
707 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
708 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
709 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
711 start with a 7x4 table without any horizontal line (to have filled
712 also the column header) and yet empty:
714 : |   |   |   |   |
715 : |   |   |   |   |
716 : |   |   |   |   |
717 : |   |   |   |   |
718 : |   |   |   |   |
719 : |   |   |   |   |
720 : |   |   |   |   |
722 Then add the =TBLFM= line below.  After recalculation this will end up with
723 the transposed copy:
725 : | year | min | avg | max |
726 : | 2004 | 401 | 402 | 403 |
727 : | 2005 | 501 | 502 | 503 |
728 : | 2006 | 601 | 602 | 603 |
729 : | 2007 | 701 | 702 | 703 |
730 : | 2008 | 801 | 802 | 803 |
731 : | 2009 | 901 | 902 | 903 |
732 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
734 The formula simply exchanges row and column numbers by taking
735 - the absolute remote row number =@$#= from the current column number =$#=
736 - the absolute remote column number =$@#= from the current row number =@#=
738 Formulas to be taken over from the remote table will have to be transformed
739 manually.
741 **** Dynamic variation of ranges
743 -- Michael Brand
745 In this example all columns next to =quote= are calculated from the column
746 =quote= and show the average change of the time series =quote[year]=
747 during the period of the preceding =1=, =2=, =3= or =4= years:
749 : | year | quote |   1 a |   2 a |   3 a |   4 a |
750 : |------+-------+-------+-------+-------+-------|
751 : | 2005 |    10 |       |       |       |       |
752 : | 2006 |    12 | 0.200 |       |       |       |
753 : | 2007 |    14 | 0.167 | 0.183 |       |       |
754 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
755 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
756 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
758 The important part of the formula without the field blanking is:
760 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
762 which is the Emacs Calc implementation of the equation
764 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
766 where /i/ is the current time and /a/ is the length of the preceding period.
768 *** Change the column sequence in one row only
769     :PROPERTIES:
770     :CUSTOM_ID: column-sequence-in-row
771     :END:
773 -- Michael Brand
775 The functions below can be used to change the column sequence in one row
776 only, without affecting the other rows above and below like with M-<left> or
777 M-<right> (org-table-move-column). Please see the docstring of the functions
778 for more explanations. Below is one example per function, with this original
779 table as the starting point for each example:
780 : | a | b | c  | d  |
781 : | e | 9 | 10 | 11 |
782 : | f | g | h  | i  |
784 **** Move in row left
786 1) place point at "10" in original table
787 2) result of M-x my-org-table-move-column-in-row-left
788 : | a | b  | c | d  |
789 : | e | 10 | 9 | 11 |
790 : | f | g  | h | i  |
792 **** Move in row right
794 1) place point at "9" in original table
795 2) result of M-x my-org-table-move-column-in-row-right
796 : | a | b  | c | d  |
797 : | e | 10 | 9 | 11 |
798 : | f | g  | h | i  |
800 **** Rotate in row left
802 1) place point at "9" in original table
803 2) result of M-x my-org-table-rotate-column-in-row-left
804 : | a | b  | c  | d |
805 : | e | 10 | 11 | 9 |
806 : | f | g  | h  | i |
808 **** Rotate in row right
810 1) place point at "9" in original table
811 2) result of M-x my-org-table-rotate-column-in-row-right
812 : | a | b  | c | d  |
813 : | e | 11 | 9 | 10 |
814 : | f | g  | h | i  |
816 **** The functions
818 #+BEGIN_SRC emacs-lisp
819 (defun my-org-table-move-column-in-row-right ()
820   "Move column to the right, limited to the current row."
821   (interactive)
822   (my-org-table-move-column-in-row nil))
823 (defun my-org-table-move-column-in-row-left ()
824   "Move column to the left, limited to the current row."
825   (interactive)
826   (my-org-table-move-column-in-row 'left))
828 (defun my-org-table-move-column-in-row (&optional left)
829   "Move the current column to the right, limited to the current row.
830 With arg LEFT, move to the left.  For repeated invocation the point follows
831 the value and changes to the target colum.  Does not fix formulas."
832   ;; derived from `org-table-move-column'
833   (interactive "P")
834   (if (not (org-at-table-p))
835       (error "Not at a table"))
836   (org-table-find-dataline)
837   (org-table-check-inside-data-field)
838   (let* ((col (org-table-current-column))
839          (col1 (if left (1- col) col))
840          ;; Current cursor position
841          (colpos (if left (1- col) (1+ col))))
842     (if (and left (= col 1))
843         (error "Cannot move column further left"))
844     (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
845         (error "Cannot move column further right"))
846     (org-table-goto-column col1 t)
847     (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
848          (replace-match "|\\2|\\1|"))
849     (org-table-goto-column colpos)
850     (org-table-align)))
852 (defun my-org-table-rotate-column-in-row-right ()
853   "Rotate column to the right, limited to the current row."
854   (interactive)
855   (my-org-table-rotate-column-in-row nil))
856 (defun my-org-table-rotate-column-in-row-left ()
857   "Rotate column to the left, limited to the current row."
858   (interactive)
859   (my-org-table-rotate-column-in-row 'left))
861 (defun my-org-table-rotate-column-in-row (&optional left)
862   "Rotate the current column to the right, limited to the current row.
863 With arg LEFT, rotate to the left.  The boundaries of the rotation range are
864 the current and the most right column for both directions.  For repeated
865 invocation the point stays on the current column.  Does not fix formulas."
866   ;; derived from `org-table-move-column'
867   (interactive "P")
868   (if (not (org-at-table-p))
869       (error "Not at a table"))
870   (org-table-find-dataline)
871   (org-table-check-inside-data-field)
872   (let ((col (org-table-current-column)))
873     (org-table-goto-column col t)
874     (and (looking-at (if left
875                          "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
876                        "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
877          (replace-match "|\\2|\\1|"))
878     (org-table-goto-column col)
879     (org-table-align)))
880 #+END_SRC
882 **** Key bindings
884 As hack I have this in an Org buffer to change temporarily to the desired
885 behavior with C-c C-c on one of the three snippets:
886 : - move in row:
887 :   #+begin_src emacs-lisp :results silent
888 :     (org-defkey org-mode-map [(meta left)]
889 :                 'my-org-table-move-column-in-row-left)
890 :     (org-defkey org-mode-map [(meta right)]
891 :                 'my-org-table-move-column-in-row-right)
892 :   #+end_src
894 : - rotate in row:
895 :   #+begin_src emacs-lisp :results silent
896 :     (org-defkey org-mode-map [(meta left)]
897 :                 'my-org-table-rotate-column-in-row-left)
898 :     (org-defkey org-mode-map [(meta right)]
899 :                 'my-org-table-rotate-column-in-row-right)
900 :   #+end_src
902 : - back to original:
903 :   #+begin_src emacs-lisp :results silent
904 :     (org-defkey org-mode-map [(meta left)]  'org-metaleft)
905 :     (org-defkey org-mode-map [(meta right)] 'org-metaright)
906 :   #+end_src
908 ** Capture and Remember
909 *** Customize the size of the frame for remember
910 (Note: this hack is likely out of date due to the development of
911 [[org-capture]].)
913 #FIXME: gmane link?
914 On emacs-orgmode, Ryan C. Thompson suggested this:
916 #+begin_quote
917 I am using org-remember set to open a new frame when used,
918 and the default frame size is much too large. To fix this, I have
919 designed some advice and a custom variable to implement custom
920 parameters for the remember frame:
921 #+end_quote
923 #+begin_src emacs-lisp
924 (defcustom remember-frame-alist nil
925   "Additional frame parameters for dedicated remember frame."
926   :type 'alist
927   :group 'remember)
929 (defadvice remember (around remember-frame-parameters activate)
930   "Set some frame parameters for the remember frame."
931   (let ((default-frame-alist (append remember-frame-alist
932                                      default-frame-alist)))
933     ad-do-it))
934 #+end_src
936 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
937 reasonable size for the frame.
938 ** Handling Links
939 *** [[#heading-to-link][Turn a heading into an org link]] 
940 *** Quickaccess to the link part of hyperlinks
941 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
942 of an org hyperling other than to use `C-c C-l C-a C-k C-g', 
943 which is indeed kind of cumbersome.
945 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
947 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
948 #+begin_src emacs-lisp
949 (fset 'getlink
950       (lambda (&optional arg) 
951         "Keyboard macro." 
952         (interactive "p") 
953         (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
954 #+end_src
956 or a function: 
957 #+begin_src emacs-lisp
958 (defun my-org-extract-link ()
959   "Extract the link location at point and put it on the killring."
960   (interactive)
961   (when (org-in-regexp org-bracket-link-regexp 1)
962     (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
963 #+end_src
965 They put the link destination on the killring and can be easily bound to a key.
967 ** Archiving Content in Org-Mode
968 *** Preserve top level headings when archiving to a file
969 - Matt Lundin
971 To preserve (somewhat) the integrity of your archive structure while
972 archiving lower level items to a file, you can use the following
973 defadvice:
975 #+begin_src emacs-lisp
976 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
977   (let ((org-archive-location
978          (if (save-excursion (org-back-to-heading)
979                              (> (org-outline-level) 1))
980              (concat (car (split-string org-archive-location "::"))
981                      "::* "
982                      (car (org-get-outline-path)))
983            org-archive-location)))
984     ad-do-it))
985 #+end_src
987 Thus, if you have an outline structure such as...
989 #+begin_src org
990 ,* Heading
991 ,** Subheading
992 ,*** Subsubheading
993 #+end_src
995 ...archiving "Subsubheading" to a new file will set the location in
996 the new file to the top level heading:
998 #+begin_src org
999 ,* Heading
1000 ,** Subsubheading
1001 #+end_src
1003 While this hack obviously destroys the outline hierarchy somewhat, it
1004 at least preserves the logic of level one groupings.
1006 A slightly more complex version of this hack will not only keep the
1007 archive organized by top-level headings, but will also preserve the
1008 tags found on those headings:
1010 #+begin_src emacs-lisp
1011   (defun my-org-inherited-no-file-tags ()
1012     (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1013           (ltags (org-entry-get nil "TAGS")))
1014       (mapc (lambda (tag)
1015               (setq tags
1016                     (replace-regexp-in-string (concat tag ":") "" tags)))
1017             (append org-file-tags (when ltags (split-string ltags ":" t))))
1018       (if (string= ":" tags) nil tags)))
1020   (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1021     (let ((tags (my-org-inherited-no-file-tags))
1022           (org-archive-location
1023            (if (save-excursion (org-back-to-heading)
1024                                (> (org-outline-level) 1))
1025                (concat (car (split-string org-archive-location "::"))
1026                        "::* "
1027                        (car (org-get-outline-path)))
1028              org-archive-location)))
1029       ad-do-it
1030       (with-current-buffer (find-file-noselect (org-extract-archive-file))
1031         (save-excursion
1032           (while (org-up-heading-safe))
1033           (org-set-tags-to tags)))))
1034 #+end_src
1036 *** Archive in a date tree
1038 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1040 (Make sure org-datetree.el is loaded for this to work.)
1042 #+begin_src emacs-lisp
1043 ;; (setq org-archive-location "%s_archive::date-tree")
1044 (defadvice org-archive-subtree
1045   (around org-archive-subtree-to-data-tree activate)
1046   "org-archive-subtree to date-tree"
1047   (if
1048       (string= "date-tree"
1049                (org-extract-archive-heading
1050                 (org-get-local-archive-location)))
1051       (let* ((dct (decode-time (org-current-time)))
1052              (y (nth 5 dct))
1053              (m (nth 4 dct))
1054              (d (nth 3 dct))
1055              (this-buffer (current-buffer))
1056              (location (org-get-local-archive-location))
1057              (afile (org-extract-archive-file location))
1058              (org-archive-location
1059               (format "%s::*** %04d-%02d-%02d %s" afile y m d
1060                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1061         (message "afile=%s" afile)
1062         (unless afile
1063           (error "Invalid `org-archive-location'"))
1064         (save-excursion
1065           (switch-to-buffer (find-file-noselect afile))
1066           (org-datetree-find-year-create y)
1067           (org-datetree-find-month-create y m)
1068           (org-datetree-find-day-create y m d)
1069           (widen)
1070           (switch-to-buffer this-buffer))
1071         ad-do-it)
1072     ad-do-it))
1073 #+end_src
1075 *** Add inherited tags to archived entries
1077 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1078 advise the function like this:
1080 #+begin_example
1081 (defadvice org-archive-subtree
1082   (before add-inherited-tags-before-org-archive-subtree activate)
1083     "add inherited tags before org-archive-subtree"
1084     (org-set-tags-to (org-get-tags-at)))
1085 #+end_example
1087 ** Using and Managing Org-Metadata
1088 *** Remove redundant tags of headlines
1089 -- David Maus
1091 A small function that processes all headlines in current buffer and
1092 removes tags that are local to a headline and inherited by a parent
1093 headline or the #+FILETAGS: statement.
1095 #+BEGIN_SRC emacs-lisp
1096   (defun dmj/org-remove-redundant-tags ()
1097     "Remove redundant tags of headlines in current buffer.
1099   A tag is considered redundant if it is local to a headline and
1100   inherited by a parent headline."
1101     (interactive)
1102     (when (eq major-mode 'org-mode)
1103       (save-excursion
1104         (org-map-entries
1105          '(lambda ()
1106             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1107                   local inherited tag)
1108               (dolist (tag alltags)
1109                 (if (get-text-property 0 'inherited tag)
1110                     (push tag inherited) (push tag local)))
1111               (dolist (tag local)
1112                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
1113          t nil))))
1114 #+END_SRC
1116 *** Remove empty property drawers
1118 David Maus proposed this:
1120 #+begin_src emacs-lisp
1121 (defun dmj:org:remove-empty-propert-drawers ()
1122   "*Remove all empty property drawers in current file."
1123   (interactive)
1124   (unless (eq major-mode 'org-mode)
1125     (error "You need to turn on Org mode for this function."))
1126   (save-excursion
1127     (goto-char (point-min))
1128     (while (re-search-forward ":PROPERTIES:" nil t)
1129       (save-excursion
1130         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1131 #+end_src
1133 *** Group task list by a property
1135 This advice allows you to group a task list in Org-Mode.  To use it,
1136 set the variable =org-agenda-group-by-property= to the name of a
1137 property in the option list for a TODO or TAGS search.  The resulting
1138 agenda view will group tasks by that property prior to searching.
1140 #+begin_src emacs-lisp
1141 (defvar org-agenda-group-by-property nil
1142   "Set this in org-mode agenda views to group tasks by property")
1144 (defun org-group-bucket-items (prop items)
1145   (let ((buckets ()))
1146     (dolist (item items)
1147       (let* ((marker (get-text-property 0 'org-marker item))
1148              (pvalue (org-entry-get marker prop t))
1149              (cell (assoc pvalue buckets)))
1150         (if cell
1151             (setcdr cell (cons item (cdr cell)))
1152           (setq buckets (cons (cons pvalue (list item))
1153                               buckets)))))
1154     (setq buckets (mapcar (lambda (bucket)
1155                             (cons (car bucket)
1156                                   (reverse (cdr bucket))))
1157                           buckets))
1158     (sort buckets (lambda (i1 i2)
1159                     (string< (car i1) (car i2))))))
1161 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1162                                                (list &optional nosort))
1163   "Prepare bucketed agenda entry lists"
1164   (if org-agenda-group-by-property
1165       ;; bucketed, handle appropriately
1166       (let ((text ""))
1167         (dolist (bucket (org-group-bucket-items
1168                          org-agenda-group-by-property
1169                          list))
1170           (let ((header (concat "Property "
1171                                 org-agenda-group-by-property
1172                                 " is "
1173                                 (or (car bucket) "<nil>") ":\n")))
1174             (add-text-properties 0 (1- (length header))
1175                                  (list 'face 'org-agenda-structure)
1176                                  header)
1177             (setq text
1178                   (concat text header
1179                           ;; recursively process
1180                           (let ((org-agenda-group-by-property nil))
1181                             (org-finalize-agenda-entries
1182                              (cdr bucket) nosort))
1183                           "\n\n"))))
1184         (setq ad-return-value text))
1185     ad-do-it))
1186 (ad-activate 'org-finalize-agenda-entries)
1187 #+end_src
1188 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1189     Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1191 A small hook run when clocking out of a task that prompts for a note
1192 when the tag "=clockout_note=" is found in a headline. It uses the tag
1193 ("=clockout_note=") so inheritance can also be used...
1195 #+begin_src emacs-lisp
1196   (defun rgr/check-for-clock-out-note()
1197         (interactive)
1198         (save-excursion
1199           (org-back-to-heading)
1200           (let ((tags (org-get-tags)))
1201             (and tags (message "tags: %s " tags)
1202                  (when (member "clocknote" tags)
1203                    (org-add-note))))))
1205   (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1206 #+end_src
1207 *** Dynamically adjust tag position
1208 Here is a bit of code that allows you to have the tags always
1209 right-adjusted in the buffer.
1211 This is useful when you have bigger window than default window-size
1212 and you dislike the aesthetics of having the tag in the middle of the
1213 line.
1215 This hack solves the problem of adjusting it whenever you change the
1216 window size.
1217 Before saving it will revert the file to having the tag position be
1218 left-adjusted so that if you track your files with version control,
1219 you won't run into artificial diffs just because the window-size
1220 changed.
1222 *IMPORTANT*: This is probably slow on very big files.
1224 #+begin_src emacs-lisp
1225 (setq ba/org-adjust-tags-column t)
1227 (defun ba/org-adjust-tags-column-reset-tags ()
1228   "In org-mode buffers it will reset tag position according to
1229 `org-tags-column'."
1230   (when (and
1231          (not (string= (buffer-name) "*Remember*"))
1232          (eql major-mode 'org-mode))
1233     (let ((b-m-p (buffer-modified-p)))
1234       (condition-case nil
1235           (save-excursion
1236             (goto-char (point-min))
1237             (command-execute 'outline-next-visible-heading)
1238             ;; disable (message) that org-set-tags generates
1239             (flet ((message (&rest ignored) nil))
1240               (org-set-tags 1 t))
1241             (set-buffer-modified-p b-m-p))
1242         (error nil)))))
1244 (defun ba/org-adjust-tags-column-now ()
1245   "Right-adjust `org-tags-column' value, then reset tag position."
1246   (set (make-local-variable 'org-tags-column)
1247        (- (- (window-width) (length org-ellipsis))))
1248   (ba/org-adjust-tags-column-reset-tags))
1250 (defun ba/org-adjust-tags-column-maybe ()
1251   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1252   (when ba/org-adjust-tags-column
1253     (ba/org-adjust-tags-column-now)))
1255 (defun ba/org-adjust-tags-column-before-save ()
1256   "Tags need to be left-adjusted when saving."
1257   (when ba/org-adjust-tags-column
1258      (setq org-tags-column 1)
1259      (ba/org-adjust-tags-column-reset-tags)))
1261 (defun ba/org-adjust-tags-column-after-save ()
1262   "Revert left-adjusted tag position done by before-save hook."
1263   (ba/org-adjust-tags-column-maybe)
1264   (set-buffer-modified-p nil))
1266 ; automatically align tags on right-hand side
1267 (add-hook 'window-configuration-change-hook
1268           'ba/org-adjust-tags-column-maybe)
1269 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1270 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1271 (add-hook 'org-agenda-mode-hook '(lambda ()
1272                                   (setq org-agenda-tags-column (- (window-width)))))
1274 ; between invoking org-refile and displaying the prompt (which
1275 ; triggers window-configuration-change-hook) tags might adjust,
1276 ; which invalidates the org-refile cache
1277 (defadvice org-refile (around org-refile-disable-adjust-tags)
1278   "Disable dynamically adjusting tags"
1279   (let ((ba/org-adjust-tags-column nil))
1280     ad-do-it))
1281 (ad-activate 'org-refile)
1282 #+end_src
1283 *** Use an "attach" link type to open files without worrying about their location
1285 -- Darlan Cavalcante Moreira
1287 In the setup part in my org-files I put:
1289 #+begin_src org
1290   ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1291 #+end_src org
1293 Now I can use the "attach" link type, but org will ask me if I want to
1294 allow executing the elisp code.  To avoid this you can even set
1295 org-confirm-elisp-link-function to nil (I don't like this because it allows
1296 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1297 appropriately.
1299 In my case I use
1301 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1303 This works very well.
1305 ** Org Agenda and Task Management
1306 *** Make it easier to set org-agenda-files from multiple directories
1307 - Matt Lundin
1309 #+begin_src emacs-lisp
1310 (defun my-org-list-files (dirs ext)
1311   "Function to create list of org files in multiple subdirectories.
1312 This can be called to generate a list of files for
1313 org-agenda-files or org-refile-targets.
1315 DIRS is a list of directories.
1317 EXT is a list of the extensions of files to be included."
1318   (let ((dirs (if (listp dirs)
1319                   dirs
1320                 (list dirs)))
1321         (ext (if (listp ext)
1322                  ext
1323                (list ext)))
1324         files)
1325     (mapc
1326      (lambda (x)
1327        (mapc
1328         (lambda (y)
1329           (setq files
1330                 (append files
1331                         (file-expand-wildcards
1332                          (concat (file-name-as-directory x) "*" y)))))
1333         ext))
1334      dirs)
1335     (mapc
1336      (lambda (x)
1337        (when (or (string-match "/.#" x)
1338                  (string-match "#$" x))
1339          (setq files (delete x files))))
1340      files)
1341     files))
1343 (defvar my-org-agenda-directories '("~/org/")
1344   "List of directories containing org files.")
1345 (defvar my-org-agenda-extensions '(".org")
1346   "List of extensions of agenda files")
1348 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1349 (setq my-org-agenda-extensions '(".org" ".ref"))
1351 (defun my-org-set-agenda-files ()
1352   (interactive)
1353   (setq org-agenda-files (my-org-list-files
1354                           my-org-agenda-directories
1355                           my-org-agenda-extensions)))
1357 (my-org-set-agenda-files)
1358 #+end_src
1360 The code above will set your "default" agenda files to all files
1361 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1362 You can change these values by setting the variables
1363 my-org-agenda-extensions and my-org-agenda-directories. The function
1364 my-org-agenda-files-by-filetag uses these two variables to determine
1365 which files to search for filetags (i.e., the larger set from which
1366 the subset will be drawn).
1368 You can also easily use my-org-list-files to "mix and match"
1369 directories and extensions to generate different lists of agenda
1370 files.
1372 *** Restrict org-agenda-files by filetag
1373   :PROPERTIES:
1374   :CUSTOM_ID: set-agenda-files-by-filetag
1375   :END:
1376 - Matt Lundin
1378 It is often helpful to limit yourself to a subset of your agenda
1379 files. For instance, at work, you might want to see only files related
1380 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1381 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
1382 commands]]. These solutions, however, require reapplying a filter each
1383 time you call the agenda or writing several new custom agenda commands
1384 for each context. Another solution is to use directories for different
1385 types of tasks and to change your agenda files with a function that
1386 sets org-agenda-files to the appropriate directory. But this relies on
1387 hard and static boundaries between files.
1389 The following functions allow for a more dynamic approach to selecting
1390 a subset of files based on filetags:
1392 #+begin_src emacs-lisp
1393 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1394   "Restrict org agenda files only to those containing filetag."
1395   (interactive)
1396   (let* ((tagslist (my-org-get-all-filetags))
1397          (ftag (or tag
1398                    (completing-read "Tag: "
1399                                     (mapcar 'car tagslist)))))
1400     (org-agenda-remove-restriction-lock 'noupdate)
1401     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1402     (setq org-agenda-overriding-restriction 'files)))
1404 (defun my-org-get-all-filetags ()
1405   "Get list of filetags from all default org-files."
1406   (let ((files org-agenda-files)
1407         tagslist x)
1408     (save-window-excursion
1409       (while (setq x (pop files))
1410         (set-buffer (find-file-noselect x))
1411         (mapc
1412          (lambda (y)
1413            (let ((tagfiles (assoc y tagslist)))
1414              (if tagfiles
1415                  (setcdr tagfiles (cons x (cdr tagfiles)))
1416                (add-to-list 'tagslist (list y x)))))
1417          (my-org-get-filetags)))
1418       tagslist)))
1420 (defun my-org-get-filetags ()
1421   "Get list of filetags for current buffer"
1422   (let ((ftags org-file-tags)
1423         x)
1424     (mapcar
1425      (lambda (x)
1426        (org-substring-no-properties x))
1427      ftags)))
1428 #+end_src
1430 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1431 with all filetags in your "normal" agenda files. When you select a
1432 tag, org-agenda-files will be restricted to only those files
1433 containing the filetag. To release the restriction, type C-c C-x >
1434 (org-agenda-remove-restriction-lock).
1436 *** Highlight the agenda line under cursor
1438 This is useful to make sure what task you are operating on.
1440 #+BEGIN_SRC emacs-lisp
1441 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1442 #+END_SRC
1444 Under XEmacs:
1446 #+BEGIN_SRC emacs-lisp
1447 ;; hl-line seems to be only for emacs
1448 (require 'highline)
1449 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1451 ;; highline-mode does not work straightaway in tty mode.
1452 ;; I use a black background
1453 (custom-set-faces
1454   '(highline-face ((((type tty) (class color))
1455                     (:background "white" :foreground "black")))))
1456 #+END_SRC
1458 *** Split horizontally for agenda
1460 If you would like to split the frame into two side-by-side windows when
1461 displaying the agenda, try this hack from Jan Rehders, which uses the
1462 `toggle-window-split' from
1464 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1466 #+BEGIN_SRC emacs-lisp
1467 ;; Patch org-mode to use vertical splitting
1468 (defadvice org-prepare-agenda (after org-fix-split)
1469   (toggle-window-split))
1470 (ad-activate 'org-prepare-agenda)
1471 #+END_SRC
1473 *** Automatically add an appointment when clocking in a task
1475 #+BEGIN_SRC emacs-lisp
1476 ;; Make sure you have a sensible value for `appt-message-warning-time'
1477 (defvar bzg-org-clock-in-appt-delay 100
1478   "Number of minutes for setting an appointment by clocking-in")
1479 #+END_SRC
1481 This function let's you add an appointment for the current entry.
1482 This can be useful when you need a reminder.
1484 #+BEGIN_SRC emacs-lisp
1485 (defun bzg-org-clock-in-add-appt (&optional n)
1486   "Add an appointment for the Org entry at point in N minutes."
1487   (interactive)
1488   (save-excursion
1489     (org-back-to-heading t)
1490     (looking-at org-complex-heading-regexp)
1491     (let* ((msg (match-string-no-properties 4))
1492            (ct-time (decode-time))
1493            (appt-min (+ (cadr ct-time)
1494                         (or n bzg-org-clock-in-appt-delay)))
1495            (appt-time ; define the time for the appointment
1496             (progn (setf (cadr ct-time) appt-min) ct-time)))
1497       (appt-add (format-time-string
1498                  "%H:%M" (apply 'encode-time appt-time)) msg)
1499       (if (interactive-p) (message "New appointment for %s" msg)))))
1500 #+END_SRC
1502 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1503 add an appointment:
1505 #+BEGIN_SRC emacs-lisp
1506 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1507   "Add an appointment when clocking a task in."
1508   (bzg-org-clock-in-add-appt))
1509 #+END_SRC
1511 You may also want to delete the associated appointment when clocking
1512 out.  This function does this:
1514 #+BEGIN_SRC emacs-lisp
1515 (defun bzg-org-clock-out-delete-appt nil
1516   "When clocking out, delete any associated appointment."
1517   (interactive)
1518   (save-excursion
1519     (org-back-to-heading t)
1520     (looking-at org-complex-heading-regexp)
1521     (let* ((msg (match-string-no-properties 4)))
1522       (setq appt-time-msg-list
1523             (delete nil
1524                     (mapcar
1525                      (lambda (appt)
1526                        (if (not (string-match (regexp-quote msg)
1527                                               (cadr appt))) appt))
1528                      appt-time-msg-list)))
1529       (appt-check))))
1530 #+END_SRC
1532 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1534 #+BEGIN_SRC emacs-lisp
1535 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1536   "Delete an appointment when clocking a task out."
1537   (bzg-org-clock-out-delete-appt))
1538 #+END_SRC
1540 *IMPORTANT*: You can add appointment by clocking in in both an
1541 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
1542 agenda buffer with the advice above will bring an error.
1544 *** Using external programs for appointments reminders
1546 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1548 *** Remove time grid lines that are in an appointment
1550 The agenda shows lines for the time grid.  Some people think that
1551 these lines are a distraction when there are appointments at those
1552 times.  You can get rid of the lines which coincide exactly with the
1553 beginning of an appointment.  Michael Ekstrand has written a piece of
1554 advice that also removes lines that are somewhere inside an
1555 appointment:
1557 #+begin_src emacs-lisp
1558 (defun org-time-to-minutes (time)
1559   "Convert an HHMM time to minutes"
1560   (+ (* (/ time 100) 60) (% time 100)))
1562 (defun org-time-from-minutes (minutes)
1563   "Convert a number of minutes to an HHMM time"
1564   (+ (* (/ minutes 60) 100) (% minutes 60)))
1566 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1567                                                   (list ndays todayp))
1568   (if (member 'remove-match (car org-agenda-time-grid))
1569       (flet ((extract-window
1570               (line)
1571               (let ((start (get-text-property 1 'time-of-day line))
1572                     (dur (get-text-property 1 'duration line)))
1573                 (cond
1574                  ((and start dur)
1575                   (cons start
1576                         (org-time-from-minutes
1577                          (+ dur (org-time-to-minutes start)))))
1578                  (start start)
1579                  (t nil)))))
1580         (let* ((windows (delq nil (mapcar 'extract-window list)))
1581                (org-agenda-time-grid
1582                 (list (car org-agenda-time-grid)
1583                       (cadr org-agenda-time-grid)
1584                       (remove-if
1585                        (lambda (time)
1586                          (find-if (lambda (w)
1587                                     (if (numberp w)
1588                                         (equal w time)
1589                                       (and (>= time (car w))
1590                                            (< time (cdr w)))))
1591                                   windows))
1592                        (caddr org-agenda-time-grid)))))
1593           ad-do-it))
1594     ad-do-it))
1595 (ad-activate 'org-agenda-add-time-grid-maybe)
1596 #+end_src
1597 *** Disable vc for Org mode agenda files
1598 -- David Maus
1600 Even if you use Git to track your agenda files you might not need
1601 vc-mode to be enabled for these files.
1603 #+begin_src emacs-lisp
1604 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1605 (defun dmj/disable-vc-for-agenda-files-hook ()
1606   "Disable vc-mode for Org agenda files."
1607   (if (and (fboundp 'org-agenda-file-p)
1608            (org-agenda-file-p (buffer-file-name)))
1609       (remove-hook 'find-file-hook 'vc-find-file-hook)
1610     (add-hook 'find-file-hook 'vc-find-file-hook)))
1611 #+end_src
1613 *** Easy customization of TODO colors
1614 -- Ryan C. Thompson
1616 Here is some code I came up with some code to make it easier to
1617 customize the colors of various TODO keywords. As long as you just
1618 want a different color and nothing else, you can customize the
1619 variable org-todo-keyword-faces and use just a string color (i.e. a
1620 string of the color name) as the face, and then org-get-todo-face
1621 will convert the color to a face, inheriting everything else from
1622 the standard org-todo face.
1624 To demonstrate, I currently have org-todo-keyword-faces set to
1626 #+BEGIN_SRC emacs-lisp
1627 (("IN PROGRESS" . "dark orange")
1628  ("WAITING" . "red4")
1629  ("CANCELED" . "saddle brown"))
1630 #+END_SRC
1632   Here's the code, in a form you can put in your =.emacs=
1634 #+BEGIN_SRC emacs-lisp
1635 (eval-after-load 'org-faces
1636  '(progn
1637     (defcustom org-todo-keyword-faces nil
1638       "Faces for specific TODO keywords.
1639 This is a list of cons cells, with TODO keywords in the car and
1640 faces in the cdr.  The face can be a symbol, a color, or a
1641 property list of attributes, like (:foreground \"blue\" :weight
1642 bold :underline t)."
1643       :group 'org-faces
1644       :group 'org-todo
1645       :type '(repeat
1646               (cons
1647                (string :tag "Keyword")
1648                (choice color (sexp :tag "Face")))))))
1650 (eval-after-load 'org
1651  '(progn
1652     (defun org-get-todo-face-from-color (color)
1653       "Returns a specification for a face that inherits from org-todo
1654  face and has the given color as foreground. Returns nil if
1655  color is nil."
1656       (when color
1657         `(:inherit org-warning :foreground ,color)))
1659     (defun org-get-todo-face (kwd)
1660       "Get the right face for a TODO keyword KWD.
1661 If KWD is a number, get the corresponding match group."
1662       (if (numberp kwd) (setq kwd (match-string kwd)))
1663       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1664             (if (stringp face)
1665                 (org-get-todo-face-from-color face)
1666               face))
1667           (and (member kwd org-done-keywords) 'org-done)
1668           'org-todo))))
1669 #+END_SRC
1671 *** Add an effort estimate on the fly when clocking in
1673 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1674 This way you can easily have a "tea-timer" for your tasks when they
1675 don't already have an effort estimate.
1677 #+begin_src emacs-lisp
1678 (add-hook 'org-clock-in-prepare-hook
1679           'my-org-mode-ask-effort)
1681 (defun my-org-mode-ask-effort ()
1682   "Ask for an effort estimate when clocking in."
1683   (unless (org-entry-get (point) "Effort")
1684     (let ((effort
1685            (completing-read
1686             "Effort: "
1687             (org-entry-get-multivalued-property (point) "Effort"))))
1688       (unless (equal effort "")
1689         (org-set-property "Effort" effort)))))
1690 #+end_src
1692 Or you can use a default effort for such a timer:
1694 #+begin_src emacs-lisp
1695 (add-hook 'org-clock-in-prepare-hook
1696           'my-org-mode-add-default-effort)
1698 (defvar org-clock-default-effort "1:00")
1700 (defun my-org-mode-add-default-effort ()
1701   "Add a default effort estimation."
1702   (unless (org-entry-get (point) "Effort")
1703     (org-set-property "Effort" org-clock-default-effort)))
1704 #+end_src
1706 *** Refresh the agenda view regurally
1708 Hack sent by Kiwon Um:
1710 #+begin_src emacs-lisp
1711 (defun kiwon/org-agenda-redo-in-other-window ()
1712   "Call org-agenda-redo function even in the non-agenda buffer."
1713   (interactive)
1714   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1715     (when agenda-window
1716       (with-selected-window agenda-window (org-agenda-redo)))))
1717 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1718 #+end_src
1720 *** Reschedule agenda items to today with a single command
1722 This was suggested by Carsten in reply to David Abrahams:
1724 #+begin_example emacs-lisp
1725 (defun org-agenda-reschedule-to-today ()
1726   (interactive)
1727   (flet ((org-read-date (&rest rest) (current-time)))
1728     (call-interactively 'org-agenda-schedule)))
1729 #+end_example
1731 *** Mark subtree DONE along with all subheadings
1733 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
1735 #+begin_src emacs-lisp
1736 (defun bh/mark-subtree-done ()
1737   (interactive)
1738   (org-mark-subtree)
1739   (let ((limit (point)))
1740     (save-excursion
1741       (exchange-point-and-mark)
1742       (while (> (point) limit)
1743         (org-todo "DONE")
1744         (outline-previous-visible-heading 1))
1745       (org-todo "DONE"))))
1746 #+end_src
1748 Then M-x bh/mark-subtree-done.
1750 ** Exporting org files
1751 *** Export Org to Org and handle includes.
1753 Nick Dokos came up with this useful function:
1755 #+begin_src emacs-lisp
1756 (defun org-to-org-handle-includes ()
1757   "Copy the contents of the current buffer to OUTFILE,
1758 recursively processing #+INCLUDEs."
1759   (let* ((s (buffer-string))
1760          (fname (buffer-file-name))
1761          (ofname (format "%s.I.org" (file-name-sans-extension fname))))
1762     (setq result
1763           (with-temp-buffer
1764             (insert s)
1765             (org-export-handle-include-files-recurse)
1766             (buffer-string)))
1767     (find-file ofname)
1768     (delete-region (point-min) (point-max))
1769     (insert result)
1770     (save-buffer)))
1771 #+end_src
1773 *** Specifying LaTeX commands to floating environments
1774     :PROPERTIES:
1775     :CUSTOM_ID: latex-command-for-floats
1776     :END:
1778 The keyword ~placement~ can be used to specify placement options to
1779 floating environments (like =\begin{figure}= and =\begin{table}=}) in
1780 LaTeX export. Org passes along everything passed in options as long as
1781 there are no spaces. One can take advantage of this to pass other
1782 LaTeX commands and have their scope limited to the floating
1783 environment.
1785 For example one can set the fontsize of a table different from the
1786 default normal size by putting something like =\footnotesize= right
1787 after the placement options. During LaTeX export using the
1788 ~#+ATTR_LaTeX:~ line below:
1790 #+begin_src org
1791   ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
1792 #+end_src
1794 exports the associated floating environment as shown in the following
1795 block.
1797 #+begin_src latex
1798 \begin{table}[<options>]\footnotesize
1800 \end{table}
1801 #+end_src
1803 It should be noted that this hack does not work for beamer export of
1804 tables since the =table= environment is not used. As an ugly
1805 workaround, one can use the following:
1807 #+begin_src org
1808   ,#+LATEX: {\footnotesize
1809   ,#+ATTR_LaTeX: align=rr
1810   ,| some | table |
1811   ,|------+-------|
1812   ,| ..   | ..    |
1813   ,#+LATEX: }
1814 #+end_src
1816 *** Styling code sections with CSS
1818 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
1819 to HTML using =<pre>= tags, and assigned CSS classes by their content
1820 type.  For example, Perl content will have an opening tag like
1821 =<pre class="src src-perl">=.  You can use those classes to add styling
1822 to the output, such as here where a small language tag is added at the
1823 top of each kind of code box:
1825 #+begin_src lisp
1826 (setq org-export-html-style
1827  "<style type=\"text/css\">
1828     <!--/*--><![CDATA[/*><!--*/
1829       .src             { background-color: #F5FFF5; position: relative; overflow: visible; }
1830       .src:before      { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
1831       .src-sh:before   { content: 'sh'; }
1832       .src-bash:before { content: 'sh'; }
1833       .src-R:before    { content: 'R'; }
1834       .src-perl:before { content: 'Perl'; }
1835       .src-sql:before  { content: 'SQL'; }
1836       .example         { background-color: #FFF5F5; }
1837     /*]]>*/-->
1838  </style>")
1839 #+end_src
1841 Additionally, we use color to distinguish code output (the =.example=
1842 class) from input (all the =.src-*= classes).
1844 * Hacking Org: Working with Org-mode and other Emacs Packages.
1845 ** org-remember-anything
1847 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1849 #+BEGIN_SRC emacs-lisp
1850 (defvar org-remember-anything
1851   '((name . "Org Remember")
1852     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1853     (action . (lambda (name)
1854                 (let* ((orig-template org-remember-templates)
1855                        (org-remember-templates
1856                         (list (assoc name orig-template))))
1857                   (call-interactively 'org-remember))))))
1858 #+END_SRC
1860 You can add it to your 'anything-sources' variable and open remember directly
1861 from anything. I imagine this would be more interesting for people with many
1862 remember templates, so that you are out of keys to assign those to.
1864 ** Org-mode and saveplace.el
1866 Fix a problem with saveplace.el putting you back in a folded position:
1868 #+begin_src emacs-lisp
1869 (add-hook 'org-mode-hook
1870           (lambda ()
1871             (when (outline-invisible-p)
1872               (save-excursion
1873                 (outline-previous-visible-heading 1)
1874                 (org-show-subtree)))))
1875 #+end_src
1877 ** Using ido-completing-read to find attachments
1878 -- Matt Lundin.
1880 Org-attach is great for quickly linking files to a project. But if you
1881 use org-attach extensively you might find yourself wanting to browse
1882 all the files you've attached to org headlines. This is not easy to do
1883 manually, since the directories containing the files are not human
1884 readable (i.e., they are based on automatically generated ids). Here's
1885 some code to browse those files using ido (obviously, you need to be
1886 using ido):
1888 #+begin_src emacs-lisp
1889 (load-library "find-lisp")
1891 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1893 (defun my-ido-find-org-attach ()
1894   "Find files in org-attachment directory"
1895   (interactive)
1896   (let* ((enable-recursive-minibuffers t)
1897          (files (find-lisp-find-files org-attach-directory "."))
1898          (file-assoc-list
1899           (mapcar (lambda (x)
1900                     (cons (file-name-nondirectory x)
1901                           x))
1902                   files))
1903          (filename-list
1904           (remove-duplicates (mapcar #'car file-assoc-list)
1905                              :test #'string=))
1906          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1907          (longname (cdr (assoc filename file-assoc-list))))
1908     (ido-set-current-directory
1909      (if (file-directory-p longname)
1910          longname
1911        (file-name-directory longname)))
1912     (setq ido-exit 'refresh
1913           ido-text-init ido-text
1914           ido-rotate-temp t)
1915     (exit-minibuffer)))
1917 (add-hook 'ido-setup-hook 'ido-my-keys)
1919 (defun ido-my-keys ()
1920   "Add my keybindings for ido."
1921   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1922 #+end_src
1924 To browse your org attachments using ido fuzzy matching and/or the
1925 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1926 press =C-;=.
1928 ** Use idle timer for automatic agenda views
1930 From John Wiegley's mailing list post (March 18, 2010):
1932 #+begin_quote
1933 I have the following snippet in my .emacs file, which I find very
1934 useful. Basically what it does is that if I don't touch my Emacs for 5
1935 minutes, it displays the current agenda. This keeps my tasks "always
1936 in mind" whenever I come back to Emacs after doing something else,
1937 whereas before I had a tendency to forget that it was there.
1938 #+end_quote
1940   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1942 #+begin_src emacs-lisp
1943 (defun jump-to-org-agenda ()
1944   (interactive)
1945   (let ((buf (get-buffer "*Org Agenda*"))
1946         wind)
1947     (if buf
1948         (if (setq wind (get-buffer-window buf))
1949             (select-window wind)
1950           (if (called-interactively-p)
1951               (progn
1952                 (select-window (display-buffer buf t t))
1953                 (org-fit-window-to-buffer)
1954                 ;; (org-agenda-redo)
1955                 )
1956             (with-selected-window (display-buffer buf)
1957               (org-fit-window-to-buffer)
1958               ;; (org-agenda-redo)
1959               )))
1960       (call-interactively 'org-agenda-list)))
1961   ;;(let ((buf (get-buffer "*Calendar*")))
1962   ;;  (unless (get-buffer-window buf)
1963   ;;    (org-agenda-goto-calendar)))
1964   )
1966 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1967 #+end_src
1969 #+results:
1970 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1972 ** Link to Gnus messages by Message-Id
1974 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1975 discussion about linking to Gnus messages without encoding the folder
1976 name in the link.  The following code hooks in to the store-link
1977 function in Gnus to capture links by Message-Id when in nnml folders,
1978 and then provides a link type "mid" which can open this link.  The
1979 =mde-org-gnus-open-message-link= function uses the
1980 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1981 scan.  It will go through them, in order, asking each to locate the
1982 message and opening it from the first one that reports success.
1984 It has only been tested with a single nnml backend, so there may be
1985 bugs lurking here and there.
1987 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1988 article]].
1990 #+begin_src emacs-lisp
1991 ;; Support for saving Gnus messages by Message-ID
1992 (defun mde-org-gnus-save-by-mid ()
1993   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1994     (when (eq major-mode 'gnus-article-mode)
1995       (gnus-article-show-summary))
1996     (let* ((group gnus-newsgroup-name)
1997            (method (gnus-find-method-for-group group)))
1998       (when (eq 'nnml (car method))
1999         (let* ((article (gnus-summary-article-number))
2000                (header (gnus-summary-article-header article))
2001                (from (mail-header-from header))
2002                (message-id
2003                 (save-match-data
2004                   (let ((mid (mail-header-id header)))
2005                     (if (string-match "<\\(.*\\)>" mid)
2006                         (match-string 1 mid)
2007                       (error "Malformed message ID header %s" mid)))))
2008                (date (mail-header-date header))
2009                (subject (gnus-summary-subject-string)))
2010           (org-store-link-props :type "mid" :from from :subject subject
2011                                 :message-id message-id :group group
2012                                 :link (org-make-link "mid:" message-id))
2013           (apply 'org-store-link-props
2014                  :description (org-email-link-description)
2015                  org-store-link-plist)
2016           t)))))
2018 (defvar mde-mid-resolve-methods '()
2019   "List of methods to try when resolving message ID's.  For Gnus,
2020 it is a cons of 'gnus and the select (type and name).")
2021 (setq mde-mid-resolve-methods
2022       '((gnus nnml "")))
2024 (defvar mde-org-gnus-open-level 1
2025   "Level at which Gnus is started when opening a link")
2026 (defun mde-org-gnus-open-message-link (msgid)
2027   "Open a message link with Gnus"
2028   (require 'gnus)
2029   (require 'org-table)
2030   (catch 'method-found
2031     (message "[MID linker] Resolving %s" msgid)
2032     (dolist (method mde-mid-resolve-methods)
2033       (cond
2034        ((and (eq (car method) 'gnus)
2035              (eq (cadr method) 'nnml))
2036         (funcall (cdr (assq 'gnus org-link-frame-setup))
2037                  mde-org-gnus-open-level)
2038         (when gnus-other-frame-object
2039           (select-frame gnus-other-frame-object))
2040         (let* ((msg-info (nnml-find-group-number
2041                           (concat "<" msgid ">")
2042                           (cdr method)))
2043                (group (and msg-info (car msg-info)))
2044                (message (and msg-info (cdr msg-info)))
2045                (qname (and group
2046                            (if (gnus-methods-equal-p
2047                                 (cdr method)
2048                                 gnus-select-method)
2049                                group
2050                              (gnus-group-full-name group (cdr method))))))
2051           (when msg-info
2052             (gnus-summary-read-group qname nil t)
2053             (gnus-summary-goto-article message nil t))
2054           (throw 'method-found t)))
2055        (t (error "Unknown link type"))))))
2057 (eval-after-load 'org-gnus
2058   '(progn
2059      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2060      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2061 #+end_src
2063 ** Store link upon sending a message in Gnus
2065 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2067 #+begin_src emacs-lisp
2068 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2069   "Send message with `message-send-and-exit' and store org link to message copy.
2070 If multiple groups appear in the Gcc header, the link refers to
2071 the copy in the last group."
2072   (interactive "P")
2073     (save-excursion
2074       (save-restriction
2075         (message-narrow-to-headers)
2076         (let ((gcc (car (last
2077                          (message-unquote-tokens
2078                           (message-tokenize-header
2079                            (mail-fetch-field "gcc" nil t) " ,")))))
2080               (buf (current-buffer))
2081               (message-kill-buffer-on-exit nil)
2082               id to from subject desc link newsgroup xarchive)
2083         (message-send-and-exit arg)
2084         (or
2085          ;; gcc group found ...
2086          (and gcc
2087               (save-current-buffer
2088                 (progn (set-buffer buf)
2089                        (setq id (org-remove-angle-brackets
2090                                  (mail-fetch-field "Message-ID")))
2091                        (setq to (mail-fetch-field "To"))
2092                        (setq from (mail-fetch-field "From"))
2093                        (setq subject (mail-fetch-field "Subject"))))
2094               (org-store-link-props :type "gnus" :from from :subject subject
2095                                     :message-id id :group gcc :to to)
2096               (setq desc (org-email-link-description))
2097               (setq link (org-gnus-article-link
2098                           gcc newsgroup id xarchive))
2099               (setq org-stored-links
2100                     (cons (list link desc) org-stored-links)))
2101          ;; no gcc group found ...
2102          (message "Can not create Org link: No Gcc header found."))))))
2104 (define-key message-mode-map [(control c) (control meta c)]
2105   'ulf-message-send-and-org-gnus-store-link)
2106 #+end_src
2108 ** Send html messages and attachments with Wanderlust
2109   -- David Maus
2111 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2112 similar functionality for both Wanderlust and Gnus.  The hack below is
2113 still somewhat different: It allows you to toggle sending of html
2114 messages within Wanderlust transparently.  I.e. html markup of the
2115 message body is created right before sending starts.
2117 *** Send HTML message
2119 Putting the code below in your .emacs adds following four functions:
2121 - dmj/wl-send-html-message
2123   Function that does the job: Convert everything between "--text
2124   follows this line--" and first mime entity (read: attachment) or
2125   end of buffer into html markup using `org-export-region-as-html'
2126   and replaces original body with a multipart MIME entity with the
2127   plain text version of body and the html markup version.  Thus a
2128   recipient that prefers html messages can see the html markup,
2129   recipients that prefer or depend on plain text can see the plain
2130   text.
2132   Cannot be called interactively: It is hooked into SEMI's
2133   `mime-edit-translate-hook' if message should be HTML message.
2135 - dmj/wl-send-html-message-draft-init
2137   Cannot be called interactively: It is hooked into WL's
2138   `wl-mail-setup-hook' and provides a buffer local variable to
2139   toggle.
2141 - dmj/wl-send-html-message-draft-maybe
2143   Cannot be called interactively: It is hooked into WL's
2144   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2145   `mime-edit-translate-hook' depending on whether HTML message is
2146   toggled on or off
2148 - dmj/wl-send-html-message-toggle
2150   Toggles sending of HTML message.  If toggled on, the letters
2151   "HTML" appear in the mode line.
2153   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
2155 If you have to send HTML messages regularly you can set a global
2156 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2157 toggle on sending HTML message by default.
2159 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2160 Google's web front end.  As you can see you have the whole markup of
2161 Org at your service: *bold*, /italics/, tables, lists...
2163 So even if you feel uncomfortable with sending HTML messages at least
2164 you send HTML that looks quite good.
2166 #+begin_src emacs-lisp
2167 (defun dmj/wl-send-html-message ()
2168   "Send message as html message.
2169 Convert body of message to html using
2170   `org-export-region-as-html'."
2171   (require 'org)
2172   (save-excursion
2173     (let (beg end html text)
2174       (goto-char (point-min))
2175       (re-search-forward "^--text follows this line--$")
2176       ;; move to beginning of next line
2177       (beginning-of-line 2)
2178       (setq beg (point))
2179       (if (not (re-search-forward "^--\\[\\[" nil t))
2180           (setq end (point-max))
2181         ;; line up
2182         (end-of-line 0)
2183         (setq end (point)))
2184       ;; grab body
2185       (setq text (buffer-substring-no-properties beg end))
2186       ;; convert to html
2187       (with-temp-buffer
2188         (org-mode)
2189         (insert text)
2190         ;; handle signature
2191         (when (re-search-backward "^-- \n" nil t)
2192           ;; preserve link breaks in signature
2193           (insert "\n#+BEGIN_VERSE\n")
2194           (goto-char (point-max))
2195           (insert "\n#+END_VERSE\n")
2196           ;; grab html
2197           (setq html (org-export-region-as-html
2198                       (point-min) (point-max) t 'string))))
2199       (delete-region beg end)
2200       (insert
2201        (concat
2202         "--" "<<alternative>>-{\n"
2203         "--" "[[text/plain]]\n" text
2204         "--" "[[text/html]]\n"  html
2205         "--" "}-<<alternative>>\n")))))
2207 (defun dmj/wl-send-html-message-toggle ()
2208   "Toggle sending of html message."
2209   (interactive)
2210   (setq dmj/wl-send-html-message-toggled-p
2211         (if dmj/wl-send-html-message-toggled-p
2212             nil "HTML"))
2213   (message "Sending html message toggled %s"
2214            (if dmj/wl-send-html-message-toggled-p
2215                "on" "off")))
2217 (defun dmj/wl-send-html-message-draft-init ()
2218   "Create buffer local settings for maybe sending html message."
2219   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2220     (setq dmj/wl-send-html-message-toggled-p nil))
2221   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2222   (add-to-list 'global-mode-string
2223                '(:eval (if (eq major-mode 'wl-draft-mode)
2224                            dmj/wl-send-html-message-toggled-p))))
2226 (defun dmj/wl-send-html-message-maybe ()
2227   "Maybe send this message as html message.
2229 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2230 non-nil, add `dmj/wl-send-html-message' to
2231 `mime-edit-translate-hook'."
2232   (if dmj/wl-send-html-message-toggled-p
2233       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2234     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2236 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2237 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2238 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2239 #+end_src
2241 *** Attach HTML of region or subtree
2243 Instead of sending a complete HTML message you might only send parts
2244 of an Org file as HTML for the poor souls who are plagued with
2245 non-proportional fonts in their mail program that messes up pretty
2246 ASCII tables.
2248 This short function does the trick: It exports region or subtree to
2249 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2250 and clipboard.  If a region is active, it uses the region, the
2251 complete subtree otherwise.
2253 #+begin_src emacs-lisp
2254 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2255   "Export region between BEG and END as html attachment.
2256 If BEG and END are not set, use current subtree.  Region or
2257 subtree is exported to html without header and footer, prefixed
2258 with a mime entity string and pushed to clipboard and killring.
2259 When called with prefix, mime entity is not marked as
2260 attachment."
2261   (interactive "r\nP")
2262   (save-excursion
2263     (let* ((beg (if (region-active-p) (region-beginning)
2264                   (progn
2265                     (org-back-to-heading)
2266                     (point))))
2267            (end (if (region-active-p) (region-end)
2268                   (progn
2269                     (org-end-of-subtree)
2270                     (point))))
2271            (html (concat "--[[text/html"
2272                          (if arg "" "\nContent-Disposition: attachment")
2273                          "]]\n"
2274                          (org-export-region-as-html beg end t 'string))))
2275       (when (fboundp 'x-set-selection)
2276         (ignore-errors (x-set-selection 'PRIMARY html))
2277         (ignore-errors (x-set-selection 'CLIPBOARD html)))
2278       (message "html export done, pushed to kill ring and clipboard"))))
2279 #+end_src
2281 *** Adopting for Gnus
2283 The whole magic lies in the special strings that mark a HTML
2284 attachment.  So you might just have to find out what these special
2285 strings are in message-mode and modify the functions accordingly.
2286 ** Add sunrise/sunset times to the agenda.
2287   -- Nick Dokos
2289 The diary package provides the function =diary-sunrise-sunset= which can be used
2290 in a diary s-expression in some agenda file like this:
2292 #+begin_src org-mode
2293 %%(diary-sunrise-sunset)
2294 #+end_src
2296 Seb Vauban asked if it is possible to put sunrise and sunset in
2297 separate lines. Here is a hack to do that. It adds two functions (they
2298 have to be available before the agenda is shown, so I add them early
2299 in my org-config file which is sourced from .emacs, but you'll have to
2300 suit yourself here) that just parse the output of
2301 diary-sunrise-sunset, instead of doing the right thing which would be
2302 to take advantage of the data structures that diary/solar.el provides.
2303 In short, a hack - so perfectly suited for inclusion here :-)
2305 The functions (and latitude/longitude settings which you have to modify for
2306 your location) are as follows:
2308 #+begin_src emacs-lisp
2309 (setq calendar-latitude 40.3)
2310 (setq calendar-longitude -71.0)
2311 (defun diary-sunrise ()
2312   (let ((dss (diary-sunrise-sunset)))
2313     (with-temp-buffer
2314       (insert dss)
2315       (goto-char (point-min))
2316       (while (re-search-forward " ([^)]*)" nil t)
2317         (replace-match "" nil nil))
2318       (goto-char (point-min))
2319       (search-forward ",")
2320       (buffer-substring (point-min) (match-beginning 0)))))
2322 (defun diary-sunset ()
2323   (let ((dss (diary-sunrise-sunset))
2324         start end)
2325     (with-temp-buffer
2326       (insert dss)
2327       (goto-char (point-min))
2328       (while (re-search-forward " ([^)]*)" nil t)
2329         (replace-match "" nil nil))
2330       (goto-char (point-min))
2331       (search-forward ", ")
2332       (setq start (match-end 0))
2333       (search-forward " at")
2334       (setq end (match-beginning 0))
2335       (goto-char start)
2336       (capitalize-word 1)
2337       (buffer-substring start end))))
2338 #+end_src
2340 You also need to add a couple of diary s-expressions in one of your agenda
2341 files:
2343 #+begin_src org-mode
2344 %%(diary-sunrise)
2345 %%(diary-sunset)
2346 #+end_src
2348 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]].
2349 In comparison to the version posted on the mailing list, this one
2350 gets rid of the timezone information.
2351 ** Export BBDB contacts to org-contacts.el
2353 Try this tool by Wes Hardaker:
2355 http://www.hardakers.net/code/bbdb-to-org-contacts/
2357 ** Calculating date differences - how to write a simple elisp function
2359 Alexander Wingård asked how to calculate the number of days between a
2360 time stamp in his org file and today (see
2361 http://thread.gmane.org/gmane.emacs.orgmode/46881).  Although the
2362 resulting answer is probably not of general interest, the method might
2363 be useful to a budding Elisp programmer.
2365 Alexander started from an already existing org function,
2366 =org-evaluate-time-range=.  When this function is called in the context
2367 of a time range (two time stamps separated by "=--="), it calculates the
2368 number of days between the two dates and outputs the result in Emacs's
2369 echo area. What he wanted was a similar function that, when called from
2370 the context of a single time stamp, would calculate the number of days
2371 between the date in the time stamp and today. The result should go to
2372 the same place: Emacs's echo area.
2374 The solution presented in the mail thread is as follows:
2376 #+begin_src emacs-lisp
2377 (defun aw/org-evaluate-time-range (&optional to-buffer)
2378   (interactive)
2379   (if (org-at-date-range-p t)
2380       (org-evaluate-time-range to-buffer)
2381     ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
2382     (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
2383       (with-temp-buffer
2384         (insert headline)
2385         (goto-char (point-at-bol))
2386         (re-search-forward org-ts-regexp (point-at-eol) t)
2387         (if (not (org-at-timestamp-p t))
2388             (error "No timestamp here"))
2389         (goto-char (match-beginning 0))
2390         (org-insert-time-stamp (current-time) nil nil)
2391         (insert "--")
2392         (org-evaluate-time-range to-buffer)))))
2393 #+end_src
2395 The function assumes that point is on some line with some time stamp
2396 (or a date range) in it. Note that =org-evaluate-time-range= does not care
2397 whether the first date is earlier than the second: it will always output
2398 the number of days between the earlier date and the later date.
2400 As stated before, the function itself is of limited interest (although
2401 it satisfied Alexander's need).The *method* used might be of wider
2402 interest however, so here is a short explanation.
2404 The idea is that we want =org-evaluate-time-range= to do all the
2405 heavy lifting, but that function requires that it be in a date-range
2406 context. So the function first checks whether it's in a date range
2407 context already: if so, it calls =org-evaluate-time-range= directly
2408 to do the work. The trick now is to arrange things so we can call this
2409 same function in the case where we do *not* have a date range
2410 context. In that case, we manufacture one: we create a temporary
2411 buffer, copy the line with the purported time stamp to the temp
2412 buffer, find the time stamp (signal an error if no time stamp is
2413 found) and insert a new time stamp with the current time before the
2414 existing time stamp, followed by "=--=": voilà, we now have a time range
2415 on which we can apply our old friend =org-evaluate-time-range= to
2416 produce the answer. Because of the above-mentioned property
2417 of =org-evaluate-time-range=, it does not matter if the existing
2418 time stamp is earlier or later than the current time: the correct
2419 number of days is output.
2421 Note that at the end of the call to =with-temp-buffer=, the temporary
2422 buffer goes away.  It was just used as a scratch pad for the function
2423 to do some figuring.
2425 The idea of using a temp buffer as a scratch pad has wide
2426 applicability in Emacs programming. The rest of the work is knowing
2427 enough about facilities provided by Emacs (e.g. regexp searching) and
2428 by Org (e.g. checking for time stamps and generating a time stamp) so
2429 that you don't reinvent the wheel, and impedance-matching between the
2430 various pieces.
2432 * Hacking Org: Working with Org-mode and External Programs.
2433 ** Use Org-mode with Screen [Andrew Hyatt]
2435 "The general idea is that you start a task in which all the work will
2436 take place in a shell.  This usually is not a leaf-task for me, but
2437 usually the parent of a leaf task.  From a task in your org-file, M-x
2438 ash-org-screen will prompt for the name of a session.  Give it a name,
2439 and it will insert a link.  Open the link at any time to go the screen
2440 session containing your work!"
2442 http://article.gmane.org/gmane.emacs.orgmode/5276
2444 #+BEGIN_SRC emacs-lisp
2445 (require 'term)
2447 (defun ash-org-goto-screen (name)
2448   "Open the screen with the specified name in the window"
2449   (interactive "MScreen name: ")
2450   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2451     (if (member screen-buffer-name
2452                 (mapcar 'buffer-name (buffer-list)))
2453         (switch-to-buffer screen-buffer-name)
2454       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2456 (defun ash-org-screen-buffer-name (name)
2457   "Returns the buffer name corresponding to the screen name given."
2458   (concat "*screen " name "*"))
2460 (defun ash-org-screen-helper (name arg)
2461   ;; Pick the name of the new buffer.
2462   (let ((term-ansi-buffer-name
2463          (generate-new-buffer-name
2464           (ash-org-screen-buffer-name name))))
2465     (setq term-ansi-buffer-name
2466           (term-ansi-make-term
2467            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2468     (set-buffer term-ansi-buffer-name)
2469     (term-mode)
2470     (term-char-mode)
2471     (term-set-escape-char ?\C-x)
2472     term-ansi-buffer-name))
2474 (defun ash-org-screen (name)
2475   "Start a screen session with name"
2476   (interactive "MScreen name: ")
2477   (save-excursion
2478     (ash-org-screen-helper name "-S"))
2479   (insert-string (concat "[[screen:" name "]]")))
2481 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2482 ;; \"%s\")") to org-link-abbrev-alist.
2483 #+END_SRC
2485 ** Org Agenda + Appt + Zenity
2486 #+BEGIN_HTML
2487 <a name="agenda-appt-zenity"></a>
2488 #+END_HTML
2489 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It makes sure your agenda
2490 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2491 popup window.
2493 #+BEGIN_SRC emacs-lisp
2494 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2495 ; For org appointment reminders
2497 ;; Get appointments for today
2498 (defun my-org-agenda-to-appt ()
2499   (interactive)
2500   (setq appt-time-msg-list nil)
2501   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
2502         (org-agenda-to-appt)))
2504 ;; Run once, activate and schedule refresh
2505 (my-org-agenda-to-appt)
2506 (appt-activate t)
2507 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2509 ; 5 minute warnings
2510 (setq appt-message-warning-time 15)
2511 (setq appt-display-interval 5)
2513 ; Update appt each time agenda opened.
2514 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2516 ; Setup zenify, we tell appt to use window, and replace default function
2517 (setq appt-display-format 'window)
2518 (setq appt-disp-window-function (function my-appt-disp-window))
2520 (defun my-appt-disp-window (min-to-app new-time msg)
2521   (save-window-excursion (shell-command (concat
2522     "/usr/bin/zenity --info --title='Appointment' --text='"
2523     msg "' &") nil nil)))
2524 #+END_SRC
2526 ** Org-Mode + gnome-osd
2528 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2529 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2531 ** remind2org
2533 From Detlef Steuer
2535 http://article.gmane.org/gmane.emacs.orgmode/5073
2537 #+BEGIN_QUOTE
2538 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2539 command line calendaring program. Its features superseed the possibilities
2540 of orgmode in the area of date specifying, so that I want to use it
2541 combined with orgmode.
2543 Using the script below I'm able use remind and incorporate its output in my
2544 agenda views.  The default of using 13 months look ahead is easily
2545 changed. It just happens I sometimes like to look a year into the
2546 future. :-)
2547 #+END_QUOTE
2549 ** Useful webjumps for conkeror
2551 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2552 your =~/.conkerorrc= file:
2554 #+begin_example
2555 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2556 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2557 #+end_example
2559 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2560 Org-mode mailing list.
2562 ** Use MathJax for HTML export without requiring JavaScript
2563 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2565 If you like the results but do not want JavaScript in the exported pages,
2566 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2567 HTML file from the exported version. It can also embed all referenced fonts
2568 within the HTML file itself, so there are no dependencies to external files.
2570 The download archive contains an elisp file which integrates it into the Org
2571 export process (configurable per file with a "#+StaticMathJax:" line).
2573 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2574 ** Search Org files using lgrep
2576 Matt Lundin suggests this:
2578 #+begin_src emacs-lisp
2579   (defun my-org-grep (search &optional context)
2580     "Search for word in org files.
2582 Prefix argument determines number of lines."
2583     (interactive "sSearch for: \nP")
2584     (let ((grep-find-ignored-files '("#*" ".#*"))
2585           (grep-template (concat "grep <X> -i -nH "
2586                                  (when context
2587                                    (concat "-C" (number-to-string context)))
2588                                  " -e <R> <F>")))
2589       (lgrep search "*org*" "/home/matt/org/")))
2591   (global-set-key (kbd "<f8>") 'my-org-grep)
2592 #+end_src
2594 ** Automatic screenshot insertion
2596 Suggested by Russell Adams
2598 #+begin_src emacs-lisp
2599   (defun my-org-screenshot ()
2600     "Take a screenshot into a time stamped unique-named file in the
2601   same directory as the org-buffer and insert a link to this file."
2602     (interactive)
2603     (setq filename
2604           (concat
2605            (make-temp-name
2606             (concat (buffer-file-name)
2607                     "_"
2608                     (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
2609     (call-process "import" nil nil nil filename)
2610     (insert (concat "[[" filename "]]"))
2611     (org-display-inline-images))
2612 #+end_src
2614 ** Capture invitations/appointments from MS Exchange emails
2616 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this.  Please check
2617 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
2619 ** Audio/video file playback within org mode
2621 Paul Sexton provided code that makes =file:= links to audio or video files
2622 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
2623 media player library. The user can pause, skip forward and backward in the
2624 track, and so on from without leaving Emacs. Links can also contain a time
2625 after a double colon -- when this is present, playback will begin at that
2626 position in the track.
2628 See the file [[file:code/elisp/org-player.el][org-player.el]]
2630 ** Under X11 Keep a window with the current agenda items at all time
2632 I struggle to keep (in emacs) a window with the agenda at all times.
2633 For a long time I have wanted a sticky window that keeps this
2634 information, and then use my window manager to place it and remove its
2635 decorations (I can also force its placement in the stack: top always,
2636 for example).
2638 I wrote a small program in qt that simply monitors an HTML file and
2639 displays it. Nothing more. It does the work for me, and maybe somebody
2640 else will find it useful. It relies on exporting the agenda as HTML
2641 every time the org file is saved, and then this little program
2642 displays the html file. The window manager is responsible of removing
2643 decorations, making it sticky, and placing it in same place always.
2645 Here is a screenshot (see window to the bottom right). The decorations
2646 are removed by the window manager:
2648 http://turingmachine.org/hacking/org-mode/orgdisplay.png
2650 Here is the code. As I said, very, very simple, but maybe somebody will
2651 find if useful.
2653 http://turingmachine.org/hacking/org-mode/
2655 --daniel german
2657 ** Script (thru procmail) to output emails to an Org file
2659 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
2661 : I've [...] created some procmail and shell glue that takes emails and
2662 : inserts them into an org-file so that I can capture stuff on the go using
2663 : the email program.
2665 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
2667 ** Meaningful diff for org files in a git repository
2669 Since most diff utilities are primarily meant for source code, it is
2670 difficult to read diffs of text files like ~.org~ files easily. If you
2671 version your org directory with a SCM like git you will know what I
2672 mean. However for git, there is a way around. You can use
2673 =gitattributes= to define a custom diff driver for org files. Then a
2674 regular expression can be used to configure how the diff driver
2675 recognises a "function".
2677 Put the following in your =<org_dir>/.gitattributes=.
2678 : *.org diff=org
2679 Then put the following lines in =<org_dir>/.git/config=
2680 : [diff "org"]
2681 :       xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
2683 This will let you see diffs for org files with each hunk identified by
2684 the unmodified headline closest to the changes. After the
2685 configuration a diff should look something like the example below.
2687 #+begin_example
2688 diff --git a/org-hacks.org b/org-hacks.org
2689 index a0672ea..92a08f7 100644
2690 --- a/org-hacks.org
2691 +++ b/org-hacks.org
2692 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
2694  Everything is documented [[http://tychoish.com/code/org-mail/][here]].
2696 +** Meaningful diff for org files in a git repository
2698 +Since most diff utilities are primarily meant for source code, it is
2699 +difficult to read diffs of text files like ~.org~ files easily. If you
2700 +version your org directory with a SCM like git you will know what I
2701 +mean. However for git, there is a way around. You can use
2702 +=gitattributes= to define a custom diff driver for org files. Then a
2703 +regular expression can be used to configure how the diff driver
2704 +recognises a "function".
2706 +Put the following in your =<org_dir>/.gitattributes=.
2707 +: *.org        diff=org
2708 +Then put the following lines in =<org_dir>/.git/config=
2709 +: [diff "org"]
2710 +:      xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
2712  * Musings
2714  ** Cooking?  Brewing?
2715 #+end_example
2717 * Musings
2719 ** Cooking?  Brewing?
2721 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
2723 It currently does metric/english conversion, and a few other tricks.
2724 Basically I just use calc’s units code.  I think scaling recipes, or
2725 turning percentages into weights would be pretty easy.
2727   https://gitorious.org/org-cook/org-cook
2729 There is also, for those interested:
2731   https://gitorious.org/org-brew/org-brew
2733 for brewing beer. This is again, mostly just calc functions, including
2734 hydrometer correction, abv calculation, priming sugar for a given CO_2
2735 volume, etc. More integration with org-mode should be possible: for
2736 instance it would be nice to be able to use a lookup table (of ingredients)
2737 to calculate target original gravity, IBUs, etc.