Add Lawrence Mitchell as a signed contributor
[Worg.git] / org-hacks.org
blob77898bc04420bfa67020c53987d2c0a65b10c348
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 ** Enhancing the Org experience
142 *** Speed Commands
143 Speed commands are described [[http://orgmode.org/manual/Speed-keys.html#Speed-keys][here]] in the manual. Add your own speed
144 commands here.
145 *** Show next/prev heading tidily
146 - Dan Davison
147   These close the current heading and open the next/previous heading.
149 #+begin_src emacs-lisp
150 (defun ded/org-show-next-heading-tidily ()
151   "Show next entry, keeping other entries closed."
152   (if (save-excursion (end-of-line) (outline-invisible-p))
153       (progn (org-show-entry) (show-children))
154     (outline-next-heading)
155     (unless (and (bolp) (org-on-heading-p))
156       (org-up-heading-safe)
157       (hide-subtree)
158       (error "Boundary reached"))
159     (org-overview)
160     (org-reveal t)
161     (org-show-entry)
162     (show-children)))
164 (defun ded/org-show-previous-heading-tidily ()
165   "Show previous entry, keeping other entries closed."
166   (let ((pos (point)))
167     (outline-previous-heading)
168     (unless (and (< (point) pos) (bolp) (org-on-heading-p))
169       (goto-char pos)
170       (hide-subtree)
171       (error "Boundary reached"))
172     (org-overview)
173     (org-reveal t)
174     (org-show-entry)
175     (show-children)))
177 (setq org-use-speed-commands t)
178 (add-to-list 'org-speed-commands-user
179              '("n" ded/org-show-next-heading-tidily))
180 (add-to-list 'org-speed-commands-user 
181              '("p" ded/org-show-previous-heading-tidily))
182 #+end_src
184 *** Changelog support for org headers
185 -- James TD Smith
187 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
188 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
189 headline as the "current function" if you add a changelog entry from an org
190 buffer.
192 #+BEGIN_SRC emacs-lisp
193   (defun org-log-current-defun ()
194     (save-excursion
195       (org-back-to-heading)
196       (if (looking-at org-complex-heading-regexp)
197           (match-string 4))))
198   
199   (add-hook 'org-mode-hook
200             (lambda ()
201               (make-variable-buffer-local 'add-log-current-defun-function)
202               (setq add-log-current-defun-function 'org-log-current-defun)))
203 #+END_SRC
205 *** Different org-cycle-level behavior
206 -- Ryan Thompson
208 In recent org versions, when your point (cursor) is at the end of an
209 empty header line (like after you first created the header), the TAB
210 key (=org-cycle=) has a special behavior: it cycles the headline through
211 all possible levels. However, I did not like the way it determined
212 "all possible levels," so I rewrote the whole function, along with a
213 couple of supporting functions.
215 The original function's definition of "all possible levels" was "every
216 level from 1 to one more than the initial level of the current
217 headline before you started cycling." My new definition is "every
218 level from 1 to one more than the previous headline's level." So, if
219 you have a headline at level 4 and you use ALT+RET to make a new
220 headline below it, it will cycle between levels 1 and 5, inclusive.
222 The main advantage of my custom =org-cycle-level= function is that it
223 is stateless: the next level in the cycle is determined entirely by
224 the contents of the buffer, and not what command you executed last.
225 This makes it more predictable, I hope.
227 #+BEGIN_SRC emacs-lisp
228 (require 'cl)
230 (defun org-point-at-end-of-empty-headline ()
231   "If point is at the end of an empty headline, return t, else nil."
232   (and (looking-at "[ \t]*$")
233        (save-excursion
234          (beginning-of-line 1)
235          (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
237 (defun org-level-increment ()
238   "Return the number of stars that will be added or removed at a
239 time to headlines when structure editing, based on the value of
240 `org-odd-levels-only'."
241   (if org-odd-levels-only 2 1))
243 (defvar org-previous-line-level-cached nil)
245 (defun org-recalculate-previous-line-level ()
246   "Same as `org-get-previous-line-level', but does not use cached
247 value. It does *set* the cached value, though."
248   (set 'org-previous-line-level-cached
249        (let ((current-level (org-current-level))
250              (prev-level (when (> (line-number-at-pos) 1)
251                            (save-excursion
252                              (previous-line)
253                              (org-current-level)))))
254          (cond ((null current-level) nil) ; Before first headline
255                ((null prev-level) 0)      ; At first headline
256                (prev-level)))))
258 (defun org-get-previous-line-level ()
259   "Return the outline depth of the last headline before the
260 current line. Returns 0 for the first headline in the buffer, and
261 nil if before the first headline."
262   ;; This calculation is quite expensive, with all the regex searching
263   ;; and stuff. Since org-cycle-level won't change lines, we can reuse
264   ;; the last value of this command.
265   (or (and (eq last-command 'org-cycle-level)
266            org-previous-line-level-cached)
267       (org-recalculate-previous-line-level)))
269 (defun org-cycle-level ()
270   (interactive)
271   (let ((org-adapt-indentation nil))
272     (when (org-point-at-end-of-empty-headline)
273       (setq this-command 'org-cycle-level) ;Only needed for caching
274       (let ((cur-level (org-current-level))
275             (prev-level (org-get-previous-line-level)))
276         (cond
277          ;; If first headline in file, promote to top-level.
278          ((= prev-level 0)
279           (loop repeat (/ (- cur-level 1) (org-level-increment))
280                 do (org-do-promote)))
281          ;; If same level as prev, demote one.
282          ((= prev-level cur-level)
283           (org-do-demote))
284          ;; If parent is top-level, promote to top level if not already.
285          ((= prev-level 1)
286           (loop repeat (/ (- cur-level 1) (org-level-increment))
287                 do (org-do-promote)))
288          ;; If top-level, return to prev-level.
289          ((= cur-level 1)
290           (loop repeat (/ (- prev-level 1) (org-level-increment))
291                 do (org-do-demote)))
292          ;; If less than prev-level, promote one.
293          ((< cur-level prev-level)
294           (org-do-promote))
295          ;; If deeper than prev-level, promote until higher than
296          ;; prev-level.
297          ((> cur-level prev-level)
298           (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
299                 do (org-do-promote))))
300         t))))
301 #+END_SRC
302 *** Org table
304 **** Transpose tables (Juan Pechiar)
306 This function by Juan Pechiar will transpose a table:
308 #+begin_src emacs-lisp
309 (defun org-transpose-table-at-point ()
310   "Transpose orgmode table at point, eliminate hlines"
311   (interactive)
312   (let ((contents 
313          (apply #'mapcar* #'list
314                 ;; remove 'hline from list
315                 (remove-if-not 'listp  
316                                ;; signals error if not table
317                                (org-table-to-lisp)))))
318     (delete-region (org-table-begin) (org-table-end))
319     (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) "  |\n" ))
320                        contents ""))
321     (org-table-align)))
322 #+end_src
324 So a table like
326 : | 1 | 2 | 4 | 5 |
327 : |---+---+---+---|
328 : | a | b | c | d |
329 : | e | f | g | h |
331 will be transposed as
333 : | 1 | a | e |
334 : | 2 | b | f |
335 : | 4 | c | g |
336 : | 5 | d | h |
338 (Note that horizontal lines disappeared.)
340 *** Times computation
341     :PROPERTIES:
342     :CUSTOM_ID: time-computation
343     :END:
344 **** Manipulate hours/minutes/seconds in table formulas
346 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
347 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
348 "=d=" is any digit) as time values in Org-mode table formula.  These
349 functions have now been wrapped up into a =with-time= macro which can
350 be used in table formula to translate table cell values to and from
351 numerical values for algebraic manipulation.
353 Here is the code implementing this macro.
354 #+begin_src emacs-lisp :results silent
355   (defun org-time-string-to-seconds (s)
356     "Convert a string HH:MM:SS to a number of seconds."
357     (cond
358      ((and (stringp s)
359            (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
360       (let ((hour (string-to-number (match-string 1 s)))
361             (min (string-to-number (match-string 2 s)))
362             (sec (string-to-number (match-string 3 s))))
363         (+ (* hour 3600) (* min 60) sec)))
364      ((and (stringp s)
365            (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
366       (let ((min (string-to-number (match-string 1 s)))
367             (sec (string-to-number (match-string 2 s))))
368         (+ (* min 60) sec)))
369      ((stringp s) (string-to-number s))
370      (t s)))
372   (defun org-time-seconds-to-string (secs)
373     "Convert a number of seconds to a time string."
374     (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
375           ((>= secs 60) (format-seconds "%m:%.2s" secs))
376           (t (format-seconds "%s" secs))))
378   (defmacro with-time (time-output-p &rest exprs)
379     "Evaluate an org-table formula, converting all fields that look
380   like time data to integer seconds.  If TIME-OUTPUT-P then return
381   the result as a time value."
382     (list
383      (if time-output-p 'org-time-seconds-to-string 'identity)
384      (cons 'progn
385            (mapcar
386             (lambda (expr)
387               `,(cons (car expr)
388                       (mapcar
389                        (lambda (el)
390                          (if (listp el)
391                              (list 'with-time nil el)
392                            (org-time-string-to-seconds el)))
393                        (cdr expr))))
394             `,@exprs))))
395 #+end_src
397 Which allows the following forms of table manipulation such as adding
398 and subtracting time values.
399 : | Date             | Start | Lunch |  Back |   End |  Sum |
400 : |------------------+-------+-------+-------+-------+------|
401 : | [2011-03-01 Tue] |  8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
402 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
404 and dividing time values by integers
405 : |  time | miles | minutes/mile |
406 : |-------+-------+--------------|
407 : | 34:43 |   2.9 |        11:58 |
408 : | 32:15 |  2.77 |        11:38 |
409 : | 33:56 |   3.0 |        11:18 |
410 : | 52:22 |  4.62 |        11:20 |
411 : #+TBLFM: $3='(with-time t (/ $1 $2))
413 *** Dates computation
415 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
417 I have a table in org which stores the date, I'm wondering if there is
418 any function to calculate the duration? For example:
420 | Start Date |   End Date | Duration |
421 |------------+------------+----------|
422 | 2004.08.07 | 2005.07.08 |          |
424 I tried to use B&-C&, but failed ...
426 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
428 Try the following:
430 | Start Date |   End Date | Duration |
431 |------------+------------+----------|
432 | 2004.08.07 | 2005.07.08 |      335 |
433 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
435 See this thread:
437     http://thread.gmane.org/gmane.emacs.orgmode/7741
439 as well as this post (which is really a followup on the
440 above):
442     http://article.gmane.org/gmane.emacs.orgmode/7753
444 The problem that this last article pointed out was solved
447     http://article.gmane.org/gmane.emacs.orgmode/8001
449 and Chris Randle's original musings are at
451     http://article.gmane.org/gmane.emacs.orgmode/6536/
453 *** Hex computation
454 As with [[#time-computation][Times computation]], the following code allows Computation with
455 Hex values in Org-mode tables using the =with-hex= macro.
457 Here is the code implementing this macro.
458 #+begin_src emacs-lisp
459   (defun org-hex-strip-lead (str)
460     (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
461         (substring str 2) str))
462   
463   (defun org-hex-to-hex (int)
464     (format "0x%x" int))
465   
466   (defun org-hex-to-dec (str)
467     (cond
468      ((and (stringp str)
469            (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
470       (let ((out 0))
471         (mapc
472          (lambda (ch)
473            (setf out (+ (* out 16)
474                         (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
475          (coerce (match-string 1 str) 'list))
476         out))
477      ((stringp str) (string-to-number str))
478      (t str)))
479   
480   (defmacro with-hex (hex-output-p &rest exprs)
481     "Evaluate an org-table formula, converting all fields that look
482       like hexadecimal to decimal integers.  If HEX-OUTPUT-P then
483       return the result as a hex value."
484     (list
485      (if hex-output-p 'org-hex-to-hex 'identity)
486      (cons 'progn
487            (mapcar
488             (lambda (expr)
489               `,(cons (car expr)
490                       (mapcar (lambda (el)
491                                 (if (listp el)
492                                     (list 'with-hex nil el)
493                                   (org-hex-to-dec el)))
494                               (cdr expr))))
495             `,@exprs))))
496 #+end_src
498 Which allows the following forms of table manipulation such as adding
499 and subtracting hex values.
500 | 0x10 | 0x0 | 0x10 |  16 |
501 | 0x20 | 0x1 | 0x21 |  33 |
502 | 0x30 | 0x2 | 0x32 |  50 |
503 | 0xf0 | 0xf | 0xff | 255 |
504 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
506 *** Field coordinates in formulas (=@#= and =$#=)
508 -- Michael Brand
510 Following are some use cases that can be implemented with the
511 _field coordinates in formulas_ described in the corresponding
512 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
514 **** Copy a column from a remote table into a column
516 current column =$3= = remote column =$2=:
517 : #+TBLFM: $3 = remote(FOO, @@#$2)
519 **** Copy a row from a remote table transposed into a column
521 current column =$1= = transposed remote row =@1=:
522 : #+TBLFM: $1 = remote(FOO, @$#$@#)
524 **** Transpose a table
526 -- Michael Brand
528 This is more like a demonstration of using _field coordinates in formulas_
529 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel.  The efficient
530 and simple solution for this with the help of org-babel and Emacs Lisp has
531 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
533 To transpose this 4x7 table
535 : #+TBLNAME: FOO
536 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
537 : |------+------+------+------+------+------+------|
538 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
539 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
540 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
542 start with a 7x4 table without any horizontal line (to have filled
543 also the column header) and yet empty:
545 : |   |   |   |   |
546 : |   |   |   |   |
547 : |   |   |   |   |
548 : |   |   |   |   |
549 : |   |   |   |   |
550 : |   |   |   |   |
551 : |   |   |   |   |
553 Then add the =TBLFM= below with the same formula repeated for each column.
554 After recalculation this will end up with the transposed copy:
556 : | year | min | avg | max |
557 : | 2004 | 401 | 402 | 403 |
558 : | 2005 | 501 | 502 | 503 |
559 : | 2006 | 601 | 602 | 603 |
560 : | 2007 | 701 | 702 | 703 |
561 : | 2008 | 801 | 802 | 803 |
562 : | 2009 | 901 | 902 | 903 |
563 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
565 The formulas simply exchange row and column numbers by taking
566 - the absolute remote row number =@$#= from the current column number =$#=
567 - the absolute remote column number =$@#= from the current row number =@#=
569 Possible field formulas from the remote table will have to be transferred
570 manually.  Since there are no row formulas yet there is no need to transfer
571 column formulas to row formulas or vice versa.
573 **** Dynamic variation of ranges
575 -- Michael Brand
577 In this example all columns next to =quote= are calculated from the column
578 =quote= and show the average change of the time series =quote[year]=
579 during the period of the preceding =1=, =2=, =3= or =4= years:
581 : | year | quote |   1 a |   2 a |   3 a |   4 a |
582 : |------+-------+-------+-------+-------+-------|
583 : | 2005 |    10 |       |       |       |       |
584 : | 2006 |    12 | 0.200 |       |       |       |
585 : | 2007 |    14 | 0.167 | 0.183 |       |       |
586 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
587 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
588 : #+TBLFM: $3=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$4=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$5=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$6=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3
590 The formula is the same for each column =$3= through =$6=.  This can easily
591 be seen with the great formula editor invoked by C-c ' on the
592 table. The important part of the formula without the field blanking is:
594 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
596 which is the Emacs Calc implementation of the equation
598 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
600 where /i/ is the current time and /a/ is the length of the preceding period.
602 *** Customize the size of the frame for remember
603 (Note: this hack is likely out of date due to the development of
604 [[org-capture]].) 
606 #FIXME: gmane link?
607 On emacs-orgmode, Ryan C. Thompson suggested this:
609 #+begin_quote
610 I am using org-remember set to open a new frame when used,
611 and the default frame size is much too large. To fix this, I have
612 designed some advice and a custom variable to implement custom
613 parameters for the remember frame:
614 #+end_quote
616 #+begin_src emacs-lisp
617 (defcustom remember-frame-alist nil
618   "Additional frame parameters for dedicated remember frame."
619   :type 'alist
620   :group 'remember)
622 (defadvice remember (around remember-frame-parameters activate)
623   "Set some frame parameters for the remember frame."
624   (let ((default-frame-alist (append remember-frame-alist
625                                      default-frame-alist)))
626     ad-do-it))
627 #+end_src
629 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
630 reasonable size for the frame.
631 *** Promote all items in subtree
632 - Matt Lundin
634 This function will promote all items in a subtree. Since I use
635 subtrees primarily to organize projects, the function is somewhat
636 unimaginatively called my-org-un-project:
638 #+begin_src emacs-lisp
639 (defun my-org-un-project ()
640   (interactive)
641   (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
642   (org-cycle t))
643 #+end_src
645 *** Turn a heading into an Org link
647 From David Maus:
649 #+begin_src emacs-lisp
650   (defun dmj:turn-headline-into-org-mode-link ()
651     "Replace word at point by an Org mode link."
652     (interactive)
653     (when (org-at-heading-p)
654       (let ((hl-text (nth 4 (org-heading-components))))
655         (unless (or (null hl-text)
656                     (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
657           (beginning-of-line)
658           (search-forward hl-text (point-at-eol))
659           (replace-string
660            hl-text
661            (format "[[file:%s.org][%s]]"
662                    (org-link-escape hl-text)
663                    (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
664            nil (- (point) (length hl-text)) (point))))))
665 #+end_src
667 *** Count words in an Org buffer
669 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
671 #+begin_src emacs-lisp
672 (defun org-word-count (beg end
673                            &optional count-latex-macro-args?
674                            count-footnotes?)
675   "Report the number of words in the Org mode buffer or selected region.
676 Ignores:
677 - comments
678 - tables
679 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
680 - hyperlinks (but does count words in hyperlink descriptions)
681 - tags, priorities, and TODO keywords in headers
682 - sections tagged as 'not for export'.
684 The text of footnote definitions is ignored, unless the optional argument
685 COUNT-FOOTNOTES? is non-nil.
687 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
688 includes LaTeX macro arguments (the material between {curly braces}).
689 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
690 of its arguments."
691   (interactive "r")
692   (unless mark-active
693     (setf beg (point-min)
694           end (point-max)))
695   (let ((wc 0)
696         (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
697     (save-excursion
698       (goto-char beg)
699       (while (< (point) end)
700         (cond
701          ;; Ignore comments.
702          ((or (org-in-commented-line) (org-at-table-p))
703           nil)
704          ;; Ignore hyperlinks. But if link has a description, count
705          ;; the words within the description.
706          ((looking-at org-bracket-link-analytic-regexp)
707           (when (match-string-no-properties 5)
708             (let ((desc (match-string-no-properties 5)))
709               (save-match-data 
710                 (incf wc (length (remove "" (org-split-string
711                                              desc "\\W")))))))
712           (goto-char (match-end 0)))
713          ((looking-at org-any-link-re)
714           (goto-char (match-end 0)))
715          ;; Ignore source code blocks.
716          ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
717           nil)
718          ;; Ignore inline source blocks, counting them as 1 word.
719          ((save-excursion
720             (backward-char)
721             (looking-at org-babel-inline-src-block-regexp))
722           (goto-char (match-end 0))
723           (setf wc (+ 2 wc)))
724          ;; Count latex macros as 1 word, ignoring their arguments.
725          ((save-excursion
726             (backward-char)
727             (looking-at latex-macro-regexp))
728           (goto-char (if count-latex-macro-args?
729                          (match-beginning 2)
730                        (match-end 0)))
731           (setf wc (+ 2 wc)))
732          ;; Ignore footnotes.
733          ((and (not count-footnotes?)
734                (or (org-footnote-at-definition-p)
735                    (org-footnote-at-reference-p)))
736           nil)
737          (t
738           (let ((contexts (org-context)))
739             (cond
740              ;; Ignore tags and TODO keywords, etc.
741              ((or (assoc :todo-keyword contexts)
742                   (assoc :priority contexts)
743                   (assoc :keyword contexts)
744                   (assoc :checkbox contexts))
745               nil)
746              ;; Ignore sections marked with tags that are
747              ;; excluded from export.
748              ((assoc :tags contexts)
749               (if (intersection (org-get-tags-at) org-export-exclude-tags
750                                 :test 'equal)
751                   (org-forward-same-level 1)
752                 nil))
753              (t
754               (incf wc))))))
755         (re-search-forward "\\w+\\W*")))
756     (message (format "%d words in %s." wc
757                      (if mark-active "region" "buffer")))))
758 #+end_src
760 ** Archiving Content in Org-Mode
761 *** Preserve top level headings when archiving to a file
762 - Matt Lundin
764 To preserve (somewhat) the integrity of your archive structure while
765 archiving lower level items to a file, you can use the following
766 defadvice:
768 #+begin_src emacs-lisp
769 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
770   (let ((org-archive-location 
771          (if (save-excursion (org-back-to-heading)
772                              (> (org-outline-level) 1))
773              (concat (car (split-string org-archive-location "::"))
774                      "::* "
775                      (car (org-get-outline-path)))
776            org-archive-location)))
777     ad-do-it))
778 #+end_src
780 Thus, if you have an outline structure such as...
782 #+begin_src org
783 ,* Heading
784 ,** Subheading
785 ,*** Subsubheading
786 #+end_src
788 ...archiving "Subsubheading" to a new file will set the location in
789 the new file to the top level heading:
791 #+begin_src org
792 ,* Heading
793 ,** Subsubheading
794 #+end_src
796 While this hack obviously destroys the outline hierarchy somewhat, it
797 at least preserves the logic of level one groupings.
799 A slightly more complex version of this hack will not only keep the
800 archive organized by top-level headings, but will also preserve the
801 tags found on those headings:
803 #+begin_src emacs-lisp
804   (defun my-org-inherited-no-file-tags ()
805     (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
806           (ltags (org-entry-get nil "TAGS")))
807       (mapc (lambda (tag)
808               (setq tags 
809                     (replace-regexp-in-string (concat tag ":") "" tags)))
810             (append org-file-tags (when ltags (split-string ltags ":" t))))
811       (if (string= ":" tags) nil tags)))
812   
813   (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
814     (let ((tags (my-org-inherited-no-file-tags))
815           (org-archive-location 
816            (if (save-excursion (org-back-to-heading)
817                                (> (org-outline-level) 1))
818                (concat (car (split-string org-archive-location "::"))
819                        "::* "
820                        (car (org-get-outline-path)))
821              org-archive-location)))
822       ad-do-it
823       (with-current-buffer (find-file-noselect (org-extract-archive-file))
824         (save-excursion
825           (while (org-up-heading-safe))
826           (org-set-tags-to tags)))))
827 #+end_src
829 *** Archive in a date tree
831 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
833 (Make sure org-datetree.el is loaded for this to work.)
835 #+begin_src emacs-lisp
836 ;; (setq org-archive-location "%s_archive::date-tree")
837 (defadvice org-archive-subtree
838   (around org-archive-subtree-to-data-tree activate)
839   "org-archive-subtree to date-tree"
840   (if
841       (string= "date-tree"
842                (org-extract-archive-heading
843                 (org-get-local-archive-location)))
844       (let* ((dct (decode-time (org-current-time)))
845              (y (nth 5 dct))
846              (m (nth 4 dct))
847              (d (nth 3 dct))
848              (this-buffer (current-buffer))
849              (location (org-get-local-archive-location))
850              (afile (org-extract-archive-file location))
851              (org-archive-location
852               (format "%s::*** %04d-%02d-%02d %s" afile y m d
853                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
854         (message "afile=%s" afile)
855         (unless afile
856           (error "Invalid `org-archive-location'"))
857         (save-excursion
858           (switch-to-buffer (find-file-noselect afile))
859           (org-datetree-find-year-create y)
860           (org-datetree-find-month-create y m)
861           (org-datetree-find-day-create y m d)
862           (widen)
863           (switch-to-buffer this-buffer))
864         ad-do-it)
865     ad-do-it))
866 #+end_src
868 *** Add inherited tags to archived entries
870 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
871 advise the function like this:
873 #+begin_example
874 (defadvice org-archive-subtree
875   (before add-inherited-tags-before-org-archive-subtree activate)
876     "add inherited tags before org-archive-subtree"
877     (org-set-tags-to (org-get-tags-at)))
878 #+end_example
880 ** Using and Managing Org-Metadata
881 *** Remove redundant tags of headlines
882 -- David Maus
884 A small function that processes all headlines in current buffer and
885 removes tags that are local to a headline and inherited by a parent
886 headline or the #+FILETAGS: statement.
888 #+BEGIN_SRC emacs-lisp
889   (defun dmj/org-remove-redundant-tags ()
890     "Remove redundant tags of headlines in current buffer.
892   A tag is considered redundant if it is local to a headline and
893   inherited by a parent headline."
894     (interactive)
895     (when (eq major-mode 'org-mode)
896       (save-excursion
897         (org-map-entries
898          '(lambda ()
899             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
900                   local inherited tag)
901               (dolist (tag alltags)
902                 (if (get-text-property 0 'inherited tag)
903                     (push tag inherited) (push tag local)))
904               (dolist (tag local)
905                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
906          t nil))))
907 #+END_SRC
909 *** Remove empty property drawers
911 David Maus proposed this:
913 #+begin_src emacs-lisp
914 (defun dmj:org:remove-empty-propert-drawers ()
915   "*Remove all empty property drawers in current file."
916   (interactive)
917   (unless (eq major-mode 'org-mode)
918     (error "You need to turn on Org mode for this function."))
919   (save-excursion
920     (goto-char (point-min))
921     (while (re-search-forward ":PROPERTIES:" nil t)
922       (save-excursion
923         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
924 #+end_src
926 *** Group task list by a property
928 This advice allows you to group a task list in Org-Mode.  To use it,
929 set the variable =org-agenda-group-by-property= to the name of a
930 property in the option list for a TODO or TAGS search.  The resulting
931 agenda view will group tasks by that property prior to searching.
933 #+begin_src emacs-lisp
934 (defvar org-agenda-group-by-property nil
935   "Set this in org-mode agenda views to group tasks by property")
937 (defun org-group-bucket-items (prop items)
938   (let ((buckets ()))
939     (dolist (item items)
940       (let* ((marker (get-text-property 0 'org-marker item))
941              (pvalue (org-entry-get marker prop t))
942              (cell (assoc pvalue buckets)))
943         (if cell
944             (setcdr cell (cons item (cdr cell)))
945           (setq buckets (cons (cons pvalue (list item))
946                               buckets)))))
947     (setq buckets (mapcar (lambda (bucket)
948                             (cons (car bucket)
949                                   (reverse (cdr bucket))))
950                           buckets))
951     (sort buckets (lambda (i1 i2)
952                     (string< (car i1) (car i2))))))
954 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
955                                                (list &optional nosort))
956   "Prepare bucketed agenda entry lists"
957   (if org-agenda-group-by-property
958       ;; bucketed, handle appropriately
959       (let ((text ""))
960         (dolist (bucket (org-group-bucket-items
961                          org-agenda-group-by-property
962                          list))
963           (let ((header (concat "Property "
964                                 org-agenda-group-by-property
965                                 " is "
966                                 (or (car bucket) "<nil>") ":\n")))
967             (add-text-properties 0 (1- (length header))
968                                  (list 'face 'org-agenda-structure)
969                                  header)
970             (setq text
971                   (concat text header
972                           ;; recursively process
973                           (let ((org-agenda-group-by-property nil))
974                             (org-finalize-agenda-entries
975                              (cdr bucket) nosort))
976                           "\n\n"))))
977         (setq ad-return-value text))
978     ad-do-it))
979 (ad-activate 'org-finalize-agenda-entries)
980 #+end_src
981 *** A way to tag a task so that when clocking-out user is prompted to take a note.
982     Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
984 A small hook run when clocking out of a task that prompts for a note
985 when the tag "=clockout_note=" is found in a headline. It uses the tag
986 ("=clockout_note=") so inheritance can also be used...
988 #+begin_src emacs-lisp
989   (defun rgr/check-for-clock-out-note()
990         (interactive)
991         (save-excursion 
992           (org-back-to-heading)
993           (let ((tags (org-get-tags)))
994             (and tags (message "tags: %s " tags)
995                  (when (member "clocknote" tags)
996                    (org-add-note))))))
997    
998   (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
999 #+end_src
1000 *** Dynamically adjust tag position
1001 Here is a bit of code that allows you to have the tags always
1002 right-adjusted in the buffer.
1004 This is useful when you have bigger window than default window-size
1005 and you dislike the aesthetics of having the tag in the middle of the
1006 line.
1008 This hack solves the problem of adjusting it whenever you change the
1009 window size.
1010 Before saving it will revert the file to having the tag position be
1011 left-adjusted so that if you track your files with version control,
1012 you won't run into artificial diffs just because the window-size
1013 changed.
1015 *IMPORTANT*: This is probably slow on very big files.
1017 #+begin_src emacs-lisp
1018 (setq ba/org-adjust-tags-column t)
1020 (defun ba/org-adjust-tags-column-reset-tags ()
1021   "In org-mode buffers it will reset tag position according to
1022 `org-tags-column'."
1023   (when (and
1024          (not (string= (buffer-name) "*Remember*"))
1025          (eql major-mode 'org-mode))
1026     (let ((b-m-p (buffer-modified-p)))
1027       (condition-case nil
1028           (save-excursion
1029             (goto-char (point-min))
1030             (command-execute 'outline-next-visible-heading)
1031             ;; disable (message) that org-set-tags generates
1032             (flet ((message (&rest ignored) nil))
1033               (org-set-tags 1 t))
1034             (set-buffer-modified-p b-m-p))
1035         (error nil)))))
1037 (defun ba/org-adjust-tags-column-now ()
1038   "Right-adjust `org-tags-column' value, then reset tag position."
1039   (set (make-local-variable 'org-tags-column)
1040        (- (- (window-width) (length org-ellipsis))))
1041   (ba/org-adjust-tags-column-reset-tags))
1043 (defun ba/org-adjust-tags-column-maybe ()
1044   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1045   (when ba/org-adjust-tags-column
1046     (ba/org-adjust-tags-column-now)))
1048 (defun ba/org-adjust-tags-column-before-save ()
1049   "Tags need to be left-adjusted when saving."
1050   (when ba/org-adjust-tags-column
1051      (setq org-tags-column 1)
1052      (ba/org-adjust-tags-column-reset-tags)))
1054 (defun ba/org-adjust-tags-column-after-save ()
1055   "Revert left-adjusted tag position done by before-save hook."
1056   (ba/org-adjust-tags-column-maybe)
1057   (set-buffer-modified-p nil))
1059 ; automatically align tags on right-hand side
1060 (add-hook 'window-configuration-change-hook
1061           'ba/org-adjust-tags-column-maybe)
1062 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1063 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1064 (add-hook 'org-agenda-mode-hook '(lambda ()
1065                                   (setq org-agenda-tags-column (- (window-width)))))
1067 ; between invoking org-refile and displaying the prompt (which
1068 ; triggers window-configuration-change-hook) tags might adjust, 
1069 ; which invalidates the org-refile cache
1070 (defadvice org-refile (around org-refile-disable-adjust-tags)
1071   "Disable dynamically adjusting tags"
1072   (let ((ba/org-adjust-tags-column nil))
1073     ad-do-it))
1074 (ad-activate 'org-refile)
1075 #+end_src
1076 ** Org Agenda and Task Management
1077 *** Make it easier to set org-agenda-files from multiple directories
1078 - Matt Lundin
1080 #+begin_src emacs-lisp
1081 (defun my-org-list-files (dirs ext)
1082   "Function to create list of org files in multiple subdirectories.
1083 This can be called to generate a list of files for
1084 org-agenda-files or org-refile-targets.
1086 DIRS is a list of directories.
1088 EXT is a list of the extensions of files to be included."
1089   (let ((dirs (if (listp dirs)
1090                   dirs
1091                 (list dirs)))
1092         (ext (if (listp ext)
1093                  ext
1094                (list ext)))
1095         files)
1096     (mapc 
1097      (lambda (x)
1098        (mapc 
1099         (lambda (y)
1100           (setq files 
1101                 (append files 
1102                         (file-expand-wildcards 
1103                          (concat (file-name-as-directory x) "*" y)))))
1104         ext))
1105      dirs)
1106     (mapc
1107      (lambda (x)
1108        (when (or (string-match "/.#" x)
1109                  (string-match "#$" x))
1110          (setq files (delete x files))))
1111      files)
1112     files))
1114 (defvar my-org-agenda-directories '("~/org/")
1115   "List of directories containing org files.")
1116 (defvar my-org-agenda-extensions '(".org")
1117   "List of extensions of agenda files")
1119 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1120 (setq my-org-agenda-extensions '(".org" ".ref"))
1122 (defun my-org-set-agenda-files ()
1123   (interactive)
1124   (setq org-agenda-files (my-org-list-files 
1125                           my-org-agenda-directories
1126                           my-org-agenda-extensions)))
1128 (my-org-set-agenda-files)
1129 #+end_src
1131 The code above will set your "default" agenda files to all files
1132 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1133 You can change these values by setting the variables
1134 my-org-agenda-extensions and my-org-agenda-directories. The function
1135 my-org-agenda-files-by-filetag uses these two variables to determine
1136 which files to search for filetags (i.e., the larger set from which
1137 the subset will be drawn).
1139 You can also easily use my-org-list-files to "mix and match"
1140 directories and extensions to generate different lists of agenda
1141 files.
1143 *** Restrict org-agenda-files by filetag
1144   :PROPERTIES:
1145   :CUSTOM_ID: set-agenda-files-by-filetag
1146   :END:
1147 - Matt Lundin
1149 It is often helpful to limit yourself to a subset of your agenda
1150 files. For instance, at work, you might want to see only files related
1151 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1152 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
1153 commands]]. These solutions, however, require reapplying a filter each
1154 time you call the agenda or writing several new custom agenda commands
1155 for each context. Another solution is to use directories for different
1156 types of tasks and to change your agenda files with a function that
1157 sets org-agenda-files to the appropriate directory. But this relies on
1158 hard and static boundaries between files.
1160 The following functions allow for a more dynamic approach to selecting
1161 a subset of files based on filetags:
1163 #+begin_src emacs-lisp
1164 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1165   "Restrict org agenda files only to those containing filetag."
1166   (interactive)
1167   (let* ((tagslist (my-org-get-all-filetags))
1168          (ftag (or tag 
1169                    (completing-read "Tag: " 
1170                                     (mapcar 'car tagslist)))))
1171     (org-agenda-remove-restriction-lock 'noupdate)
1172     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1173     (setq org-agenda-overriding-restriction 'files)))
1175 (defun my-org-get-all-filetags ()
1176   "Get list of filetags from all default org-files."
1177   (let ((files org-agenda-files)
1178         tagslist x)
1179     (save-window-excursion
1180       (while (setq x (pop files))
1181         (set-buffer (find-file-noselect x))
1182         (mapc
1183          (lambda (y)
1184            (let ((tagfiles (assoc y tagslist)))
1185              (if tagfiles
1186                  (setcdr tagfiles (cons x (cdr tagfiles)))
1187                (add-to-list 'tagslist (list y x)))))
1188          (my-org-get-filetags)))
1189       tagslist)))
1191 (defun my-org-get-filetags ()
1192   "Get list of filetags for current buffer"
1193   (let ((ftags org-file-tags)
1194         x)
1195     (mapcar 
1196      (lambda (x)
1197        (org-substring-no-properties x))
1198      ftags)))
1199 #+end_src
1201 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1202 with all filetags in your "normal" agenda files. When you select a
1203 tag, org-agenda-files will be restricted to only those files
1204 containing the filetag. To release the restriction, type C-c C-x >
1205 (org-agenda-remove-restriction-lock).
1207 *** Highlight the agenda line under cursor
1209 This is useful to make sure what task you are operating on.
1211 #+BEGIN_SRC emacs-lisp
1212 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1213 #+END_SRC emacs-lisp
1215 Under XEmacs:
1217 #+BEGIN_SRC emacs-lisp
1218 ;; hl-line seems to be only for emacs
1219 (require 'highline)
1220 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1222 ;; highline-mode does not work straightaway in tty mode.
1223 ;; I use a black background
1224 (custom-set-faces
1225   '(highline-face ((((type tty) (class color))
1226                     (:background "white" :foreground "black")))))
1227 #+END_SRC emacs-lisp
1229 *** Split horizontally for agenda
1231 If you would like to split the frame into two side-by-side windows when
1232 displaying the agenda, try this hack from Jan Rehders, which uses the
1233 `toggle-window-split' from
1235 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1237 #+BEGIN_SRC emacs-lisp
1238 ;; Patch org-mode to use vertical splitting
1239 (defadvice org-prepare-agenda (after org-fix-split)
1240   (toggle-window-split))
1241 (ad-activate 'org-prepare-agenda)
1242 #+END_SRC
1244 *** Automatically add an appointment when clocking in a task
1246 #+BEGIN_SRC emacs-lisp
1247 ;; Make sure you have a sensible value for `appt-message-warning-time'
1248 (defvar bzg-org-clock-in-appt-delay 100
1249   "Number of minutes for setting an appointment by clocking-in")
1250 #+END_SRC
1252 This function let's you add an appointment for the current entry.
1253 This can be useful when you need a reminder.
1255 #+BEGIN_SRC emacs-lisp
1256 (defun bzg-org-clock-in-add-appt (&optional n)
1257   "Add an appointment for the Org entry at point in N minutes."
1258   (interactive)
1259   (save-excursion
1260     (org-back-to-heading t)
1261     (looking-at org-complex-heading-regexp)
1262     (let* ((msg (match-string-no-properties 4))
1263            (ct-time (decode-time))
1264            (appt-min (+ (cadr ct-time)
1265                         (or n bzg-org-clock-in-appt-delay)))
1266            (appt-time ; define the time for the appointment
1267             (progn (setf (cadr ct-time) appt-min) ct-time)))
1268       (appt-add (format-time-string
1269                  "%H:%M" (apply 'encode-time appt-time)) msg)
1270       (if (interactive-p) (message "New appointment for %s" msg)))))
1271 #+END_SRC
1273 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1274 add an appointment:
1276 #+BEGIN_SRC emacs-lisp
1277 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1278   "Add an appointment when clocking a task in."
1279   (bzg-org-clock-in-add-appt))
1280 #+END_SRC
1282 You may also want to delete the associated appointment when clocking
1283 out.  This function does this:
1285 #+BEGIN_SRC emacs-lisp
1286 (defun bzg-org-clock-out-delete-appt nil
1287   "When clocking out, delete any associated appointment."
1288   (interactive)
1289   (save-excursion
1290     (org-back-to-heading t)
1291     (looking-at org-complex-heading-regexp)
1292     (let* ((msg (match-string-no-properties 4)))
1293       (setq appt-time-msg-list
1294             (delete nil
1295                     (mapcar
1296                      (lambda (appt)
1297                        (if (not (string-match (regexp-quote msg)
1298                                               (cadr appt))) appt))
1299                      appt-time-msg-list)))
1300       (appt-check))))
1301 #+END_SRC
1303 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1305 #+BEGIN_SRC emacs-lisp
1306 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1307   "Delete an appointment when clocking a task out."
1308   (bzg-org-clock-out-delete-appt))
1309 #+END_SRC
1311 *IMPORTANT*: You can add appointment by clocking in in both an
1312 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
1313 agenda buffer with the advice above will bring an error.
1315 *** Remove time grid lines that are in an appointment
1317 The agenda shows lines for the time grid.  Some people think that
1318 these lines are a distraction when there are appointments at those
1319 times.  You can get rid of the lines which coincide exactly with the
1320 beginning of an appointment.  Michael Ekstrand has written a piece of
1321 advice that also removes lines that are somewhere inside an
1322 appointment:
1324 #+begin_src emacs-lisp
1325 (defun org-time-to-minutes (time)
1326   "Convert an HHMM time to minutes"
1327   (+ (* (/ time 100) 60) (% time 100)))
1329 (defun org-time-from-minutes (minutes)
1330   "Convert a number of minutes to an HHMM time"
1331   (+ (* (/ minutes 60) 100) (% minutes 60)))
1333 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1334                                                   (list ndays todayp))
1335   (if (member 'remove-match (car org-agenda-time-grid))
1336       (flet ((extract-window
1337               (line)
1338               (let ((start (get-text-property 1 'time-of-day line))
1339                     (dur (get-text-property 1 'duration line)))
1340                 (cond
1341                  ((and start dur)
1342                   (cons start
1343                         (org-time-from-minutes
1344                          (+ dur (org-time-to-minutes start)))))
1345                  (start start)
1346                  (t nil)))))
1347         (let* ((windows (delq nil (mapcar 'extract-window list)))
1348                (org-agenda-time-grid
1349                 (list (car org-agenda-time-grid)
1350                       (cadr org-agenda-time-grid)
1351                       (remove-if
1352                        (lambda (time)
1353                          (find-if (lambda (w)
1354                                     (if (numberp w)
1355                                         (equal w time)
1356                                       (and (>= time (car w))
1357                                            (< time (cdr w)))))
1358                                   windows))
1359                        (caddr org-agenda-time-grid)))))
1360           ad-do-it))
1361     ad-do-it))
1362 (ad-activate 'org-agenda-add-time-grid-maybe)
1363 #+end_src
1364 *** Disable vc for Org mode agenda files
1365 -- David Maus
1367 Even if you use Git to track your agenda files you might not need
1368 vc-mode to be enabled for these files.
1370 #+begin_src emacs-lisp
1371 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1372 (defun dmj/disable-vc-for-agenda-files-hook ()
1373   "Disable vc-mode for Org agenda files."
1374   (if (and (fboundp 'org-agenda-file-p)
1375            (org-agenda-file-p (buffer-file-name)))
1376       (remove-hook 'find-file-hook 'vc-find-file-hook)
1377     (add-hook 'find-file-hook 'vc-find-file-hook)))
1378 #+end_src
1380 *** Easy customization of TODO colors
1381 -- Ryan C. Thompson
1383 Here is some code I came up with some code to make it easier to
1384 customize the colors of various TODO keywords. As long as you just
1385 want a different color and nothing else, you can customize the
1386 variable org-todo-keyword-faces and use just a string color (i.e. a
1387 string of the color name) as the face, and then org-get-todo-face
1388 will convert the color to a face, inheriting everything else from
1389 the standard org-todo face.
1391 To demonstrate, I currently have org-todo-keyword-faces set to
1393 #+BEGIN_SRC emacs-lisp
1394 (("IN PROGRESS" . "dark orange")
1395  ("WAITING" . "red4")
1396  ("CANCELED" . "saddle brown"))
1397 #+END_SRC emacs-lisp
1399   Here's the code, in a form you can put in your =.emacs=
1401 #+BEGIN_SRC emacs-lisp
1402 (eval-after-load 'org-faces
1403  '(progn
1404     (defcustom org-todo-keyword-faces nil
1405       "Faces for specific TODO keywords.
1406 This is a list of cons cells, with TODO keywords in the car and
1407 faces in the cdr.  The face can be a symbol, a color, or a
1408 property list of attributes, like (:foreground \"blue\" :weight
1409 bold :underline t)."
1410       :group 'org-faces
1411       :group 'org-todo
1412       :type '(repeat
1413               (cons
1414                (string :tag "Keyword")
1415                (choice color (sexp :tag "Face")))))))
1417 (eval-after-load 'org
1418  '(progn
1419     (defun org-get-todo-face-from-color (color)
1420       "Returns a specification for a face that inherits from org-todo
1421  face and has the given color as foreground. Returns nil if
1422  color is nil."
1423       (when color
1424         `(:inherit org-warning :foreground ,color)))
1426     (defun org-get-todo-face (kwd)
1427       "Get the right face for a TODO keyword KWD.
1428 If KWD is a number, get the corresponding match group."
1429       (if (numberp kwd) (setq kwd (match-string kwd)))
1430       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1431             (if (stringp face)
1432                 (org-get-todo-face-from-color face)
1433               face))
1434           (and (member kwd org-done-keywords) 'org-done)
1435           'org-todo))))
1436 #+END_SRC emacs-lisp
1438 *** Add an effort estimate on the fly when clocking in
1440 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1441 This way you can easily have a "tea-timer" for your tasks when they
1442 don't already have an effort estimate.
1444 #+begin_src emacs-lisp
1445 (add-hook 'org-clock-in-prepare-hook
1446           'my-org-mode-ask-effort)
1448 (defun my-org-mode-ask-effort ()
1449   "Ask for an effort estimate when clocking in."
1450   (unless (org-entry-get (point) "Effort")
1451     (let ((effort
1452            (completing-read
1453             "Effort: "
1454             (org-entry-get-multivalued-property (point) "Effort"))))
1455       (unless (equal effort "")
1456         (org-set-property "Effort" effort)))))
1457 #+end_src
1459 Or you can use a default effort for such a timer:
1461 #+begin_src emacs-lisp
1462 (add-hook 'org-clock-in-prepare-hook
1463           'my-org-mode-add-default-effort)
1465 (defvar org-clock-default-effort "1:00")
1467 (defun my-org-mode-add-default-effort ()
1468   "Add a default effort estimation."
1469   (unless (org-entry-get (point) "Effort")
1470     (org-set-property "Effort" org-clock-default-effort)))
1471 #+end_src
1473 *** Refresh the agenda view regurally
1475 Hack sent by Kiwon Um:
1477 #+begin_src emacs-lisp
1478 (defun kiwon/org-agenda-redo-in-other-window ()
1479   "Call org-agenda-redo function even in the non-agenda buffer."
1480   (interactive)
1481   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1482     (when agenda-window
1483       (with-selected-window agenda-window (org-agenda-redo)))))
1484 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1485 #+end_src
1487 *** Reschedule agenda items to today with a single command
1489 This was suggested by Carsten in reply to David Abrahams:
1491 #+begin_example emacs-lisp
1492 (defun org-agenda-reschedule-to-today ()
1493   (interactive)
1494   (flet ((org-read-date (&rest rest) (current-time)))
1495     (call-interactively 'org-agenda-schedule)))
1496 #+end_example
1498 * Hacking Org: Working with Org-mode and other Emacs Packages.
1499 ** org-remember-anything
1501 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1503 #+BEGIN_SRC emacs-lisp
1504 (defvar org-remember-anything
1505   '((name . "Org Remember")
1506     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1507     (action . (lambda (name)
1508                 (let* ((orig-template org-remember-templates)
1509                        (org-remember-templates
1510                         (list (assoc name orig-template))))
1511                   (call-interactively 'org-remember))))))
1512 #+END_SRC
1514 You can add it to your 'anything-sources' variable and open remember directly
1515 from anything. I imagine this would be more interesting for people with many
1516 remember templatesm, so that you are out of keys to assign those to. You should
1517 get something like this:
1519 [[file:images/thumbs/org-remember-anything.png]]
1521 ** Org-mode and saveplace.el
1523 Fix a problem with saveplace.el putting you back in a folded position:
1525 #+begin_src emacs-lisp
1526 (add-hook 'org-mode-hook
1527           (lambda ()
1528             (when (outline-invisible-p)
1529               (save-excursion
1530                 (outline-previous-visible-heading 1)
1531                 (org-show-subtree)))))
1532 #+end_src
1534 ** Using ido-completing-read to find attachments
1535 -- Matt Lundin
1537 Org-attach is great for quickly linking files to a project. But if you
1538 use org-attach extensively you might find yourself wanting to browse
1539 all the files you've attached to org headlines. This is not easy to do
1540 manually, since the directories containing the files are not human
1541 readable (i.e., they are based on automatically generated ids). Here's
1542 some code to browse those files using ido (obviously, you need to be
1543 using ido):
1545 #+begin_src emacs-lisp
1546 (load-library "find-lisp")
1548 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1550 (defun my-ido-find-org-attach ()
1551   "Find files in org-attachment directory"
1552   (interactive)
1553   (let* ((enable-recursive-minibuffers t)
1554          (files (find-lisp-find-files org-attach-directory "."))
1555          (file-assoc-list
1556           (mapcar (lambda (x)
1557                     (cons (file-name-nondirectory x)
1558                           x))
1559                   files))
1560          (filename-list
1561           (remove-duplicates (mapcar #'car file-assoc-list)
1562                              :test #'string=))
1563          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1564          (longname (cdr (assoc filename file-assoc-list))))
1565     (ido-set-current-directory
1566      (if (file-directory-p longname)
1567          longname
1568        (file-name-directory longname)))
1569     (setq ido-exit 'refresh
1570           ido-text-init ido-text
1571           ido-rotate-temp t)
1572     (exit-minibuffer)))
1574 (add-hook 'ido-setup-hook 'ido-my-keys)
1576 (defun ido-my-keys ()
1577   "Add my keybindings for ido."
1578   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1579 #+end_src
1581 To browse your org attachments using ido fuzzy matching and/or the
1582 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1583 press =C-;=.
1585 ** Use idle timer for automatic agenda views
1587 From John Wiegley's mailing list post (March 18, 2010):
1589 #+begin_quote
1590 I have the following snippet in my .emacs file, which I find very
1591 useful. Basically what it does is that if I don't touch my Emacs for 5
1592 minutes, it displays the current agenda. This keeps my tasks "always
1593 in mind" whenever I come back to Emacs after doing something else,
1594 whereas before I had a tendency to forget that it was there.
1595 #+end_quote  
1597   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1599 #+begin_src emacs-lisp
1600 (defun jump-to-org-agenda ()
1601   (interactive)
1602   (let ((buf (get-buffer "*Org Agenda*"))
1603         wind)
1604     (if buf
1605         (if (setq wind (get-buffer-window buf))
1606             (select-window wind)
1607           (if (called-interactively-p)
1608               (progn
1609                 (select-window (display-buffer buf t t))
1610                 (org-fit-window-to-buffer)
1611                 ;; (org-agenda-redo)
1612                 )
1613             (with-selected-window (display-buffer buf)
1614               (org-fit-window-to-buffer)
1615               ;; (org-agenda-redo)
1616               )))
1617       (call-interactively 'org-agenda-list)))
1618   ;;(let ((buf (get-buffer "*Calendar*")))
1619   ;;  (unless (get-buffer-window buf)
1620   ;;    (org-agenda-goto-calendar)))
1621   )
1622   
1623 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1624 #+end_src
1626 #+results:
1627 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1629 ** Link to Gnus messages by Message-Id
1631 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1632 discussion about linking to Gnus messages without encoding the folder
1633 name in the link.  The following code hooks in to the store-link
1634 function in Gnus to capture links by Message-Id when in nnml folders,
1635 and then provides a link type "mid" which can open this link.  The
1636 =mde-org-gnus-open-message-link= function uses the
1637 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1638 scan.  It will go through them, in order, asking each to locate the
1639 message and opening it from the first one that reports success.
1641 It has only been tested with a single nnml backend, so there may be
1642 bugs lurking here and there.
1644 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1645 article]].
1647 #+begin_src emacs-lisp
1648 ;; Support for saving Gnus messages by Message-ID
1649 (defun mde-org-gnus-save-by-mid ()
1650   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1651     (when (eq major-mode 'gnus-article-mode)
1652       (gnus-article-show-summary))
1653     (let* ((group gnus-newsgroup-name)
1654            (method (gnus-find-method-for-group group)))
1655       (when (eq 'nnml (car method))
1656         (let* ((article (gnus-summary-article-number))
1657                (header (gnus-summary-article-header article))
1658                (from (mail-header-from header))
1659                (message-id
1660                 (save-match-data
1661                   (let ((mid (mail-header-id header)))
1662                     (if (string-match "<\\(.*\\)>" mid)
1663                         (match-string 1 mid)
1664                       (error "Malformed message ID header %s" mid)))))
1665                (date (mail-header-date header))
1666                (subject (gnus-summary-subject-string)))
1667           (org-store-link-props :type "mid" :from from :subject subject
1668                                 :message-id message-id :group group
1669                                 :link (org-make-link "mid:" message-id))
1670           (apply 'org-store-link-props
1671                  :description (org-email-link-description)
1672                  org-store-link-plist)
1673           t)))))
1675 (defvar mde-mid-resolve-methods '()
1676   "List of methods to try when resolving message ID's.  For Gnus,
1677 it is a cons of 'gnus and the select (type and name).")
1678 (setq mde-mid-resolve-methods
1679       '((gnus nnml "")))
1681 (defvar mde-org-gnus-open-level 1
1682   "Level at which Gnus is started when opening a link")
1683 (defun mde-org-gnus-open-message-link (msgid)
1684   "Open a message link with Gnus"
1685   (require 'gnus)
1686   (require 'org-table)
1687   (catch 'method-found
1688     (message "[MID linker] Resolving %s" msgid)
1689     (dolist (method mde-mid-resolve-methods)
1690       (cond
1691        ((and (eq (car method) 'gnus)
1692              (eq (cadr method) 'nnml))
1693         (funcall (cdr (assq 'gnus org-link-frame-setup))
1694                  mde-org-gnus-open-level)
1695         (when gnus-other-frame-object
1696           (select-frame gnus-other-frame-object))
1697         (let* ((msg-info (nnml-find-group-number
1698                           (concat "<" msgid ">")
1699                           (cdr method)))
1700                (group (and msg-info (car msg-info)))
1701                (message (and msg-info (cdr msg-info)))
1702                (qname (and group
1703                            (if (gnus-methods-equal-p
1704                                 (cdr method)
1705                                 gnus-select-method)
1706                                group
1707                              (gnus-group-full-name group (cdr method))))))
1708           (when msg-info
1709             (gnus-summary-read-group qname nil t)
1710             (gnus-summary-goto-article message nil t))
1711           (throw 'method-found t)))
1712        (t (error "Unknown link type"))))))
1714 (eval-after-load 'org-gnus
1715   '(progn
1716      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1717      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1718 #+end_src
1720 ** Store link upon sending a message in Gnus
1722 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1724 #+begin_src emacs-lisp
1725 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1726   "Send message with `message-send-and-exit' and store org link to message copy.
1727 If multiple groups appear in the Gcc header, the link refers to
1728 the copy in the last group."
1729   (interactive "P")
1730     (save-excursion
1731       (save-restriction
1732         (message-narrow-to-headers)
1733         (let ((gcc (car (last
1734                          (message-unquote-tokens
1735                           (message-tokenize-header
1736                            (mail-fetch-field "gcc" nil t) " ,")))))
1737               (buf (current-buffer))
1738               (message-kill-buffer-on-exit nil)
1739               id to from subject desc link newsgroup xarchive)
1740         (message-send-and-exit arg)
1741         (or
1742          ;; gcc group found ...
1743          (and gcc
1744               (save-current-buffer
1745                 (progn (set-buffer buf)
1746                        (setq id (org-remove-angle-brackets
1747                                  (mail-fetch-field "Message-ID")))
1748                        (setq to (mail-fetch-field "To"))
1749                        (setq from (mail-fetch-field "From"))
1750                        (setq subject (mail-fetch-field "Subject"))))
1751               (org-store-link-props :type "gnus" :from from :subject subject
1752                                     :message-id id :group gcc :to to)
1753               (setq desc (org-email-link-description))
1754               (setq link (org-gnus-article-link
1755                           gcc newsgroup id xarchive))
1756               (setq org-stored-links
1757                     (cons (list link desc) org-stored-links)))
1758          ;; no gcc group found ...
1759          (message "Can not create Org link: No Gcc header found."))))))
1761 (define-key message-mode-map [(control c) (control meta c)]
1762   'ulf-message-send-and-org-gnus-store-link)
1763 #+end_src
1765 ** Send html messages and attachments with Wanderlust
1766   -- David Maus
1768 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1769 similar functionality for both Wanderlust and Gnus.  The hack below is
1770 still somewhat different: It allows you to toggle sending of html
1771 messages within Wanderlust transparently.  I.e. html markup of the
1772 message body is created right before sending starts.
1774 *** Send HTML message
1776 Putting the code below in your .emacs adds following four functions:
1778 - dmj/wl-send-html-message
1780   Function that does the job: Convert everything between "--text
1781   follows this line--" and first mime entity (read: attachment) or
1782   end of buffer into html markup using `org-export-region-as-html'
1783   and replaces original body with a multipart MIME entity with the
1784   plain text version of body and the html markup version.  Thus a
1785   recipient that prefers html messages can see the html markup,
1786   recipients that prefer or depend on plain text can see the plain
1787   text.
1789   Cannot be called interactively: It is hooked into SEMI's
1790   `mime-edit-translate-hook' if message should be HTML message.
1792 - dmj/wl-send-html-message-draft-init
1794   Cannot be called interactively: It is hooked into WL's
1795   `wl-mail-setup-hook' and provides a buffer local variable to
1796   toggle.
1798 - dmj/wl-send-html-message-draft-maybe
1800   Cannot be called interactively: It is hooked into WL's
1801   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1802   `mime-edit-translate-hook' depending on whether HTML message is
1803   toggled on or off
1805 - dmj/wl-send-html-message-toggle
1807   Toggles sending of HTML message.  If toggled on, the letters
1808   "HTML" appear in the mode line.
1810   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1812 If you have to send HTML messages regularly you can set a global
1813 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1814 toggle on sending HTML message by default.
1816 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1817 Google's web front end.  As you can see you have the whole markup of
1818 Org at your service: *bold*, /italics/, tables, lists...
1820 So even if you feel uncomfortable with sending HTML messages at least
1821 you send HTML that looks quite good.
1823 #+begin_src emacs-lisp
1824 (defun dmj/wl-send-html-message ()
1825   "Send message as html message.
1826 Convert body of message to html using
1827   `org-export-region-as-html'."
1828   (require 'org)
1829   (save-excursion
1830     (let (beg end html text)
1831       (goto-char (point-min))
1832       (re-search-forward "^--text follows this line--$")
1833       ;; move to beginning of next line
1834       (beginning-of-line 2)
1835       (setq beg (point))
1836       (if (not (re-search-forward "^--\\[\\[" nil t))
1837           (setq end (point-max))
1838         ;; line up
1839         (end-of-line 0)
1840         (setq end (point)))
1841       ;; grab body
1842       (setq text (buffer-substring-no-properties beg end))
1843       ;; convert to html
1844       (with-temp-buffer
1845         (org-mode)
1846         (insert text)
1847         ;; handle signature
1848         (when (re-search-backward "^-- \n" nil t)
1849           ;; preserve link breaks in signature
1850           (insert "\n#+BEGIN_VERSE\n")
1851           (goto-char (point-max))
1852           (insert "\n#+END_VERSE\n")
1853           ;; grab html
1854           (setq html (org-export-region-as-html
1855                       (point-min) (point-max) t 'string))))
1856       (delete-region beg end)
1857       (insert
1858        (concat
1859         "--" "<<alternative>>-{\n"
1860         "--" "[[text/plain]]\n" text
1861         "--" "[[text/html]]\n"  html
1862         "--" "}-<<alternative>>\n")))))
1864 (defun dmj/wl-send-html-message-toggle ()
1865   "Toggle sending of html message."
1866   (interactive)
1867   (setq dmj/wl-send-html-message-toggled-p
1868         (if dmj/wl-send-html-message-toggled-p
1869             nil "HTML"))
1870   (message "Sending html message toggled %s"
1871            (if dmj/wl-send-html-message-toggled-p
1872                "on" "off")))
1874 (defun dmj/wl-send-html-message-draft-init ()
1875   "Create buffer local settings for maybe sending html message."
1876   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1877     (setq dmj/wl-send-html-message-toggled-p nil))
1878   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1879   (add-to-list 'global-mode-string
1880                '(:eval (if (eq major-mode 'wl-draft-mode)
1881                            dmj/wl-send-html-message-toggled-p))))
1883 (defun dmj/wl-send-html-message-maybe ()
1884   "Maybe send this message as html message.
1886 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1887 non-nil, add `dmj/wl-send-html-message' to
1888 `mime-edit-translate-hook'."
1889   (if dmj/wl-send-html-message-toggled-p
1890       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1891     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1893 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1894 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1895 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1896 #+end_src
1898 *** Attach HTML of region or subtree
1900 Instead of sending a complete HTML message you might only send parts
1901 of an Org file as HTML for the poor souls who are plagued with
1902 non-proportional fonts in their mail program that messes up pretty
1903 ASCII tables.
1905 This short function does the trick: It exports region or subtree to
1906 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1907 and clipboard.  If a region is active, it uses the region, the
1908 complete subtree otherwise.
1910 #+begin_src emacs-lisp
1911 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1912   "Export region between BEG and END as html attachment.
1913 If BEG and END are not set, use current subtree.  Region or
1914 subtree is exported to html without header and footer, prefixed
1915 with a mime entity string and pushed to clipboard and killring.
1916 When called with prefix, mime entity is not marked as
1917 attachment."
1918   (interactive "r\nP")
1919   (save-excursion
1920     (let* ((beg (if (region-active-p) (region-beginning)
1921                   (progn
1922                     (org-back-to-heading)
1923                     (point))))
1924            (end (if (region-active-p) (region-end)
1925                   (progn
1926                     (org-end-of-subtree)
1927                     (point))))
1928            (html (concat "--[[text/html"
1929                          (if arg "" "\nContent-Disposition: attachment")
1930                          "]]\n"
1931                          (org-export-region-as-html beg end t 'string))))
1932       (when (fboundp 'x-set-selection)
1933         (ignore-errors (x-set-selection 'PRIMARY html))
1934         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1935       (message "html export done, pushed to kill ring and clipboard"))))
1936 #+end_src
1938 *** Adopting for Gnus
1940 The whole magic lies in the special strings that mark a HTML
1941 attachment.  So you might just have to find out what these special
1942 strings are in message-mode and modify the functions accordingly.
1943 ** Add sunrise/sunset times to the agenda.
1944   -- Nick Dokos
1946 The diary package provides the function =diary-sunrise-sunset= which can be used
1947 in a diary s-expression in some agenda file like this:
1949 #+begin_src org-mode
1950 %%(diary-sunrise-sunset)
1951 #+end_src
1953 Seb Vauban asked if it is possible to put sunrise and sunset in
1954 separate lines. Here is a hack to do that. It adds two functions (they
1955 have to be available before the agenda is shown, so I add them early
1956 in my org-config file which is sourced from .emacs, but you'll have to
1957 suit yourself here) that just parse the output of
1958 diary-sunrise-sunset, instead of doing the right thing which would be
1959 to take advantage of the data structures that diary/solar.el provides.
1960 In short, a hack - so perfectly suited for inclusion here :-)
1962 The functions (and latitude/longitude settings which you have to modify for
1963 your location) are as follows:
1965 #+begin_src emacs-lisp
1966 (setq calendar-latitude 40.3)
1967 (setq calendar-longitude -71.0)
1968 (defun diary-sunrise ()
1969   (let ((dss (diary-sunrise-sunset)))
1970     (with-temp-buffer
1971       (insert dss)
1972       (goto-char (point-min))
1973       (while (re-search-forward " ([^)]*)" nil t)
1974         (replace-match "" nil nil))
1975       (goto-char (point-min))
1976       (search-forward ",")
1977       (buffer-substring (point-min) (match-beginning 0)))))
1979 (defun diary-sunset ()
1980   (let ((dss (diary-sunrise-sunset))
1981         start end)
1982     (with-temp-buffer
1983       (insert dss)
1984       (goto-char (point-min))
1985       (while (re-search-forward " ([^)]*)" nil t)
1986         (replace-match "" nil nil))
1987       (goto-char (point-min))
1988       (search-forward ", ")
1989       (setq start (match-end 0))
1990       (search-forward " at")
1991       (setq end (match-beginning 0))
1992       (goto-char start)
1993       (capitalize-word 1)
1994       (buffer-substring start end))))
1995 #+end_src
1997 You also need to add a couple of diary s-expressions in one of your agenda
1998 files:
2000 #+begin_src org-mode
2001 %%(diary-sunrise)
2002 %%(diary-sunset)
2003 #+end_src
2005 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]].
2006 In comparison to the version posted on the mailing list, this one
2007 gets rid of the timezone information.
2008 * Hacking Org: Working with Org-mode and External Programs.
2009 ** Use Org-mode with Screen [Andrew Hyatt]
2011 "The general idea is that you start a task in which all the work will
2012 take place in a shell.  This usually is not a leaf-task for me, but
2013 usually the parent of a leaf task.  From a task in your org-file, M-x
2014 ash-org-screen will prompt for the name of a session.  Give it a name,
2015 and it will insert a link.  Open the link at any time to go the screen
2016 session containing your work!"
2018 http://article.gmane.org/gmane.emacs.orgmode/5276
2020 #+BEGIN_SRC emacs-lisp
2021 (require 'term)
2023 (defun ash-org-goto-screen (name)
2024   "Open the screen with the specified name in the window"
2025   (interactive "MScreen name: ")
2026   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
2027     (if (member screen-buffer-name
2028                 (mapcar 'buffer-name (buffer-list)))
2029         (switch-to-buffer screen-buffer-name)
2030       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
2032 (defun ash-org-screen-buffer-name (name)
2033   "Returns the buffer name corresponding to the screen name given."
2034   (concat "*screen " name "*"))
2036 (defun ash-org-screen-helper (name arg)
2037   ;; Pick the name of the new buffer.
2038   (let ((term-ansi-buffer-name
2039          (generate-new-buffer-name
2040           (ash-org-screen-buffer-name name))))
2041     (setq term-ansi-buffer-name
2042           (term-ansi-make-term
2043            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
2044     (set-buffer term-ansi-buffer-name)
2045     (term-mode)
2046     (term-char-mode)
2047     (term-set-escape-char ?\C-x)
2048     term-ansi-buffer-name))
2050 (defun ash-org-screen (name)
2051   "Start a screen session with name"
2052   (interactive "MScreen name: ")
2053   (save-excursion
2054     (ash-org-screen-helper name "-S"))
2055   (insert-string (concat "[[screen:" name "]]")))
2057 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
2058 ;; \"%s\")") to org-link-abbrev-alist.
2059 #+END_SRC
2061 ** Org Agenda + Appt + Zenity
2062 #+BEGIN_HTML
2063 <a name="agenda-appt-zenity"></a>
2064 #+END_HTML
2065 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It makes sure your agenda
2066 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
2067 popup window.
2069 #+BEGIN_SRC emacs-lisp
2070 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2071 ; For org appointment reminders
2073 ;; Get appointments for today
2074 (defun my-org-agenda-to-appt ()
2075   (interactive)
2076   (setq appt-time-msg-list nil)
2077   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
2078         (org-agenda-to-appt)))
2080 ;; Run once, activate and schedule refresh
2081 (my-org-agenda-to-appt)
2082 (appt-activate t)
2083 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2085 ; 5 minute warnings
2086 (setq appt-message-warning-time 15)
2087 (setq appt-display-interval 5)
2089 ; Update appt each time agenda opened.
2090 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2092 ; Setup zenify, we tell appt to use window, and replace default function
2093 (setq appt-display-format 'window)
2094 (setq appt-disp-window-function (function my-appt-disp-window))
2096 (defun my-appt-disp-window (min-to-app new-time msg)
2097   (save-window-excursion (shell-command (concat
2098     "/usr/bin/zenity --info --title='Appointment' --text='"
2099     msg "' &") nil nil)))
2100 #+END_SRC
2102 ** Org-Mode + gnome-osd
2104 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2105 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2107 ** remind2org
2109 From Detlef Steuer
2111 http://article.gmane.org/gmane.emacs.orgmode/5073
2113 #+BEGIN_QUOTE
2114 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2115 command line calendaring program. Its features superseed the possibilities
2116 of orgmode in the area of date specifying, so that I want to use it
2117 combined with orgmode.
2119 Using the script below I'm able use remind and incorporate its output in my
2120 agenda views.  The default of using 13 months look ahead is easily
2121 changed. It just happens I sometimes like to look a year into the
2122 future. :-)
2123 #+END_QUOTE
2125 ** Useful webjumps for conkeror
2127 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2128 your =~/.conkerorrc= file:
2130 #+begin_example
2131 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2132 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2133 #+end_example
2135 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2136 Org-mode mailing list.
2138 ** Use MathJax for HTML export without requiring JavaScript
2139 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2141 If you like the results but do not want JavaScript in the exported pages,
2142 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2143 HTML file from the exported version. It can also embed all referenced fonts
2144 within the HTML file itself, so there are no dependencies to external files.
2146 The download archive contains an elisp file which integrates it into the Org
2147 export process (configurable per file with a "#+StaticMathJax:" line).
2149 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2150 ** Search Org files using lgrep
2152 Matt Lundin suggests this:
2154 #+begin_src emacs-lisp
2155   (defun my-org-grep (search &optional context)
2156     "Search for word in org files. 
2158 Prefix argument determines number of lines."
2159     (interactive "sSearch for: \nP")
2160     (let ((grep-find-ignored-files '("#*" ".#*"))
2161           (grep-template (concat "grep <X> -i -nH " 
2162                                  (when context
2163                                    (concat "-C" (number-to-string context)))
2164                                  " -e <R> <F>")))
2165       (lgrep search "*org*" "/home/matt/org/")))
2167   (global-set-key (kbd "<f8>") 'my-org-grep)
2168 #+end_src
2170 ** Automatic screenshot insertion
2172 Suggested by Jonathan Bisson:
2174 #+begin_src emacs-lisp
2175   (defun my-screenshot ()
2176   "Take a screenshot into a unique-named file in the current buffer file
2177   directory and insert a link to this file."
2178     (interactive)
2179     (setq filename
2180           (concat
2181            (make-temp-name
2182             (file-name-directory (buffer-file-name))) ".jpg"))
2183     (call-process "import" nil nil nil filename)
2184     (insert (concat "[[" filename "]]"))
2185     (org-display-inline-images))
2186 #+end_src
2188 ** Capture invitations/appointments from MS Exchange emails
2190 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this.  Please check
2191 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]