org-hacks.org: reschedule agenda items to today with a single command
[Worg.git] / org-hacks.org
blobfd93e0111b14870d4b5cce7409b839ace90b3af2
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 *** Refresh the agenda view regurally
1092 Hack sent by Kiwon Um:
1094 #+begin_src emacs-lisp
1095 (defun kiwon/org-agenda-redo-in-other-window ()
1096   "Call org-agenda-redo function even in the non-agenda buffer."
1097   (interactive)
1098   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1099     (when agenda-window
1100       (with-selected-window agenda-window (org-agenda-redo)))))
1101 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1102 #+end_src
1104 *** Reschedule agenda items to today with a single command
1106 This was suggested by Carsten in reply to David Abrahams:
1108 #+begin_example emacs-lisp
1109 (defun org-agenda-reschedule-to-today ()
1110   (interactive)
1111   (flet ((org-read-date (&rest rest) (current-time)))
1112     (call-interactively 'org-agenda-schedule)))
1113 #+end_example
1115 * Hacking Org: Working with Org-mode and other Emacs Packages.
1116 ** org-remember-anything
1118 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1120 #+BEGIN_SRC emacs-lisp
1121 (defvar org-remember-anything
1122   '((name . "Org Remember")
1123     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1124     (action . (lambda (name)
1125                 (let* ((orig-template org-remember-templates)
1126                        (org-remember-templates
1127                         (list (assoc name orig-template))))
1128                   (call-interactively 'org-remember))))))
1129 #+END_SRC
1131 You can add it to your 'anything-sources' variable and open remember directly
1132 from anything. I imagine this would be more interesting for people with many
1133 remember templatesm, so that you are out of keys to assign those to. You should
1134 get something like this:
1136 [[file:images/thumbs/org-remember-anything.png]]
1138 ** Org-mode and saveplace.el
1140 Fix a problem with saveplace.el putting you back in a folded position:
1142 #+begin_src emacs-lisp
1143 (add-hook 'org-mode-hook
1144           (lambda ()
1145             (when (outline-invisible-p)
1146               (save-excursion
1147                 (outline-previous-visible-heading 1)
1148                 (org-show-subtree)))))
1149 #+end_src
1151 ** Using ido-completing-read to find attachments
1152 -- Matt Lundin
1154 Org-attach is great for quickly linking files to a project. But if you
1155 use org-attach extensively you might find yourself wanting to browse
1156 all the files you've attached to org headlines. This is not easy to do
1157 manually, since the directories containing the files are not human
1158 readable (i.e., they are based on automatically generated ids). Here's
1159 some code to browse those files using ido (obviously, you need to be
1160 using ido):
1162 #+begin_src emacs-lisp
1163 (load-library "find-lisp")
1165 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1167 (defun my-ido-find-org-attach ()
1168   "Find files in org-attachment directory"
1169   (interactive)
1170   (let* ((enable-recursive-minibuffers t)
1171          (files (find-lisp-find-files org-attach-directory "."))
1172          (file-assoc-list
1173           (mapcar (lambda (x)
1174                     (cons (file-name-nondirectory x)
1175                           x))
1176                   files))
1177          (filename-list
1178           (remove-duplicates (mapcar #'car file-assoc-list)
1179                              :test #'string=))
1180          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1181          (longname (cdr (assoc filename file-assoc-list))))
1182     (ido-set-current-directory
1183      (if (file-directory-p longname)
1184          longname
1185        (file-name-directory longname)))
1186     (setq ido-exit 'refresh
1187           ido-text-init ido-text
1188           ido-rotate-temp t)
1189     (exit-minibuffer)))
1191 (add-hook 'ido-setup-hook 'ido-my-keys)
1193 (defun ido-my-keys ()
1194   "Add my keybindings for ido."
1195   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1196 #+end_src
1198 To browse your org attachments using ido fuzzy matching and/or the
1199 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1200 press =C-;=.
1202 ** Use idle timer for automatic agenda views
1204 From John Wiegley's mailing list post (March 18, 2010):
1206 #+begin_quote
1207 I have the following snippet in my .emacs file, which I find very
1208 useful. Basically what it does is that if I don't touch my Emacs for 5
1209 minutes, it displays the current agenda. This keeps my tasks "always
1210 in mind" whenever I come back to Emacs after doing something else,
1211 whereas before I had a tendency to forget that it was there.
1212 #+end_quote  
1214   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1216 #+begin_src emacs-lisp
1217 (defun jump-to-org-agenda ()
1218   (interactive)
1219   (let ((buf (get-buffer "*Org Agenda*"))
1220         wind)
1221     (if buf
1222         (if (setq wind (get-buffer-window buf))
1223             (select-window wind)
1224           (if (called-interactively-p)
1225               (progn
1226                 (select-window (display-buffer buf t t))
1227                 (org-fit-window-to-buffer)
1228                 ;; (org-agenda-redo)
1229                 )
1230             (with-selected-window (display-buffer buf)
1231               (org-fit-window-to-buffer)
1232               ;; (org-agenda-redo)
1233               )))
1234       (call-interactively 'org-agenda-list)))
1235   ;;(let ((buf (get-buffer "*Calendar*")))
1236   ;;  (unless (get-buffer-window buf)
1237   ;;    (org-agenda-goto-calendar)))
1238   )
1239   
1240 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1241 #+end_src
1243 #+results:
1244 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1246 ** Link to Gnus messages by Message-Id
1248 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1249 discussion about linking to Gnus messages without encoding the folder
1250 name in the link.  The following code hooks in to the store-link
1251 function in Gnus to capture links by Message-Id when in nnml folders,
1252 and then provides a link type "mid" which can open this link.  The
1253 =mde-org-gnus-open-message-link= function uses the
1254 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1255 scan.  It will go through them, in order, asking each to locate the
1256 message and opening it from the first one that reports success.
1258 It has only been tested with a single nnml backend, so there may be
1259 bugs lurking here and there.
1261 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1262 article]].
1264 #+begin_src emacs-lisp
1265 ;; Support for saving Gnus messages by Message-ID
1266 (defun mde-org-gnus-save-by-mid ()
1267   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1268     (when (eq major-mode 'gnus-article-mode)
1269       (gnus-article-show-summary))
1270     (let* ((group gnus-newsgroup-name)
1271            (method (gnus-find-method-for-group group)))
1272       (when (eq 'nnml (car method))
1273         (let* ((article (gnus-summary-article-number))
1274                (header (gnus-summary-article-header article))
1275                (from (mail-header-from header))
1276                (message-id
1277                 (save-match-data
1278                   (let ((mid (mail-header-id header)))
1279                     (if (string-match "<\\(.*\\)>" mid)
1280                         (match-string 1 mid)
1281                       (error "Malformed message ID header %s" mid)))))
1282                (date (mail-header-date header))
1283                (subject (gnus-summary-subject-string)))
1284           (org-store-link-props :type "mid" :from from :subject subject
1285                                 :message-id message-id :group group
1286                                 :link (org-make-link "mid:" message-id))
1287           (apply 'org-store-link-props
1288                  :description (org-email-link-description)
1289                  org-store-link-plist)
1290           t)))))
1292 (defvar mde-mid-resolve-methods '()
1293   "List of methods to try when resolving message ID's.  For Gnus,
1294 it is a cons of 'gnus and the select (type and name).")
1295 (setq mde-mid-resolve-methods
1296       '((gnus nnml "")))
1298 (defvar mde-org-gnus-open-level 1
1299   "Level at which Gnus is started when opening a link")
1300 (defun mde-org-gnus-open-message-link (msgid)
1301   "Open a message link with Gnus"
1302   (require 'gnus)
1303   (require 'org-table)
1304   (catch 'method-found
1305     (message "[MID linker] Resolving %s" msgid)
1306     (dolist (method mde-mid-resolve-methods)
1307       (cond
1308        ((and (eq (car method) 'gnus)
1309              (eq (cadr method) 'nnml))
1310         (funcall (cdr (assq 'gnus org-link-frame-setup))
1311                  mde-org-gnus-open-level)
1312         (when gnus-other-frame-object
1313           (select-frame gnus-other-frame-object))
1314         (let* ((msg-info (nnml-find-group-number
1315                           (concat "<" msgid ">")
1316                           (cdr method)))
1317                (group (and msg-info (car msg-info)))
1318                (message (and msg-info (cdr msg-info)))
1319                (qname (and group
1320                            (if (gnus-methods-equal-p
1321                                 (cdr method)
1322                                 gnus-select-method)
1323                                group
1324                              (gnus-group-full-name group (cdr method))))))
1325           (when msg-info
1326             (gnus-summary-read-group qname nil t)
1327             (gnus-summary-goto-article message nil t))
1328           (throw 'method-found t)))
1329        (t (error "Unknown link type"))))))
1331 (eval-after-load 'org-gnus
1332   '(progn
1333      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1334      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1335 #+end_src
1337 ** Store link upon sending a message in Gnus
1339 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1341 #+begin_src emacs-lisp
1342 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1343   "Send message with `message-send-and-exit' and store org link to message copy.
1344 If multiple groups appear in the Gcc header, the link refers to
1345 the copy in the last group."
1346   (interactive "P")
1347     (save-excursion
1348       (save-restriction
1349         (message-narrow-to-headers)
1350         (let ((gcc (car (last
1351                          (message-unquote-tokens
1352                           (message-tokenize-header
1353                            (mail-fetch-field "gcc" nil t) " ,")))))
1354               (buf (current-buffer))
1355               (message-kill-buffer-on-exit nil)
1356               id to from subject desc link newsgroup xarchive)
1357         (message-send-and-exit arg)
1358         (or
1359          ;; gcc group found ...
1360          (and gcc
1361               (save-current-buffer
1362                 (progn (set-buffer buf)
1363                        (setq id (org-remove-angle-brackets
1364                                  (mail-fetch-field "Message-ID")))
1365                        (setq to (mail-fetch-field "To"))
1366                        (setq from (mail-fetch-field "From"))
1367                        (setq subject (mail-fetch-field "Subject"))))
1368               (org-store-link-props :type "gnus" :from from :subject subject
1369                                     :message-id id :group gcc :to to)
1370               (setq desc (org-email-link-description))
1371               (setq link (org-gnus-article-link
1372                           gcc newsgroup id xarchive))
1373               (setq org-stored-links
1374                     (cons (list link desc) org-stored-links)))
1375          ;; no gcc group found ...
1376          (message "Can not create Org link: No Gcc header found."))))))
1378 (define-key message-mode-map [(control c) (control meta c)]
1379   'ulf-message-send-and-org-gnus-store-link)
1380 #+end_src
1382 ** Send html messages and attachments with Wanderlust
1383   -- David Maus
1385 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1386 similar functionality for both Wanderlust and Gnus.  The hack below is
1387 still somewhat different: It allows you to toggle sending of html
1388 messages within Wanderlust transparently.  I.e. html markup of the
1389 message body is created right before sending starts.
1391 *** Send HTML message
1393 Putting the code below in your .emacs adds following four functions:
1395 - dmj/wl-send-html-message
1397   Function that does the job: Convert everything between "--text
1398   follows this line--" and first mime entity (read: attachment) or
1399   end of buffer into html markup using `org-export-region-as-html'
1400   and replaces original body with a multipart MIME entity with the
1401   plain text version of body and the html markup version.  Thus a
1402   recipient that prefers html messages can see the html markup,
1403   recipients that prefer or depend on plain text can see the plain
1404   text.
1406   Cannot be called interactively: It is hooked into SEMI's
1407   `mime-edit-translate-hook' if message should be HTML message.
1409 - dmj/wl-send-html-message-draft-init
1411   Cannot be called interactively: It is hooked into WL's
1412   `wl-mail-setup-hook' and provides a buffer local variable to
1413   toggle.
1415 - dmj/wl-send-html-message-draft-maybe
1417   Cannot be called interactively: It is hooked into WL's
1418   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1419   `mime-edit-translate-hook' depending on whether HTML message is
1420   toggled on or off
1422 - dmj/wl-send-html-message-toggle
1424   Toggles sending of HTML message.  If toggled on, the letters
1425   "HTML" appear in the mode line.
1427   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1429 If you have to send HTML messages regularly you can set a global
1430 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1431 toggle on sending HTML message by default.
1433 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1434 Google's web front end.  As you can see you have the whole markup of
1435 Org at your service: *bold*, /italics/, tables, lists...
1437 So even if you feel uncomfortable with sending HTML messages at least
1438 you send HTML that looks quite good.
1440 #+begin_src emacs-lisp
1441 (defun dmj/wl-send-html-message ()
1442   "Send message as html message.
1443 Convert body of message to html using
1444   `org-export-region-as-html'."
1445   (require 'org)
1446   (save-excursion
1447     (let (beg end html text)
1448       (goto-char (point-min))
1449       (re-search-forward "^--text follows this line--$")
1450       ;; move to beginning of next line
1451       (beginning-of-line 2)
1452       (setq beg (point))
1453       (if (not (re-search-forward "^--\\[\\[" nil t))
1454           (setq end (point-max))
1455         ;; line up
1456         (end-of-line 0)
1457         (setq end (point)))
1458       ;; grab body
1459       (setq text (buffer-substring-no-properties beg end))
1460       ;; convert to html
1461       (with-temp-buffer
1462         (org-mode)
1463         (insert text)
1464         ;; handle signature
1465         (when (re-search-backward "^-- \n" nil t)
1466           ;; preserve link breaks in signature
1467           (insert "\n#+BEGIN_VERSE\n")
1468           (goto-char (point-max))
1469           (insert "\n#+END_VERSE\n")
1470           ;; grab html
1471           (setq html (org-export-region-as-html
1472                       (point-min) (point-max) t 'string))))
1473       (delete-region beg end)
1474       (insert
1475        (concat
1476         "--" "<<alternative>>-{\n"
1477         "--" "[[text/plain]]\n" text
1478         "--" "[[text/html]]\n"  html
1479         "--" "}-<<alternative>>\n")))))
1481 (defun dmj/wl-send-html-message-toggle ()
1482   "Toggle sending of html message."
1483   (interactive)
1484   (setq dmj/wl-send-html-message-toggled-p
1485         (if dmj/wl-send-html-message-toggled-p
1486             nil "HTML"))
1487   (message "Sending html message toggled %s"
1488            (if dmj/wl-send-html-message-toggled-p
1489                "on" "off")))
1491 (defun dmj/wl-send-html-message-draft-init ()
1492   "Create buffer local settings for maybe sending html message."
1493   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1494     (setq dmj/wl-send-html-message-toggled-p nil))
1495   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1496   (add-to-list 'global-mode-string
1497                '(:eval (if (eq major-mode 'wl-draft-mode)
1498                            dmj/wl-send-html-message-toggled-p))))
1500 (defun dmj/wl-send-html-message-maybe ()
1501   "Maybe send this message as html message.
1503 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1504 non-nil, add `dmj/wl-send-html-message' to
1505 `mime-edit-translate-hook'."
1506   (if dmj/wl-send-html-message-toggled-p
1507       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1508     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1510 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1511 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1512 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1513 #+end_src
1515 *** Attach HTML of region or subtree
1517 Instead of sending a complete HTML message you might only send parts
1518 of an Org file as HTML for the poor souls who are plagued with
1519 non-proportional fonts in their mail program that messes up pretty
1520 ASCII tables.
1522 This short function does the trick: It exports region or subtree to
1523 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1524 and clipboard.  If a region is active, it uses the region, the
1525 complete subtree otherwise.
1527 #+begin_src emacs-lisp
1528 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1529   "Export region between BEG and END as html attachment.
1530 If BEG and END are not set, use current subtree.  Region or
1531 subtree is exported to html without header and footer, prefixed
1532 with a mime entity string and pushed to clipboard and killring.
1533 When called with prefix, mime entity is not marked as
1534 attachment."
1535   (interactive "r\nP")
1536   (save-excursion
1537     (let* ((beg (if (region-active-p) (region-beginning)
1538                   (progn
1539                     (org-back-to-heading)
1540                     (point))))
1541            (end (if (region-active-p) (region-end)
1542                   (progn
1543                     (org-end-of-subtree)
1544                     (point))))
1545            (html (concat "--[[text/html"
1546                          (if arg "" "\nContent-Disposition: attachment")
1547                          "]]\n"
1548                          (org-export-region-as-html beg end t 'string))))
1549       (when (fboundp 'x-set-selection)
1550         (ignore-errors (x-set-selection 'PRIMARY html))
1551         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1552       (message "html export done, pushed to kill ring and clipboard"))))
1553 #+end_src
1555 *** Adopting for Gnus
1557 The whole magic lies in the special strings that mark a HTML
1558 attachment.  So you might just have to find out what these special
1559 strings are in message-mode and modify the functions accordingly.
1560 * Hacking Org: Working with Org-mode and External Programs.
1561 ** Use Org-mode with Screen [Andrew Hyatt]
1563 "The general idea is that you start a task in which all the work will
1564 take place in a shell.  This usually is not a leaf-task for me, but
1565 usually the parent of a leaf task.  From a task in your org-file, M-x
1566 ash-org-screen will prompt for the name of a session.  Give it a name,
1567 and it will insert a link.  Open the link at any time to go the screen
1568 session containing your work!"
1570 http://article.gmane.org/gmane.emacs.orgmode/5276
1572 #+BEGIN_SRC emacs-lisp
1573 (require 'term)
1575 (defun ash-org-goto-screen (name)
1576   "Open the screen with the specified name in the window"
1577   (interactive "MScreen name: ")
1578   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1579     (if (member screen-buffer-name
1580                 (mapcar 'buffer-name (buffer-list)))
1581         (switch-to-buffer screen-buffer-name)
1582       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1584 (defun ash-org-screen-buffer-name (name)
1585   "Returns the buffer name corresponding to the screen name given."
1586   (concat "*screen " name "*"))
1588 (defun ash-org-screen-helper (name arg)
1589   ;; Pick the name of the new buffer.
1590   (let ((term-ansi-buffer-name
1591          (generate-new-buffer-name
1592           (ash-org-screen-buffer-name name))))
1593     (setq term-ansi-buffer-name
1594           (term-ansi-make-term
1595            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1596     (set-buffer term-ansi-buffer-name)
1597     (term-mode)
1598     (term-char-mode)
1599     (term-set-escape-char ?\C-x)
1600     term-ansi-buffer-name))
1602 (defun ash-org-screen (name)
1603   "Start a screen session with name"
1604   (interactive "MScreen name: ")
1605   (save-excursion
1606     (ash-org-screen-helper name "-S"))
1607   (insert-string (concat "[[screen:" name "]]")))
1609 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1610 ;; \"%s\")") to org-link-abbrev-alist.
1611 #+END_SRC
1613 ** Org Agenda + Appt + Zenity
1615 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It make sure your agenda
1616 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1617 popup window.
1619 #+BEGIN_SRC emacs-lisp
1620 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1621 ; For org appointment reminders
1623 ;; Get appointments for today
1624 (defun my-org-agenda-to-appt ()
1625   (interactive)
1626   (setq appt-time-msg-list nil)
1627   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
1628         (org-agenda-to-appt)))
1630 ;; Run once, activate and schedule refresh
1631 (my-org-agenda-to-appt)
1632 (appt-activate t)
1633 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
1635 ; 5 minute warnings
1636 (setq appt-message-warning-time 15)
1637 (setq appt-display-interval 5)
1639 ; Update appt each time agenda opened.
1640 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
1642 ; Setup zenify, we tell appt to use window, and replace default function
1643 (setq appt-display-format 'window)
1644 (setq appt-disp-window-function (function my-appt-disp-window))
1646 (defun my-appt-disp-window (min-to-app new-time msg)
1647   (save-window-excursion (shell-command (concat
1648     "/usr/bin/zenity --info --title='Appointment' --text='"
1649     msg "' &") nil nil)))
1650 #+END_SRC
1652 ** Org-Mode + gnome-osd
1654 Richard Riley uses gnome-osd in interaction with Org-Mode to display
1655 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
1657 ** remind2org
1659 From Detlef Steuer
1661 http://article.gmane.org/gmane.emacs.orgmode/5073
1663 #+BEGIN_QUOTE
1664 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
1665 command line calendaring program. Its features superseed the possibilities
1666 of orgmode in the area of date specifying, so that I want to use it
1667 combined with orgmode.
1669 Using the script below I'm able use remind and incorporate its output in my
1670 agenda views.  The default of using 13 months look ahead is easily
1671 changed. It just happens I sometimes like to look a year into the
1672 future. :-)
1673 #+END_QUOTE
1675 ** Useful webjumps for conkeror
1677 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
1678 your =~/.conkerorrc= file:
1680 #+begin_example
1681 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
1682 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
1683 #+end_example
1685 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
1686 Org-mode mailing list.
1688 ** Use MathJax for HTML export without requiring JavaScript
1689 As of 2010-08-14, MathJax is the default method used to export math to HTML.
1691 If you like the results but do not want JavaScript in the exported pages,
1692 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
1693 HTML file from the exported version. It can also embed all referenced fonts
1694 within the HTML file itself, so there are no dependencies to external files.
1696 The download archive contains an elisp file which integrates it into the Org
1697 export process (configurable per file with a "#+StaticMathJax:" line).
1699 Read README.org and the comments in org-static-mathjax.el for usage instructions.
1700 ** Search Org files using lgrep
1702 Matt Lundi suggests this:
1704 #+begin_src emacs-lisp
1705   (defun my-org-grep (search &optional context)
1706     "Search for word in org files. 
1708 Prefix argument determines number of lines."
1709     (interactive "sSearch for: \nP")
1710     (let ((grep-find-ignored-files '("#*" ".#*"))
1711           (grep-template (concat "grep <X> -i -nH " 
1712                                  (when context
1713                                    (concat "-C" (number-to-string context)))
1714                                  " -e <R> <F>")))
1715       (lgrep search "*org*" "/home/matt/org/")))
1717   (global-set-key (kbd "<f8>") 'my-org-grep)
1718 #+end_src