Merge branch 'master' of git+ssh://repo.or.cz/srv/git/Worg
[Worg.git] / org-hacks.org
blob9818dac71fc110d579fd9e0a0e87fa53e32b6635
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 *** Turn a heading into an Org link
441 From David Maus:
443 #+begin_src emacs-lisp
444   (defun dmj:turn-headline-into-org-mode-link ()
445     "Replace word at point by an Org mode link."
446     (interactive)
447     (when (org-at-heading-p)
448       (let ((hl-text (nth 4 (org-heading-components))))
449         (unless (or (null hl-text)
450                     (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
451           (beginning-of-line)
452           (search-forward hl-text (point-at-eol))
453           (replace-string
454            hl-text
455            (format "[[file:%s.org][%s]]"
456                    (org-link-escape hl-text)
457                    (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
458            nil (- (point) (length hl-text)) (point))))))
459 #+end_src
461 ** Archiving Content in Org-Mode
462 *** Preserve top level headings when archiving to a file
463 - Matt Lundin
465 To preserve (somewhat) the integrity of your archive structure while
466 archiving lower level items to a file, you can use the following
467 defadvice:
469 #+begin_src emacs-lisp
470 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
471   (let ((org-archive-location 
472          (if (save-excursion (org-back-to-heading)
473                              (> (org-outline-level) 1))
474              (concat (car (split-string org-archive-location "::"))
475                      "::* "
476                      (car (org-get-outline-path)))
477            org-archive-location)))
478     ad-do-it))
479 #+end_src
481 Thus, if you have an outline structure such as...
483 #+begin_src org
484 ,* Heading
485 ,** Subheading
486 ,*** Subsubheading
487 #+end_src
489 ...archiving "Subsubheading" to a new file will set the location in
490 the new file to the top level heading:
492 #+begin_src org
493 ,* Heading
494 ,** Subsubheading
495 #+end_src
497 While this hack obviously destroys the outline hierarchy somewhat, it
498 at least preserves the logic of level one groupings.
500 *** Archive in a date tree
502 Posted to Org-mode mailing list by Osamu Okano
503 [2010-04-21 Wed]
505 #+begin_src emacs-lisp
506 ;; (setq org-archive-location "%s_archive::date-tree")
507 (defadvice org-archive-subtree
508   (around org-archive-subtree-to-data-tree activate)
509   "org-archive-subtree to date-tree"
510   (if
511       (string= "date-tree"
512                (org-extract-archive-heading
513                 (org-get-local-archive-location)))
514       (let* ((dct (decode-time (org-current-time)))
515              (y (nth 5 dct))
516              (m (nth 4 dct))
517              (d (nth 3 dct))
518              (this-buffer (current-buffer))
519              (location (org-get-local-archive-location))
520              (afile (org-extract-archive-file location))
521              (org-archive-location
522               (format "%s::*** %04d-%02d-%02d %s" afile y m d
523                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
524         (message "afile=%s" afile)
525         (unless afile
526           (error "Invalid `org-archive-location'"))
527         (save-excursion
528           (switch-to-buffer (find-file-noselect afile))
529           (org-datetree-find-year-create y)
530           (org-datetree-find-month-create y m)
531           (org-datetree-find-day-create y m d)
532           (widen)
533           (switch-to-buffer this-buffer))
534         ad-do-it)
535     ad-do-it))
536 #+end_src
538 ** Using and Managing Org-Metadata
539 *** Remove redundant tags of headlines
540 -- David Maus
542 A small function that processes all headlines in current buffer and
543 removes tags that are local to a headline and inherited by a parent
544 headline or the #+FILETAGS: statement.
546 #+BEGIN_SRC emacs-lisp
547   (defun dmj/org-remove-redundant-tags ()
548     "Remove redundant tags of headlines in current buffer.
550   A tag is considered redundant if it is local to a headline and
551   inherited by a parent headline."
552     (interactive)
553     (when (eq major-mode 'org-mode)
554       (save-excursion
555         (org-map-entries
556          '(lambda ()
557             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
558                   local inherited tag)
559               (dolist (tag alltags)
560                 (if (get-text-property 0 'inherited tag)
561                     (push tag inherited) (push tag local)))
562               (dolist (tag local)
563                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
564          t nil))))
565 #+END_SRC
567 *** Remove empty property drawers
569 David Maus proposed this:
571 #+begin_src emacs-lisp
572 (defun dmj:org:remove-empty-propert-drawers ()
573   "*Remove all empty property drawers in current file."
574   (interactive)
575   (unless (eq major-mode 'org-mode)
576     (error "You need to turn on Org mode for this function."))
577   (save-excursion
578     (goto-char (point-min))
579     (while (re-search-forward ":PROPERTIES:" nil t)
580       (save-excursion
581         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
582 #+end_src
584 *** Group task list by a property
586 This advice allows you to group a task list in Org-Mode.  To use it,
587 set the variable =org-agenda-group-by-property= to the name of a
588 property in the option list for a TODO or TAGS search.  The resulting
589 agenda view will group tasks by that property prior to searching.
591 #+begin_src emacs-lisp
592 (defvar org-agenda-group-by-property nil
593   "Set this in org-mode agenda views to group tasks by property")
595 (defun org-group-bucket-items (prop items)
596   (let ((buckets ()))
597     (dolist (item items)
598       (let* ((marker (get-text-property 0 'org-marker item))
599              (pvalue (org-entry-get marker prop t))
600              (cell (assoc pvalue buckets)))
601         (if cell
602             (setcdr cell (cons item (cdr cell)))
603           (setq buckets (cons (cons pvalue (list item))
604                               buckets)))))
605     (setq buckets (mapcar (lambda (bucket)
606                             (cons (car bucket)
607                                   (reverse (cdr bucket))))
608                           buckets))
609     (sort buckets (lambda (i1 i2)
610                     (string< (car i1) (car i2))))))
612 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
613                                                (list &optional nosort))
614   "Prepare bucketed agenda entry lists"
615   (if org-agenda-group-by-property
616       ;; bucketed, handle appropriately
617       (let ((text ""))
618         (dolist (bucket (org-group-bucket-items
619                          org-agenda-group-by-property
620                          list))
621           (let ((header (concat "Property "
622                                 org-agenda-group-by-property
623                                 " is "
624                                 (or (car bucket) "<nil>") ":\n")))
625             (add-text-properties 0 (1- (length header))
626                                  (list 'face 'org-agenda-structure)
627                                  header)
628             (setq text
629                   (concat text header
630                           ;; recursively process
631                           (let ((org-agenda-group-by-property nil))
632                             (org-finalize-agenda-entries
633                              (cdr bucket) nosort))
634                           "\n\n"))))
635         (setq ad-return-value text))
636     ad-do-it))
637 (ad-activate 'org-finalize-agenda-entries)
638 #+end_src
639 *** Dynamically adjust tag position
640 Here is a bit of code that allows you to have the tags always
641 right-adjusted in the buffer.
643 This is useful when you have bigger window than default window-size
644 and you dislike the aesthetics of having the tag in the middle of the
645 line.
647 This hack solves the problem of adjusting it whenever you change the
648 window size.
649 Before saving it will revert the file to having the tag position be
650 left-adjusted so that if you track your files with version control,
651 you won't run into artificial diffs just because the window-size
652 changed.
654 *IMPORTANT*: This is probably slow on very big files.
656 #+begin_src emacs-lisp
657 (setq ba/org-adjust-tags-column t)
659 (defun ba/org-adjust-tags-column-reset-tags ()
660   "In org-mode buffers it will reset tag position according to
661 `org-tags-column'."
662   (when (and
663          (not (string= (buffer-name) "*Remember*"))
664          (eql major-mode 'org-mode))
665     (let ((b-m-p (buffer-modified-p)))
666       (condition-case nil
667           (save-excursion
668             (goto-char (point-min))
669             (command-execute 'outline-next-visible-heading)
670             ;; disable (message) that org-set-tags generates
671             (flet ((message (&rest ignored) nil))
672               (org-set-tags 1 t))
673             (set-buffer-modified-p b-m-p))
674         (error nil)))))
676 (defun ba/org-adjust-tags-column-now ()
677   "Right-adjust `org-tags-column' value, then reset tag position."
678   (set (make-local-variable 'org-tags-column)
679        (- (- (window-width) (length org-ellipsis))))
680   (ba/org-adjust-tags-column-reset-tags))
682 (defun ba/org-adjust-tags-column-maybe ()
683   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
684   (when ba/org-adjust-tags-column
685     (ba/org-adjust-tags-column-now)))
687 (defun ba/org-adjust-tags-column-before-save ()
688   "Tags need to be left-adjusted when saving."
689   (when ba/org-adjust-tags-column
690      (setq org-tags-column 1)
691      (ba/org-adjust-tags-column-reset-tags)))
693 (defun ba/org-adjust-tags-column-after-save ()
694   "Revert left-adjusted tag position done by before-save hook."
695   (ba/org-adjust-tags-column-maybe)
696   (set-buffer-modified-p nil))
698 ; automatically align tags on right-hand side
699 (add-hook 'window-configuration-change-hook
700           'ba/org-adjust-tags-column-maybe)
701 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
702 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
703 (add-hook 'org-agenda-mode-hook '(lambda ()
704                                   (setq org-agenda-tags-column (- (window-width)))))
706 ; between invoking org-refile and displaying the prompt (which
707 ; triggers window-configuration-change-hook) tags might adjust, 
708 ; which invalidates the org-refile cache
709 (defadvice org-refile (around org-refile-disable-adjust-tags)
710   "Disable dynamically adjusting tags"
711   (let ((ba/org-adjust-tags-column nil))
712     ad-do-it))
713 (ad-activate 'org-refile)
714 #+end_src
715 ** Org Agenda and Task Management
716 *** Make it easier to set org-agenda-files from multiple directories
717 - Matt Lundin
719 #+begin_src emacs-lisp
720 (defun my-org-list-files (dirs ext)
721   "Function to create list of org files in multiple subdirectories.
722 This can be called to generate a list of files for
723 org-agenda-files or org-refile-targets.
725 DIRS is a list of directories.
727 EXT is a list of the extensions of files to be included."
728   (let ((dirs (if (listp dirs)
729                   dirs
730                 (list dirs)))
731         (ext (if (listp ext)
732                  ext
733                (list ext)))
734         files)
735     (mapc 
736      (lambda (x)
737        (mapc 
738         (lambda (y)
739           (setq files 
740                 (append files 
741                         (file-expand-wildcards 
742                          (concat (file-name-as-directory x) "*" y)))))
743         ext))
744      dirs)
745     (mapc
746      (lambda (x)
747        (when (or (string-match "/.#" x)
748                  (string-match "#$" x))
749          (setq files (delete x files))))
750      files)
751     files))
753 (defvar my-org-agenda-directories '("~/org/")
754   "List of directories containing org files.")
755 (defvar my-org-agenda-extensions '(".org")
756   "List of extensions of agenda files")
758 (setq my-org-agenda-directories '("~/org/" "~/work/"))
759 (setq my-org-agenda-extensions '(".org" ".ref"))
761 (defun my-org-set-agenda-files ()
762   (interactive)
763   (setq org-agenda-files (my-org-list-files 
764                           my-org-agenda-directories
765                           my-org-agenda-extensions)))
767 (my-org-set-agenda-files)
768 #+end_src
770 The code above will set your "default" agenda files to all files
771 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
772 You can change these values by setting the variables
773 my-org-agenda-extensions and my-org-agenda-directories. The function
774 my-org-agenda-files-by-filetag uses these two variables to determine
775 which files to search for filetags (i.e., the larger set from which
776 the subset will be drawn).
778 You can also easily use my-org-list-files to "mix and match"
779 directories and extensions to generate different lists of agenda
780 files.
782 *** Restrict org-agenda-files by filetag
783   :PROPERTIES:
784   :CUSTOM_ID: set-agenda-files-by-filetag
785   :END:
786 - Matt Lundin
788 It is often helpful to limit yourself to a subset of your agenda
789 files. For instance, at work, you might want to see only files related
790 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
791 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
792 commands]]. These solutions, however, require reapplying a filter each
793 time you call the agenda or writing several new custom agenda commands
794 for each context. Another solution is to use directories for different
795 types of tasks and to change your agenda files with a function that
796 sets org-agenda-files to the appropriate directory. But this relies on
797 hard and static boundaries between files.
799 The following functions allow for a more dynamic approach to selecting
800 a subset of files based on filetags:
802 #+begin_src emacs-lisp
803 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
804   "Restrict org agenda files only to those containing filetag."
805   (interactive)
806   (let* ((tagslist (my-org-get-all-filetags))
807          (ftag (or tag 
808                    (completing-read "Tag: " 
809                                     (mapcar 'car tagslist)))))
810     (org-agenda-remove-restriction-lock 'noupdate)
811     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
812     (setq org-agenda-overriding-restriction 'files)))
814 (defun my-org-get-all-filetags ()
815   "Get list of filetags from all default org-files."
816   (let ((files org-agenda-files)
817         tagslist x)
818     (save-window-excursion
819       (while (setq x (pop files))
820         (set-buffer (find-file-noselect x))
821         (mapc
822          (lambda (y)
823            (let ((tagfiles (assoc y tagslist)))
824              (if tagfiles
825                  (setcdr tagfiles (cons x (cdr tagfiles)))
826                (add-to-list 'tagslist (list y x)))))
827          (my-org-get-filetags)))
828       tagslist)))
830 (defun my-org-get-filetags ()
831   "Get list of filetags for current buffer"
832   (let ((ftags org-file-tags)
833         x)
834     (mapcar 
835      (lambda (x)
836        (org-substring-no-properties x))
837      ftags)))
838 #+end_src
840 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
841 with all filetags in your "normal" agenda files. When you select a
842 tag, org-agenda-files will be restricted to only those files
843 containing the filetag. To release the restriction, type C-c C-x >
844 (org-agenda-remove-restriction-lock).
846 *** Highlight the agenda line under cursor
848 This is useful to make sure what task you are operating on.
850 #+BEGIN_SRC emacs-lisp
851 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
852 #+END_SRC emacs-lisp
854 Under XEmacs:
856 #+BEGIN_SRC emacs-lisp
857 ;; hl-line seems to be only for emacs
858 (require 'highline)
859 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
861 ;; highline-mode does not work straightaway in tty mode.
862 ;; I use a black background
863 (custom-set-faces
864   '(highline-face ((((type tty) (class color))
865                     (:background "white" :foreground "black")))))
866 #+END_SRC emacs-lisp
868 *** Split horizontally for agenda
870 If you would like to split the frame into two side-by-side windows when
871 displaying the agenda, try this hack from Jan Rehders, which uses the
872 `toggle-window-split' from
874 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
876 #+BEGIN_SRC emacs-lisp
877 ;; Patch org-mode to use vertical splitting
878 (defadvice org-prepare-agenda (after org-fix-split)
879   (toggle-window-split))
880 (ad-activate 'org-prepare-agenda)
881 #+END_SRC
883 *** Automatically add an appointment when clocking in a task
885 #+BEGIN_SRC emacs-lisp
886 ;; Make sure you have a sensible value for `appt-message-warning-time'
887 (defvar bzg-org-clock-in-appt-delay 100
888   "Number of minutes for setting an appointment by clocking-in")
889 #+END_SRC
891 This function let's you add an appointment for the current entry.
892 This can be useful when you need a reminder.
894 #+BEGIN_SRC emacs-lisp
895 (defun bzg-org-clock-in-add-appt (&optional n)
896   "Add an appointment for the Org entry at point in N minutes."
897   (interactive)
898   (save-excursion
899     (org-back-to-heading t)
900     (looking-at org-complex-heading-regexp)
901     (let* ((msg (match-string-no-properties 4))
902            (ct-time (decode-time))
903            (appt-min (+ (cadr ct-time)
904                         (or n bzg-org-clock-in-appt-delay)))
905            (appt-time ; define the time for the appointment
906             (progn (setf (cadr ct-time) appt-min) ct-time)))
907       (appt-add (format-time-string
908                  "%H:%M" (apply 'encode-time appt-time)) msg)
909       (if (interactive-p) (message "New appointment for %s" msg)))))
910 #+END_SRC
912 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
913 add an appointment:
915 #+BEGIN_SRC emacs-lisp
916 (defadvice org-clock-in (after org-clock-in-add-appt activate)
917   "Add an appointment when clocking a task in."
918   (bzg-org-clock-in-add-appt))
919 #+END_SRC
921 You may also want to delete the associated appointment when clocking
922 out.  This function does this:
924 #+BEGIN_SRC emacs-lisp
925 (defun bzg-org-clock-out-delete-appt nil
926   "When clocking out, delete any associated appointment."
927   (interactive)
928   (save-excursion
929     (org-back-to-heading t)
930     (looking-at org-complex-heading-regexp)
931     (let* ((msg (match-string-no-properties 4)))
932       (setq appt-time-msg-list
933             (delete nil
934                     (mapcar
935                      (lambda (appt)
936                        (if (not (string-match (regexp-quote msg)
937                                               (cadr appt))) appt))
938                      appt-time-msg-list)))
939       (appt-check))))
940 #+END_SRC
942 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
944 #+BEGIN_SRC emacs-lisp
945 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
946   "Delete an appointment when clocking a task out."
947   (bzg-org-clock-out-delete-appt))
948 #+END_SRC
950 *IMPORTANT*: You can add appointment by clocking in in both an
951 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
952 agenda buffer with the advice above will bring an error.
954 *** Remove time grid lines that are in an appointment
956 The agenda shows lines for the time grid.  Some people think that
957 these lines are a distraction when there are appointments at those
958 times.  You can get rid of the lines which coincide exactly with the
959 beginning of an appointment.  Michael Ekstrand has written a piece of
960 advice that also removes lines that are somewhere inside an
961 appointment:
963 #+begin_src emacs-lisp
964 (defun org-time-to-minutes (time)
965   "Convert an HHMM time to minutes"
966   (+ (* (/ time 100) 60) (% time 100)))
968 (defun org-time-from-minutes (minutes)
969   "Convert a number of minutes to an HHMM time"
970   (+ (* (/ minutes 60) 100) (% minutes 60)))
972 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
973                                                   (list ndays todayp))
974   (if (member 'remove-match (car org-agenda-time-grid))
975       (flet ((extract-window
976               (line)
977               (let ((start (get-text-property 1 'time-of-day line))
978                     (dur (get-text-property 1 'duration line)))
979                 (cond
980                  ((and start dur)
981                   (cons start
982                         (org-time-from-minutes
983                          (+ dur (org-time-to-minutes start)))))
984                  (start start)
985                  (t nil)))))
986         (let* ((windows (delq nil (mapcar 'extract-window list)))
987                (org-agenda-time-grid
988                 (list (car org-agenda-time-grid)
989                       (cadr org-agenda-time-grid)
990                       (remove-if
991                        (lambda (time)
992                          (find-if (lambda (w)
993                                     (if (numberp w)
994                                         (equal w time)
995                                       (and (>= time (car w))
996                                            (< time (cdr w)))))
997                                   windows))
998                        (caddr org-agenda-time-grid)))))
999           ad-do-it))
1000     ad-do-it))
1001 (ad-activate 'org-agenda-add-time-grid-maybe)
1002 #+end_src
1003 *** Disable vc for Org mode agenda files
1004 -- David Maus
1006 Even if you use Git to track your agenda files you might not need
1007 vc-mode to be enabled for these files.
1009 #+begin_src emacs-lisp
1010 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1011 (defun dmj/disable-vc-for-agenda-files-hook ()
1012   "Disable vc-mode for Org agenda files."
1013   (if (and (fboundp 'org-agenda-file-p)
1014            (org-agenda-file-p (buffer-file-name)))
1015       (remove-hook 'find-file-hook 'vc-find-file-hook)
1016     (add-hook 'find-file-hook 'vc-find-file-hook)))
1017 #+end_src
1019 *** Easy customization of TODO colors
1020 -- Ryan C. Thompson
1022 Here is some code I came up with some code to make it easier to
1023 customize the colors of various TODO keywords. As long as you just
1024 want a different color and nothing else, you can customize the
1025 variable org-todo-keyword-faces and use just a string color (i.e. a
1026 string of the color name) as the face, and then org-get-todo-face
1027 will convert the color to a face, inheriting everything else from
1028 the standard org-todo face.
1030 To demonstrate, I currently have org-todo-keyword-faces set to
1032 #+BEGIN_SRC emacs-lisp
1033 (("IN PROGRESS" . "dark orange")
1034  ("WAITING" . "red4")
1035  ("CANCELED" . "saddle brown"))
1036 #+END_SRC emacs-lisp
1038   Here's the code, in a form you can put in your =.emacs=
1040 #+BEGIN_SRC emacs-lisp
1041 (eval-after-load 'org-faces
1042  '(progn
1043     (defcustom org-todo-keyword-faces nil
1044       "Faces for specific TODO keywords.
1045 This is a list of cons cells, with TODO keywords in the car and
1046 faces in the cdr.  The face can be a symbol, a color, or a
1047 property list of attributes, like (:foreground \"blue\" :weight
1048 bold :underline t)."
1049       :group 'org-faces
1050       :group 'org-todo
1051       :type '(repeat
1052               (cons
1053                (string :tag "Keyword")
1054                (choice color (sexp :tag "Face")))))))
1056 (eval-after-load 'org
1057  '(progn
1058     (defun org-get-todo-face-from-color (color)
1059       "Returns a specification for a face that inherits from org-todo
1060  face and has the given color as foreground. Returns nil if
1061  color is nil."
1062       (when color
1063         `(:inherit org-warning :foreground ,color)))
1065     (defun org-get-todo-face (kwd)
1066       "Get the right face for a TODO keyword KWD.
1067 If KWD is a number, get the corresponding match group."
1068       (if (numberp kwd) (setq kwd (match-string kwd)))
1069       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1070             (if (stringp face)
1071                 (org-get-todo-face-from-color face)
1072               face))
1073           (and (member kwd org-done-keywords) 'org-done)
1074           'org-todo))))
1075 #+END_SRC emacs-lisp
1077 *** Add an effort estimate on the fly when clocking in
1079 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1080 This way you can easily have a "tea-timer" for your tasks when they
1081 don't already have an effort estimate.
1083 #+begin_src emacs-lisp
1084 (add-hook 'org-clock-in-prepare-hook
1085           'my-org-mode-ask-effort)
1087 (defun my-org-mode-ask-effort ()
1088   "Ask for an effort estimate when clocking in."
1089   (unless (org-entry-get (point) "Effort")
1090     (let ((effort
1091            (completing-read
1092             "Effort: "
1093             (org-entry-get-multivalued-property (point) "Effort"))))
1094       (unless (equal effort "")
1095         (org-set-property "Effort" effort)))))
1096 #+end_src
1098 Or you can use a default effort for such a timer:
1100 #+begin_src emacs-lisp
1101 (add-hook 'org-clock-in-prepare-hook
1102           'my-org-mode-add-default-effort)
1104 (defvar org-clock-default-effort "1:00")
1106 (defun my-org-mode-add-default-effort ()
1107   "Add a default effort estimation."
1108   (unless (org-entry-get (point) "Effort")
1109     (org-set-property "Effort" org-clock-default-effort)))
1110 #+end_src
1112 *** Refresh the agenda view regurally
1114 Hack sent by Kiwon Um:
1116 #+begin_src emacs-lisp
1117 (defun kiwon/org-agenda-redo-in-other-window ()
1118   "Call org-agenda-redo function even in the non-agenda buffer."
1119   (interactive)
1120   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1121     (when agenda-window
1122       (with-selected-window agenda-window (org-agenda-redo)))))
1123 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1124 #+end_src
1126 *** Reschedule agenda items to today with a single command
1128 This was suggested by Carsten in reply to David Abrahams:
1130 #+begin_example emacs-lisp
1131 (defun org-agenda-reschedule-to-today ()
1132   (interactive)
1133   (flet ((org-read-date (&rest rest) (current-time)))
1134     (call-interactively 'org-agenda-schedule)))
1135 #+end_example
1137 * Hacking Org: Working with Org-mode and other Emacs Packages.
1138 ** org-remember-anything
1140 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1142 #+BEGIN_SRC emacs-lisp
1143 (defvar org-remember-anything
1144   '((name . "Org Remember")
1145     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1146     (action . (lambda (name)
1147                 (let* ((orig-template org-remember-templates)
1148                        (org-remember-templates
1149                         (list (assoc name orig-template))))
1150                   (call-interactively 'org-remember))))))
1151 #+END_SRC
1153 You can add it to your 'anything-sources' variable and open remember directly
1154 from anything. I imagine this would be more interesting for people with many
1155 remember templatesm, so that you are out of keys to assign those to. You should
1156 get something like this:
1158 [[file:images/thumbs/org-remember-anything.png]]
1160 ** Org-mode and saveplace.el
1162 Fix a problem with saveplace.el putting you back in a folded position:
1164 #+begin_src emacs-lisp
1165 (add-hook 'org-mode-hook
1166           (lambda ()
1167             (when (outline-invisible-p)
1168               (save-excursion
1169                 (outline-previous-visible-heading 1)
1170                 (org-show-subtree)))))
1171 #+end_src
1173 ** Using ido-completing-read to find attachments
1174 -- Matt Lundin
1176 Org-attach is great for quickly linking files to a project. But if you
1177 use org-attach extensively you might find yourself wanting to browse
1178 all the files you've attached to org headlines. This is not easy to do
1179 manually, since the directories containing the files are not human
1180 readable (i.e., they are based on automatically generated ids). Here's
1181 some code to browse those files using ido (obviously, you need to be
1182 using ido):
1184 #+begin_src emacs-lisp
1185 (load-library "find-lisp")
1187 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1189 (defun my-ido-find-org-attach ()
1190   "Find files in org-attachment directory"
1191   (interactive)
1192   (let* ((enable-recursive-minibuffers t)
1193          (files (find-lisp-find-files org-attach-directory "."))
1194          (file-assoc-list
1195           (mapcar (lambda (x)
1196                     (cons (file-name-nondirectory x)
1197                           x))
1198                   files))
1199          (filename-list
1200           (remove-duplicates (mapcar #'car file-assoc-list)
1201                              :test #'string=))
1202          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1203          (longname (cdr (assoc filename file-assoc-list))))
1204     (ido-set-current-directory
1205      (if (file-directory-p longname)
1206          longname
1207        (file-name-directory longname)))
1208     (setq ido-exit 'refresh
1209           ido-text-init ido-text
1210           ido-rotate-temp t)
1211     (exit-minibuffer)))
1213 (add-hook 'ido-setup-hook 'ido-my-keys)
1215 (defun ido-my-keys ()
1216   "Add my keybindings for ido."
1217   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1218 #+end_src
1220 To browse your org attachments using ido fuzzy matching and/or the
1221 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1222 press =C-;=.
1224 ** Use idle timer for automatic agenda views
1226 From John Wiegley's mailing list post (March 18, 2010):
1228 #+begin_quote
1229 I have the following snippet in my .emacs file, which I find very
1230 useful. Basically what it does is that if I don't touch my Emacs for 5
1231 minutes, it displays the current agenda. This keeps my tasks "always
1232 in mind" whenever I come back to Emacs after doing something else,
1233 whereas before I had a tendency to forget that it was there.
1234 #+end_quote  
1236   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1238 #+begin_src emacs-lisp
1239 (defun jump-to-org-agenda ()
1240   (interactive)
1241   (let ((buf (get-buffer "*Org Agenda*"))
1242         wind)
1243     (if buf
1244         (if (setq wind (get-buffer-window buf))
1245             (select-window wind)
1246           (if (called-interactively-p)
1247               (progn
1248                 (select-window (display-buffer buf t t))
1249                 (org-fit-window-to-buffer)
1250                 ;; (org-agenda-redo)
1251                 )
1252             (with-selected-window (display-buffer buf)
1253               (org-fit-window-to-buffer)
1254               ;; (org-agenda-redo)
1255               )))
1256       (call-interactively 'org-agenda-list)))
1257   ;;(let ((buf (get-buffer "*Calendar*")))
1258   ;;  (unless (get-buffer-window buf)
1259   ;;    (org-agenda-goto-calendar)))
1260   )
1261   
1262 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1263 #+end_src
1265 #+results:
1266 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1268 ** Link to Gnus messages by Message-Id
1270 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1271 discussion about linking to Gnus messages without encoding the folder
1272 name in the link.  The following code hooks in to the store-link
1273 function in Gnus to capture links by Message-Id when in nnml folders,
1274 and then provides a link type "mid" which can open this link.  The
1275 =mde-org-gnus-open-message-link= function uses the
1276 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1277 scan.  It will go through them, in order, asking each to locate the
1278 message and opening it from the first one that reports success.
1280 It has only been tested with a single nnml backend, so there may be
1281 bugs lurking here and there.
1283 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1284 article]].
1286 #+begin_src emacs-lisp
1287 ;; Support for saving Gnus messages by Message-ID
1288 (defun mde-org-gnus-save-by-mid ()
1289   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1290     (when (eq major-mode 'gnus-article-mode)
1291       (gnus-article-show-summary))
1292     (let* ((group gnus-newsgroup-name)
1293            (method (gnus-find-method-for-group group)))
1294       (when (eq 'nnml (car method))
1295         (let* ((article (gnus-summary-article-number))
1296                (header (gnus-summary-article-header article))
1297                (from (mail-header-from header))
1298                (message-id
1299                 (save-match-data
1300                   (let ((mid (mail-header-id header)))
1301                     (if (string-match "<\\(.*\\)>" mid)
1302                         (match-string 1 mid)
1303                       (error "Malformed message ID header %s" mid)))))
1304                (date (mail-header-date header))
1305                (subject (gnus-summary-subject-string)))
1306           (org-store-link-props :type "mid" :from from :subject subject
1307                                 :message-id message-id :group group
1308                                 :link (org-make-link "mid:" message-id))
1309           (apply 'org-store-link-props
1310                  :description (org-email-link-description)
1311                  org-store-link-plist)
1312           t)))))
1314 (defvar mde-mid-resolve-methods '()
1315   "List of methods to try when resolving message ID's.  For Gnus,
1316 it is a cons of 'gnus and the select (type and name).")
1317 (setq mde-mid-resolve-methods
1318       '((gnus nnml "")))
1320 (defvar mde-org-gnus-open-level 1
1321   "Level at which Gnus is started when opening a link")
1322 (defun mde-org-gnus-open-message-link (msgid)
1323   "Open a message link with Gnus"
1324   (require 'gnus)
1325   (require 'org-table)
1326   (catch 'method-found
1327     (message "[MID linker] Resolving %s" msgid)
1328     (dolist (method mde-mid-resolve-methods)
1329       (cond
1330        ((and (eq (car method) 'gnus)
1331              (eq (cadr method) 'nnml))
1332         (funcall (cdr (assq 'gnus org-link-frame-setup))
1333                  mde-org-gnus-open-level)
1334         (when gnus-other-frame-object
1335           (select-frame gnus-other-frame-object))
1336         (let* ((msg-info (nnml-find-group-number
1337                           (concat "<" msgid ">")
1338                           (cdr method)))
1339                (group (and msg-info (car msg-info)))
1340                (message (and msg-info (cdr msg-info)))
1341                (qname (and group
1342                            (if (gnus-methods-equal-p
1343                                 (cdr method)
1344                                 gnus-select-method)
1345                                group
1346                              (gnus-group-full-name group (cdr method))))))
1347           (when msg-info
1348             (gnus-summary-read-group qname nil t)
1349             (gnus-summary-goto-article message nil t))
1350           (throw 'method-found t)))
1351        (t (error "Unknown link type"))))))
1353 (eval-after-load 'org-gnus
1354   '(progn
1355      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1356      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1357 #+end_src
1359 ** Store link upon sending a message in Gnus
1361 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1363 #+begin_src emacs-lisp
1364 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1365   "Send message with `message-send-and-exit' and store org link to message copy.
1366 If multiple groups appear in the Gcc header, the link refers to
1367 the copy in the last group."
1368   (interactive "P")
1369     (save-excursion
1370       (save-restriction
1371         (message-narrow-to-headers)
1372         (let ((gcc (car (last
1373                          (message-unquote-tokens
1374                           (message-tokenize-header
1375                            (mail-fetch-field "gcc" nil t) " ,")))))
1376               (buf (current-buffer))
1377               (message-kill-buffer-on-exit nil)
1378               id to from subject desc link newsgroup xarchive)
1379         (message-send-and-exit arg)
1380         (or
1381          ;; gcc group found ...
1382          (and gcc
1383               (save-current-buffer
1384                 (progn (set-buffer buf)
1385                        (setq id (org-remove-angle-brackets
1386                                  (mail-fetch-field "Message-ID")))
1387                        (setq to (mail-fetch-field "To"))
1388                        (setq from (mail-fetch-field "From"))
1389                        (setq subject (mail-fetch-field "Subject"))))
1390               (org-store-link-props :type "gnus" :from from :subject subject
1391                                     :message-id id :group gcc :to to)
1392               (setq desc (org-email-link-description))
1393               (setq link (org-gnus-article-link
1394                           gcc newsgroup id xarchive))
1395               (setq org-stored-links
1396                     (cons (list link desc) org-stored-links)))
1397          ;; no gcc group found ...
1398          (message "Can not create Org link: No Gcc header found."))))))
1400 (define-key message-mode-map [(control c) (control meta c)]
1401   'ulf-message-send-and-org-gnus-store-link)
1402 #+end_src
1404 ** Send html messages and attachments with Wanderlust
1405   -- David Maus
1407 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1408 similar functionality for both Wanderlust and Gnus.  The hack below is
1409 still somewhat different: It allows you to toggle sending of html
1410 messages within Wanderlust transparently.  I.e. html markup of the
1411 message body is created right before sending starts.
1413 *** Send HTML message
1415 Putting the code below in your .emacs adds following four functions:
1417 - dmj/wl-send-html-message
1419   Function that does the job: Convert everything between "--text
1420   follows this line--" and first mime entity (read: attachment) or
1421   end of buffer into html markup using `org-export-region-as-html'
1422   and replaces original body with a multipart MIME entity with the
1423   plain text version of body and the html markup version.  Thus a
1424   recipient that prefers html messages can see the html markup,
1425   recipients that prefer or depend on plain text can see the plain
1426   text.
1428   Cannot be called interactively: It is hooked into SEMI's
1429   `mime-edit-translate-hook' if message should be HTML message.
1431 - dmj/wl-send-html-message-draft-init
1433   Cannot be called interactively: It is hooked into WL's
1434   `wl-mail-setup-hook' and provides a buffer local variable to
1435   toggle.
1437 - dmj/wl-send-html-message-draft-maybe
1439   Cannot be called interactively: It is hooked into WL's
1440   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1441   `mime-edit-translate-hook' depending on whether HTML message is
1442   toggled on or off
1444 - dmj/wl-send-html-message-toggle
1446   Toggles sending of HTML message.  If toggled on, the letters
1447   "HTML" appear in the mode line.
1449   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1451 If you have to send HTML messages regularly you can set a global
1452 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1453 toggle on sending HTML message by default.
1455 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1456 Google's web front end.  As you can see you have the whole markup of
1457 Org at your service: *bold*, /italics/, tables, lists...
1459 So even if you feel uncomfortable with sending HTML messages at least
1460 you send HTML that looks quite good.
1462 #+begin_src emacs-lisp
1463 (defun dmj/wl-send-html-message ()
1464   "Send message as html message.
1465 Convert body of message to html using
1466   `org-export-region-as-html'."
1467   (require 'org)
1468   (save-excursion
1469     (let (beg end html text)
1470       (goto-char (point-min))
1471       (re-search-forward "^--text follows this line--$")
1472       ;; move to beginning of next line
1473       (beginning-of-line 2)
1474       (setq beg (point))
1475       (if (not (re-search-forward "^--\\[\\[" nil t))
1476           (setq end (point-max))
1477         ;; line up
1478         (end-of-line 0)
1479         (setq end (point)))
1480       ;; grab body
1481       (setq text (buffer-substring-no-properties beg end))
1482       ;; convert to html
1483       (with-temp-buffer
1484         (org-mode)
1485         (insert text)
1486         ;; handle signature
1487         (when (re-search-backward "^-- \n" nil t)
1488           ;; preserve link breaks in signature
1489           (insert "\n#+BEGIN_VERSE\n")
1490           (goto-char (point-max))
1491           (insert "\n#+END_VERSE\n")
1492           ;; grab html
1493           (setq html (org-export-region-as-html
1494                       (point-min) (point-max) t 'string))))
1495       (delete-region beg end)
1496       (insert
1497        (concat
1498         "--" "<<alternative>>-{\n"
1499         "--" "[[text/plain]]\n" text
1500         "--" "[[text/html]]\n"  html
1501         "--" "}-<<alternative>>\n")))))
1503 (defun dmj/wl-send-html-message-toggle ()
1504   "Toggle sending of html message."
1505   (interactive)
1506   (setq dmj/wl-send-html-message-toggled-p
1507         (if dmj/wl-send-html-message-toggled-p
1508             nil "HTML"))
1509   (message "Sending html message toggled %s"
1510            (if dmj/wl-send-html-message-toggled-p
1511                "on" "off")))
1513 (defun dmj/wl-send-html-message-draft-init ()
1514   "Create buffer local settings for maybe sending html message."
1515   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1516     (setq dmj/wl-send-html-message-toggled-p nil))
1517   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1518   (add-to-list 'global-mode-string
1519                '(:eval (if (eq major-mode 'wl-draft-mode)
1520                            dmj/wl-send-html-message-toggled-p))))
1522 (defun dmj/wl-send-html-message-maybe ()
1523   "Maybe send this message as html message.
1525 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1526 non-nil, add `dmj/wl-send-html-message' to
1527 `mime-edit-translate-hook'."
1528   (if dmj/wl-send-html-message-toggled-p
1529       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1530     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1532 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1533 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1534 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1535 #+end_src
1537 *** Attach HTML of region or subtree
1539 Instead of sending a complete HTML message you might only send parts
1540 of an Org file as HTML for the poor souls who are plagued with
1541 non-proportional fonts in their mail program that messes up pretty
1542 ASCII tables.
1544 This short function does the trick: It exports region or subtree to
1545 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1546 and clipboard.  If a region is active, it uses the region, the
1547 complete subtree otherwise.
1549 #+begin_src emacs-lisp
1550 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1551   "Export region between BEG and END as html attachment.
1552 If BEG and END are not set, use current subtree.  Region or
1553 subtree is exported to html without header and footer, prefixed
1554 with a mime entity string and pushed to clipboard and killring.
1555 When called with prefix, mime entity is not marked as
1556 attachment."
1557   (interactive "r\nP")
1558   (save-excursion
1559     (let* ((beg (if (region-active-p) (region-beginning)
1560                   (progn
1561                     (org-back-to-heading)
1562                     (point))))
1563            (end (if (region-active-p) (region-end)
1564                   (progn
1565                     (org-end-of-subtree)
1566                     (point))))
1567            (html (concat "--[[text/html"
1568                          (if arg "" "\nContent-Disposition: attachment")
1569                          "]]\n"
1570                          (org-export-region-as-html beg end t 'string))))
1571       (when (fboundp 'x-set-selection)
1572         (ignore-errors (x-set-selection 'PRIMARY html))
1573         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1574       (message "html export done, pushed to kill ring and clipboard"))))
1575 #+end_src
1577 *** Adopting for Gnus
1579 The whole magic lies in the special strings that mark a HTML
1580 attachment.  So you might just have to find out what these special
1581 strings are in message-mode and modify the functions accordingly.
1582 * Hacking Org: Working with Org-mode and External Programs.
1583 ** Use Org-mode with Screen [Andrew Hyatt]
1585 "The general idea is that you start a task in which all the work will
1586 take place in a shell.  This usually is not a leaf-task for me, but
1587 usually the parent of a leaf task.  From a task in your org-file, M-x
1588 ash-org-screen will prompt for the name of a session.  Give it a name,
1589 and it will insert a link.  Open the link at any time to go the screen
1590 session containing your work!"
1592 http://article.gmane.org/gmane.emacs.orgmode/5276
1594 #+BEGIN_SRC emacs-lisp
1595 (require 'term)
1597 (defun ash-org-goto-screen (name)
1598   "Open the screen with the specified name in the window"
1599   (interactive "MScreen name: ")
1600   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1601     (if (member screen-buffer-name
1602                 (mapcar 'buffer-name (buffer-list)))
1603         (switch-to-buffer screen-buffer-name)
1604       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1606 (defun ash-org-screen-buffer-name (name)
1607   "Returns the buffer name corresponding to the screen name given."
1608   (concat "*screen " name "*"))
1610 (defun ash-org-screen-helper (name arg)
1611   ;; Pick the name of the new buffer.
1612   (let ((term-ansi-buffer-name
1613          (generate-new-buffer-name
1614           (ash-org-screen-buffer-name name))))
1615     (setq term-ansi-buffer-name
1616           (term-ansi-make-term
1617            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1618     (set-buffer term-ansi-buffer-name)
1619     (term-mode)
1620     (term-char-mode)
1621     (term-set-escape-char ?\C-x)
1622     term-ansi-buffer-name))
1624 (defun ash-org-screen (name)
1625   "Start a screen session with name"
1626   (interactive "MScreen name: ")
1627   (save-excursion
1628     (ash-org-screen-helper name "-S"))
1629   (insert-string (concat "[[screen:" name "]]")))
1631 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1632 ;; \"%s\")") to org-link-abbrev-alist.
1633 #+END_SRC
1635 ** Org Agenda + Appt + Zenity
1637 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It make sure your agenda
1638 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1639 popup window.
1641 #+BEGIN_SRC emacs-lisp
1642 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1643 ; For org appointment reminders
1645 ;; Get appointments for today
1646 (defun my-org-agenda-to-appt ()
1647   (interactive)
1648   (setq appt-time-msg-list nil)
1649   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
1650         (org-agenda-to-appt)))
1652 ;; Run once, activate and schedule refresh
1653 (my-org-agenda-to-appt)
1654 (appt-activate t)
1655 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
1657 ; 5 minute warnings
1658 (setq appt-message-warning-time 15)
1659 (setq appt-display-interval 5)
1661 ; Update appt each time agenda opened.
1662 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
1664 ; Setup zenify, we tell appt to use window, and replace default function
1665 (setq appt-display-format 'window)
1666 (setq appt-disp-window-function (function my-appt-disp-window))
1668 (defun my-appt-disp-window (min-to-app new-time msg)
1669   (save-window-excursion (shell-command (concat
1670     "/usr/bin/zenity --info --title='Appointment' --text='"
1671     msg "' &") nil nil)))
1672 #+END_SRC
1674 ** Org-Mode + gnome-osd
1676 Richard Riley uses gnome-osd in interaction with Org-Mode to display
1677 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
1679 ** remind2org
1681 From Detlef Steuer
1683 http://article.gmane.org/gmane.emacs.orgmode/5073
1685 #+BEGIN_QUOTE
1686 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
1687 command line calendaring program. Its features superseed the possibilities
1688 of orgmode in the area of date specifying, so that I want to use it
1689 combined with orgmode.
1691 Using the script below I'm able use remind and incorporate its output in my
1692 agenda views.  The default of using 13 months look ahead is easily
1693 changed. It just happens I sometimes like to look a year into the
1694 future. :-)
1695 #+END_QUOTE
1697 ** Useful webjumps for conkeror
1699 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
1700 your =~/.conkerorrc= file:
1702 #+begin_example
1703 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
1704 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
1705 #+end_example
1707 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
1708 Org-mode mailing list.
1710 ** Use MathJax for HTML export without requiring JavaScript
1711 As of 2010-08-14, MathJax is the default method used to export math to HTML.
1713 If you like the results but do not want JavaScript in the exported pages,
1714 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
1715 HTML file from the exported version. It can also embed all referenced fonts
1716 within the HTML file itself, so there are no dependencies to external files.
1718 The download archive contains an elisp file which integrates it into the Org
1719 export process (configurable per file with a "#+StaticMathJax:" line).
1721 Read README.org and the comments in org-static-mathjax.el for usage instructions.
1722 ** Search Org files using lgrep
1724 Matt Lundi suggests this:
1726 #+begin_src emacs-lisp
1727   (defun my-org-grep (search &optional context)
1728     "Search for word in org files. 
1730 Prefix argument determines number of lines."
1731     (interactive "sSearch for: \nP")
1732     (let ((grep-find-ignored-files '("#*" ".#*"))
1733           (grep-template (concat "grep <X> -i -nH " 
1734                                  (when context
1735                                    (concat "-C" (number-to-string context)))
1736                                  " -e <R> <F>")))
1737       (lgrep search "*org*" "/home/matt/org/")))
1739   (global-set-key (kbd "<f8>") 'my-org-grep)
1740 #+end_src