Fix link to git website.
[Worg.git] / org-hacks.org
blob33a811cabd6f9a8a9557adf411c861640588bfc3
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 ** Enhancing the Org experience.
99 *** Speed Commands
100 Speed commands are described [[http://orgmode.org/manual/Speed-keys.html#Speed-keys][here]] in the manual. Add your own speed
101 commands here.
102 *** Show next/prev heading tidily
103 - Dan Davison
104   These close the current heading and open the next/previous heading.
106 #+begin_src emacs-lisp
107 (defun ded/org-show-next-heading-tidily ()
108   "Show next entry, keeping other entries closed."
109   (if (save-excursion (end-of-line) (outline-invisible-p))
110       (progn (org-show-entry) (show-children))
111     (outline-next-heading)
112     (unless (and (bolp) (org-on-heading-p))
113       (org-up-heading-safe)
114       (hide-subtree)
115       (error "Boundary reached"))
116     (org-overview)
117     (org-reveal t)
118     (org-show-entry)
119     (show-children)))
121 (defun ded/org-show-previous-heading-tidily ()
122   "Show previous entry, keeping other entries closed."
123   (let ((pos (point)))
124     (outline-previous-heading)
125     (unless (and (< (point) pos) (bolp) (org-on-heading-p))
126       (goto-char pos)
127       (hide-subtree)
128       (error "Boundary reached"))
129     (org-overview)
130     (org-reveal t)
131     (org-show-entry)
132     (show-children)))
134 (setq org-use-speed-commands t)
135 (add-to-list 'org-speed-commands-user
136              '("n" ded/org-show-next-heading-tidily))
137 (add-to-list 'org-speed-commands-user 
138              '("p" ded/org-show-previous-heading-tidily))
139 #+end_src
141 *** Changelog support for org headers
142 -- James TD Smith
144 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
145 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
146 headline as the "current function" if you add a changelog entry from an org
147 buffer.
149 #+BEGIN_SRC emacs-lisp
150   (defun org-log-current-defun ()
151     (save-excursion
152       (org-back-to-heading)
153       (if (looking-at org-complex-heading-regexp)
154           (match-string 4))))
155   
156   (add-hook 'org-mode-hook
157             (lambda ()
158               (make-variable-buffer-local 'add-log-current-defun-function)
159               (setq add-log-current-defun-function 'org-log-current-defun)))
160 #+END_SRC
162 *** Different org-cycle-level behavior
163 -- Ryan Thompson
165 In recent org versions, when your point (cursor) is at the end of an
166 empty header line (like after you first created the header), the TAB
167 key (=org-cycle=) has a special behavior: it cycles the headline through
168 all possible levels. However, I did not like the way it determined
169 "all possible levels," so I rewrote the whole function, along with a
170 couple of supporting functions.
172 The original function's definition of "all possible levels" was "every
173 level from 1 to one more than the initial level of the current
174 headline before you started cycling." My new definition is "every
175 level from 1 to one more than the previous headline's level." So, if
176 you have a headline at level 4 and you use ALT+RET to make a new
177 headline below it, it will cycle between levels 1 and 5, inclusive.
179 The main advantage of my custom =org-cycle-level= function is that it
180 is stateless: the next level in the cycle is determined entirely by
181 the contents of the buffer, and not what command you executed last.
182 This makes it more predictable, I hope.
184 #+BEGIN_SRC emacs-lisp
185 (require 'cl)
187 (defun org-point-at-end-of-empty-headline ()
188   "If point is at the end of an empty headline, return t, else nil."
189   (and (looking-at "[ \t]*$")
190        (save-excursion
191          (beginning-of-line 1)
192          (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
194 (defun org-level-increment ()
195   "Return the number of stars that will be added or removed at a
196 time to headlines when structure editing, based on the value of
197 `org-odd-levels-only'."
198   (if org-odd-levels-only 2 1))
200 (defvar org-previous-line-level-cached nil)
202 (defun org-recalculate-previous-line-level ()
203   "Same as `org-get-previous-line-level', but does not use cached
204 value. It does *set* the cached value, though."
205   (set 'org-previous-line-level-cached
206        (let ((current-level (org-current-level))
207              (prev-level (when (> (line-number-at-pos) 1)
208                            (save-excursion
209                              (previous-line)
210                              (org-current-level)))))
211          (cond ((null current-level) nil) ; Before first headline
212                ((null prev-level) 0)      ; At first headline
213                (prev-level)))))
215 (defun org-get-previous-line-level ()
216   "Return the outline depth of the last headline before the
217 current line. Returns 0 for the first headline in the buffer, and
218 nil if before the first headline."
219   ;; This calculation is quite expensive, with all the regex searching
220   ;; and stuff. Since org-cycle-level won't change lines, we can reuse
221   ;; the last value of this command.
222   (or (and (eq last-command 'org-cycle-level)
223            org-previous-line-level-cached)
224       (org-recalculate-previous-line-level)))
226 (defun org-cycle-level ()
227   (interactive)
228   (let ((org-adapt-indentation nil))
229     (when (org-point-at-end-of-empty-headline)
230       (setq this-command 'org-cycle-level) ;Only needed for caching
231       (let ((cur-level (org-current-level))
232             (prev-level (org-get-previous-line-level)))
233         (cond
234          ;; If first headline in file, promote to top-level.
235          ((= prev-level 0)
236           (loop repeat (/ (- cur-level 1) (org-level-increment))
237                 do (org-do-promote)))
238          ;; If same level as prev, demote one.
239          ((= prev-level cur-level)
240           (org-do-demote))
241          ;; If parent is top-level, promote to top level if not already.
242          ((= prev-level 1)
243           (loop repeat (/ (- cur-level 1) (org-level-increment))
244                 do (org-do-promote)))
245          ;; If top-level, return to prev-level.
246          ((= cur-level 1)
247           (loop repeat (/ (- prev-level 1) (org-level-increment))
248                 do (org-do-demote)))
249          ;; If less than prev-level, promote one.
250          ((< cur-level prev-level)
251           (org-do-promote))
252          ;; If deeper than prev-level, promote until higher than
253          ;; prev-level.
254          ((> cur-level prev-level)
255           (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
256                 do (org-do-promote))))
257         t))))
258 #+END_SRC
259 *** Org table
260 *** Dates computation
262 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
264 I have a table in org which stores the date, I'm wondering if there is
265 any function to calculate the duration? For example:
267 | Start Date |   End Date | Duration |
268 |------------+------------+----------|
269 | 2004.08.07 | 2005.07.08 |          |
271 I tried to use B&-C&, but failed ...
273 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
275 Try the following:
277 | Start Date |   End Date | Duration |
278 |------------+------------+----------|
279 | 2004.08.07 | 2005.07.08 |      335 |
280 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
282 See this thread:
284     http://thread.gmane.org/gmane.emacs.orgmode/7741
286 as well as this post (which is really a followup on the
287 above):
289     http://article.gmane.org/gmane.emacs.orgmode/7753
291 The problem that this last article pointed out was solved
294     http://article.gmane.org/gmane.emacs.orgmode/8001
296 and Chris Randle's original musings are at
298     http://article.gmane.org/gmane.emacs.orgmode/6536/
300 *** Field coordinates in formulas (=@#= and =$#=)
302 -- Michael Brand
304 Following are some use cases that can be implemented with the
305 _field coordinates in formulas_ described in the corresponding
306 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
308 **** Copy a column from a remote table into a column
310 current column =$3= = remote column =$2=:
311 : #+TBLFM: $3 = remote(FOO, @@#$2)
313 **** Copy a row from a remote table transposed into a column
315 current column =$1= = transposed remote row =@1=:
316 : #+TBLFM: $1 = remote(FOO, @$#$@#)
318 **** Transpose a table
320 -- Michael Brand
322 This is more like a demonstration of using _field coordinates in formulas_
323 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel.  The efficient
324 and simple solution for this with the help of org-babel and Emacs Lisp has
325 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
327 To transpose this 4x7 table
329 : #+TBLNAME: FOO
330 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
331 : |------+------+------+------+------+------+------|
332 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
333 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
334 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
336 start with a 7x4 table without any horizontal line (to have filled
337 also the column header) and yet empty:
339 : |   |   |   |   |
340 : |   |   |   |   |
341 : |   |   |   |   |
342 : |   |   |   |   |
343 : |   |   |   |   |
344 : |   |   |   |   |
345 : |   |   |   |   |
347 Then add the =TBLFM= below with the same formula repeated for each column.
348 After recalculation this will end up with the transposed copy:
350 : | year | min | avg | max |
351 : | 2004 | 401 | 402 | 403 |
352 : | 2005 | 501 | 502 | 503 |
353 : | 2006 | 601 | 602 | 603 |
354 : | 2007 | 701 | 702 | 703 |
355 : | 2008 | 801 | 802 | 803 |
356 : | 2009 | 901 | 902 | 903 |
357 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
359 The formulas simply exchange row and column numbers by taking
360 - the absolute remote row number =@$#= from the current column number =$#=
361 - the absolute remote column number =$@#= from the current row number =@#=
363 Possible field formulas from the remote table will have to be transferred
364 manually.  Since there are no row formulas yet there is no need to transfer
365 column formulas to row formulas or vice versa.
367 **** Dynamic variation of ranges
369 -- Michael Brand
371 In this example all columns next to =quote= are calculated from the column
372 =quote= and show the average change of the time series =quote[year]=
373 during the period of the preceding =1=, =2=, =3= or =4= years:
375 : | year | quote |   1 a |   2 a |   3 a |   4 a |
376 : |------+-------+-------+-------+-------+-------|
377 : | 2005 |    10 |       |       |       |       |
378 : | 2006 |    12 | 0.200 |       |       |       |
379 : | 2007 |    14 | 0.167 | 0.183 |       |       |
380 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
381 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
382 : #+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
384 The formula is the same for each column =$3= through =$6=.  This can easily
385 be seen with the great formula editor invoked by C-c ' on the
386 table. The important part of the formula without the field blanking is:
388 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
390 which is the Emacs Calc implementation of the equation
392 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
394 where /i/ is the current time and /a/ is the length of the preceding period.
396 *** Customize the size of the frame for remember
397 (Note: this hack is likely out of date due to the development of
398 [[org-capture]].) 
400 #FIXME: gmane link?
401 On emacs-orgmode, Ryan C. Thompson suggested this:
403 #+begin_quote
404 I am using org-remember set to open a new frame when used,
405 and the default frame size is much too large. To fix this, I have
406 designed some advice and a custom variable to implement custom
407 parameters for the remember frame:
408 #+end_quote
410 #+begin_src emacs-lisp
411 (defcustom remember-frame-alist nil
412   "Additional frame parameters for dedicated remember frame."
413   :type 'alist
414   :group 'remember)
416 (defadvice remember (around remember-frame-parameters activate)
417   "Set some frame parameters for the remember frame."
418   (let ((default-frame-alist (append remember-frame-alist
419                                      default-frame-alist)))
420     ad-do-it))
421 #+end_src
423 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
424 reasonable size for the frame.
425 *** Promote all items in subtree
426 - Matt Lundin
428 This function will promote all items in a subtree. Since I use
429 subtrees primarily to organize projects, the function is somewhat
430 unimaginatively called my-org-un-project:
432 #+begin_src emacs-lisp
433 (defun my-org-un-project ()
434   (interactive)
435   (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
436   (org-cycle t))
437 #+end_src
439 ** Archiving Content in Org-Mode
440 *** Preserve top level headings when archiving to a file
441 - Matt Lundin
443 To preserve (somewhat) the integrity of your archive structure while
444 archiving lower level items to a file, you can use the following
445 defadvice:
447 #+begin_src emacs-lisp
448 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
449   (let ((org-archive-location 
450          (if (save-excursion (org-back-to-heading)
451                              (> (org-outline-level) 1))
452              (concat (car (split-string org-archive-location "::"))
453                      "::* "
454                      (car (org-get-outline-path)))
455            org-archive-location)))
456     ad-do-it))
457 #+end_src
459 Thus, if you have an outline structure such as...
461 #+begin_src org
462 ,* Heading
463 ,** Subheading
464 ,*** Subsubheading
465 #+end_src
467 ...archiving "Subsubheading" to a new file will set the location in
468 the new file to the top level heading:
470 #+begin_src org
471 ,* Heading
472 ,** Subsubheading
473 #+end_src
475 While this hack obviously destroys the outline hierarchy somewhat, it
476 at least preserves the logic of level one groupings.
478 *** Archive in a date tree
480 Posted to Org-mode mailing list by Osamu Okano
481 [2010-04-21 Wed]
483 #+begin_src emacs-lisp
484 ;; (setq org-archive-location "%s_archive::date-tree")
485 (defadvice org-archive-subtree
486   (around org-archive-subtree-to-data-tree activate)
487   "org-archive-subtree to date-tree"
488   (if
489       (string= "date-tree"
490                (org-extract-archive-heading
491                 (org-get-local-archive-location)))
492       (let* ((dct (decode-time (org-current-time)))
493              (y (nth 5 dct))
494              (m (nth 4 dct))
495              (d (nth 3 dct))
496              (this-buffer (current-buffer))
497              (location (org-get-local-archive-location))
498              (afile (org-extract-archive-file location))
499              (org-archive-location
500               (format "%s::*** %04d-%02d-%02d %s" afile y m d
501                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
502         (message "afile=%s" afile)
503         (unless afile
504           (error "Invalid `org-archive-location'"))
505         (save-excursion
506           (switch-to-buffer (find-file-noselect afile))
507           (org-datetree-find-year-create y)
508           (org-datetree-find-month-create y m)
509           (org-datetree-find-day-create y m d)
510           (widen)
511           (switch-to-buffer this-buffer))
512         ad-do-it)
513     ad-do-it))
514 #+end_src
516 ** Using and Managing Org-Metadata
517 *** Remove redundant tags of headlines
518 -- David Maus
520 A small function that processes all headlines in current buffer and
521 removes tags that are local to a headline and inherited by a parent
522 headline or the #+FILETAGS: statement.
524 #+BEGIN_SRC emacs-lisp
525   (defun dmj/org-remove-redundant-tags ()
526     "Remove redundant tags of headlines in current buffer.
528   A tag is considered redundant if it is local to a headline and
529   inherited by a parent headline."
530     (interactive)
531     (when (eq major-mode 'org-mode)
532       (save-excursion
533         (org-map-entries
534          '(lambda ()
535             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
536                   local inherited tag)
537               (dolist (tag alltags)
538                 (if (get-text-property 0 'inherited tag)
539                     (push tag inherited) (push tag local)))
540               (dolist (tag local)
541                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
542          t nil))))
543 #+END_SRC
545 *** Remove empty property drawers
547 David Maus proposed this:
549 #+begin_src emacs-lisp
550 (defun dmj:org:remove-empty-propert-drawers ()
551   "*Remove all empty property drawers in current file."
552   (interactive)
553   (unless (eq major-mode 'org-mode)
554     (error "You need to turn on Org mode for this function."))
555   (save-excursion
556     (goto-char (point-min))
557     (while (re-search-forward ":PROPERTIES:" nil t)
558       (save-excursion
559         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
560 #+end_src
562 *** Group task list by a property
564 This advice allows you to group a task list in Org-Mode.  To use it,
565 set the variable =org-agenda-group-by-property= to the name of a
566 property in the option list for a TODO or TAGS search.  The resulting
567 agenda view will group tasks by that property prior to searching.
569 #+begin_src emacs-lisp
570 (defvar org-agenda-group-by-property nil
571   "Set this in org-mode agenda views to group tasks by property")
573 (defun org-group-bucket-items (prop items)
574   (let ((buckets ()))
575     (dolist (item items)
576       (let* ((marker (get-text-property 0 'org-marker item))
577              (pvalue (org-entry-get marker prop t))
578              (cell (assoc pvalue buckets)))
579         (if cell
580             (setcdr cell (cons item (cdr cell)))
581           (setq buckets (cons (cons pvalue (list item))
582                               buckets)))))
583     (setq buckets (mapcar (lambda (bucket)
584                             (cons (car bucket)
585                                   (reverse (cdr bucket))))
586                           buckets))
587     (sort buckets (lambda (i1 i2)
588                     (string< (car i1) (car i2))))))
590 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
591                                                (list &optional nosort))
592   "Prepare bucketed agenda entry lists"
593   (if org-agenda-group-by-property
594       ;; bucketed, handle appropriately
595       (let ((text ""))
596         (dolist (bucket (org-group-bucket-items
597                          org-agenda-group-by-property
598                          list))
599           (let ((header (concat "Property "
600                                 org-agenda-group-by-property
601                                 " is "
602                                 (or (car bucket) "<nil>") ":\n")))
603             (add-text-properties 0 (1- (length header))
604                                  (list 'face 'org-agenda-structure)
605                                  header)
606             (setq text
607                   (concat text header
608                           ;; recursively process
609                           (let ((org-agenda-group-by-property nil))
610                             (org-finalize-agenda-entries
611                              (cdr bucket) nosort))
612                           "\n\n"))))
613         (setq ad-return-value text))
614     ad-do-it))
615 (ad-activate 'org-finalize-agenda-entries)
616 #+end_src
617 *** Dynamically adjust tag position
618 Here is a bit of code that allows you to have the tags always
619 right-adjusted in the buffer.
621 This is useful when you have bigger window than default window-size
622 and you dislike the aesthetics of having the tag in the middle of the
623 line.
625 This hack solves the problem of adjusting it whenever you change the
626 window size.
627 Before saving it will revert the file to having the tag position be
628 left-adjusted so that if you track your files with version control,
629 you won't run into artificial diffs just because the window-size
630 changed.
632 *IMPORTANT*: This is probably slow on very big files.
634 #+begin_src emacs-lisp
635 (setq ba/org-adjust-tags-column t)
637 (defun ba/org-adjust-tags-column-reset-tags ()
638   "In org-mode buffers it will reset tag position according to
639 `org-tags-column'."
640   (when (and
641          (not (string= (buffer-name) "*Remember*"))
642          (eql major-mode 'org-mode))
643     (let ((b-m-p (buffer-modified-p)))
644       (condition-case nil
645           (save-excursion
646             (goto-char (point-min))
647             (command-execute 'outline-next-visible-heading)
648             ;; disable (message) that org-set-tags generates
649             (flet ((message (&rest ignored) nil))
650               (org-set-tags 1 t))
651             (set-buffer-modified-p b-m-p))
652         (error nil)))))
654 (defun ba/org-adjust-tags-column-now ()
655   "Right-adjust `org-tags-column' value, then reset tag position."
656   (set (make-local-variable 'org-tags-column)
657        (- (- (window-width) (length org-ellipsis))))
658   (ba/org-adjust-tags-column-reset-tags))
660 (defun ba/org-adjust-tags-column-maybe ()
661   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
662   (when ba/org-adjust-tags-column
663     (ba/org-adjust-tags-column-now)))
665 (defun ba/org-adjust-tags-column-before-save ()
666   "Tags need to be left-adjusted when saving."
667   (when ba/org-adjust-tags-column
668      (setq org-tags-column 1)
669      (ba/org-adjust-tags-column-reset-tags)))
671 (defun ba/org-adjust-tags-column-after-save ()
672   "Revert left-adjusted tag position done by before-save hook."
673   (ba/org-adjust-tags-column-maybe)
674   (set-buffer-modified-p nil))
676 ; automatically align tags on right-hand side
677 (add-hook 'window-configuration-change-hook
678           'ba/org-adjust-tags-column-maybe)
679 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
680 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
681 (add-hook 'org-agenda-mode-hook '(lambda ()
682                                   (setq org-agenda-tags-column (- (window-width)))))
684 ; between invoking org-refile and displaying the prompt (which
685 ; triggers window-configuration-change-hook) tags might adjust, 
686 ; which invalidates the org-refile cache
687 (defadvice org-refile (around org-refile-disable-adjust-tags)
688   "Disable dynamically adjusting tags"
689   (let ((ba/org-adjust-tags-column nil))
690     ad-do-it))
691 (ad-activate 'org-refile)
692 #+end_src
693 ** Org Agenda and Task Management
694 *** Make it easier to set org-agenda-files from multiple directories
695 - Matt Lundin
697 #+begin_src emacs-lisp
698 (defun my-org-list-files (dirs ext)
699   "Function to create list of org files in multiple subdirectories.
700 This can be called to generate a list of files for
701 org-agenda-files or org-refile-targets.
703 DIRS is a list of directories.
705 EXT is a list of the extensions of files to be included."
706   (let ((dirs (if (listp dirs)
707                   dirs
708                 (list dirs)))
709         (ext (if (listp ext)
710                  ext
711                (list ext)))
712         files)
713     (mapc 
714      (lambda (x)
715        (mapc 
716         (lambda (y)
717           (setq files 
718                 (append files 
719                         (file-expand-wildcards 
720                          (concat (file-name-as-directory x) "*" y)))))
721         ext))
722      dirs)
723     (mapc
724      (lambda (x)
725        (when (or (string-match "/.#" x)
726                  (string-match "#$" x))
727          (setq files (delete x files))))
728      files)
729     files))
731 (defvar my-org-agenda-directories '("~/org/")
732   "List of directories containing org files.")
733 (defvar my-org-agenda-extensions '(".org")
734   "List of extensions of agenda files")
736 (setq my-org-agenda-directories '("~/org/" "~/work/"))
737 (setq my-org-agenda-extensions '(".org" ".ref"))
739 (defun my-org-set-agenda-files ()
740   (interactive)
741   (setq org-agenda-files (my-org-list-files 
742                           my-org-agenda-directories
743                           my-org-agenda-extensions)))
745 (my-org-set-agenda-files)
746 #+end_src
748 The code above will set your "default" agenda files to all files
749 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
750 You can change these values by setting the variables
751 my-org-agenda-extensions and my-org-agenda-directories. The function
752 my-org-agenda-files-by-filetag uses these two variables to determine
753 which files to search for filetags (i.e., the larger set from which
754 the subset will be drawn).
756 You can also easily use my-org-list-files to "mix and match"
757 directories and extensions to generate different lists of agenda
758 files.
760 *** Restrict org-agenda-files by filetag
761   :PROPERTIES:
762   :CUSTOM_ID: set-agenda-files-by-filetag
763   :END:
764 - Matt Lundin
766 It is often helpful to limit yourself to a subset of your agenda
767 files. For instance, at work, you might want to see only files related
768 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
769 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
770 commands]]. These solutions, however, require reapplying a filter each
771 time you call the agenda or writing several new custom agenda commands
772 for each context. Another solution is to use directories for different
773 types of tasks and to change your agenda files with a function that
774 sets org-agenda-files to the appropriate directory. But this relies on
775 hard and static boundaries between files.
777 The following functions allow for a more dynamic approach to selecting
778 a subset of files based on filetags:
780 #+begin_src emacs-lisp
781 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
782   "Restrict org agenda files only to those containing filetag."
783   (interactive)
784   (let* ((tagslist (my-org-get-all-filetags))
785          (ftag (or tag 
786                    (completing-read "Tag: " 
787                                     (mapcar 'car tagslist)))))
788     (org-agenda-remove-restriction-lock 'noupdate)
789     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
790     (setq org-agenda-overriding-restriction 'files)))
792 (defun my-org-get-all-filetags ()
793   "Get list of filetags from all default org-files."
794   (let ((files org-agenda-files)
795         tagslist x)
796     (save-window-excursion
797       (while (setq x (pop files))
798         (set-buffer (find-file-noselect x))
799         (mapc
800          (lambda (y)
801            (let ((tagfiles (assoc y tagslist)))
802              (if tagfiles
803                  (setcdr tagfiles (cons x (cdr tagfiles)))
804                (add-to-list 'tagslist (list y x)))))
805          (my-org-get-filetags)))
806       tagslist)))
808 (defun my-org-get-filetags ()
809   "Get list of filetags for current buffer"
810   (let ((ftags org-file-tags)
811         x)
812     (mapcar 
813      (lambda (x)
814        (org-substring-no-properties x))
815      ftags)))
816 #+end_src
818 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
819 with all filetags in your "normal" agenda files. When you select a
820 tag, org-agenda-files will be restricted to only those files
821 containing the filetag. To release the restriction, type C-c C-x >
822 (org-agenda-remove-restriction-lock).
824 *** Highlight the agenda line under cursor
826 This is useful to make sure what task you are operating on.
828 #+BEGIN_SRC emacs-lisp
829 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
830 #+END_SRC emacs-lisp
832 Under XEmacs:
834 #+BEGIN_SRC emacs-lisp
835 ;; hl-line seems to be only for emacs
836 (require 'highline)
837 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
839 ;; highline-mode does not work straightaway in tty mode.
840 ;; I use a black background
841 (custom-set-faces
842   '(highline-face ((((type tty) (class color))
843                     (:background "white" :foreground "black")))))
844 #+END_SRC emacs-lisp
846 *** Split horizontally for agenda
848 If you would like to split the frame into two side-by-side windows when
849 displaying the agenda, try this hack from Jan Rehders, which uses the
850 `toggle-window-split' from
852 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
854 #+BEGIN_SRC emacs-lisp
855 ;; Patch org-mode to use vertical splitting
856 (defadvice org-prepare-agenda (after org-fix-split)
857   (toggle-window-split))
858 (ad-activate 'org-prepare-agenda)
859 #+END_SRC
861 *** Automatically add an appointment when clocking in a task
863 #+BEGIN_SRC emacs-lisp
864 ;; Make sure you have a sensible value for `appt-message-warning-time'
865 (defvar bzg-org-clock-in-appt-delay 100
866   "Number of minutes for setting an appointment by clocking-in")
867 #+END_SRC
869 This function let's you add an appointment for the current entry.
870 This can be useful when you need a reminder.
872 #+BEGIN_SRC emacs-lisp
873 (defun bzg-org-clock-in-add-appt (&optional n)
874   "Add an appointment for the Org entry at point in N minutes."
875   (interactive)
876   (save-excursion
877     (org-back-to-heading t)
878     (looking-at org-complex-heading-regexp)
879     (let* ((msg (match-string-no-properties 4))
880            (ct-time (decode-time))
881            (appt-min (+ (cadr ct-time)
882                         (or n bzg-org-clock-in-appt-delay)))
883            (appt-time ; define the time for the appointment
884             (progn (setf (cadr ct-time) appt-min) ct-time)))
885       (appt-add (format-time-string
886                  "%H:%M" (apply 'encode-time appt-time)) msg)
887       (if (interactive-p) (message "New appointment for %s" msg)))))
888 #+END_SRC
890 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
891 add an appointment:
893 #+BEGIN_SRC emacs-lisp
894 (defadvice org-clock-in (after org-clock-in-add-appt activate)
895   "Add an appointment when clocking a task in."
896   (bzg-org-clock-in-add-appt))
897 #+END_SRC
899 You may also want to delete the associated appointment when clocking
900 out.  This function does this:
902 #+BEGIN_SRC emacs-lisp
903 (defun bzg-org-clock-out-delete-appt nil
904   "When clocking out, delete any associated appointment."
905   (interactive)
906   (save-excursion
907     (org-back-to-heading t)
908     (looking-at org-complex-heading-regexp)
909     (let* ((msg (match-string-no-properties 4)))
910       (setq appt-time-msg-list
911             (delete nil
912                     (mapcar
913                      (lambda (appt)
914                        (if (not (string-match (regexp-quote msg)
915                                               (cadr appt))) appt))
916                      appt-time-msg-list)))
917       (appt-check))))
918 #+END_SRC
920 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
922 #+BEGIN_SRC emacs-lisp
923 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
924   "Delete an appointment when clocking a task out."
925   (bzg-org-clock-out-delete-appt))
926 #+END_SRC
928 *IMPORTANT*: You can add appointment by clocking in in both an
929 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
930 agenda buffer with the advice above will bring an error.
932 *** Remove time grid lines that are in an appointment
934 The agenda shows lines for the time grid.  Some people think that
935 these lines are a distraction when there are appointments at those
936 times.  You can get rid of the lines which coincide exactly with the
937 beginning of an appointment.  Michael Ekstrand has written a piece of
938 advice that also removes lines that are somewhere inside an
939 appointment:
941 #+begin_src emacs-lisp
942 (defun org-time-to-minutes (time)
943   "Convert an HHMM time to minutes"
944   (+ (* (/ time 100) 60) (% time 100)))
946 (defun org-time-from-minutes (minutes)
947   "Convert a number of minutes to an HHMM time"
948   (+ (* (/ minutes 60) 100) (% minutes 60)))
950 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
951                                                   (list ndays todayp))
952   (if (member 'remove-match (car org-agenda-time-grid))
953       (flet ((extract-window
954               (line)
955               (let ((start (get-text-property 1 'time-of-day line))
956                     (dur (get-text-property 1 'duration line)))
957                 (cond
958                  ((and start dur)
959                   (cons start
960                         (org-time-from-minutes
961                          (+ dur (org-time-to-minutes start)))))
962                  (start start)
963                  (t nil)))))
964         (let* ((windows (delq nil (mapcar 'extract-window list)))
965                (org-agenda-time-grid
966                 (list (car org-agenda-time-grid)
967                       (cadr org-agenda-time-grid)
968                       (remove-if
969                        (lambda (time)
970                          (find-if (lambda (w)
971                                     (if (numberp w)
972                                         (equal w time)
973                                       (and (>= time (car w))
974                                            (< time (cdr w)))))
975                                   windows))
976                        (caddr org-agenda-time-grid)))))
977           ad-do-it))
978     ad-do-it))
979 (ad-activate 'org-agenda-add-time-grid-maybe)
980 #+end_src
981 *** Disable vc for Org mode agenda files
982 -- David Maus
984 Even if you use Git to track your agenda files you might not need
985 vc-mode to be enabled for these files.
987 #+begin_src emacs-lisp
988 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
989 (defun dmj/disable-vc-for-agenda-files-hook ()
990   "Disable vc-mode for Org agenda files."
991   (if (and (fboundp 'org-agenda-file-p)
992            (org-agenda-file-p (buffer-file-name)))
993       (remove-hook 'find-file-hook 'vc-find-file-hook)
994     (add-hook 'find-file-hook 'vc-find-file-hook)))
995 #+end_src
997 *** Easy customization of TODO colors
998 -- Ryan C. Thompson
1000 Here is some code I came up with some code to make it easier to
1001 customize the colors of various TODO keywords. As long as you just
1002 want a different color and nothing else, you can customize the
1003 variable org-todo-keyword-faces and use just a string color (i.e. a
1004 string of the color name) as the face, and then org-get-todo-face
1005 will convert the color to a face, inheriting everything else from
1006 the standard org-todo face.
1008 To demonstrate, I currently have org-todo-keyword-faces set to
1010 #+BEGIN_SRC emacs-lisp
1011 (("IN PROGRESS" . "dark orange")
1012  ("WAITING" . "red4")
1013  ("CANCELED" . "saddle brown"))
1014 #+END_SRC emacs-lisp
1016   Here's the code, in a form you can put in your =.emacs=
1018 #+BEGIN_SRC emacs-lisp
1019 (eval-after-load 'org-faces
1020  '(progn
1021     (defcustom org-todo-keyword-faces nil
1022       "Faces for specific TODO keywords.
1023 This is a list of cons cells, with TODO keywords in the car and
1024 faces in the cdr.  The face can be a symbol, a color, or a
1025 property list of attributes, like (:foreground \"blue\" :weight
1026 bold :underline t)."
1027       :group 'org-faces
1028       :group 'org-todo
1029       :type '(repeat
1030               (cons
1031                (string :tag "Keyword")
1032                (choice color (sexp :tag "Face")))))))
1034 (eval-after-load 'org
1035  '(progn
1036     (defun org-get-todo-face-from-color (color)
1037       "Returns a specification for a face that inherits from org-todo
1038  face and has the given color as foreground. Returns nil if
1039  color is nil."
1040       (when color
1041         `(:inherit org-warning :foreground ,color)))
1043     (defun org-get-todo-face (kwd)
1044       "Get the right face for a TODO keyword KWD.
1045 If KWD is a number, get the corresponding match group."
1046       (if (numberp kwd) (setq kwd (match-string kwd)))
1047       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1048             (if (stringp face)
1049                 (org-get-todo-face-from-color face)
1050               face))
1051           (and (member kwd org-done-keywords) 'org-done)
1052           'org-todo))))
1053 #+END_SRC emacs-lisp
1055 *** Add an effort estimate on the fly when clocking in
1057 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1058 This way you can easily have a "tea-timer" for your tasks when they
1059 don't already have an effort estimate.
1061 #+begin_src emacs-lisp
1062 (add-hook 'org-clock-in-prepare-hook
1063           'my-org-mode-ask-effort)
1065 (defun my-org-mode-ask-effort ()
1066   "Ask for an effort estimate when clocking in."
1067   (unless (org-entry-get (point) "Effort")
1068     (let ((effort
1069            (completing-read
1070             "Effort: "
1071             (org-entry-get-multivalued-property (point) "Effort"))))
1072       (unless (equal effort "")
1073         (org-set-property "Effort" effort)))))
1074 #+end_src
1076 Or you can use a default effort for such a timer:
1078 #+begin_src emacs-lisp
1079 (add-hook 'org-clock-in-prepare-hook
1080           'my-org-mode-add-default-effort)
1082 (defvar org-clock-default-effort "1:00")
1084 (defun my-org-mode-add-default-effort ()
1085   "Add a default effort estimation."
1086   (unless (org-entry-get (point) "Effort")
1087     (org-set-property "Effort" org-clock-default-effort)))
1088 #+end_src
1090 * Hacking Org: Working with Org-mode and other Emacs Packages.
1091 ** org-remember-anything
1093 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1095 #+BEGIN_SRC emacs-lisp
1096 (defvar org-remember-anything
1097   '((name . "Org Remember")
1098     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1099     (action . (lambda (name)
1100                 (let* ((orig-template org-remember-templates)
1101                        (org-remember-templates
1102                         (list (assoc name orig-template))))
1103                   (call-interactively 'org-remember))))))
1104 #+END_SRC
1106 You can add it to your 'anything-sources' variable and open remember directly
1107 from anything. I imagine this would be more interesting for people with many
1108 remember templatesm, so that you are out of keys to assign those to. You should
1109 get something like this:
1111 [[file:images/thumbs/org-remember-anything.png]]
1113 ** Org-mode and saveplace.el
1115 Fix a problem with saveplace.el putting you back in a folded position:
1117 #+begin_src emacs-lisp
1118 (add-hook 'org-mode-hook
1119           (lambda ()
1120             (when (outline-invisible-p)
1121               (save-excursion
1122                 (outline-previous-visible-heading 1)
1123                 (org-show-subtree)))))
1124 #+end_src
1126 ** Using ido-completing-read to find attachments
1127 -- Matt Lundin
1129 Org-attach is great for quickly linking files to a project. But if you
1130 use org-attach extensively you might find yourself wanting to browse
1131 all the files you've attached to org headlines. This is not easy to do
1132 manually, since the directories containing the files are not human
1133 readable (i.e., they are based on automatically generated ids). Here's
1134 some code to browse those files using ido (obviously, you need to be
1135 using ido):
1137 #+begin_src emacs-lisp
1138 (load-library "find-lisp")
1140 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1142 (defun my-ido-find-org-attach ()
1143   "Find files in org-attachment directory"
1144   (interactive)
1145   (let* ((enable-recursive-minibuffers t)
1146          (files (find-lisp-find-files org-attach-directory "."))
1147          (file-assoc-list
1148           (mapcar (lambda (x)
1149                     (cons (file-name-nondirectory x)
1150                           x))
1151                   files))
1152          (filename-list
1153           (remove-duplicates (mapcar #'car file-assoc-list)
1154                              :test #'string=))
1155          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1156          (longname (cdr (assoc filename file-assoc-list))))
1157     (ido-set-current-directory
1158      (if (file-directory-p longname)
1159          longname
1160        (file-name-directory longname)))
1161     (setq ido-exit 'refresh
1162           ido-text-init ido-text
1163           ido-rotate-temp t)
1164     (exit-minibuffer)))
1166 (add-hook 'ido-setup-hook 'ido-my-keys)
1168 (defun ido-my-keys ()
1169   "Add my keybindings for ido."
1170   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1171 #+end_src
1173 To browse your org attachments using ido fuzzy matching and/or the
1174 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1175 press =C-;=.
1177 ** Use idle timer for automatic agenda views
1179 From John Wiegley's mailing list post (March 18, 2010):
1181 #+begin_quote
1182 I have the following snippet in my .emacs file, which I find very
1183 useful. Basically what it does is that if I don't touch my Emacs for 5
1184 minutes, it displays the current agenda. This keeps my tasks "always
1185 in mind" whenever I come back to Emacs after doing something else,
1186 whereas before I had a tendency to forget that it was there.
1187 #+end_quote  
1189   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1191 #+begin_src emacs-lisp
1192 (defun jump-to-org-agenda ()
1193   (interactive)
1194   (let ((buf (get-buffer "*Org Agenda*"))
1195         wind)
1196     (if buf
1197         (if (setq wind (get-buffer-window buf))
1198             (select-window wind)
1199           (if (called-interactively-p)
1200               (progn
1201                 (select-window (display-buffer buf t t))
1202                 (org-fit-window-to-buffer)
1203                 ;; (org-agenda-redo)
1204                 )
1205             (with-selected-window (display-buffer buf)
1206               (org-fit-window-to-buffer)
1207               ;; (org-agenda-redo)
1208               )))
1209       (call-interactively 'org-agenda-list)))
1210   ;;(let ((buf (get-buffer "*Calendar*")))
1211   ;;  (unless (get-buffer-window buf)
1212   ;;    (org-agenda-goto-calendar)))
1213   )
1214   
1215 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1216 #+end_src
1218 #+results:
1219 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1221 ** Link to Gnus messages by Message-Id
1223 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1224 discussion about linking to Gnus messages without encoding the folder
1225 name in the link.  The following code hooks in to the store-link
1226 function in Gnus to capture links by Message-Id when in nnml folders,
1227 and then provides a link type "mid" which can open this link.  The
1228 =mde-org-gnus-open-message-link= function uses the
1229 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1230 scan.  It will go through them, in order, asking each to locate the
1231 message and opening it from the first one that reports success.
1233 It has only been tested with a single nnml backend, so there may be
1234 bugs lurking here and there.
1236 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1237 article]].
1239 #+begin_src emacs-lisp
1240 ;; Support for saving Gnus messages by Message-ID
1241 (defun mde-org-gnus-save-by-mid ()
1242   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1243     (when (eq major-mode 'gnus-article-mode)
1244       (gnus-article-show-summary))
1245     (let* ((group gnus-newsgroup-name)
1246            (method (gnus-find-method-for-group group)))
1247       (when (eq 'nnml (car method))
1248         (let* ((article (gnus-summary-article-number))
1249                (header (gnus-summary-article-header article))
1250                (from (mail-header-from header))
1251                (message-id
1252                 (save-match-data
1253                   (let ((mid (mail-header-id header)))
1254                     (if (string-match "<\\(.*\\)>" mid)
1255                         (match-string 1 mid)
1256                       (error "Malformed message ID header %s" mid)))))
1257                (date (mail-header-date header))
1258                (subject (gnus-summary-subject-string)))
1259           (org-store-link-props :type "mid" :from from :subject subject
1260                                 :message-id message-id :group group
1261                                 :link (org-make-link "mid:" message-id))
1262           (apply 'org-store-link-props
1263                  :description (org-email-link-description)
1264                  org-store-link-plist)
1265           t)))))
1267 (defvar mde-mid-resolve-methods '()
1268   "List of methods to try when resolving message ID's.  For Gnus,
1269 it is a cons of 'gnus and the select (type and name).")
1270 (setq mde-mid-resolve-methods
1271       '((gnus nnml "")))
1273 (defvar mde-org-gnus-open-level 1
1274   "Level at which Gnus is started when opening a link")
1275 (defun mde-org-gnus-open-message-link (msgid)
1276   "Open a message link with Gnus"
1277   (require 'gnus)
1278   (require 'org-table)
1279   (catch 'method-found
1280     (message "[MID linker] Resolving %s" msgid)
1281     (dolist (method mde-mid-resolve-methods)
1282       (cond
1283        ((and (eq (car method) 'gnus)
1284              (eq (cadr method) 'nnml))
1285         (funcall (cdr (assq 'gnus org-link-frame-setup))
1286                  mde-org-gnus-open-level)
1287         (when gnus-other-frame-object
1288           (select-frame gnus-other-frame-object))
1289         (let* ((msg-info (nnml-find-group-number
1290                           (concat "<" msgid ">")
1291                           (cdr method)))
1292                (group (and msg-info (car msg-info)))
1293                (message (and msg-info (cdr msg-info)))
1294                (qname (and group
1295                            (if (gnus-methods-equal-p
1296                                 (cdr method)
1297                                 gnus-select-method)
1298                                group
1299                              (gnus-group-full-name group (cdr method))))))
1300           (when msg-info
1301             (gnus-summary-read-group qname nil t)
1302             (gnus-summary-goto-article message nil t))
1303           (throw 'method-found t)))
1304        (t (error "Unknown link type"))))))
1306 (eval-after-load 'org-gnus
1307   '(progn
1308      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1309      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1310 #+end_src
1312 ** Store link upon sending a message in Gnus
1314 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1316 #+begin_src emacs-lisp
1317 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1318   "Send message with `message-send-and-exit' and store org link to message copy.
1319 If multiple groups appear in the Gcc header, the link refers to
1320 the copy in the last group."
1321   (interactive "P")
1322     (save-excursion
1323       (save-restriction
1324         (message-narrow-to-headers)
1325         (let ((gcc (car (last
1326                          (message-unquote-tokens
1327                           (message-tokenize-header
1328                            (mail-fetch-field "gcc" nil t) " ,")))))
1329               (buf (current-buffer))
1330               (message-kill-buffer-on-exit nil)
1331               id to from subject desc link newsgroup xarchive)
1332         (message-send-and-exit arg)
1333         (or
1334          ;; gcc group found ...
1335          (and gcc
1336               (save-current-buffer
1337                 (progn (set-buffer buf)
1338                        (setq id (org-remove-angle-brackets
1339                                  (mail-fetch-field "Message-ID")))
1340                        (setq to (mail-fetch-field "To"))
1341                        (setq from (mail-fetch-field "From"))
1342                        (setq subject (mail-fetch-field "Subject"))))
1343               (org-store-link-props :type "gnus" :from from :subject subject
1344                                     :message-id id :group gcc :to to)
1345               (setq desc (org-email-link-description))
1346               (setq link (org-gnus-article-link
1347                           gcc newsgroup id xarchive))
1348               (setq org-stored-links
1349                     (cons (list link desc) org-stored-links)))
1350          ;; no gcc group found ...
1351          (message "Can not create Org link: No Gcc header found."))))))
1353 (define-key message-mode-map [(control c) (control meta c)]
1354   'ulf-message-send-and-org-gnus-store-link)
1355 #+end_src
1357 ** Send html messages and attachments with Wanderlust
1358   -- David Maus
1360 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1361 similar functionality for both Wanderlust and Gnus.  The hack below is
1362 still somewhat different: It allows you to toggle sending of html
1363 messages within Wanderlust transparently.  I.e. html markup of the
1364 message body is created right before sending starts.
1366 *** Send HTML message
1368 Putting the code below in your .emacs adds following four functions:
1370 - dmj/wl-send-html-message
1372   Function that does the job: Convert everything between "--text
1373   follows this line--" and first mime entity (read: attachment) or
1374   end of buffer into html markup using `org-export-region-as-html'
1375   and replaces original body with a multipart MIME entity with the
1376   plain text version of body and the html markup version.  Thus a
1377   recipient that prefers html messages can see the html markup,
1378   recipients that prefer or depend on plain text can see the plain
1379   text.
1381   Cannot be called interactively: It is hooked into SEMI's
1382   `mime-edit-translate-hook' if message should be HTML message.
1384 - dmj/wl-send-html-message-draft-init
1386   Cannot be called interactively: It is hooked into WL's
1387   `wl-mail-setup-hook' and provides a buffer local variable to
1388   toggle.
1390 - dmj/wl-send-html-message-draft-maybe
1392   Cannot be called interactively: It is hooked into WL's
1393   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1394   `mime-edit-translate-hook' depending on whether HTML message is
1395   toggled on or off
1397 - dmj/wl-send-html-message-toggle
1399   Toggles sending of HTML message.  If toggled on, the letters
1400   "HTML" appear in the mode line.
1402   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1404 If you have to send HTML messages regularly you can set a global
1405 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1406 toggle on sending HTML message by default.
1408 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1409 Google's web front end.  As you can see you have the whole markup of
1410 Org at your service: *bold*, /italics/, tables, lists...
1412 So even if you feel uncomfortable with sending HTML messages at least
1413 you send HTML that looks quite good.
1415 #+begin_src emacs-lisp
1416 (defun dmj/wl-send-html-message ()
1417   "Send message as html message.
1418 Convert body of message to html using
1419   `org-export-region-as-html'."
1420   (require 'org)
1421   (save-excursion
1422     (let (beg end html text)
1423       (goto-char (point-min))
1424       (re-search-forward "^--text follows this line--$")
1425       ;; move to beginning of next line
1426       (beginning-of-line 2)
1427       (setq beg (point))
1428       (if (not (re-search-forward "^--\\[\\[" nil t))
1429           (setq end (point-max))
1430         ;; line up
1431         (end-of-line 0)
1432         (setq end (point)))
1433       ;; grab body
1434       (setq text (buffer-substring-no-properties beg end))
1435       ;; convert to html
1436       (with-temp-buffer
1437         (org-mode)
1438         (insert text)
1439         ;; handle signature
1440         (when (re-search-backward "^-- \n" nil t)
1441           ;; preserve link breaks in signature
1442           (insert "\n#+BEGIN_VERSE\n")
1443           (goto-char (point-max))
1444           (insert "\n#+END_VERSE\n")
1445           ;; grab html
1446           (setq html (org-export-region-as-html
1447                       (point-min) (point-max) t 'string))))
1448       (delete-region beg end)
1449       (insert
1450        (concat
1451         "--" "<<alternative>>-{\n"
1452         "--" "[[text/plain]]\n" text
1453         "--" "[[text/html]]\n"  html
1454         "--" "}-<<alternative>>\n")))))
1456 (defun dmj/wl-send-html-message-toggle ()
1457   "Toggle sending of html message."
1458   (interactive)
1459   (setq dmj/wl-send-html-message-toggled-p
1460         (if dmj/wl-send-html-message-toggled-p
1461             nil "HTML"))
1462   (message "Sending html message toggled %s"
1463            (if dmj/wl-send-html-message-toggled-p
1464                "on" "off")))
1466 (defun dmj/wl-send-html-message-draft-init ()
1467   "Create buffer local settings for maybe sending html message."
1468   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1469     (setq dmj/wl-send-html-message-toggled-p nil))
1470   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1471   (add-to-list 'global-mode-string
1472                '(:eval (if (eq major-mode 'wl-draft-mode)
1473                            dmj/wl-send-html-message-toggled-p))))
1475 (defun dmj/wl-send-html-message-maybe ()
1476   "Maybe send this message as html message.
1478 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1479 non-nil, add `dmj/wl-send-html-message' to
1480 `mime-edit-translate-hook'."
1481   (if dmj/wl-send-html-message-toggled-p
1482       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1483     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1485 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1486 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1487 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1488 #+end_src
1490 *** Attach HTML of region or subtree
1492 Instead of sending a complete HTML message you might only send parts
1493 of an Org file as HTML for the poor souls who are plagued with
1494 non-proportional fonts in their mail program that messes up pretty
1495 ASCII tables.
1497 This short function does the trick: It exports region or subtree to
1498 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1499 and clipboard.  If a region is active, it uses the region, the
1500 complete subtree otherwise.
1502 #+begin_src emacs-lisp
1503 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1504   "Export region between BEG and END as html attachment.
1505 If BEG and END are not set, use current subtree.  Region or
1506 subtree is exported to html without header and footer, prefixed
1507 with a mime entity string and pushed to clipboard and killring.
1508 When called with prefix, mime entity is not marked as
1509 attachment."
1510   (interactive "r\nP")
1511   (save-excursion
1512     (let* ((beg (if (region-active-p) (region-beginning)
1513                   (progn
1514                     (org-back-to-heading)
1515                     (point))))
1516            (end (if (region-active-p) (region-end)
1517                   (progn
1518                     (org-end-of-subtree)
1519                     (point))))
1520            (html (concat "--[[text/html"
1521                          (if arg "" "\nContent-Disposition: attachment")
1522                          "]]\n"
1523                          (org-export-region-as-html beg end t 'string))))
1524       (when (fboundp 'x-set-selection)
1525         (ignore-errors (x-set-selection 'PRIMARY html))
1526         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1527       (message "html export done, pushed to kill ring and clipboard"))))
1528 #+end_src
1530 *** Adopting for Gnus
1532 The whole magic lies in the special strings that mark a HTML
1533 attachment.  So you might just have to find out what these special
1534 strings are in message-mode and modify the functions accordingly.
1535 * Hacking Org: Working with Org-mode and External Programs.
1536 ** Use Org-mode with Screen [Andrew Hyatt]
1538 "The general idea is that you start a task in which all the work will
1539 take place in a shell.  This usually is not a leaf-task for me, but
1540 usually the parent of a leaf task.  From a task in your org-file, M-x
1541 ash-org-screen will prompt for the name of a session.  Give it a name,
1542 and it will insert a link.  Open the link at any time to go the screen
1543 session containing your work!"
1545 http://article.gmane.org/gmane.emacs.orgmode/5276
1547 #+BEGIN_SRC emacs-lisp
1548 (require 'term)
1550 (defun ash-org-goto-screen (name)
1551   "Open the screen with the specified name in the window"
1552   (interactive "MScreen name: ")
1553   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1554     (if (member screen-buffer-name
1555                 (mapcar 'buffer-name (buffer-list)))
1556         (switch-to-buffer screen-buffer-name)
1557       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1559 (defun ash-org-screen-buffer-name (name)
1560   "Returns the buffer name corresponding to the screen name given."
1561   (concat "*screen " name "*"))
1563 (defun ash-org-screen-helper (name arg)
1564   ;; Pick the name of the new buffer.
1565   (let ((term-ansi-buffer-name
1566          (generate-new-buffer-name
1567           (ash-org-screen-buffer-name name))))
1568     (setq term-ansi-buffer-name
1569           (term-ansi-make-term
1570            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1571     (set-buffer term-ansi-buffer-name)
1572     (term-mode)
1573     (term-char-mode)
1574     (term-set-escape-char ?\C-x)
1575     term-ansi-buffer-name))
1577 (defun ash-org-screen (name)
1578   "Start a screen session with name"
1579   (interactive "MScreen name: ")
1580   (save-excursion
1581     (ash-org-screen-helper name "-S"))
1582   (insert-string (concat "[[screen:" name "]]")))
1584 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1585 ;; \"%s\")") to org-link-abbrev-alist.
1586 #+END_SRC
1588 ** Org Agenda + Appt + Zenity
1590 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It make sure your agenda
1591 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1592 popup window.
1594 #+BEGIN_SRC emacs-lisp
1595 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1596 ; For org appointment reminders
1598 ;; Get appointments for today
1599 (defun my-org-agenda-to-appt ()
1600   (interactive)
1601   (setq appt-time-msg-list nil)
1602   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
1603         (org-agenda-to-appt)))
1605 ;; Run once, activate and schedule refresh
1606 (my-org-agenda-to-appt)
1607 (appt-activate t)
1608 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
1610 ; 5 minute warnings
1611 (setq appt-message-warning-time 15)
1612 (setq appt-display-interval 5)
1614 ; Update appt each time agenda opened.
1615 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
1617 ; Setup zenify, we tell appt to use window, and replace default function
1618 (setq appt-display-format 'window)
1619 (setq appt-disp-window-function (function my-appt-disp-window))
1621 (defun my-appt-disp-window (min-to-app new-time msg)
1622   (save-window-excursion (shell-command (concat
1623     "/usr/bin/zenity --info --title='Appointment' --text='"
1624     msg "' &") nil nil)))
1625 #+END_SRC
1627 ** Org-Mode + gnome-osd
1629 Richard Riley uses gnome-osd in interaction with Org-Mode to display
1630 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
1632 ** remind2org
1634 From Detlef Steuer
1636 http://article.gmane.org/gmane.emacs.orgmode/5073
1638 #+BEGIN_QUOTE
1639 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
1640 command line calendaring program. Its features superseed the possibilities
1641 of orgmode in the area of date specifying, so that I want to use it
1642 combined with orgmode.
1644 Using the script below I'm able use remind and incorporate its output in my
1645 agenda views.  The default of using 13 months look ahead is easily
1646 changed. It just happens I sometimes like to look a year into the
1647 future. :-)
1648 #+END_QUOTE
1650 ** Useful webjumps for conkeror
1652 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
1653 your =~/.conkerorrc= file:
1655 #+begin_example
1656 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
1657 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
1658 #+end_example
1660 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
1661 Org-mode mailing list.
1663 ** Use MathJax for HTML export without requiring JavaScript
1664 As of 2010-08-14, MathJax is the default method used to export math to HTML.
1666 If you like the results but do not want JavaScript in the exported pages,
1667 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
1668 HTML file from the exported version. It can also embed all referenced fonts
1669 within the HTML file itself, so there are no dependencies to external files.
1671 The download archive contains an elisp file which integrates it into the Org
1672 export process (configurable per file with a "#+StaticMathJax:" line).
1674 Read README.org and the comments in org-static-mathjax.el for usage instructions.
1675 ** Search Org files using lgrep
1677 Matt Lundi suggests this:
1679 #+begin_src emacs-lisp
1680   (defun my-org-grep (search &optional context)
1681     "Search for word in org files. 
1683 Prefix argument determines number of lines."
1684     (interactive "sSearch for: \nP")
1685     (let ((grep-find-ignored-files '("#*" ".#*"))
1686           (grep-template (concat "grep <X> -i -nH " 
1687                                  (when context
1688                                    (concat "-C" (number-to-string context)))
1689                                  " -e <R> <F>")))
1690       (lgrep search "*org*" "/home/matt/org/")))
1692   (global-set-key (kbd "<f8>") 'my-org-grep)
1693 #+end_src