Merge branch 'master' of git+ssh://repo.or.cz/srv/git/Worg
[Worg.git] / org-hacks.org
blob0d01ceb9d7f19816553a92dd33270ab45d1096db
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 **** Manipulate hours/minutes/seconds in table formulas
343 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
344 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
345 "=d=" is any digit) as time values in Org-mode table formula.  These
346 functions have now been wrapped up into a =with-time= macro which can
347 be used in table formula to translate table cell values to and from
348 numerical values for algebraic manipulation.
350 Here is the code implementing this macro.
351 #+begin_src emacs-lisp :results silent
352   (defun org-time-string-to-seconds (s)
353     "Convert a string HH:MM:SS to a number of seconds."
354     (cond
355      ((and (stringp s)
356            (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
357       (let ((hour (string-to-number (match-string 1 s)))
358             (min (string-to-number (match-string 2 s)))
359             (sec (string-to-number (match-string 3 s))))
360         (+ (* hour 3600) (* min 60) sec)))
361      ((and (stringp s)
362            (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
363       (let ((min (string-to-number (match-string 1 s)))
364             (sec (string-to-number (match-string 2 s))))
365         (+ (* min 60) sec)))
366      ((stringp s) (string-to-number s))
367      (t s)))
369   (defun org-time-seconds-to-string (secs)
370     "Convert a number of seconds to a time string."
371     (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
372           ((>= secs 60) (format-seconds "%m:%.2s" secs))
373           (t (format-seconds "%s" secs))))
375   (defmacro with-time (time-output-p &rest exprs)
376     "Evaluate an org-table formula, converting all fields that look
377   like time data to integer seconds.  If TIME-OUTPUT-P then return
378   the result as a time value."
379     (list
380      (if time-output-p 'org-time-seconds-to-string 'identity)
381      (cons 'progn
382            (mapcar
383             (lambda (expr)
384               `,(cons (car expr)
385                       (mapcar
386                        (lambda (el)
387                          (if (listp el)
388                              (list 'with-time nil el)
389                            (org-time-string-to-seconds el)))
390                        (cdr expr))))
391             `,@exprs))))
392 #+end_src
394 Which allows the following forms of table manipulation such as adding
395 and subtracting time values.
396 : | Date             | Start | Lunch |  Back |   End |  Sum |
397 : |------------------+-------+-------+-------+-------+------|
398 : | [2011-03-01 Tue] |  8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
399 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
401 and dividing time values by integers
402 : |  time | miles | minutes/mile |
403 : |-------+-------+--------------|
404 : | 34:43 |   2.9 |        11:58 |
405 : | 32:15 |  2.77 |        11:38 |
406 : | 33:56 |   3.0 |        11:18 |
407 : | 52:22 |  4.62 |        11:20 |
408 : #+TBLFM: $3='(with-time t (/ $1 $2))
410 *** Dates computation
412 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
414 I have a table in org which stores the date, I'm wondering if there is
415 any function to calculate the duration? For example:
417 | Start Date |   End Date | Duration |
418 |------------+------------+----------|
419 | 2004.08.07 | 2005.07.08 |          |
421 I tried to use B&-C&, but failed ...
423 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
425 Try the following:
427 | Start Date |   End Date | Duration |
428 |------------+------------+----------|
429 | 2004.08.07 | 2005.07.08 |      335 |
430 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
432 See this thread:
434     http://thread.gmane.org/gmane.emacs.orgmode/7741
436 as well as this post (which is really a followup on the
437 above):
439     http://article.gmane.org/gmane.emacs.orgmode/7753
441 The problem that this last article pointed out was solved
444     http://article.gmane.org/gmane.emacs.orgmode/8001
446 and Chris Randle's original musings are at
448     http://article.gmane.org/gmane.emacs.orgmode/6536/
450 *** Field coordinates in formulas (=@#= and =$#=)
452 -- Michael Brand
454 Following are some use cases that can be implemented with the
455 _field coordinates in formulas_ described in the corresponding
456 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
458 **** Copy a column from a remote table into a column
460 current column =$3= = remote column =$2=:
461 : #+TBLFM: $3 = remote(FOO, @@#$2)
463 **** Copy a row from a remote table transposed into a column
465 current column =$1= = transposed remote row =@1=:
466 : #+TBLFM: $1 = remote(FOO, @$#$@#)
468 **** Transpose a table
470 -- Michael Brand
472 This is more like a demonstration of using _field coordinates in formulas_
473 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel.  The efficient
474 and simple solution for this with the help of org-babel and Emacs Lisp has
475 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
477 To transpose this 4x7 table
479 : #+TBLNAME: FOO
480 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
481 : |------+------+------+------+------+------+------|
482 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
483 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
484 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
486 start with a 7x4 table without any horizontal line (to have filled
487 also the column header) and yet empty:
489 : |   |   |   |   |
490 : |   |   |   |   |
491 : |   |   |   |   |
492 : |   |   |   |   |
493 : |   |   |   |   |
494 : |   |   |   |   |
495 : |   |   |   |   |
497 Then add the =TBLFM= below with the same formula repeated for each column.
498 After recalculation this will end up with the transposed copy:
500 : | year | min | avg | max |
501 : | 2004 | 401 | 402 | 403 |
502 : | 2005 | 501 | 502 | 503 |
503 : | 2006 | 601 | 602 | 603 |
504 : | 2007 | 701 | 702 | 703 |
505 : | 2008 | 801 | 802 | 803 |
506 : | 2009 | 901 | 902 | 903 |
507 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
509 The formulas simply exchange row and column numbers by taking
510 - the absolute remote row number =@$#= from the current column number =$#=
511 - the absolute remote column number =$@#= from the current row number =@#=
513 Possible field formulas from the remote table will have to be transferred
514 manually.  Since there are no row formulas yet there is no need to transfer
515 column formulas to row formulas or vice versa.
517 **** Dynamic variation of ranges
519 -- Michael Brand
521 In this example all columns next to =quote= are calculated from the column
522 =quote= and show the average change of the time series =quote[year]=
523 during the period of the preceding =1=, =2=, =3= or =4= years:
525 : | year | quote |   1 a |   2 a |   3 a |   4 a |
526 : |------+-------+-------+-------+-------+-------|
527 : | 2005 |    10 |       |       |       |       |
528 : | 2006 |    12 | 0.200 |       |       |       |
529 : | 2007 |    14 | 0.167 | 0.183 |       |       |
530 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
531 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
532 : #+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
534 The formula is the same for each column =$3= through =$6=.  This can easily
535 be seen with the great formula editor invoked by C-c ' on the
536 table. The important part of the formula without the field blanking is:
538 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
540 which is the Emacs Calc implementation of the equation
542 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
544 where /i/ is the current time and /a/ is the length of the preceding period.
546 *** Customize the size of the frame for remember
547 (Note: this hack is likely out of date due to the development of
548 [[org-capture]].) 
550 #FIXME: gmane link?
551 On emacs-orgmode, Ryan C. Thompson suggested this:
553 #+begin_quote
554 I am using org-remember set to open a new frame when used,
555 and the default frame size is much too large. To fix this, I have
556 designed some advice and a custom variable to implement custom
557 parameters for the remember frame:
558 #+end_quote
560 #+begin_src emacs-lisp
561 (defcustom remember-frame-alist nil
562   "Additional frame parameters for dedicated remember frame."
563   :type 'alist
564   :group 'remember)
566 (defadvice remember (around remember-frame-parameters activate)
567   "Set some frame parameters for the remember frame."
568   (let ((default-frame-alist (append remember-frame-alist
569                                      default-frame-alist)))
570     ad-do-it))
571 #+end_src
573 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
574 reasonable size for the frame.
575 *** Promote all items in subtree
576 - Matt Lundin
578 This function will promote all items in a subtree. Since I use
579 subtrees primarily to organize projects, the function is somewhat
580 unimaginatively called my-org-un-project:
582 #+begin_src emacs-lisp
583 (defun my-org-un-project ()
584   (interactive)
585   (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
586   (org-cycle t))
587 #+end_src
589 *** Turn a heading into an Org link
591 From David Maus:
593 #+begin_src emacs-lisp
594   (defun dmj:turn-headline-into-org-mode-link ()
595     "Replace word at point by an Org mode link."
596     (interactive)
597     (when (org-at-heading-p)
598       (let ((hl-text (nth 4 (org-heading-components))))
599         (unless (or (null hl-text)
600                     (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
601           (beginning-of-line)
602           (search-forward hl-text (point-at-eol))
603           (replace-string
604            hl-text
605            (format "[[file:%s.org][%s]]"
606                    (org-link-escape hl-text)
607                    (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
608            nil (- (point) (length hl-text)) (point))))))
609 #+end_src
611 *** Count words in an Org buffer
613 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
615 #+begin_src emacs-lisp
616 (defun org-word-count (beg end
617                            &optional count-latex-macro-args?
618                            count-footnotes?)
619   "Report the number of words in the Org mode buffer or selected region.
620 Ignores:
621 - comments
622 - tables
623 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
624 - hyperlinks (but does count words in hyperlink descriptions)
625 - tags, priorities, and TODO keywords in headers
626 - sections tagged as 'not for export'.
628 The text of footnote definitions is ignored, unless the optional argument
629 COUNT-FOOTNOTES? is non-nil.
631 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
632 includes LaTeX macro arguments (the material between {curly braces}).
633 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
634 of its arguments."
635   (interactive "r")
636   (unless mark-active
637     (setf beg (point-min)
638           end (point-max)))
639   (let ((wc 0)
640         (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
641     (save-excursion
642       (goto-char beg)
643       (while (< (point) end)
644         (cond
645          ;; Ignore comments.
646          ((or (org-in-commented-line) (org-at-table-p))
647           nil)
648          ;; Ignore hyperlinks. But if link has a description, count
649          ;; the words within the description.
650          ((looking-at org-bracket-link-analytic-regexp)
651           (when (match-string-no-properties 5)
652             (let ((desc (match-string-no-properties 5)))
653               (save-match-data 
654                 (incf wc (length (remove "" (org-split-string
655                                              desc "\\W")))))))
656           (goto-char (match-end 0)))
657          ((looking-at org-any-link-re)
658           (goto-char (match-end 0)))
659          ;; Ignore source code blocks.
660          ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
661           nil)
662          ;; Ignore inline source blocks, counting them as 1 word.
663          ((save-excursion
664             (backward-char)
665             (looking-at org-babel-inline-src-block-regexp))
666           (goto-char (match-end 0))
667           (setf wc (+ 2 wc)))
668          ;; Count latex macros as 1 word, ignoring their arguments.
669          ((save-excursion
670             (backward-char)
671             (looking-at latex-macro-regexp))
672           (goto-char (if count-latex-macro-args?
673                          (match-beginning 2)
674                        (match-end 0)))
675           (setf wc (+ 2 wc)))
676          ;; Ignore footnotes.
677          ((and (not count-footnotes?)
678                (or (org-footnote-at-definition-p)
679                    (org-footnote-at-reference-p)))
680           nil)
681          (t
682           (let ((contexts (org-context)))
683             (cond
684              ;; Ignore tags and TODO keywords, etc.
685              ((or (assoc :todo-keyword contexts)
686                   (assoc :priority contexts)
687                   (assoc :keyword contexts)
688                   (assoc :checkbox contexts))
689               nil)
690              ;; Ignore sections marked with tags that are
691              ;; excluded from export.
692              ((assoc :tags contexts)
693               (if (intersection (org-get-tags-at) org-export-exclude-tags
694                                 :test 'equal)
695                   (org-forward-same-level 1)
696                 nil))
697              (t
698               (incf wc))))))
699         (re-search-forward "\\w+\\W*")))
700     (message (format "%d words in %s." wc
701                      (if mark-active "region" "buffer")))))
702 #+end_src
704 ** Archiving Content in Org-Mode
705 *** Preserve top level headings when archiving to a file
706 - Matt Lundin
708 To preserve (somewhat) the integrity of your archive structure while
709 archiving lower level items to a file, you can use the following
710 defadvice:
712 #+begin_src emacs-lisp
713 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
714   (let ((org-archive-location 
715          (if (save-excursion (org-back-to-heading)
716                              (> (org-outline-level) 1))
717              (concat (car (split-string org-archive-location "::"))
718                      "::* "
719                      (car (org-get-outline-path)))
720            org-archive-location)))
721     ad-do-it))
722 #+end_src
724 Thus, if you have an outline structure such as...
726 #+begin_src org
727 ,* Heading
728 ,** Subheading
729 ,*** Subsubheading
730 #+end_src
732 ...archiving "Subsubheading" to a new file will set the location in
733 the new file to the top level heading:
735 #+begin_src org
736 ,* Heading
737 ,** Subsubheading
738 #+end_src
740 While this hack obviously destroys the outline hierarchy somewhat, it
741 at least preserves the logic of level one groupings.
743 A slightly more complex version of this hack will not only keep the
744 archive organized by top-level headings, but will also preserve the
745 tags found on those headings:
747 #+begin_src emacs-lisp
748   (defun my-org-inherited-no-file-tags ()
749     (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
750           (ltags (org-entry-get nil "TAGS")))
751       (mapc (lambda (tag)
752               (setq tags 
753                     (replace-regexp-in-string (concat tag ":") "" tags)))
754             (append org-file-tags (when ltags (split-string ltags ":" t))))
755       (if (string= ":" tags) nil tags)))
756   
757   (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
758     (let ((tags (my-org-inherited-no-file-tags))
759           (org-archive-location 
760            (if (save-excursion (org-back-to-heading)
761                                (> (org-outline-level) 1))
762                (concat (car (split-string org-archive-location "::"))
763                        "::* "
764                        (car (org-get-outline-path)))
765              org-archive-location)))
766       ad-do-it
767       (with-current-buffer (find-file-noselect (org-extract-archive-file))
768         (save-excursion
769           (while (org-up-heading-safe))
770           (org-set-tags-to tags)))))
771 #+end_src
773 *** Archive in a date tree
775 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
777 (Make sure org-datetree.el is loaded for this to work.)
779 #+begin_src emacs-lisp
780 ;; (setq org-archive-location "%s_archive::date-tree")
781 (defadvice org-archive-subtree
782   (around org-archive-subtree-to-data-tree activate)
783   "org-archive-subtree to date-tree"
784   (if
785       (string= "date-tree"
786                (org-extract-archive-heading
787                 (org-get-local-archive-location)))
788       (let* ((dct (decode-time (org-current-time)))
789              (y (nth 5 dct))
790              (m (nth 4 dct))
791              (d (nth 3 dct))
792              (this-buffer (current-buffer))
793              (location (org-get-local-archive-location))
794              (afile (org-extract-archive-file location))
795              (org-archive-location
796               (format "%s::*** %04d-%02d-%02d %s" afile y m d
797                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
798         (message "afile=%s" afile)
799         (unless afile
800           (error "Invalid `org-archive-location'"))
801         (save-excursion
802           (switch-to-buffer (find-file-noselect afile))
803           (org-datetree-find-year-create y)
804           (org-datetree-find-month-create y m)
805           (org-datetree-find-day-create y m d)
806           (widen)
807           (switch-to-buffer this-buffer))
808         ad-do-it)
809     ad-do-it))
810 #+end_src
812 *** Add inherited tags to archived entries
814 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
815 advise the function like this:
817 #+begin_example
818 (defadvice org-archive-subtree
819   (before add-inherited-tags-before-org-archive-subtree activate)
820     "add inherited tags before org-archive-subtree"
821     (org-set-tags-to (org-get-tags-at)))
822 #+end_example
824 ** Using and Managing Org-Metadata
825 *** Remove redundant tags of headlines
826 -- David Maus
828 A small function that processes all headlines in current buffer and
829 removes tags that are local to a headline and inherited by a parent
830 headline or the #+FILETAGS: statement.
832 #+BEGIN_SRC emacs-lisp
833   (defun dmj/org-remove-redundant-tags ()
834     "Remove redundant tags of headlines in current buffer.
836   A tag is considered redundant if it is local to a headline and
837   inherited by a parent headline."
838     (interactive)
839     (when (eq major-mode 'org-mode)
840       (save-excursion
841         (org-map-entries
842          '(lambda ()
843             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
844                   local inherited tag)
845               (dolist (tag alltags)
846                 (if (get-text-property 0 'inherited tag)
847                     (push tag inherited) (push tag local)))
848               (dolist (tag local)
849                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
850          t nil))))
851 #+END_SRC
853 *** Remove empty property drawers
855 David Maus proposed this:
857 #+begin_src emacs-lisp
858 (defun dmj:org:remove-empty-propert-drawers ()
859   "*Remove all empty property drawers in current file."
860   (interactive)
861   (unless (eq major-mode 'org-mode)
862     (error "You need to turn on Org mode for this function."))
863   (save-excursion
864     (goto-char (point-min))
865     (while (re-search-forward ":PROPERTIES:" nil t)
866       (save-excursion
867         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
868 #+end_src
870 *** Group task list by a property
872 This advice allows you to group a task list in Org-Mode.  To use it,
873 set the variable =org-agenda-group-by-property= to the name of a
874 property in the option list for a TODO or TAGS search.  The resulting
875 agenda view will group tasks by that property prior to searching.
877 #+begin_src emacs-lisp
878 (defvar org-agenda-group-by-property nil
879   "Set this in org-mode agenda views to group tasks by property")
881 (defun org-group-bucket-items (prop items)
882   (let ((buckets ()))
883     (dolist (item items)
884       (let* ((marker (get-text-property 0 'org-marker item))
885              (pvalue (org-entry-get marker prop t))
886              (cell (assoc pvalue buckets)))
887         (if cell
888             (setcdr cell (cons item (cdr cell)))
889           (setq buckets (cons (cons pvalue (list item))
890                               buckets)))))
891     (setq buckets (mapcar (lambda (bucket)
892                             (cons (car bucket)
893                                   (reverse (cdr bucket))))
894                           buckets))
895     (sort buckets (lambda (i1 i2)
896                     (string< (car i1) (car i2))))))
898 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
899                                                (list &optional nosort))
900   "Prepare bucketed agenda entry lists"
901   (if org-agenda-group-by-property
902       ;; bucketed, handle appropriately
903       (let ((text ""))
904         (dolist (bucket (org-group-bucket-items
905                          org-agenda-group-by-property
906                          list))
907           (let ((header (concat "Property "
908                                 org-agenda-group-by-property
909                                 " is "
910                                 (or (car bucket) "<nil>") ":\n")))
911             (add-text-properties 0 (1- (length header))
912                                  (list 'face 'org-agenda-structure)
913                                  header)
914             (setq text
915                   (concat text header
916                           ;; recursively process
917                           (let ((org-agenda-group-by-property nil))
918                             (org-finalize-agenda-entries
919                              (cdr bucket) nosort))
920                           "\n\n"))))
921         (setq ad-return-value text))
922     ad-do-it))
923 (ad-activate 'org-finalize-agenda-entries)
924 #+end_src
925 *** Dynamically adjust tag position
926 Here is a bit of code that allows you to have the tags always
927 right-adjusted in the buffer.
929 This is useful when you have bigger window than default window-size
930 and you dislike the aesthetics of having the tag in the middle of the
931 line.
933 This hack solves the problem of adjusting it whenever you change the
934 window size.
935 Before saving it will revert the file to having the tag position be
936 left-adjusted so that if you track your files with version control,
937 you won't run into artificial diffs just because the window-size
938 changed.
940 *IMPORTANT*: This is probably slow on very big files.
942 #+begin_src emacs-lisp
943 (setq ba/org-adjust-tags-column t)
945 (defun ba/org-adjust-tags-column-reset-tags ()
946   "In org-mode buffers it will reset tag position according to
947 `org-tags-column'."
948   (when (and
949          (not (string= (buffer-name) "*Remember*"))
950          (eql major-mode 'org-mode))
951     (let ((b-m-p (buffer-modified-p)))
952       (condition-case nil
953           (save-excursion
954             (goto-char (point-min))
955             (command-execute 'outline-next-visible-heading)
956             ;; disable (message) that org-set-tags generates
957             (flet ((message (&rest ignored) nil))
958               (org-set-tags 1 t))
959             (set-buffer-modified-p b-m-p))
960         (error nil)))))
962 (defun ba/org-adjust-tags-column-now ()
963   "Right-adjust `org-tags-column' value, then reset tag position."
964   (set (make-local-variable 'org-tags-column)
965        (- (- (window-width) (length org-ellipsis))))
966   (ba/org-adjust-tags-column-reset-tags))
968 (defun ba/org-adjust-tags-column-maybe ()
969   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
970   (when ba/org-adjust-tags-column
971     (ba/org-adjust-tags-column-now)))
973 (defun ba/org-adjust-tags-column-before-save ()
974   "Tags need to be left-adjusted when saving."
975   (when ba/org-adjust-tags-column
976      (setq org-tags-column 1)
977      (ba/org-adjust-tags-column-reset-tags)))
979 (defun ba/org-adjust-tags-column-after-save ()
980   "Revert left-adjusted tag position done by before-save hook."
981   (ba/org-adjust-tags-column-maybe)
982   (set-buffer-modified-p nil))
984 ; automatically align tags on right-hand side
985 (add-hook 'window-configuration-change-hook
986           'ba/org-adjust-tags-column-maybe)
987 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
988 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
989 (add-hook 'org-agenda-mode-hook '(lambda ()
990                                   (setq org-agenda-tags-column (- (window-width)))))
992 ; between invoking org-refile and displaying the prompt (which
993 ; triggers window-configuration-change-hook) tags might adjust, 
994 ; which invalidates the org-refile cache
995 (defadvice org-refile (around org-refile-disable-adjust-tags)
996   "Disable dynamically adjusting tags"
997   (let ((ba/org-adjust-tags-column nil))
998     ad-do-it))
999 (ad-activate 'org-refile)
1000 #+end_src
1001 ** Org Agenda and Task Management
1002 *** Make it easier to set org-agenda-files from multiple directories
1003 - Matt Lundin
1005 #+begin_src emacs-lisp
1006 (defun my-org-list-files (dirs ext)
1007   "Function to create list of org files in multiple subdirectories.
1008 This can be called to generate a list of files for
1009 org-agenda-files or org-refile-targets.
1011 DIRS is a list of directories.
1013 EXT is a list of the extensions of files to be included."
1014   (let ((dirs (if (listp dirs)
1015                   dirs
1016                 (list dirs)))
1017         (ext (if (listp ext)
1018                  ext
1019                (list ext)))
1020         files)
1021     (mapc 
1022      (lambda (x)
1023        (mapc 
1024         (lambda (y)
1025           (setq files 
1026                 (append files 
1027                         (file-expand-wildcards 
1028                          (concat (file-name-as-directory x) "*" y)))))
1029         ext))
1030      dirs)
1031     (mapc
1032      (lambda (x)
1033        (when (or (string-match "/.#" x)
1034                  (string-match "#$" x))
1035          (setq files (delete x files))))
1036      files)
1037     files))
1039 (defvar my-org-agenda-directories '("~/org/")
1040   "List of directories containing org files.")
1041 (defvar my-org-agenda-extensions '(".org")
1042   "List of extensions of agenda files")
1044 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1045 (setq my-org-agenda-extensions '(".org" ".ref"))
1047 (defun my-org-set-agenda-files ()
1048   (interactive)
1049   (setq org-agenda-files (my-org-list-files 
1050                           my-org-agenda-directories
1051                           my-org-agenda-extensions)))
1053 (my-org-set-agenda-files)
1054 #+end_src
1056 The code above will set your "default" agenda files to all files
1057 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1058 You can change these values by setting the variables
1059 my-org-agenda-extensions and my-org-agenda-directories. The function
1060 my-org-agenda-files-by-filetag uses these two variables to determine
1061 which files to search for filetags (i.e., the larger set from which
1062 the subset will be drawn).
1064 You can also easily use my-org-list-files to "mix and match"
1065 directories and extensions to generate different lists of agenda
1066 files.
1068 *** Restrict org-agenda-files by filetag
1069   :PROPERTIES:
1070   :CUSTOM_ID: set-agenda-files-by-filetag
1071   :END:
1072 - Matt Lundin
1074 It is often helpful to limit yourself to a subset of your agenda
1075 files. For instance, at work, you might want to see only files related
1076 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1077 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
1078 commands]]. These solutions, however, require reapplying a filter each
1079 time you call the agenda or writing several new custom agenda commands
1080 for each context. Another solution is to use directories for different
1081 types of tasks and to change your agenda files with a function that
1082 sets org-agenda-files to the appropriate directory. But this relies on
1083 hard and static boundaries between files.
1085 The following functions allow for a more dynamic approach to selecting
1086 a subset of files based on filetags:
1088 #+begin_src emacs-lisp
1089 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1090   "Restrict org agenda files only to those containing filetag."
1091   (interactive)
1092   (let* ((tagslist (my-org-get-all-filetags))
1093          (ftag (or tag 
1094                    (completing-read "Tag: " 
1095                                     (mapcar 'car tagslist)))))
1096     (org-agenda-remove-restriction-lock 'noupdate)
1097     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1098     (setq org-agenda-overriding-restriction 'files)))
1100 (defun my-org-get-all-filetags ()
1101   "Get list of filetags from all default org-files."
1102   (let ((files org-agenda-files)
1103         tagslist x)
1104     (save-window-excursion
1105       (while (setq x (pop files))
1106         (set-buffer (find-file-noselect x))
1107         (mapc
1108          (lambda (y)
1109            (let ((tagfiles (assoc y tagslist)))
1110              (if tagfiles
1111                  (setcdr tagfiles (cons x (cdr tagfiles)))
1112                (add-to-list 'tagslist (list y x)))))
1113          (my-org-get-filetags)))
1114       tagslist)))
1116 (defun my-org-get-filetags ()
1117   "Get list of filetags for current buffer"
1118   (let ((ftags org-file-tags)
1119         x)
1120     (mapcar 
1121      (lambda (x)
1122        (org-substring-no-properties x))
1123      ftags)))
1124 #+end_src
1126 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1127 with all filetags in your "normal" agenda files. When you select a
1128 tag, org-agenda-files will be restricted to only those files
1129 containing the filetag. To release the restriction, type C-c C-x >
1130 (org-agenda-remove-restriction-lock).
1132 *** Highlight the agenda line under cursor
1134 This is useful to make sure what task you are operating on.
1136 #+BEGIN_SRC emacs-lisp
1137 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1138 #+END_SRC emacs-lisp
1140 Under XEmacs:
1142 #+BEGIN_SRC emacs-lisp
1143 ;; hl-line seems to be only for emacs
1144 (require 'highline)
1145 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1147 ;; highline-mode does not work straightaway in tty mode.
1148 ;; I use a black background
1149 (custom-set-faces
1150   '(highline-face ((((type tty) (class color))
1151                     (:background "white" :foreground "black")))))
1152 #+END_SRC emacs-lisp
1154 *** Split horizontally for agenda
1156 If you would like to split the frame into two side-by-side windows when
1157 displaying the agenda, try this hack from Jan Rehders, which uses the
1158 `toggle-window-split' from
1160 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1162 #+BEGIN_SRC emacs-lisp
1163 ;; Patch org-mode to use vertical splitting
1164 (defadvice org-prepare-agenda (after org-fix-split)
1165   (toggle-window-split))
1166 (ad-activate 'org-prepare-agenda)
1167 #+END_SRC
1169 *** Automatically add an appointment when clocking in a task
1171 #+BEGIN_SRC emacs-lisp
1172 ;; Make sure you have a sensible value for `appt-message-warning-time'
1173 (defvar bzg-org-clock-in-appt-delay 100
1174   "Number of minutes for setting an appointment by clocking-in")
1175 #+END_SRC
1177 This function let's you add an appointment for the current entry.
1178 This can be useful when you need a reminder.
1180 #+BEGIN_SRC emacs-lisp
1181 (defun bzg-org-clock-in-add-appt (&optional n)
1182   "Add an appointment for the Org entry at point in N minutes."
1183   (interactive)
1184   (save-excursion
1185     (org-back-to-heading t)
1186     (looking-at org-complex-heading-regexp)
1187     (let* ((msg (match-string-no-properties 4))
1188            (ct-time (decode-time))
1189            (appt-min (+ (cadr ct-time)
1190                         (or n bzg-org-clock-in-appt-delay)))
1191            (appt-time ; define the time for the appointment
1192             (progn (setf (cadr ct-time) appt-min) ct-time)))
1193       (appt-add (format-time-string
1194                  "%H:%M" (apply 'encode-time appt-time)) msg)
1195       (if (interactive-p) (message "New appointment for %s" msg)))))
1196 #+END_SRC
1198 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1199 add an appointment:
1201 #+BEGIN_SRC emacs-lisp
1202 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1203   "Add an appointment when clocking a task in."
1204   (bzg-org-clock-in-add-appt))
1205 #+END_SRC
1207 You may also want to delete the associated appointment when clocking
1208 out.  This function does this:
1210 #+BEGIN_SRC emacs-lisp
1211 (defun bzg-org-clock-out-delete-appt nil
1212   "When clocking out, delete any associated appointment."
1213   (interactive)
1214   (save-excursion
1215     (org-back-to-heading t)
1216     (looking-at org-complex-heading-regexp)
1217     (let* ((msg (match-string-no-properties 4)))
1218       (setq appt-time-msg-list
1219             (delete nil
1220                     (mapcar
1221                      (lambda (appt)
1222                        (if (not (string-match (regexp-quote msg)
1223                                               (cadr appt))) appt))
1224                      appt-time-msg-list)))
1225       (appt-check))))
1226 #+END_SRC
1228 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1230 #+BEGIN_SRC emacs-lisp
1231 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1232   "Delete an appointment when clocking a task out."
1233   (bzg-org-clock-out-delete-appt))
1234 #+END_SRC
1236 *IMPORTANT*: You can add appointment by clocking in in both an
1237 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
1238 agenda buffer with the advice above will bring an error.
1240 *** Remove time grid lines that are in an appointment
1242 The agenda shows lines for the time grid.  Some people think that
1243 these lines are a distraction when there are appointments at those
1244 times.  You can get rid of the lines which coincide exactly with the
1245 beginning of an appointment.  Michael Ekstrand has written a piece of
1246 advice that also removes lines that are somewhere inside an
1247 appointment:
1249 #+begin_src emacs-lisp
1250 (defun org-time-to-minutes (time)
1251   "Convert an HHMM time to minutes"
1252   (+ (* (/ time 100) 60) (% time 100)))
1254 (defun org-time-from-minutes (minutes)
1255   "Convert a number of minutes to an HHMM time"
1256   (+ (* (/ minutes 60) 100) (% minutes 60)))
1258 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1259                                                   (list ndays todayp))
1260   (if (member 'remove-match (car org-agenda-time-grid))
1261       (flet ((extract-window
1262               (line)
1263               (let ((start (get-text-property 1 'time-of-day line))
1264                     (dur (get-text-property 1 'duration line)))
1265                 (cond
1266                  ((and start dur)
1267                   (cons start
1268                         (org-time-from-minutes
1269                          (+ dur (org-time-to-minutes start)))))
1270                  (start start)
1271                  (t nil)))))
1272         (let* ((windows (delq nil (mapcar 'extract-window list)))
1273                (org-agenda-time-grid
1274                 (list (car org-agenda-time-grid)
1275                       (cadr org-agenda-time-grid)
1276                       (remove-if
1277                        (lambda (time)
1278                          (find-if (lambda (w)
1279                                     (if (numberp w)
1280                                         (equal w time)
1281                                       (and (>= time (car w))
1282                                            (< time (cdr w)))))
1283                                   windows))
1284                        (caddr org-agenda-time-grid)))))
1285           ad-do-it))
1286     ad-do-it))
1287 (ad-activate 'org-agenda-add-time-grid-maybe)
1288 #+end_src
1289 *** Disable vc for Org mode agenda files
1290 -- David Maus
1292 Even if you use Git to track your agenda files you might not need
1293 vc-mode to be enabled for these files.
1295 #+begin_src emacs-lisp
1296 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1297 (defun dmj/disable-vc-for-agenda-files-hook ()
1298   "Disable vc-mode for Org agenda files."
1299   (if (and (fboundp 'org-agenda-file-p)
1300            (org-agenda-file-p (buffer-file-name)))
1301       (remove-hook 'find-file-hook 'vc-find-file-hook)
1302     (add-hook 'find-file-hook 'vc-find-file-hook)))
1303 #+end_src
1305 *** Easy customization of TODO colors
1306 -- Ryan C. Thompson
1308 Here is some code I came up with some code to make it easier to
1309 customize the colors of various TODO keywords. As long as you just
1310 want a different color and nothing else, you can customize the
1311 variable org-todo-keyword-faces and use just a string color (i.e. a
1312 string of the color name) as the face, and then org-get-todo-face
1313 will convert the color to a face, inheriting everything else from
1314 the standard org-todo face.
1316 To demonstrate, I currently have org-todo-keyword-faces set to
1318 #+BEGIN_SRC emacs-lisp
1319 (("IN PROGRESS" . "dark orange")
1320  ("WAITING" . "red4")
1321  ("CANCELED" . "saddle brown"))
1322 #+END_SRC emacs-lisp
1324   Here's the code, in a form you can put in your =.emacs=
1326 #+BEGIN_SRC emacs-lisp
1327 (eval-after-load 'org-faces
1328  '(progn
1329     (defcustom org-todo-keyword-faces nil
1330       "Faces for specific TODO keywords.
1331 This is a list of cons cells, with TODO keywords in the car and
1332 faces in the cdr.  The face can be a symbol, a color, or a
1333 property list of attributes, like (:foreground \"blue\" :weight
1334 bold :underline t)."
1335       :group 'org-faces
1336       :group 'org-todo
1337       :type '(repeat
1338               (cons
1339                (string :tag "Keyword")
1340                (choice color (sexp :tag "Face")))))))
1342 (eval-after-load 'org
1343  '(progn
1344     (defun org-get-todo-face-from-color (color)
1345       "Returns a specification for a face that inherits from org-todo
1346  face and has the given color as foreground. Returns nil if
1347  color is nil."
1348       (when color
1349         `(:inherit org-warning :foreground ,color)))
1351     (defun org-get-todo-face (kwd)
1352       "Get the right face for a TODO keyword KWD.
1353 If KWD is a number, get the corresponding match group."
1354       (if (numberp kwd) (setq kwd (match-string kwd)))
1355       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1356             (if (stringp face)
1357                 (org-get-todo-face-from-color face)
1358               face))
1359           (and (member kwd org-done-keywords) 'org-done)
1360           'org-todo))))
1361 #+END_SRC emacs-lisp
1363 *** Add an effort estimate on the fly when clocking in
1365 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1366 This way you can easily have a "tea-timer" for your tasks when they
1367 don't already have an effort estimate.
1369 #+begin_src emacs-lisp
1370 (add-hook 'org-clock-in-prepare-hook
1371           'my-org-mode-ask-effort)
1373 (defun my-org-mode-ask-effort ()
1374   "Ask for an effort estimate when clocking in."
1375   (unless (org-entry-get (point) "Effort")
1376     (let ((effort
1377            (completing-read
1378             "Effort: "
1379             (org-entry-get-multivalued-property (point) "Effort"))))
1380       (unless (equal effort "")
1381         (org-set-property "Effort" effort)))))
1382 #+end_src
1384 Or you can use a default effort for such a timer:
1386 #+begin_src emacs-lisp
1387 (add-hook 'org-clock-in-prepare-hook
1388           'my-org-mode-add-default-effort)
1390 (defvar org-clock-default-effort "1:00")
1392 (defun my-org-mode-add-default-effort ()
1393   "Add a default effort estimation."
1394   (unless (org-entry-get (point) "Effort")
1395     (org-set-property "Effort" org-clock-default-effort)))
1396 #+end_src
1398 *** Refresh the agenda view regurally
1400 Hack sent by Kiwon Um:
1402 #+begin_src emacs-lisp
1403 (defun kiwon/org-agenda-redo-in-other-window ()
1404   "Call org-agenda-redo function even in the non-agenda buffer."
1405   (interactive)
1406   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1407     (when agenda-window
1408       (with-selected-window agenda-window (org-agenda-redo)))))
1409 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1410 #+end_src
1412 *** Reschedule agenda items to today with a single command
1414 This was suggested by Carsten in reply to David Abrahams:
1416 #+begin_example emacs-lisp
1417 (defun org-agenda-reschedule-to-today ()
1418   (interactive)
1419   (flet ((org-read-date (&rest rest) (current-time)))
1420     (call-interactively 'org-agenda-schedule)))
1421 #+end_example
1423 * Hacking Org: Working with Org-mode and other Emacs Packages.
1424 ** org-remember-anything
1426 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1428 #+BEGIN_SRC emacs-lisp
1429 (defvar org-remember-anything
1430   '((name . "Org Remember")
1431     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1432     (action . (lambda (name)
1433                 (let* ((orig-template org-remember-templates)
1434                        (org-remember-templates
1435                         (list (assoc name orig-template))))
1436                   (call-interactively 'org-remember))))))
1437 #+END_SRC
1439 You can add it to your 'anything-sources' variable and open remember directly
1440 from anything. I imagine this would be more interesting for people with many
1441 remember templatesm, so that you are out of keys to assign those to. You should
1442 get something like this:
1444 [[file:images/thumbs/org-remember-anything.png]]
1446 ** Org-mode and saveplace.el
1448 Fix a problem with saveplace.el putting you back in a folded position:
1450 #+begin_src emacs-lisp
1451 (add-hook 'org-mode-hook
1452           (lambda ()
1453             (when (outline-invisible-p)
1454               (save-excursion
1455                 (outline-previous-visible-heading 1)
1456                 (org-show-subtree)))))
1457 #+end_src
1459 ** Using ido-completing-read to find attachments
1460 -- Matt Lundin
1462 Org-attach is great for quickly linking files to a project. But if you
1463 use org-attach extensively you might find yourself wanting to browse
1464 all the files you've attached to org headlines. This is not easy to do
1465 manually, since the directories containing the files are not human
1466 readable (i.e., they are based on automatically generated ids). Here's
1467 some code to browse those files using ido (obviously, you need to be
1468 using ido):
1470 #+begin_src emacs-lisp
1471 (load-library "find-lisp")
1473 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1475 (defun my-ido-find-org-attach ()
1476   "Find files in org-attachment directory"
1477   (interactive)
1478   (let* ((enable-recursive-minibuffers t)
1479          (files (find-lisp-find-files org-attach-directory "."))
1480          (file-assoc-list
1481           (mapcar (lambda (x)
1482                     (cons (file-name-nondirectory x)
1483                           x))
1484                   files))
1485          (filename-list
1486           (remove-duplicates (mapcar #'car file-assoc-list)
1487                              :test #'string=))
1488          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1489          (longname (cdr (assoc filename file-assoc-list))))
1490     (ido-set-current-directory
1491      (if (file-directory-p longname)
1492          longname
1493        (file-name-directory longname)))
1494     (setq ido-exit 'refresh
1495           ido-text-init ido-text
1496           ido-rotate-temp t)
1497     (exit-minibuffer)))
1499 (add-hook 'ido-setup-hook 'ido-my-keys)
1501 (defun ido-my-keys ()
1502   "Add my keybindings for ido."
1503   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1504 #+end_src
1506 To browse your org attachments using ido fuzzy matching and/or the
1507 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1508 press =C-;=.
1510 ** Use idle timer for automatic agenda views
1512 From John Wiegley's mailing list post (March 18, 2010):
1514 #+begin_quote
1515 I have the following snippet in my .emacs file, which I find very
1516 useful. Basically what it does is that if I don't touch my Emacs for 5
1517 minutes, it displays the current agenda. This keeps my tasks "always
1518 in mind" whenever I come back to Emacs after doing something else,
1519 whereas before I had a tendency to forget that it was there.
1520 #+end_quote  
1522   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1524 #+begin_src emacs-lisp
1525 (defun jump-to-org-agenda ()
1526   (interactive)
1527   (let ((buf (get-buffer "*Org Agenda*"))
1528         wind)
1529     (if buf
1530         (if (setq wind (get-buffer-window buf))
1531             (select-window wind)
1532           (if (called-interactively-p)
1533               (progn
1534                 (select-window (display-buffer buf t t))
1535                 (org-fit-window-to-buffer)
1536                 ;; (org-agenda-redo)
1537                 )
1538             (with-selected-window (display-buffer buf)
1539               (org-fit-window-to-buffer)
1540               ;; (org-agenda-redo)
1541               )))
1542       (call-interactively 'org-agenda-list)))
1543   ;;(let ((buf (get-buffer "*Calendar*")))
1544   ;;  (unless (get-buffer-window buf)
1545   ;;    (org-agenda-goto-calendar)))
1546   )
1547   
1548 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1549 #+end_src
1551 #+results:
1552 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1554 ** Link to Gnus messages by Message-Id
1556 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1557 discussion about linking to Gnus messages without encoding the folder
1558 name in the link.  The following code hooks in to the store-link
1559 function in Gnus to capture links by Message-Id when in nnml folders,
1560 and then provides a link type "mid" which can open this link.  The
1561 =mde-org-gnus-open-message-link= function uses the
1562 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1563 scan.  It will go through them, in order, asking each to locate the
1564 message and opening it from the first one that reports success.
1566 It has only been tested with a single nnml backend, so there may be
1567 bugs lurking here and there.
1569 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1570 article]].
1572 #+begin_src emacs-lisp
1573 ;; Support for saving Gnus messages by Message-ID
1574 (defun mde-org-gnus-save-by-mid ()
1575   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1576     (when (eq major-mode 'gnus-article-mode)
1577       (gnus-article-show-summary))
1578     (let* ((group gnus-newsgroup-name)
1579            (method (gnus-find-method-for-group group)))
1580       (when (eq 'nnml (car method))
1581         (let* ((article (gnus-summary-article-number))
1582                (header (gnus-summary-article-header article))
1583                (from (mail-header-from header))
1584                (message-id
1585                 (save-match-data
1586                   (let ((mid (mail-header-id header)))
1587                     (if (string-match "<\\(.*\\)>" mid)
1588                         (match-string 1 mid)
1589                       (error "Malformed message ID header %s" mid)))))
1590                (date (mail-header-date header))
1591                (subject (gnus-summary-subject-string)))
1592           (org-store-link-props :type "mid" :from from :subject subject
1593                                 :message-id message-id :group group
1594                                 :link (org-make-link "mid:" message-id))
1595           (apply 'org-store-link-props
1596                  :description (org-email-link-description)
1597                  org-store-link-plist)
1598           t)))))
1600 (defvar mde-mid-resolve-methods '()
1601   "List of methods to try when resolving message ID's.  For Gnus,
1602 it is a cons of 'gnus and the select (type and name).")
1603 (setq mde-mid-resolve-methods
1604       '((gnus nnml "")))
1606 (defvar mde-org-gnus-open-level 1
1607   "Level at which Gnus is started when opening a link")
1608 (defun mde-org-gnus-open-message-link (msgid)
1609   "Open a message link with Gnus"
1610   (require 'gnus)
1611   (require 'org-table)
1612   (catch 'method-found
1613     (message "[MID linker] Resolving %s" msgid)
1614     (dolist (method mde-mid-resolve-methods)
1615       (cond
1616        ((and (eq (car method) 'gnus)
1617              (eq (cadr method) 'nnml))
1618         (funcall (cdr (assq 'gnus org-link-frame-setup))
1619                  mde-org-gnus-open-level)
1620         (when gnus-other-frame-object
1621           (select-frame gnus-other-frame-object))
1622         (let* ((msg-info (nnml-find-group-number
1623                           (concat "<" msgid ">")
1624                           (cdr method)))
1625                (group (and msg-info (car msg-info)))
1626                (message (and msg-info (cdr msg-info)))
1627                (qname (and group
1628                            (if (gnus-methods-equal-p
1629                                 (cdr method)
1630                                 gnus-select-method)
1631                                group
1632                              (gnus-group-full-name group (cdr method))))))
1633           (when msg-info
1634             (gnus-summary-read-group qname nil t)
1635             (gnus-summary-goto-article message nil t))
1636           (throw 'method-found t)))
1637        (t (error "Unknown link type"))))))
1639 (eval-after-load 'org-gnus
1640   '(progn
1641      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1642      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1643 #+end_src
1645 ** Store link upon sending a message in Gnus
1647 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1649 #+begin_src emacs-lisp
1650 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1651   "Send message with `message-send-and-exit' and store org link to message copy.
1652 If multiple groups appear in the Gcc header, the link refers to
1653 the copy in the last group."
1654   (interactive "P")
1655     (save-excursion
1656       (save-restriction
1657         (message-narrow-to-headers)
1658         (let ((gcc (car (last
1659                          (message-unquote-tokens
1660                           (message-tokenize-header
1661                            (mail-fetch-field "gcc" nil t) " ,")))))
1662               (buf (current-buffer))
1663               (message-kill-buffer-on-exit nil)
1664               id to from subject desc link newsgroup xarchive)
1665         (message-send-and-exit arg)
1666         (or
1667          ;; gcc group found ...
1668          (and gcc
1669               (save-current-buffer
1670                 (progn (set-buffer buf)
1671                        (setq id (org-remove-angle-brackets
1672                                  (mail-fetch-field "Message-ID")))
1673                        (setq to (mail-fetch-field "To"))
1674                        (setq from (mail-fetch-field "From"))
1675                        (setq subject (mail-fetch-field "Subject"))))
1676               (org-store-link-props :type "gnus" :from from :subject subject
1677                                     :message-id id :group gcc :to to)
1678               (setq desc (org-email-link-description))
1679               (setq link (org-gnus-article-link
1680                           gcc newsgroup id xarchive))
1681               (setq org-stored-links
1682                     (cons (list link desc) org-stored-links)))
1683          ;; no gcc group found ...
1684          (message "Can not create Org link: No Gcc header found."))))))
1686 (define-key message-mode-map [(control c) (control meta c)]
1687   'ulf-message-send-and-org-gnus-store-link)
1688 #+end_src
1690 ** Send html messages and attachments with Wanderlust
1691   -- David Maus
1693 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1694 similar functionality for both Wanderlust and Gnus.  The hack below is
1695 still somewhat different: It allows you to toggle sending of html
1696 messages within Wanderlust transparently.  I.e. html markup of the
1697 message body is created right before sending starts.
1699 *** Send HTML message
1701 Putting the code below in your .emacs adds following four functions:
1703 - dmj/wl-send-html-message
1705   Function that does the job: Convert everything between "--text
1706   follows this line--" and first mime entity (read: attachment) or
1707   end of buffer into html markup using `org-export-region-as-html'
1708   and replaces original body with a multipart MIME entity with the
1709   plain text version of body and the html markup version.  Thus a
1710   recipient that prefers html messages can see the html markup,
1711   recipients that prefer or depend on plain text can see the plain
1712   text.
1714   Cannot be called interactively: It is hooked into SEMI's
1715   `mime-edit-translate-hook' if message should be HTML message.
1717 - dmj/wl-send-html-message-draft-init
1719   Cannot be called interactively: It is hooked into WL's
1720   `wl-mail-setup-hook' and provides a buffer local variable to
1721   toggle.
1723 - dmj/wl-send-html-message-draft-maybe
1725   Cannot be called interactively: It is hooked into WL's
1726   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1727   `mime-edit-translate-hook' depending on whether HTML message is
1728   toggled on or off
1730 - dmj/wl-send-html-message-toggle
1732   Toggles sending of HTML message.  If toggled on, the letters
1733   "HTML" appear in the mode line.
1735   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1737 If you have to send HTML messages regularly you can set a global
1738 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1739 toggle on sending HTML message by default.
1741 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1742 Google's web front end.  As you can see you have the whole markup of
1743 Org at your service: *bold*, /italics/, tables, lists...
1745 So even if you feel uncomfortable with sending HTML messages at least
1746 you send HTML that looks quite good.
1748 #+begin_src emacs-lisp
1749 (defun dmj/wl-send-html-message ()
1750   "Send message as html message.
1751 Convert body of message to html using
1752   `org-export-region-as-html'."
1753   (require 'org)
1754   (save-excursion
1755     (let (beg end html text)
1756       (goto-char (point-min))
1757       (re-search-forward "^--text follows this line--$")
1758       ;; move to beginning of next line
1759       (beginning-of-line 2)
1760       (setq beg (point))
1761       (if (not (re-search-forward "^--\\[\\[" nil t))
1762           (setq end (point-max))
1763         ;; line up
1764         (end-of-line 0)
1765         (setq end (point)))
1766       ;; grab body
1767       (setq text (buffer-substring-no-properties beg end))
1768       ;; convert to html
1769       (with-temp-buffer
1770         (org-mode)
1771         (insert text)
1772         ;; handle signature
1773         (when (re-search-backward "^-- \n" nil t)
1774           ;; preserve link breaks in signature
1775           (insert "\n#+BEGIN_VERSE\n")
1776           (goto-char (point-max))
1777           (insert "\n#+END_VERSE\n")
1778           ;; grab html
1779           (setq html (org-export-region-as-html
1780                       (point-min) (point-max) t 'string))))
1781       (delete-region beg end)
1782       (insert
1783        (concat
1784         "--" "<<alternative>>-{\n"
1785         "--" "[[text/plain]]\n" text
1786         "--" "[[text/html]]\n"  html
1787         "--" "}-<<alternative>>\n")))))
1789 (defun dmj/wl-send-html-message-toggle ()
1790   "Toggle sending of html message."
1791   (interactive)
1792   (setq dmj/wl-send-html-message-toggled-p
1793         (if dmj/wl-send-html-message-toggled-p
1794             nil "HTML"))
1795   (message "Sending html message toggled %s"
1796            (if dmj/wl-send-html-message-toggled-p
1797                "on" "off")))
1799 (defun dmj/wl-send-html-message-draft-init ()
1800   "Create buffer local settings for maybe sending html message."
1801   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1802     (setq dmj/wl-send-html-message-toggled-p nil))
1803   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1804   (add-to-list 'global-mode-string
1805                '(:eval (if (eq major-mode 'wl-draft-mode)
1806                            dmj/wl-send-html-message-toggled-p))))
1808 (defun dmj/wl-send-html-message-maybe ()
1809   "Maybe send this message as html message.
1811 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1812 non-nil, add `dmj/wl-send-html-message' to
1813 `mime-edit-translate-hook'."
1814   (if dmj/wl-send-html-message-toggled-p
1815       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1816     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1818 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1819 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1820 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1821 #+end_src
1823 *** Attach HTML of region or subtree
1825 Instead of sending a complete HTML message you might only send parts
1826 of an Org file as HTML for the poor souls who are plagued with
1827 non-proportional fonts in their mail program that messes up pretty
1828 ASCII tables.
1830 This short function does the trick: It exports region or subtree to
1831 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1832 and clipboard.  If a region is active, it uses the region, the
1833 complete subtree otherwise.
1835 #+begin_src emacs-lisp
1836 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1837   "Export region between BEG and END as html attachment.
1838 If BEG and END are not set, use current subtree.  Region or
1839 subtree is exported to html without header and footer, prefixed
1840 with a mime entity string and pushed to clipboard and killring.
1841 When called with prefix, mime entity is not marked as
1842 attachment."
1843   (interactive "r\nP")
1844   (save-excursion
1845     (let* ((beg (if (region-active-p) (region-beginning)
1846                   (progn
1847                     (org-back-to-heading)
1848                     (point))))
1849            (end (if (region-active-p) (region-end)
1850                   (progn
1851                     (org-end-of-subtree)
1852                     (point))))
1853            (html (concat "--[[text/html"
1854                          (if arg "" "\nContent-Disposition: attachment")
1855                          "]]\n"
1856                          (org-export-region-as-html beg end t 'string))))
1857       (when (fboundp 'x-set-selection)
1858         (ignore-errors (x-set-selection 'PRIMARY html))
1859         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1860       (message "html export done, pushed to kill ring and clipboard"))))
1861 #+end_src
1863 *** Adopting for Gnus
1865 The whole magic lies in the special strings that mark a HTML
1866 attachment.  So you might just have to find out what these special
1867 strings are in message-mode and modify the functions accordingly.
1868 ** Add sunrise/sunset times to the agenda.
1869   -- Nick Dokos
1871 The diary package provides the function =diary-sunrise-sunset= which can be used
1872 in a diary s-expression in some agenda file like this:
1874 #+begin_src org-mode
1875 %%(diary-sunrise-sunset)
1876 #+end_src
1878 Seb Vauban asked if it is possible to put sunrise and sunset in
1879 separate lines. Here is a hack to do that. It adds two functions (they
1880 have to be available before the agenda is shown, so I add them early
1881 in my org-config file which is sourced from .emacs, but you'll have to
1882 suit yourself here) that just parse the output of
1883 diary-sunrise-sunset, instead of doing the right thing which would be
1884 to take advantage of the data structures that diary/solar.el provides.
1885 In short, a hack - so perfectly suited for inclusion here :-)
1887 The functions (and latitude/longitude settings which you have to modify for
1888 your location) are as follows:
1890 #+begin_src emacs-lisp
1891 (setq calendar-latitude 40.3)
1892 (setq calendar-longitude -71.0)
1893 (defun diary-sunrise ()
1894   (let ((dss (diary-sunrise-sunset)))
1895     (with-temp-buffer
1896       (insert dss)
1897       (goto-char (point-min))
1898       (while (re-search-forward " ([^)]*)" nil t)
1899         (replace-match "" nil nil))
1900       (goto-char (point-min))
1901       (search-forward ",")
1902       (buffer-substring (point-min) (match-beginning 0)))))
1904 (defun diary-sunset ()
1905   (let ((dss (diary-sunrise-sunset))
1906         start end)
1907     (with-temp-buffer
1908       (insert dss)
1909       (goto-char (point-min))
1910       (while (re-search-forward " ([^)]*)" nil t)
1911         (replace-match "" nil nil))
1912       (goto-char (point-min))
1913       (search-forward ", ")
1914       (setq start (match-end 0))
1915       (search-forward " at")
1916       (setq end (match-beginning 0))
1917       (goto-char start)
1918       (capitalize-word 1)
1919       (buffer-substring start end))))
1920 #+end_src
1922 You also need to add a couple of diary s-expressions in one of your agenda
1923 files:
1925 #+begin_src org-mode
1926 %%(diary-sunrise)
1927 %%(diary-sunset)
1928 #+end_src
1930 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]].
1931 In comparison to the version posted on the mailing list, this one
1932 gets rid of the timezone information.
1933 * Hacking Org: Working with Org-mode and External Programs.
1934 ** Use Org-mode with Screen [Andrew Hyatt]
1936 "The general idea is that you start a task in which all the work will
1937 take place in a shell.  This usually is not a leaf-task for me, but
1938 usually the parent of a leaf task.  From a task in your org-file, M-x
1939 ash-org-screen will prompt for the name of a session.  Give it a name,
1940 and it will insert a link.  Open the link at any time to go the screen
1941 session containing your work!"
1943 http://article.gmane.org/gmane.emacs.orgmode/5276
1945 #+BEGIN_SRC emacs-lisp
1946 (require 'term)
1948 (defun ash-org-goto-screen (name)
1949   "Open the screen with the specified name in the window"
1950   (interactive "MScreen name: ")
1951   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1952     (if (member screen-buffer-name
1953                 (mapcar 'buffer-name (buffer-list)))
1954         (switch-to-buffer screen-buffer-name)
1955       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1957 (defun ash-org-screen-buffer-name (name)
1958   "Returns the buffer name corresponding to the screen name given."
1959   (concat "*screen " name "*"))
1961 (defun ash-org-screen-helper (name arg)
1962   ;; Pick the name of the new buffer.
1963   (let ((term-ansi-buffer-name
1964          (generate-new-buffer-name
1965           (ash-org-screen-buffer-name name))))
1966     (setq term-ansi-buffer-name
1967           (term-ansi-make-term
1968            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1969     (set-buffer term-ansi-buffer-name)
1970     (term-mode)
1971     (term-char-mode)
1972     (term-set-escape-char ?\C-x)
1973     term-ansi-buffer-name))
1975 (defun ash-org-screen (name)
1976   "Start a screen session with name"
1977   (interactive "MScreen name: ")
1978   (save-excursion
1979     (ash-org-screen-helper name "-S"))
1980   (insert-string (concat "[[screen:" name "]]")))
1982 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1983 ;; \"%s\")") to org-link-abbrev-alist.
1984 #+END_SRC
1986 ** Org Agenda + Appt + Zenity
1987 #+BEGIN_HTML
1988 <a name="agenda-appt-zenity"></a>
1989 #+END_HTML
1990 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It makes sure your agenda
1991 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1992 popup window.
1994 #+BEGIN_SRC emacs-lisp
1995 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1996 ; For org appointment reminders
1998 ;; Get appointments for today
1999 (defun my-org-agenda-to-appt ()
2000   (interactive)
2001   (setq appt-time-msg-list nil)
2002   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
2003         (org-agenda-to-appt)))
2005 ;; Run once, activate and schedule refresh
2006 (my-org-agenda-to-appt)
2007 (appt-activate t)
2008 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2010 ; 5 minute warnings
2011 (setq appt-message-warning-time 15)
2012 (setq appt-display-interval 5)
2014 ; Update appt each time agenda opened.
2015 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2017 ; Setup zenify, we tell appt to use window, and replace default function
2018 (setq appt-display-format 'window)
2019 (setq appt-disp-window-function (function my-appt-disp-window))
2021 (defun my-appt-disp-window (min-to-app new-time msg)
2022   (save-window-excursion (shell-command (concat
2023     "/usr/bin/zenity --info --title='Appointment' --text='"
2024     msg "' &") nil nil)))
2025 #+END_SRC
2027 ** Org-Mode + gnome-osd
2029 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2030 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2032 ** remind2org
2034 From Detlef Steuer
2036 http://article.gmane.org/gmane.emacs.orgmode/5073
2038 #+BEGIN_QUOTE
2039 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2040 command line calendaring program. Its features superseed the possibilities
2041 of orgmode in the area of date specifying, so that I want to use it
2042 combined with orgmode.
2044 Using the script below I'm able use remind and incorporate its output in my
2045 agenda views.  The default of using 13 months look ahead is easily
2046 changed. It just happens I sometimes like to look a year into the
2047 future. :-)
2048 #+END_QUOTE
2050 ** Useful webjumps for conkeror
2052 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2053 your =~/.conkerorrc= file:
2055 #+begin_example
2056 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2057 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2058 #+end_example
2060 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2061 Org-mode mailing list.
2063 ** Use MathJax for HTML export without requiring JavaScript
2064 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2066 If you like the results but do not want JavaScript in the exported pages,
2067 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2068 HTML file from the exported version. It can also embed all referenced fonts
2069 within the HTML file itself, so there are no dependencies to external files.
2071 The download archive contains an elisp file which integrates it into the Org
2072 export process (configurable per file with a "#+StaticMathJax:" line).
2074 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2075 ** Search Org files using lgrep
2077 Matt Lundin suggests this:
2079 #+begin_src emacs-lisp
2080   (defun my-org-grep (search &optional context)
2081     "Search for word in org files. 
2083 Prefix argument determines number of lines."
2084     (interactive "sSearch for: \nP")
2085     (let ((grep-find-ignored-files '("#*" ".#*"))
2086           (grep-template (concat "grep <X> -i -nH " 
2087                                  (when context
2088                                    (concat "-C" (number-to-string context)))
2089                                  " -e <R> <F>")))
2090       (lgrep search "*org*" "/home/matt/org/")))
2092   (global-set-key (kbd "<f8>") 'my-org-grep)
2093 #+end_src
2095 ** Automatic screenshot insertion
2097 Suggested by Jonathan Bisson:
2099 #+begin_src emacs-lisp
2100   (defun my-screenshot ()
2101   "Take a screenshot into a unique-named file in the current buffer file
2102   directory and insert a link to this file."
2103     (interactive)
2104     (setq filename
2105           (concat
2106            (make-temp-name
2107             (file-name-directory (buffer-file-name))) ".jpg"))
2108     (call-process "import" nil nil nil filename)
2109     (insert (concat "[[" filename "]]"))
2110     (org-display-inline-images))
2111 #+end_src
2113 ** Capture invitations/appointments from MS Exchange emails
2115 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this.  Please check
2116 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]