Turn of section numbering for meeting action tutorial
[Worg.git] / org-hacks.org
blob64051e1965a8623a95daff7e8e51c9639780e94c
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           (catch 'break
770             (while t
771               (when (= 1 (org-up-heading-safe))
772                 (throw 'break t))))
773           (org-set-tags-to tags)))))
774 #+end_src
776 *** Archive in a date tree
778 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
780 (Make sure org-datetree.el is loaded for this to work.)
782 #+begin_src emacs-lisp
783 ;; (setq org-archive-location "%s_archive::date-tree")
784 (defadvice org-archive-subtree
785   (around org-archive-subtree-to-data-tree activate)
786   "org-archive-subtree to date-tree"
787   (if
788       (string= "date-tree"
789                (org-extract-archive-heading
790                 (org-get-local-archive-location)))
791       (let* ((dct (decode-time (org-current-time)))
792              (y (nth 5 dct))
793              (m (nth 4 dct))
794              (d (nth 3 dct))
795              (this-buffer (current-buffer))
796              (location (org-get-local-archive-location))
797              (afile (org-extract-archive-file location))
798              (org-archive-location
799               (format "%s::*** %04d-%02d-%02d %s" afile y m d
800                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
801         (message "afile=%s" afile)
802         (unless afile
803           (error "Invalid `org-archive-location'"))
804         (save-excursion
805           (switch-to-buffer (find-file-noselect afile))
806           (org-datetree-find-year-create y)
807           (org-datetree-find-month-create y m)
808           (org-datetree-find-day-create y m d)
809           (widen)
810           (switch-to-buffer this-buffer))
811         ad-do-it)
812     ad-do-it))
813 #+end_src
815 *** Add inherited tags to archived entries
817 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
818 advise the function like this:
820 #+begin_example
821 (defadvice org-archive-subtree
822   (before add-inherited-tags-before-org-archive-subtree activate)
823     "add inherited tags before org-archive-subtree"
824     (org-set-tags-to (org-get-tags-at)))
825 #+end_example
827 ** Using and Managing Org-Metadata
828 *** Remove redundant tags of headlines
829 -- David Maus
831 A small function that processes all headlines in current buffer and
832 removes tags that are local to a headline and inherited by a parent
833 headline or the #+FILETAGS: statement.
835 #+BEGIN_SRC emacs-lisp
836   (defun dmj/org-remove-redundant-tags ()
837     "Remove redundant tags of headlines in current buffer.
839   A tag is considered redundant if it is local to a headline and
840   inherited by a parent headline."
841     (interactive)
842     (when (eq major-mode 'org-mode)
843       (save-excursion
844         (org-map-entries
845          '(lambda ()
846             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
847                   local inherited tag)
848               (dolist (tag alltags)
849                 (if (get-text-property 0 'inherited tag)
850                     (push tag inherited) (push tag local)))
851               (dolist (tag local)
852                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
853          t nil))))
854 #+END_SRC
856 *** Remove empty property drawers
858 David Maus proposed this:
860 #+begin_src emacs-lisp
861 (defun dmj:org:remove-empty-propert-drawers ()
862   "*Remove all empty property drawers in current file."
863   (interactive)
864   (unless (eq major-mode 'org-mode)
865     (error "You need to turn on Org mode for this function."))
866   (save-excursion
867     (goto-char (point-min))
868     (while (re-search-forward ":PROPERTIES:" nil t)
869       (save-excursion
870         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
871 #+end_src
873 *** Group task list by a property
875 This advice allows you to group a task list in Org-Mode.  To use it,
876 set the variable =org-agenda-group-by-property= to the name of a
877 property in the option list for a TODO or TAGS search.  The resulting
878 agenda view will group tasks by that property prior to searching.
880 #+begin_src emacs-lisp
881 (defvar org-agenda-group-by-property nil
882   "Set this in org-mode agenda views to group tasks by property")
884 (defun org-group-bucket-items (prop items)
885   (let ((buckets ()))
886     (dolist (item items)
887       (let* ((marker (get-text-property 0 'org-marker item))
888              (pvalue (org-entry-get marker prop t))
889              (cell (assoc pvalue buckets)))
890         (if cell
891             (setcdr cell (cons item (cdr cell)))
892           (setq buckets (cons (cons pvalue (list item))
893                               buckets)))))
894     (setq buckets (mapcar (lambda (bucket)
895                             (cons (car bucket)
896                                   (reverse (cdr bucket))))
897                           buckets))
898     (sort buckets (lambda (i1 i2)
899                     (string< (car i1) (car i2))))))
901 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
902                                                (list &optional nosort))
903   "Prepare bucketed agenda entry lists"
904   (if org-agenda-group-by-property
905       ;; bucketed, handle appropriately
906       (let ((text ""))
907         (dolist (bucket (org-group-bucket-items
908                          org-agenda-group-by-property
909                          list))
910           (let ((header (concat "Property "
911                                 org-agenda-group-by-property
912                                 " is "
913                                 (or (car bucket) "<nil>") ":\n")))
914             (add-text-properties 0 (1- (length header))
915                                  (list 'face 'org-agenda-structure)
916                                  header)
917             (setq text
918                   (concat text header
919                           ;; recursively process
920                           (let ((org-agenda-group-by-property nil))
921                             (org-finalize-agenda-entries
922                              (cdr bucket) nosort))
923                           "\n\n"))))
924         (setq ad-return-value text))
925     ad-do-it))
926 (ad-activate 'org-finalize-agenda-entries)
927 #+end_src
928 *** Dynamically adjust tag position
929 Here is a bit of code that allows you to have the tags always
930 right-adjusted in the buffer.
932 This is useful when you have bigger window than default window-size
933 and you dislike the aesthetics of having the tag in the middle of the
934 line.
936 This hack solves the problem of adjusting it whenever you change the
937 window size.
938 Before saving it will revert the file to having the tag position be
939 left-adjusted so that if you track your files with version control,
940 you won't run into artificial diffs just because the window-size
941 changed.
943 *IMPORTANT*: This is probably slow on very big files.
945 #+begin_src emacs-lisp
946 (setq ba/org-adjust-tags-column t)
948 (defun ba/org-adjust-tags-column-reset-tags ()
949   "In org-mode buffers it will reset tag position according to
950 `org-tags-column'."
951   (when (and
952          (not (string= (buffer-name) "*Remember*"))
953          (eql major-mode 'org-mode))
954     (let ((b-m-p (buffer-modified-p)))
955       (condition-case nil
956           (save-excursion
957             (goto-char (point-min))
958             (command-execute 'outline-next-visible-heading)
959             ;; disable (message) that org-set-tags generates
960             (flet ((message (&rest ignored) nil))
961               (org-set-tags 1 t))
962             (set-buffer-modified-p b-m-p))
963         (error nil)))))
965 (defun ba/org-adjust-tags-column-now ()
966   "Right-adjust `org-tags-column' value, then reset tag position."
967   (set (make-local-variable 'org-tags-column)
968        (- (- (window-width) (length org-ellipsis))))
969   (ba/org-adjust-tags-column-reset-tags))
971 (defun ba/org-adjust-tags-column-maybe ()
972   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
973   (when ba/org-adjust-tags-column
974     (ba/org-adjust-tags-column-now)))
976 (defun ba/org-adjust-tags-column-before-save ()
977   "Tags need to be left-adjusted when saving."
978   (when ba/org-adjust-tags-column
979      (setq org-tags-column 1)
980      (ba/org-adjust-tags-column-reset-tags)))
982 (defun ba/org-adjust-tags-column-after-save ()
983   "Revert left-adjusted tag position done by before-save hook."
984   (ba/org-adjust-tags-column-maybe)
985   (set-buffer-modified-p nil))
987 ; automatically align tags on right-hand side
988 (add-hook 'window-configuration-change-hook
989           'ba/org-adjust-tags-column-maybe)
990 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
991 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
992 (add-hook 'org-agenda-mode-hook '(lambda ()
993                                   (setq org-agenda-tags-column (- (window-width)))))
995 ; between invoking org-refile and displaying the prompt (which
996 ; triggers window-configuration-change-hook) tags might adjust, 
997 ; which invalidates the org-refile cache
998 (defadvice org-refile (around org-refile-disable-adjust-tags)
999   "Disable dynamically adjusting tags"
1000   (let ((ba/org-adjust-tags-column nil))
1001     ad-do-it))
1002 (ad-activate 'org-refile)
1003 #+end_src
1004 ** Org Agenda and Task Management
1005 *** Make it easier to set org-agenda-files from multiple directories
1006 - Matt Lundin
1008 #+begin_src emacs-lisp
1009 (defun my-org-list-files (dirs ext)
1010   "Function to create list of org files in multiple subdirectories.
1011 This can be called to generate a list of files for
1012 org-agenda-files or org-refile-targets.
1014 DIRS is a list of directories.
1016 EXT is a list of the extensions of files to be included."
1017   (let ((dirs (if (listp dirs)
1018                   dirs
1019                 (list dirs)))
1020         (ext (if (listp ext)
1021                  ext
1022                (list ext)))
1023         files)
1024     (mapc 
1025      (lambda (x)
1026        (mapc 
1027         (lambda (y)
1028           (setq files 
1029                 (append files 
1030                         (file-expand-wildcards 
1031                          (concat (file-name-as-directory x) "*" y)))))
1032         ext))
1033      dirs)
1034     (mapc
1035      (lambda (x)
1036        (when (or (string-match "/.#" x)
1037                  (string-match "#$" x))
1038          (setq files (delete x files))))
1039      files)
1040     files))
1042 (defvar my-org-agenda-directories '("~/org/")
1043   "List of directories containing org files.")
1044 (defvar my-org-agenda-extensions '(".org")
1045   "List of extensions of agenda files")
1047 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1048 (setq my-org-agenda-extensions '(".org" ".ref"))
1050 (defun my-org-set-agenda-files ()
1051   (interactive)
1052   (setq org-agenda-files (my-org-list-files 
1053                           my-org-agenda-directories
1054                           my-org-agenda-extensions)))
1056 (my-org-set-agenda-files)
1057 #+end_src
1059 The code above will set your "default" agenda files to all files
1060 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1061 You can change these values by setting the variables
1062 my-org-agenda-extensions and my-org-agenda-directories. The function
1063 my-org-agenda-files-by-filetag uses these two variables to determine
1064 which files to search for filetags (i.e., the larger set from which
1065 the subset will be drawn).
1067 You can also easily use my-org-list-files to "mix and match"
1068 directories and extensions to generate different lists of agenda
1069 files.
1071 *** Restrict org-agenda-files by filetag
1072   :PROPERTIES:
1073   :CUSTOM_ID: set-agenda-files-by-filetag
1074   :END:
1075 - Matt Lundin
1077 It is often helpful to limit yourself to a subset of your agenda
1078 files. For instance, at work, you might want to see only files related
1079 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1080 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
1081 commands]]. These solutions, however, require reapplying a filter each
1082 time you call the agenda or writing several new custom agenda commands
1083 for each context. Another solution is to use directories for different
1084 types of tasks and to change your agenda files with a function that
1085 sets org-agenda-files to the appropriate directory. But this relies on
1086 hard and static boundaries between files.
1088 The following functions allow for a more dynamic approach to selecting
1089 a subset of files based on filetags:
1091 #+begin_src emacs-lisp
1092 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1093   "Restrict org agenda files only to those containing filetag."
1094   (interactive)
1095   (let* ((tagslist (my-org-get-all-filetags))
1096          (ftag (or tag 
1097                    (completing-read "Tag: " 
1098                                     (mapcar 'car tagslist)))))
1099     (org-agenda-remove-restriction-lock 'noupdate)
1100     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1101     (setq org-agenda-overriding-restriction 'files)))
1103 (defun my-org-get-all-filetags ()
1104   "Get list of filetags from all default org-files."
1105   (let ((files org-agenda-files)
1106         tagslist x)
1107     (save-window-excursion
1108       (while (setq x (pop files))
1109         (set-buffer (find-file-noselect x))
1110         (mapc
1111          (lambda (y)
1112            (let ((tagfiles (assoc y tagslist)))
1113              (if tagfiles
1114                  (setcdr tagfiles (cons x (cdr tagfiles)))
1115                (add-to-list 'tagslist (list y x)))))
1116          (my-org-get-filetags)))
1117       tagslist)))
1119 (defun my-org-get-filetags ()
1120   "Get list of filetags for current buffer"
1121   (let ((ftags org-file-tags)
1122         x)
1123     (mapcar 
1124      (lambda (x)
1125        (org-substring-no-properties x))
1126      ftags)))
1127 #+end_src
1129 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1130 with all filetags in your "normal" agenda files. When you select a
1131 tag, org-agenda-files will be restricted to only those files
1132 containing the filetag. To release the restriction, type C-c C-x >
1133 (org-agenda-remove-restriction-lock).
1135 *** Highlight the agenda line under cursor
1137 This is useful to make sure what task you are operating on.
1139 #+BEGIN_SRC emacs-lisp
1140 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1141 #+END_SRC emacs-lisp
1143 Under XEmacs:
1145 #+BEGIN_SRC emacs-lisp
1146 ;; hl-line seems to be only for emacs
1147 (require 'highline)
1148 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1150 ;; highline-mode does not work straightaway in tty mode.
1151 ;; I use a black background
1152 (custom-set-faces
1153   '(highline-face ((((type tty) (class color))
1154                     (:background "white" :foreground "black")))))
1155 #+END_SRC emacs-lisp
1157 *** Split horizontally for agenda
1159 If you would like to split the frame into two side-by-side windows when
1160 displaying the agenda, try this hack from Jan Rehders, which uses the
1161 `toggle-window-split' from
1163 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1165 #+BEGIN_SRC emacs-lisp
1166 ;; Patch org-mode to use vertical splitting
1167 (defadvice org-prepare-agenda (after org-fix-split)
1168   (toggle-window-split))
1169 (ad-activate 'org-prepare-agenda)
1170 #+END_SRC
1172 *** Automatically add an appointment when clocking in a task
1174 #+BEGIN_SRC emacs-lisp
1175 ;; Make sure you have a sensible value for `appt-message-warning-time'
1176 (defvar bzg-org-clock-in-appt-delay 100
1177   "Number of minutes for setting an appointment by clocking-in")
1178 #+END_SRC
1180 This function let's you add an appointment for the current entry.
1181 This can be useful when you need a reminder.
1183 #+BEGIN_SRC emacs-lisp
1184 (defun bzg-org-clock-in-add-appt (&optional n)
1185   "Add an appointment for the Org entry at point in N minutes."
1186   (interactive)
1187   (save-excursion
1188     (org-back-to-heading t)
1189     (looking-at org-complex-heading-regexp)
1190     (let* ((msg (match-string-no-properties 4))
1191            (ct-time (decode-time))
1192            (appt-min (+ (cadr ct-time)
1193                         (or n bzg-org-clock-in-appt-delay)))
1194            (appt-time ; define the time for the appointment
1195             (progn (setf (cadr ct-time) appt-min) ct-time)))
1196       (appt-add (format-time-string
1197                  "%H:%M" (apply 'encode-time appt-time)) msg)
1198       (if (interactive-p) (message "New appointment for %s" msg)))))
1199 #+END_SRC
1201 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1202 add an appointment:
1204 #+BEGIN_SRC emacs-lisp
1205 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1206   "Add an appointment when clocking a task in."
1207   (bzg-org-clock-in-add-appt))
1208 #+END_SRC
1210 You may also want to delete the associated appointment when clocking
1211 out.  This function does this:
1213 #+BEGIN_SRC emacs-lisp
1214 (defun bzg-org-clock-out-delete-appt nil
1215   "When clocking out, delete any associated appointment."
1216   (interactive)
1217   (save-excursion
1218     (org-back-to-heading t)
1219     (looking-at org-complex-heading-regexp)
1220     (let* ((msg (match-string-no-properties 4)))
1221       (setq appt-time-msg-list
1222             (delete nil
1223                     (mapcar
1224                      (lambda (appt)
1225                        (if (not (string-match (regexp-quote msg)
1226                                               (cadr appt))) appt))
1227                      appt-time-msg-list)))
1228       (appt-check))))
1229 #+END_SRC
1231 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1233 #+BEGIN_SRC emacs-lisp
1234 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1235   "Delete an appointment when clocking a task out."
1236   (bzg-org-clock-out-delete-appt))
1237 #+END_SRC
1239 *IMPORTANT*: You can add appointment by clocking in in both an
1240 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
1241 agenda buffer with the advice above will bring an error.
1243 *** Remove time grid lines that are in an appointment
1245 The agenda shows lines for the time grid.  Some people think that
1246 these lines are a distraction when there are appointments at those
1247 times.  You can get rid of the lines which coincide exactly with the
1248 beginning of an appointment.  Michael Ekstrand has written a piece of
1249 advice that also removes lines that are somewhere inside an
1250 appointment:
1252 #+begin_src emacs-lisp
1253 (defun org-time-to-minutes (time)
1254   "Convert an HHMM time to minutes"
1255   (+ (* (/ time 100) 60) (% time 100)))
1257 (defun org-time-from-minutes (minutes)
1258   "Convert a number of minutes to an HHMM time"
1259   (+ (* (/ minutes 60) 100) (% minutes 60)))
1261 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1262                                                   (list ndays todayp))
1263   (if (member 'remove-match (car org-agenda-time-grid))
1264       (flet ((extract-window
1265               (line)
1266               (let ((start (get-text-property 1 'time-of-day line))
1267                     (dur (get-text-property 1 'duration line)))
1268                 (cond
1269                  ((and start dur)
1270                   (cons start
1271                         (org-time-from-minutes
1272                          (+ dur (org-time-to-minutes start)))))
1273                  (start start)
1274                  (t nil)))))
1275         (let* ((windows (delq nil (mapcar 'extract-window list)))
1276                (org-agenda-time-grid
1277                 (list (car org-agenda-time-grid)
1278                       (cadr org-agenda-time-grid)
1279                       (remove-if
1280                        (lambda (time)
1281                          (find-if (lambda (w)
1282                                     (if (numberp w)
1283                                         (equal w time)
1284                                       (and (>= time (car w))
1285                                            (< time (cdr w)))))
1286                                   windows))
1287                        (caddr org-agenda-time-grid)))))
1288           ad-do-it))
1289     ad-do-it))
1290 (ad-activate 'org-agenda-add-time-grid-maybe)
1291 #+end_src
1292 *** Disable vc for Org mode agenda files
1293 -- David Maus
1295 Even if you use Git to track your agenda files you might not need
1296 vc-mode to be enabled for these files.
1298 #+begin_src emacs-lisp
1299 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1300 (defun dmj/disable-vc-for-agenda-files-hook ()
1301   "Disable vc-mode for Org agenda files."
1302   (if (and (fboundp 'org-agenda-file-p)
1303            (org-agenda-file-p (buffer-file-name)))
1304       (remove-hook 'find-file-hook 'vc-find-file-hook)
1305     (add-hook 'find-file-hook 'vc-find-file-hook)))
1306 #+end_src
1308 *** Easy customization of TODO colors
1309 -- Ryan C. Thompson
1311 Here is some code I came up with some code to make it easier to
1312 customize the colors of various TODO keywords. As long as you just
1313 want a different color and nothing else, you can customize the
1314 variable org-todo-keyword-faces and use just a string color (i.e. a
1315 string of the color name) as the face, and then org-get-todo-face
1316 will convert the color to a face, inheriting everything else from
1317 the standard org-todo face.
1319 To demonstrate, I currently have org-todo-keyword-faces set to
1321 #+BEGIN_SRC emacs-lisp
1322 (("IN PROGRESS" . "dark orange")
1323  ("WAITING" . "red4")
1324  ("CANCELED" . "saddle brown"))
1325 #+END_SRC emacs-lisp
1327   Here's the code, in a form you can put in your =.emacs=
1329 #+BEGIN_SRC emacs-lisp
1330 (eval-after-load 'org-faces
1331  '(progn
1332     (defcustom org-todo-keyword-faces nil
1333       "Faces for specific TODO keywords.
1334 This is a list of cons cells, with TODO keywords in the car and
1335 faces in the cdr.  The face can be a symbol, a color, or a
1336 property list of attributes, like (:foreground \"blue\" :weight
1337 bold :underline t)."
1338       :group 'org-faces
1339       :group 'org-todo
1340       :type '(repeat
1341               (cons
1342                (string :tag "Keyword")
1343                (choice color (sexp :tag "Face")))))))
1345 (eval-after-load 'org
1346  '(progn
1347     (defun org-get-todo-face-from-color (color)
1348       "Returns a specification for a face that inherits from org-todo
1349  face and has the given color as foreground. Returns nil if
1350  color is nil."
1351       (when color
1352         `(:inherit org-warning :foreground ,color)))
1354     (defun org-get-todo-face (kwd)
1355       "Get the right face for a TODO keyword KWD.
1356 If KWD is a number, get the corresponding match group."
1357       (if (numberp kwd) (setq kwd (match-string kwd)))
1358       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1359             (if (stringp face)
1360                 (org-get-todo-face-from-color face)
1361               face))
1362           (and (member kwd org-done-keywords) 'org-done)
1363           'org-todo))))
1364 #+END_SRC emacs-lisp
1366 *** Add an effort estimate on the fly when clocking in
1368 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1369 This way you can easily have a "tea-timer" for your tasks when they
1370 don't already have an effort estimate.
1372 #+begin_src emacs-lisp
1373 (add-hook 'org-clock-in-prepare-hook
1374           'my-org-mode-ask-effort)
1376 (defun my-org-mode-ask-effort ()
1377   "Ask for an effort estimate when clocking in."
1378   (unless (org-entry-get (point) "Effort")
1379     (let ((effort
1380            (completing-read
1381             "Effort: "
1382             (org-entry-get-multivalued-property (point) "Effort"))))
1383       (unless (equal effort "")
1384         (org-set-property "Effort" effort)))))
1385 #+end_src
1387 Or you can use a default effort for such a timer:
1389 #+begin_src emacs-lisp
1390 (add-hook 'org-clock-in-prepare-hook
1391           'my-org-mode-add-default-effort)
1393 (defvar org-clock-default-effort "1:00")
1395 (defun my-org-mode-add-default-effort ()
1396   "Add a default effort estimation."
1397   (unless (org-entry-get (point) "Effort")
1398     (org-set-property "Effort" org-clock-default-effort)))
1399 #+end_src
1401 *** Refresh the agenda view regurally
1403 Hack sent by Kiwon Um:
1405 #+begin_src emacs-lisp
1406 (defun kiwon/org-agenda-redo-in-other-window ()
1407   "Call org-agenda-redo function even in the non-agenda buffer."
1408   (interactive)
1409   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1410     (when agenda-window
1411       (with-selected-window agenda-window (org-agenda-redo)))))
1412 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1413 #+end_src
1415 *** Reschedule agenda items to today with a single command
1417 This was suggested by Carsten in reply to David Abrahams:
1419 #+begin_example emacs-lisp
1420 (defun org-agenda-reschedule-to-today ()
1421   (interactive)
1422   (flet ((org-read-date (&rest rest) (current-time)))
1423     (call-interactively 'org-agenda-schedule)))
1424 #+end_example
1426 * Hacking Org: Working with Org-mode and other Emacs Packages.
1427 ** org-remember-anything
1429 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1431 #+BEGIN_SRC emacs-lisp
1432 (defvar org-remember-anything
1433   '((name . "Org Remember")
1434     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1435     (action . (lambda (name)
1436                 (let* ((orig-template org-remember-templates)
1437                        (org-remember-templates
1438                         (list (assoc name orig-template))))
1439                   (call-interactively 'org-remember))))))
1440 #+END_SRC
1442 You can add it to your 'anything-sources' variable and open remember directly
1443 from anything. I imagine this would be more interesting for people with many
1444 remember templatesm, so that you are out of keys to assign those to. You should
1445 get something like this:
1447 [[file:images/thumbs/org-remember-anything.png]]
1449 ** Org-mode and saveplace.el
1451 Fix a problem with saveplace.el putting you back in a folded position:
1453 #+begin_src emacs-lisp
1454 (add-hook 'org-mode-hook
1455           (lambda ()
1456             (when (outline-invisible-p)
1457               (save-excursion
1458                 (outline-previous-visible-heading 1)
1459                 (org-show-subtree)))))
1460 #+end_src
1462 ** Using ido-completing-read to find attachments
1463 -- Matt Lundin
1465 Org-attach is great for quickly linking files to a project. But if you
1466 use org-attach extensively you might find yourself wanting to browse
1467 all the files you've attached to org headlines. This is not easy to do
1468 manually, since the directories containing the files are not human
1469 readable (i.e., they are based on automatically generated ids). Here's
1470 some code to browse those files using ido (obviously, you need to be
1471 using ido):
1473 #+begin_src emacs-lisp
1474 (load-library "find-lisp")
1476 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1478 (defun my-ido-find-org-attach ()
1479   "Find files in org-attachment directory"
1480   (interactive)
1481   (let* ((enable-recursive-minibuffers t)
1482          (files (find-lisp-find-files org-attach-directory "."))
1483          (file-assoc-list
1484           (mapcar (lambda (x)
1485                     (cons (file-name-nondirectory x)
1486                           x))
1487                   files))
1488          (filename-list
1489           (remove-duplicates (mapcar #'car file-assoc-list)
1490                              :test #'string=))
1491          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1492          (longname (cdr (assoc filename file-assoc-list))))
1493     (ido-set-current-directory
1494      (if (file-directory-p longname)
1495          longname
1496        (file-name-directory longname)))
1497     (setq ido-exit 'refresh
1498           ido-text-init ido-text
1499           ido-rotate-temp t)
1500     (exit-minibuffer)))
1502 (add-hook 'ido-setup-hook 'ido-my-keys)
1504 (defun ido-my-keys ()
1505   "Add my keybindings for ido."
1506   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1507 #+end_src
1509 To browse your org attachments using ido fuzzy matching and/or the
1510 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1511 press =C-;=.
1513 ** Use idle timer for automatic agenda views
1515 From John Wiegley's mailing list post (March 18, 2010):
1517 #+begin_quote
1518 I have the following snippet in my .emacs file, which I find very
1519 useful. Basically what it does is that if I don't touch my Emacs for 5
1520 minutes, it displays the current agenda. This keeps my tasks "always
1521 in mind" whenever I come back to Emacs after doing something else,
1522 whereas before I had a tendency to forget that it was there.
1523 #+end_quote  
1525   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1527 #+begin_src emacs-lisp
1528 (defun jump-to-org-agenda ()
1529   (interactive)
1530   (let ((buf (get-buffer "*Org Agenda*"))
1531         wind)
1532     (if buf
1533         (if (setq wind (get-buffer-window buf))
1534             (select-window wind)
1535           (if (called-interactively-p)
1536               (progn
1537                 (select-window (display-buffer buf t t))
1538                 (org-fit-window-to-buffer)
1539                 ;; (org-agenda-redo)
1540                 )
1541             (with-selected-window (display-buffer buf)
1542               (org-fit-window-to-buffer)
1543               ;; (org-agenda-redo)
1544               )))
1545       (call-interactively 'org-agenda-list)))
1546   ;;(let ((buf (get-buffer "*Calendar*")))
1547   ;;  (unless (get-buffer-window buf)
1548   ;;    (org-agenda-goto-calendar)))
1549   )
1550   
1551 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1552 #+end_src
1554 #+results:
1555 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1557 ** Link to Gnus messages by Message-Id
1559 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1560 discussion about linking to Gnus messages without encoding the folder
1561 name in the link.  The following code hooks in to the store-link
1562 function in Gnus to capture links by Message-Id when in nnml folders,
1563 and then provides a link type "mid" which can open this link.  The
1564 =mde-org-gnus-open-message-link= function uses the
1565 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1566 scan.  It will go through them, in order, asking each to locate the
1567 message and opening it from the first one that reports success.
1569 It has only been tested with a single nnml backend, so there may be
1570 bugs lurking here and there.
1572 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1573 article]].
1575 #+begin_src emacs-lisp
1576 ;; Support for saving Gnus messages by Message-ID
1577 (defun mde-org-gnus-save-by-mid ()
1578   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1579     (when (eq major-mode 'gnus-article-mode)
1580       (gnus-article-show-summary))
1581     (let* ((group gnus-newsgroup-name)
1582            (method (gnus-find-method-for-group group)))
1583       (when (eq 'nnml (car method))
1584         (let* ((article (gnus-summary-article-number))
1585                (header (gnus-summary-article-header article))
1586                (from (mail-header-from header))
1587                (message-id
1588                 (save-match-data
1589                   (let ((mid (mail-header-id header)))
1590                     (if (string-match "<\\(.*\\)>" mid)
1591                         (match-string 1 mid)
1592                       (error "Malformed message ID header %s" mid)))))
1593                (date (mail-header-date header))
1594                (subject (gnus-summary-subject-string)))
1595           (org-store-link-props :type "mid" :from from :subject subject
1596                                 :message-id message-id :group group
1597                                 :link (org-make-link "mid:" message-id))
1598           (apply 'org-store-link-props
1599                  :description (org-email-link-description)
1600                  org-store-link-plist)
1601           t)))))
1603 (defvar mde-mid-resolve-methods '()
1604   "List of methods to try when resolving message ID's.  For Gnus,
1605 it is a cons of 'gnus and the select (type and name).")
1606 (setq mde-mid-resolve-methods
1607       '((gnus nnml "")))
1609 (defvar mde-org-gnus-open-level 1
1610   "Level at which Gnus is started when opening a link")
1611 (defun mde-org-gnus-open-message-link (msgid)
1612   "Open a message link with Gnus"
1613   (require 'gnus)
1614   (require 'org-table)
1615   (catch 'method-found
1616     (message "[MID linker] Resolving %s" msgid)
1617     (dolist (method mde-mid-resolve-methods)
1618       (cond
1619        ((and (eq (car method) 'gnus)
1620              (eq (cadr method) 'nnml))
1621         (funcall (cdr (assq 'gnus org-link-frame-setup))
1622                  mde-org-gnus-open-level)
1623         (when gnus-other-frame-object
1624           (select-frame gnus-other-frame-object))
1625         (let* ((msg-info (nnml-find-group-number
1626                           (concat "<" msgid ">")
1627                           (cdr method)))
1628                (group (and msg-info (car msg-info)))
1629                (message (and msg-info (cdr msg-info)))
1630                (qname (and group
1631                            (if (gnus-methods-equal-p
1632                                 (cdr method)
1633                                 gnus-select-method)
1634                                group
1635                              (gnus-group-full-name group (cdr method))))))
1636           (when msg-info
1637             (gnus-summary-read-group qname nil t)
1638             (gnus-summary-goto-article message nil t))
1639           (throw 'method-found t)))
1640        (t (error "Unknown link type"))))))
1642 (eval-after-load 'org-gnus
1643   '(progn
1644      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1645      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1646 #+end_src
1648 ** Store link upon sending a message in Gnus
1650 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1652 #+begin_src emacs-lisp
1653 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1654   "Send message with `message-send-and-exit' and store org link to message copy.
1655 If multiple groups appear in the Gcc header, the link refers to
1656 the copy in the last group."
1657   (interactive "P")
1658     (save-excursion
1659       (save-restriction
1660         (message-narrow-to-headers)
1661         (let ((gcc (car (last
1662                          (message-unquote-tokens
1663                           (message-tokenize-header
1664                            (mail-fetch-field "gcc" nil t) " ,")))))
1665               (buf (current-buffer))
1666               (message-kill-buffer-on-exit nil)
1667               id to from subject desc link newsgroup xarchive)
1668         (message-send-and-exit arg)
1669         (or
1670          ;; gcc group found ...
1671          (and gcc
1672               (save-current-buffer
1673                 (progn (set-buffer buf)
1674                        (setq id (org-remove-angle-brackets
1675                                  (mail-fetch-field "Message-ID")))
1676                        (setq to (mail-fetch-field "To"))
1677                        (setq from (mail-fetch-field "From"))
1678                        (setq subject (mail-fetch-field "Subject"))))
1679               (org-store-link-props :type "gnus" :from from :subject subject
1680                                     :message-id id :group gcc :to to)
1681               (setq desc (org-email-link-description))
1682               (setq link (org-gnus-article-link
1683                           gcc newsgroup id xarchive))
1684               (setq org-stored-links
1685                     (cons (list link desc) org-stored-links)))
1686          ;; no gcc group found ...
1687          (message "Can not create Org link: No Gcc header found."))))))
1689 (define-key message-mode-map [(control c) (control meta c)]
1690   'ulf-message-send-and-org-gnus-store-link)
1691 #+end_src
1693 ** Send html messages and attachments with Wanderlust
1694   -- David Maus
1696 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1697 similar functionality for both Wanderlust and Gnus.  The hack below is
1698 still somewhat different: It allows you to toggle sending of html
1699 messages within Wanderlust transparently.  I.e. html markup of the
1700 message body is created right before sending starts.
1702 *** Send HTML message
1704 Putting the code below in your .emacs adds following four functions:
1706 - dmj/wl-send-html-message
1708   Function that does the job: Convert everything between "--text
1709   follows this line--" and first mime entity (read: attachment) or
1710   end of buffer into html markup using `org-export-region-as-html'
1711   and replaces original body with a multipart MIME entity with the
1712   plain text version of body and the html markup version.  Thus a
1713   recipient that prefers html messages can see the html markup,
1714   recipients that prefer or depend on plain text can see the plain
1715   text.
1717   Cannot be called interactively: It is hooked into SEMI's
1718   `mime-edit-translate-hook' if message should be HTML message.
1720 - dmj/wl-send-html-message-draft-init
1722   Cannot be called interactively: It is hooked into WL's
1723   `wl-mail-setup-hook' and provides a buffer local variable to
1724   toggle.
1726 - dmj/wl-send-html-message-draft-maybe
1728   Cannot be called interactively: It is hooked into WL's
1729   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1730   `mime-edit-translate-hook' depending on whether HTML message is
1731   toggled on or off
1733 - dmj/wl-send-html-message-toggle
1735   Toggles sending of HTML message.  If toggled on, the letters
1736   "HTML" appear in the mode line.
1738   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1740 If you have to send HTML messages regularly you can set a global
1741 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1742 toggle on sending HTML message by default.
1744 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1745 Google's web front end.  As you can see you have the whole markup of
1746 Org at your service: *bold*, /italics/, tables, lists...
1748 So even if you feel uncomfortable with sending HTML messages at least
1749 you send HTML that looks quite good.
1751 #+begin_src emacs-lisp
1752 (defun dmj/wl-send-html-message ()
1753   "Send message as html message.
1754 Convert body of message to html using
1755   `org-export-region-as-html'."
1756   (require 'org)
1757   (save-excursion
1758     (let (beg end html text)
1759       (goto-char (point-min))
1760       (re-search-forward "^--text follows this line--$")
1761       ;; move to beginning of next line
1762       (beginning-of-line 2)
1763       (setq beg (point))
1764       (if (not (re-search-forward "^--\\[\\[" nil t))
1765           (setq end (point-max))
1766         ;; line up
1767         (end-of-line 0)
1768         (setq end (point)))
1769       ;; grab body
1770       (setq text (buffer-substring-no-properties beg end))
1771       ;; convert to html
1772       (with-temp-buffer
1773         (org-mode)
1774         (insert text)
1775         ;; handle signature
1776         (when (re-search-backward "^-- \n" nil t)
1777           ;; preserve link breaks in signature
1778           (insert "\n#+BEGIN_VERSE\n")
1779           (goto-char (point-max))
1780           (insert "\n#+END_VERSE\n")
1781           ;; grab html
1782           (setq html (org-export-region-as-html
1783                       (point-min) (point-max) t 'string))))
1784       (delete-region beg end)
1785       (insert
1786        (concat
1787         "--" "<<alternative>>-{\n"
1788         "--" "[[text/plain]]\n" text
1789         "--" "[[text/html]]\n"  html
1790         "--" "}-<<alternative>>\n")))))
1792 (defun dmj/wl-send-html-message-toggle ()
1793   "Toggle sending of html message."
1794   (interactive)
1795   (setq dmj/wl-send-html-message-toggled-p
1796         (if dmj/wl-send-html-message-toggled-p
1797             nil "HTML"))
1798   (message "Sending html message toggled %s"
1799            (if dmj/wl-send-html-message-toggled-p
1800                "on" "off")))
1802 (defun dmj/wl-send-html-message-draft-init ()
1803   "Create buffer local settings for maybe sending html message."
1804   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1805     (setq dmj/wl-send-html-message-toggled-p nil))
1806   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1807   (add-to-list 'global-mode-string
1808                '(:eval (if (eq major-mode 'wl-draft-mode)
1809                            dmj/wl-send-html-message-toggled-p))))
1811 (defun dmj/wl-send-html-message-maybe ()
1812   "Maybe send this message as html message.
1814 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1815 non-nil, add `dmj/wl-send-html-message' to
1816 `mime-edit-translate-hook'."
1817   (if dmj/wl-send-html-message-toggled-p
1818       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1819     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1821 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1822 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1823 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1824 #+end_src
1826 *** Attach HTML of region or subtree
1828 Instead of sending a complete HTML message you might only send parts
1829 of an Org file as HTML for the poor souls who are plagued with
1830 non-proportional fonts in their mail program that messes up pretty
1831 ASCII tables.
1833 This short function does the trick: It exports region or subtree to
1834 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1835 and clipboard.  If a region is active, it uses the region, the
1836 complete subtree otherwise.
1838 #+begin_src emacs-lisp
1839 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1840   "Export region between BEG and END as html attachment.
1841 If BEG and END are not set, use current subtree.  Region or
1842 subtree is exported to html without header and footer, prefixed
1843 with a mime entity string and pushed to clipboard and killring.
1844 When called with prefix, mime entity is not marked as
1845 attachment."
1846   (interactive "r\nP")
1847   (save-excursion
1848     (let* ((beg (if (region-active-p) (region-beginning)
1849                   (progn
1850                     (org-back-to-heading)
1851                     (point))))
1852            (end (if (region-active-p) (region-end)
1853                   (progn
1854                     (org-end-of-subtree)
1855                     (point))))
1856            (html (concat "--[[text/html"
1857                          (if arg "" "\nContent-Disposition: attachment")
1858                          "]]\n"
1859                          (org-export-region-as-html beg end t 'string))))
1860       (when (fboundp 'x-set-selection)
1861         (ignore-errors (x-set-selection 'PRIMARY html))
1862         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1863       (message "html export done, pushed to kill ring and clipboard"))))
1864 #+end_src
1866 *** Adopting for Gnus
1868 The whole magic lies in the special strings that mark a HTML
1869 attachment.  So you might just have to find out what these special
1870 strings are in message-mode and modify the functions accordingly.
1871 ** Add sunrise/sunset times to the agenda.
1872   -- Nick Dokos
1874 The diary package provides the function =diary-sunrise-sunset= which can be used
1875 in a diary s-expression in some agenda file like this:
1877 #+begin_src org-mode
1878 %%(diary-sunrise-sunset)
1879 #+end_src
1881 Seb Vauban asked if it is possible to put sunrise and sunset in
1882 separate lines. Here is a hack to do that. It adds two functions (they
1883 have to be available before the agenda is shown, so I add them early
1884 in my org-config file which is sourced from .emacs, but you'll have to
1885 suit yourself here) that just parse the output of
1886 diary-sunrise-sunset, instead of doing the right thing which would be
1887 to take advantage of the data structures that diary/solar.el provides.
1888 In short, a hack - so perfectly suited for inclusion here :-)
1890 The functions (and latitude/longitude settings which you have to modify for
1891 your location) are as follows:
1893 #+begin_src emacs-lisp
1894 (setq calendar-latitude 40.3)
1895 (setq calendar-longitude -71.0)
1896 (defun diary-sunrise ()
1897   (let ((dss (diary-sunrise-sunset)))
1898     (with-temp-buffer
1899       (insert dss)
1900       (goto-char (point-min))
1901       (while (re-search-forward " ([^)]*)" nil t)
1902         (replace-match "" nil nil))
1903       (goto-char (point-min))
1904       (search-forward ",")
1905       (buffer-substring (point-min) (match-beginning 0)))))
1907 (defun diary-sunset ()
1908   (let ((dss (diary-sunrise-sunset))
1909         start end)
1910     (with-temp-buffer
1911       (insert dss)
1912       (goto-char (point-min))
1913       (while (re-search-forward " ([^)]*)" nil t)
1914         (replace-match "" nil nil))
1915       (goto-char (point-min))
1916       (search-forward ", ")
1917       (setq start (match-end 0))
1918       (search-forward " at")
1919       (setq end (match-beginning 0))
1920       (goto-char start)
1921       (capitalize-word 1)
1922       (buffer-substring start end))))
1923 #+end_src
1925 You also need to add a couple of diary s-expressions in one of your agenda
1926 files:
1928 #+begin_src org-mode
1929 %%(diary-sunrise)
1930 %%(diary-sunset)
1931 #+end_src
1933 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]].
1934 In comparison to the version posted on the mailing list, this one
1935 gets rid of the timezone information.
1936 * Hacking Org: Working with Org-mode and External Programs.
1937 ** Use Org-mode with Screen [Andrew Hyatt]
1939 "The general idea is that you start a task in which all the work will
1940 take place in a shell.  This usually is not a leaf-task for me, but
1941 usually the parent of a leaf task.  From a task in your org-file, M-x
1942 ash-org-screen will prompt for the name of a session.  Give it a name,
1943 and it will insert a link.  Open the link at any time to go the screen
1944 session containing your work!"
1946 http://article.gmane.org/gmane.emacs.orgmode/5276
1948 #+BEGIN_SRC emacs-lisp
1949 (require 'term)
1951 (defun ash-org-goto-screen (name)
1952   "Open the screen with the specified name in the window"
1953   (interactive "MScreen name: ")
1954   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1955     (if (member screen-buffer-name
1956                 (mapcar 'buffer-name (buffer-list)))
1957         (switch-to-buffer screen-buffer-name)
1958       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1960 (defun ash-org-screen-buffer-name (name)
1961   "Returns the buffer name corresponding to the screen name given."
1962   (concat "*screen " name "*"))
1964 (defun ash-org-screen-helper (name arg)
1965   ;; Pick the name of the new buffer.
1966   (let ((term-ansi-buffer-name
1967          (generate-new-buffer-name
1968           (ash-org-screen-buffer-name name))))
1969     (setq term-ansi-buffer-name
1970           (term-ansi-make-term
1971            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1972     (set-buffer term-ansi-buffer-name)
1973     (term-mode)
1974     (term-char-mode)
1975     (term-set-escape-char ?\C-x)
1976     term-ansi-buffer-name))
1978 (defun ash-org-screen (name)
1979   "Start a screen session with name"
1980   (interactive "MScreen name: ")
1981   (save-excursion
1982     (ash-org-screen-helper name "-S"))
1983   (insert-string (concat "[[screen:" name "]]")))
1985 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1986 ;; \"%s\")") to org-link-abbrev-alist.
1987 #+END_SRC
1989 ** Org Agenda + Appt + Zenity
1990 #+BEGIN_HTML
1991 <a name="agenda-appt-zenity"></a>
1992 #+END_HTML
1993 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It makes sure your agenda
1994 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1995 popup window.
1997 #+BEGIN_SRC emacs-lisp
1998 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1999 ; For org appointment reminders
2001 ;; Get appointments for today
2002 (defun my-org-agenda-to-appt ()
2003   (interactive)
2004   (setq appt-time-msg-list nil)
2005   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
2006         (org-agenda-to-appt)))
2008 ;; Run once, activate and schedule refresh
2009 (my-org-agenda-to-appt)
2010 (appt-activate t)
2011 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
2013 ; 5 minute warnings
2014 (setq appt-message-warning-time 15)
2015 (setq appt-display-interval 5)
2017 ; Update appt each time agenda opened.
2018 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
2020 ; Setup zenify, we tell appt to use window, and replace default function
2021 (setq appt-display-format 'window)
2022 (setq appt-disp-window-function (function my-appt-disp-window))
2024 (defun my-appt-disp-window (min-to-app new-time msg)
2025   (save-window-excursion (shell-command (concat
2026     "/usr/bin/zenity --info --title='Appointment' --text='"
2027     msg "' &") nil nil)))
2028 #+END_SRC
2030 ** Org-Mode + gnome-osd
2032 Richard Riley uses gnome-osd in interaction with Org-Mode to display
2033 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
2035 ** remind2org
2037 From Detlef Steuer
2039 http://article.gmane.org/gmane.emacs.orgmode/5073
2041 #+BEGIN_QUOTE
2042 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
2043 command line calendaring program. Its features superseed the possibilities
2044 of orgmode in the area of date specifying, so that I want to use it
2045 combined with orgmode.
2047 Using the script below I'm able use remind and incorporate its output in my
2048 agenda views.  The default of using 13 months look ahead is easily
2049 changed. It just happens I sometimes like to look a year into the
2050 future. :-)
2051 #+END_QUOTE
2053 ** Useful webjumps for conkeror
2055 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
2056 your =~/.conkerorrc= file:
2058 #+begin_example
2059 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
2060 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
2061 #+end_example
2063 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
2064 Org-mode mailing list.
2066 ** Use MathJax for HTML export without requiring JavaScript
2067 As of 2010-08-14, MathJax is the default method used to export math to HTML.
2069 If you like the results but do not want JavaScript in the exported pages,
2070 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
2071 HTML file from the exported version. It can also embed all referenced fonts
2072 within the HTML file itself, so there are no dependencies to external files.
2074 The download archive contains an elisp file which integrates it into the Org
2075 export process (configurable per file with a "#+StaticMathJax:" line).
2077 Read README.org and the comments in org-static-mathjax.el for usage instructions.
2078 ** Search Org files using lgrep
2080 Matt Lundin suggests this:
2082 #+begin_src emacs-lisp
2083   (defun my-org-grep (search &optional context)
2084     "Search for word in org files. 
2086 Prefix argument determines number of lines."
2087     (interactive "sSearch for: \nP")
2088     (let ((grep-find-ignored-files '("#*" ".#*"))
2089           (grep-template (concat "grep <X> -i -nH " 
2090                                  (when context
2091                                    (concat "-C" (number-to-string context)))
2092                                  " -e <R> <F>")))
2093       (lgrep search "*org*" "/home/matt/org/")))
2095   (global-set-key (kbd "<f8>") 'my-org-grep)
2096 #+end_src
2098 ** Automatic screenshot insertion
2100 Suggested by Jonathan Bisson:
2102 #+begin_src emacs-lisp
2103   (defun my-screenshot ()
2104   "Take a screenshot into a unique-named file in the current buffer file
2105   directory and insert a link to this file."
2106     (interactive)
2107     (setq filename
2108           (concat
2109            (make-temp-name
2110             (file-name-directory (buffer-file-name))) ".jpg"))
2111     (call-process "import" nil nil nil filename)
2112     (insert (concat "[[" filename "]]"))
2113     (org-display-inline-images))
2114 #+end_src
2116 ** Capture invitations/appointments from MS Exchange emails
2118 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this.  Please check
2119 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]