worg.css: use Jason style.
[Worg.git] / org-hacks.org
blob12d661507a14950dd5d7353afe1fc37e96f01d88
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
261 **** Transpose tables (Juan Pechiar)
263 This function by Juan Pechiar will transpose a table:
265 #+begin_src emacs-lisp
266 (defun org-transpose-table-at-point ()
267   "Transpose orgmode table at point, eliminate hlines"
268   (interactive)
269   (let ((contents 
270          (apply #'mapcar* #'list
271                 ;; remove 'hline from list
272                 (remove-if-not 'listp  
273                                ;; signals error if not table
274                                (org-table-to-lisp)))))
275     (delete-region (org-table-begin) (org-table-end))
276     (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) "  |\n" ))
277                        contents ""))
278     (org-table-align)))
279 #+end_src
281 So a table like
283 : | 1 | 2 | 4 | 5 |
284 : |---+---+---+---|
285 : | a | b | c | d |
286 : | e | f | g | h |
288 will be transposed as
290 : | 1 | a | e |
291 : | 2 | b | f |
292 : | 4 | c | g |
293 : | 5 | d | h |
295 (Note that horizontal lines disappeared.)
297 *** Dates computation
299 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
301 I have a table in org which stores the date, I'm wondering if there is
302 any function to calculate the duration? For example:
304 | Start Date |   End Date | Duration |
305 |------------+------------+----------|
306 | 2004.08.07 | 2005.07.08 |          |
308 I tried to use B&-C&, but failed ...
310 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
312 Try the following:
314 | Start Date |   End Date | Duration |
315 |------------+------------+----------|
316 | 2004.08.07 | 2005.07.08 |      335 |
317 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
319 See this thread:
321     http://thread.gmane.org/gmane.emacs.orgmode/7741
323 as well as this post (which is really a followup on the
324 above):
326     http://article.gmane.org/gmane.emacs.orgmode/7753
328 The problem that this last article pointed out was solved
331     http://article.gmane.org/gmane.emacs.orgmode/8001
333 and Chris Randle's original musings are at
335     http://article.gmane.org/gmane.emacs.orgmode/6536/
337 *** Field coordinates in formulas (=@#= and =$#=)
339 -- Michael Brand
341 Following are some use cases that can be implemented with the
342 _field coordinates in formulas_ described in the corresponding
343 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
345 **** Copy a column from a remote table into a column
347 current column =$3= = remote column =$2=:
348 : #+TBLFM: $3 = remote(FOO, @@#$2)
350 **** Copy a row from a remote table transposed into a column
352 current column =$1= = transposed remote row =@1=:
353 : #+TBLFM: $1 = remote(FOO, @$#$@#)
355 **** Transpose a table
357 -- Michael Brand
359 This is more like a demonstration of using _field coordinates in formulas_
360 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel.  The efficient
361 and simple solution for this with the help of org-babel and Emacs Lisp has
362 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
364 To transpose this 4x7 table
366 : #+TBLNAME: FOO
367 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
368 : |------+------+------+------+------+------+------|
369 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
370 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
371 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
373 start with a 7x4 table without any horizontal line (to have filled
374 also the column header) and yet empty:
376 : |   |   |   |   |
377 : |   |   |   |   |
378 : |   |   |   |   |
379 : |   |   |   |   |
380 : |   |   |   |   |
381 : |   |   |   |   |
382 : |   |   |   |   |
384 Then add the =TBLFM= below with the same formula repeated for each column.
385 After recalculation this will end up with the transposed copy:
387 : | year | min | avg | max |
388 : | 2004 | 401 | 402 | 403 |
389 : | 2005 | 501 | 502 | 503 |
390 : | 2006 | 601 | 602 | 603 |
391 : | 2007 | 701 | 702 | 703 |
392 : | 2008 | 801 | 802 | 803 |
393 : | 2009 | 901 | 902 | 903 |
394 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
396 The formulas simply exchange row and column numbers by taking
397 - the absolute remote row number =@$#= from the current column number =$#=
398 - the absolute remote column number =$@#= from the current row number =@#=
400 Possible field formulas from the remote table will have to be transferred
401 manually.  Since there are no row formulas yet there is no need to transfer
402 column formulas to row formulas or vice versa.
404 **** Dynamic variation of ranges
406 -- Michael Brand
408 In this example all columns next to =quote= are calculated from the column
409 =quote= and show the average change of the time series =quote[year]=
410 during the period of the preceding =1=, =2=, =3= or =4= years:
412 : | year | quote |   1 a |   2 a |   3 a |   4 a |
413 : |------+-------+-------+-------+-------+-------|
414 : | 2005 |    10 |       |       |       |       |
415 : | 2006 |    12 | 0.200 |       |       |       |
416 : | 2007 |    14 | 0.167 | 0.183 |       |       |
417 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
418 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
419 : #+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
421 The formula is the same for each column =$3= through =$6=.  This can easily
422 be seen with the great formula editor invoked by C-c ' on the
423 table. The important part of the formula without the field blanking is:
425 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
427 which is the Emacs Calc implementation of the equation
429 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
431 where /i/ is the current time and /a/ is the length of the preceding period.
433 *** Customize the size of the frame for remember
434 (Note: this hack is likely out of date due to the development of
435 [[org-capture]].) 
437 #FIXME: gmane link?
438 On emacs-orgmode, Ryan C. Thompson suggested this:
440 #+begin_quote
441 I am using org-remember set to open a new frame when used,
442 and the default frame size is much too large. To fix this, I have
443 designed some advice and a custom variable to implement custom
444 parameters for the remember frame:
445 #+end_quote
447 #+begin_src emacs-lisp
448 (defcustom remember-frame-alist nil
449   "Additional frame parameters for dedicated remember frame."
450   :type 'alist
451   :group 'remember)
453 (defadvice remember (around remember-frame-parameters activate)
454   "Set some frame parameters for the remember frame."
455   (let ((default-frame-alist (append remember-frame-alist
456                                      default-frame-alist)))
457     ad-do-it))
458 #+end_src
460 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
461 reasonable size for the frame.
462 *** Promote all items in subtree
463 - Matt Lundin
465 This function will promote all items in a subtree. Since I use
466 subtrees primarily to organize projects, the function is somewhat
467 unimaginatively called my-org-un-project:
469 #+begin_src emacs-lisp
470 (defun my-org-un-project ()
471   (interactive)
472   (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
473   (org-cycle t))
474 #+end_src
476 *** Turn a heading into an Org link
478 From David Maus:
480 #+begin_src emacs-lisp
481   (defun dmj:turn-headline-into-org-mode-link ()
482     "Replace word at point by an Org mode link."
483     (interactive)
484     (when (org-at-heading-p)
485       (let ((hl-text (nth 4 (org-heading-components))))
486         (unless (or (null hl-text)
487                     (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
488           (beginning-of-line)
489           (search-forward hl-text (point-at-eol))
490           (replace-string
491            hl-text
492            (format "[[file:%s.org][%s]]"
493                    (org-link-escape hl-text)
494                    (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
495            nil (- (point) (length hl-text)) (point))))))
496 #+end_src
498 ** Archiving Content in Org-Mode
499 *** Preserve top level headings when archiving to a file
500 - Matt Lundin
502 To preserve (somewhat) the integrity of your archive structure while
503 archiving lower level items to a file, you can use the following
504 defadvice:
506 #+begin_src emacs-lisp
507 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
508   (let ((org-archive-location 
509          (if (save-excursion (org-back-to-heading)
510                              (> (org-outline-level) 1))
511              (concat (car (split-string org-archive-location "::"))
512                      "::* "
513                      (car (org-get-outline-path)))
514            org-archive-location)))
515     ad-do-it))
516 #+end_src
518 Thus, if you have an outline structure such as...
520 #+begin_src org
521 ,* Heading
522 ,** Subheading
523 ,*** Subsubheading
524 #+end_src
526 ...archiving "Subsubheading" to a new file will set the location in
527 the new file to the top level heading:
529 #+begin_src org
530 ,* Heading
531 ,** Subsubheading
532 #+end_src
534 While this hack obviously destroys the outline hierarchy somewhat, it
535 at least preserves the logic of level one groupings.
537 *** Archive in a date tree
539 Posted to Org-mode mailing list by Osamu Okano
540 [2010-04-21 Wed]
542 #+begin_src emacs-lisp
543 ;; (setq org-archive-location "%s_archive::date-tree")
544 (defadvice org-archive-subtree
545   (around org-archive-subtree-to-data-tree activate)
546   "org-archive-subtree to date-tree"
547   (if
548       (string= "date-tree"
549                (org-extract-archive-heading
550                 (org-get-local-archive-location)))
551       (let* ((dct (decode-time (org-current-time)))
552              (y (nth 5 dct))
553              (m (nth 4 dct))
554              (d (nth 3 dct))
555              (this-buffer (current-buffer))
556              (location (org-get-local-archive-location))
557              (afile (org-extract-archive-file location))
558              (org-archive-location
559               (format "%s::*** %04d-%02d-%02d %s" afile y m d
560                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
561         (message "afile=%s" afile)
562         (unless afile
563           (error "Invalid `org-archive-location'"))
564         (save-excursion
565           (switch-to-buffer (find-file-noselect afile))
566           (org-datetree-find-year-create y)
567           (org-datetree-find-month-create y m)
568           (org-datetree-find-day-create y m d)
569           (widen)
570           (switch-to-buffer this-buffer))
571         ad-do-it)
572     ad-do-it))
573 #+end_src
575 ** Using and Managing Org-Metadata
576 *** Remove redundant tags of headlines
577 -- David Maus
579 A small function that processes all headlines in current buffer and
580 removes tags that are local to a headline and inherited by a parent
581 headline or the #+FILETAGS: statement.
583 #+BEGIN_SRC emacs-lisp
584   (defun dmj/org-remove-redundant-tags ()
585     "Remove redundant tags of headlines in current buffer.
587   A tag is considered redundant if it is local to a headline and
588   inherited by a parent headline."
589     (interactive)
590     (when (eq major-mode 'org-mode)
591       (save-excursion
592         (org-map-entries
593          '(lambda ()
594             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
595                   local inherited tag)
596               (dolist (tag alltags)
597                 (if (get-text-property 0 'inherited tag)
598                     (push tag inherited) (push tag local)))
599               (dolist (tag local)
600                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
601          t nil))))
602 #+END_SRC
604 *** Remove empty property drawers
606 David Maus proposed this:
608 #+begin_src emacs-lisp
609 (defun dmj:org:remove-empty-propert-drawers ()
610   "*Remove all empty property drawers in current file."
611   (interactive)
612   (unless (eq major-mode 'org-mode)
613     (error "You need to turn on Org mode for this function."))
614   (save-excursion
615     (goto-char (point-min))
616     (while (re-search-forward ":PROPERTIES:" nil t)
617       (save-excursion
618         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
619 #+end_src
621 *** Group task list by a property
623 This advice allows you to group a task list in Org-Mode.  To use it,
624 set the variable =org-agenda-group-by-property= to the name of a
625 property in the option list for a TODO or TAGS search.  The resulting
626 agenda view will group tasks by that property prior to searching.
628 #+begin_src emacs-lisp
629 (defvar org-agenda-group-by-property nil
630   "Set this in org-mode agenda views to group tasks by property")
632 (defun org-group-bucket-items (prop items)
633   (let ((buckets ()))
634     (dolist (item items)
635       (let* ((marker (get-text-property 0 'org-marker item))
636              (pvalue (org-entry-get marker prop t))
637              (cell (assoc pvalue buckets)))
638         (if cell
639             (setcdr cell (cons item (cdr cell)))
640           (setq buckets (cons (cons pvalue (list item))
641                               buckets)))))
642     (setq buckets (mapcar (lambda (bucket)
643                             (cons (car bucket)
644                                   (reverse (cdr bucket))))
645                           buckets))
646     (sort buckets (lambda (i1 i2)
647                     (string< (car i1) (car i2))))))
649 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
650                                                (list &optional nosort))
651   "Prepare bucketed agenda entry lists"
652   (if org-agenda-group-by-property
653       ;; bucketed, handle appropriately
654       (let ((text ""))
655         (dolist (bucket (org-group-bucket-items
656                          org-agenda-group-by-property
657                          list))
658           (let ((header (concat "Property "
659                                 org-agenda-group-by-property
660                                 " is "
661                                 (or (car bucket) "<nil>") ":\n")))
662             (add-text-properties 0 (1- (length header))
663                                  (list 'face 'org-agenda-structure)
664                                  header)
665             (setq text
666                   (concat text header
667                           ;; recursively process
668                           (let ((org-agenda-group-by-property nil))
669                             (org-finalize-agenda-entries
670                              (cdr bucket) nosort))
671                           "\n\n"))))
672         (setq ad-return-value text))
673     ad-do-it))
674 (ad-activate 'org-finalize-agenda-entries)
675 #+end_src
676 *** Dynamically adjust tag position
677 Here is a bit of code that allows you to have the tags always
678 right-adjusted in the buffer.
680 This is useful when you have bigger window than default window-size
681 and you dislike the aesthetics of having the tag in the middle of the
682 line.
684 This hack solves the problem of adjusting it whenever you change the
685 window size.
686 Before saving it will revert the file to having the tag position be
687 left-adjusted so that if you track your files with version control,
688 you won't run into artificial diffs just because the window-size
689 changed.
691 *IMPORTANT*: This is probably slow on very big files.
693 #+begin_src emacs-lisp
694 (setq ba/org-adjust-tags-column t)
696 (defun ba/org-adjust-tags-column-reset-tags ()
697   "In org-mode buffers it will reset tag position according to
698 `org-tags-column'."
699   (when (and
700          (not (string= (buffer-name) "*Remember*"))
701          (eql major-mode 'org-mode))
702     (let ((b-m-p (buffer-modified-p)))
703       (condition-case nil
704           (save-excursion
705             (goto-char (point-min))
706             (command-execute 'outline-next-visible-heading)
707             ;; disable (message) that org-set-tags generates
708             (flet ((message (&rest ignored) nil))
709               (org-set-tags 1 t))
710             (set-buffer-modified-p b-m-p))
711         (error nil)))))
713 (defun ba/org-adjust-tags-column-now ()
714   "Right-adjust `org-tags-column' value, then reset tag position."
715   (set (make-local-variable 'org-tags-column)
716        (- (- (window-width) (length org-ellipsis))))
717   (ba/org-adjust-tags-column-reset-tags))
719 (defun ba/org-adjust-tags-column-maybe ()
720   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
721   (when ba/org-adjust-tags-column
722     (ba/org-adjust-tags-column-now)))
724 (defun ba/org-adjust-tags-column-before-save ()
725   "Tags need to be left-adjusted when saving."
726   (when ba/org-adjust-tags-column
727      (setq org-tags-column 1)
728      (ba/org-adjust-tags-column-reset-tags)))
730 (defun ba/org-adjust-tags-column-after-save ()
731   "Revert left-adjusted tag position done by before-save hook."
732   (ba/org-adjust-tags-column-maybe)
733   (set-buffer-modified-p nil))
735 ; automatically align tags on right-hand side
736 (add-hook 'window-configuration-change-hook
737           'ba/org-adjust-tags-column-maybe)
738 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
739 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
740 (add-hook 'org-agenda-mode-hook '(lambda ()
741                                   (setq org-agenda-tags-column (- (window-width)))))
743 ; between invoking org-refile and displaying the prompt (which
744 ; triggers window-configuration-change-hook) tags might adjust, 
745 ; which invalidates the org-refile cache
746 (defadvice org-refile (around org-refile-disable-adjust-tags)
747   "Disable dynamically adjusting tags"
748   (let ((ba/org-adjust-tags-column nil))
749     ad-do-it))
750 (ad-activate 'org-refile)
751 #+end_src
752 ** Org Agenda and Task Management
753 *** Make it easier to set org-agenda-files from multiple directories
754 - Matt Lundin
756 #+begin_src emacs-lisp
757 (defun my-org-list-files (dirs ext)
758   "Function to create list of org files in multiple subdirectories.
759 This can be called to generate a list of files for
760 org-agenda-files or org-refile-targets.
762 DIRS is a list of directories.
764 EXT is a list of the extensions of files to be included."
765   (let ((dirs (if (listp dirs)
766                   dirs
767                 (list dirs)))
768         (ext (if (listp ext)
769                  ext
770                (list ext)))
771         files)
772     (mapc 
773      (lambda (x)
774        (mapc 
775         (lambda (y)
776           (setq files 
777                 (append files 
778                         (file-expand-wildcards 
779                          (concat (file-name-as-directory x) "*" y)))))
780         ext))
781      dirs)
782     (mapc
783      (lambda (x)
784        (when (or (string-match "/.#" x)
785                  (string-match "#$" x))
786          (setq files (delete x files))))
787      files)
788     files))
790 (defvar my-org-agenda-directories '("~/org/")
791   "List of directories containing org files.")
792 (defvar my-org-agenda-extensions '(".org")
793   "List of extensions of agenda files")
795 (setq my-org-agenda-directories '("~/org/" "~/work/"))
796 (setq my-org-agenda-extensions '(".org" ".ref"))
798 (defun my-org-set-agenda-files ()
799   (interactive)
800   (setq org-agenda-files (my-org-list-files 
801                           my-org-agenda-directories
802                           my-org-agenda-extensions)))
804 (my-org-set-agenda-files)
805 #+end_src
807 The code above will set your "default" agenda files to all files
808 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
809 You can change these values by setting the variables
810 my-org-agenda-extensions and my-org-agenda-directories. The function
811 my-org-agenda-files-by-filetag uses these two variables to determine
812 which files to search for filetags (i.e., the larger set from which
813 the subset will be drawn).
815 You can also easily use my-org-list-files to "mix and match"
816 directories and extensions to generate different lists of agenda
817 files.
819 *** Restrict org-agenda-files by filetag
820   :PROPERTIES:
821   :CUSTOM_ID: set-agenda-files-by-filetag
822   :END:
823 - Matt Lundin
825 It is often helpful to limit yourself to a subset of your agenda
826 files. For instance, at work, you might want to see only files related
827 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
828 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
829 commands]]. These solutions, however, require reapplying a filter each
830 time you call the agenda or writing several new custom agenda commands
831 for each context. Another solution is to use directories for different
832 types of tasks and to change your agenda files with a function that
833 sets org-agenda-files to the appropriate directory. But this relies on
834 hard and static boundaries between files.
836 The following functions allow for a more dynamic approach to selecting
837 a subset of files based on filetags:
839 #+begin_src emacs-lisp
840 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
841   "Restrict org agenda files only to those containing filetag."
842   (interactive)
843   (let* ((tagslist (my-org-get-all-filetags))
844          (ftag (or tag 
845                    (completing-read "Tag: " 
846                                     (mapcar 'car tagslist)))))
847     (org-agenda-remove-restriction-lock 'noupdate)
848     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
849     (setq org-agenda-overriding-restriction 'files)))
851 (defun my-org-get-all-filetags ()
852   "Get list of filetags from all default org-files."
853   (let ((files org-agenda-files)
854         tagslist x)
855     (save-window-excursion
856       (while (setq x (pop files))
857         (set-buffer (find-file-noselect x))
858         (mapc
859          (lambda (y)
860            (let ((tagfiles (assoc y tagslist)))
861              (if tagfiles
862                  (setcdr tagfiles (cons x (cdr tagfiles)))
863                (add-to-list 'tagslist (list y x)))))
864          (my-org-get-filetags)))
865       tagslist)))
867 (defun my-org-get-filetags ()
868   "Get list of filetags for current buffer"
869   (let ((ftags org-file-tags)
870         x)
871     (mapcar 
872      (lambda (x)
873        (org-substring-no-properties x))
874      ftags)))
875 #+end_src
877 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
878 with all filetags in your "normal" agenda files. When you select a
879 tag, org-agenda-files will be restricted to only those files
880 containing the filetag. To release the restriction, type C-c C-x >
881 (org-agenda-remove-restriction-lock).
883 *** Highlight the agenda line under cursor
885 This is useful to make sure what task you are operating on.
887 #+BEGIN_SRC emacs-lisp
888 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
889 #+END_SRC emacs-lisp
891 Under XEmacs:
893 #+BEGIN_SRC emacs-lisp
894 ;; hl-line seems to be only for emacs
895 (require 'highline)
896 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
898 ;; highline-mode does not work straightaway in tty mode.
899 ;; I use a black background
900 (custom-set-faces
901   '(highline-face ((((type tty) (class color))
902                     (:background "white" :foreground "black")))))
903 #+END_SRC emacs-lisp
905 *** Split horizontally for agenda
907 If you would like to split the frame into two side-by-side windows when
908 displaying the agenda, try this hack from Jan Rehders, which uses the
909 `toggle-window-split' from
911 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
913 #+BEGIN_SRC emacs-lisp
914 ;; Patch org-mode to use vertical splitting
915 (defadvice org-prepare-agenda (after org-fix-split)
916   (toggle-window-split))
917 (ad-activate 'org-prepare-agenda)
918 #+END_SRC
920 *** Automatically add an appointment when clocking in a task
922 #+BEGIN_SRC emacs-lisp
923 ;; Make sure you have a sensible value for `appt-message-warning-time'
924 (defvar bzg-org-clock-in-appt-delay 100
925   "Number of minutes for setting an appointment by clocking-in")
926 #+END_SRC
928 This function let's you add an appointment for the current entry.
929 This can be useful when you need a reminder.
931 #+BEGIN_SRC emacs-lisp
932 (defun bzg-org-clock-in-add-appt (&optional n)
933   "Add an appointment for the Org entry at point in N minutes."
934   (interactive)
935   (save-excursion
936     (org-back-to-heading t)
937     (looking-at org-complex-heading-regexp)
938     (let* ((msg (match-string-no-properties 4))
939            (ct-time (decode-time))
940            (appt-min (+ (cadr ct-time)
941                         (or n bzg-org-clock-in-appt-delay)))
942            (appt-time ; define the time for the appointment
943             (progn (setf (cadr ct-time) appt-min) ct-time)))
944       (appt-add (format-time-string
945                  "%H:%M" (apply 'encode-time appt-time)) msg)
946       (if (interactive-p) (message "New appointment for %s" msg)))))
947 #+END_SRC
949 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
950 add an appointment:
952 #+BEGIN_SRC emacs-lisp
953 (defadvice org-clock-in (after org-clock-in-add-appt activate)
954   "Add an appointment when clocking a task in."
955   (bzg-org-clock-in-add-appt))
956 #+END_SRC
958 You may also want to delete the associated appointment when clocking
959 out.  This function does this:
961 #+BEGIN_SRC emacs-lisp
962 (defun bzg-org-clock-out-delete-appt nil
963   "When clocking out, delete any associated appointment."
964   (interactive)
965   (save-excursion
966     (org-back-to-heading t)
967     (looking-at org-complex-heading-regexp)
968     (let* ((msg (match-string-no-properties 4)))
969       (setq appt-time-msg-list
970             (delete nil
971                     (mapcar
972                      (lambda (appt)
973                        (if (not (string-match (regexp-quote msg)
974                                               (cadr appt))) appt))
975                      appt-time-msg-list)))
976       (appt-check))))
977 #+END_SRC
979 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
981 #+BEGIN_SRC emacs-lisp
982 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
983   "Delete an appointment when clocking a task out."
984   (bzg-org-clock-out-delete-appt))
985 #+END_SRC
987 *IMPORTANT*: You can add appointment by clocking in in both an
988 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
989 agenda buffer with the advice above will bring an error.
991 *** Remove time grid lines that are in an appointment
993 The agenda shows lines for the time grid.  Some people think that
994 these lines are a distraction when there are appointments at those
995 times.  You can get rid of the lines which coincide exactly with the
996 beginning of an appointment.  Michael Ekstrand has written a piece of
997 advice that also removes lines that are somewhere inside an
998 appointment:
1000 #+begin_src emacs-lisp
1001 (defun org-time-to-minutes (time)
1002   "Convert an HHMM time to minutes"
1003   (+ (* (/ time 100) 60) (% time 100)))
1005 (defun org-time-from-minutes (minutes)
1006   "Convert a number of minutes to an HHMM time"
1007   (+ (* (/ minutes 60) 100) (% minutes 60)))
1009 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1010                                                   (list ndays todayp))
1011   (if (member 'remove-match (car org-agenda-time-grid))
1012       (flet ((extract-window
1013               (line)
1014               (let ((start (get-text-property 1 'time-of-day line))
1015                     (dur (get-text-property 1 'duration line)))
1016                 (cond
1017                  ((and start dur)
1018                   (cons start
1019                         (org-time-from-minutes
1020                          (+ dur (org-time-to-minutes start)))))
1021                  (start start)
1022                  (t nil)))))
1023         (let* ((windows (delq nil (mapcar 'extract-window list)))
1024                (org-agenda-time-grid
1025                 (list (car org-agenda-time-grid)
1026                       (cadr org-agenda-time-grid)
1027                       (remove-if
1028                        (lambda (time)
1029                          (find-if (lambda (w)
1030                                     (if (numberp w)
1031                                         (equal w time)
1032                                       (and (>= time (car w))
1033                                            (< time (cdr w)))))
1034                                   windows))
1035                        (caddr org-agenda-time-grid)))))
1036           ad-do-it))
1037     ad-do-it))
1038 (ad-activate 'org-agenda-add-time-grid-maybe)
1039 #+end_src
1040 *** Disable vc for Org mode agenda files
1041 -- David Maus
1043 Even if you use Git to track your agenda files you might not need
1044 vc-mode to be enabled for these files.
1046 #+begin_src emacs-lisp
1047 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1048 (defun dmj/disable-vc-for-agenda-files-hook ()
1049   "Disable vc-mode for Org agenda files."
1050   (if (and (fboundp 'org-agenda-file-p)
1051            (org-agenda-file-p (buffer-file-name)))
1052       (remove-hook 'find-file-hook 'vc-find-file-hook)
1053     (add-hook 'find-file-hook 'vc-find-file-hook)))
1054 #+end_src
1056 *** Easy customization of TODO colors
1057 -- Ryan C. Thompson
1059 Here is some code I came up with some code to make it easier to
1060 customize the colors of various TODO keywords. As long as you just
1061 want a different color and nothing else, you can customize the
1062 variable org-todo-keyword-faces and use just a string color (i.e. a
1063 string of the color name) as the face, and then org-get-todo-face
1064 will convert the color to a face, inheriting everything else from
1065 the standard org-todo face.
1067 To demonstrate, I currently have org-todo-keyword-faces set to
1069 #+BEGIN_SRC emacs-lisp
1070 (("IN PROGRESS" . "dark orange")
1071  ("WAITING" . "red4")
1072  ("CANCELED" . "saddle brown"))
1073 #+END_SRC emacs-lisp
1075   Here's the code, in a form you can put in your =.emacs=
1077 #+BEGIN_SRC emacs-lisp
1078 (eval-after-load 'org-faces
1079  '(progn
1080     (defcustom org-todo-keyword-faces nil
1081       "Faces for specific TODO keywords.
1082 This is a list of cons cells, with TODO keywords in the car and
1083 faces in the cdr.  The face can be a symbol, a color, or a
1084 property list of attributes, like (:foreground \"blue\" :weight
1085 bold :underline t)."
1086       :group 'org-faces
1087       :group 'org-todo
1088       :type '(repeat
1089               (cons
1090                (string :tag "Keyword")
1091                (choice color (sexp :tag "Face")))))))
1093 (eval-after-load 'org
1094  '(progn
1095     (defun org-get-todo-face-from-color (color)
1096       "Returns a specification for a face that inherits from org-todo
1097  face and has the given color as foreground. Returns nil if
1098  color is nil."
1099       (when color
1100         `(:inherit org-warning :foreground ,color)))
1102     (defun org-get-todo-face (kwd)
1103       "Get the right face for a TODO keyword KWD.
1104 If KWD is a number, get the corresponding match group."
1105       (if (numberp kwd) (setq kwd (match-string kwd)))
1106       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1107             (if (stringp face)
1108                 (org-get-todo-face-from-color face)
1109               face))
1110           (and (member kwd org-done-keywords) 'org-done)
1111           'org-todo))))
1112 #+END_SRC emacs-lisp
1114 *** Add an effort estimate on the fly when clocking in
1116 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1117 This way you can easily have a "tea-timer" for your tasks when they
1118 don't already have an effort estimate.
1120 #+begin_src emacs-lisp
1121 (add-hook 'org-clock-in-prepare-hook
1122           'my-org-mode-ask-effort)
1124 (defun my-org-mode-ask-effort ()
1125   "Ask for an effort estimate when clocking in."
1126   (unless (org-entry-get (point) "Effort")
1127     (let ((effort
1128            (completing-read
1129             "Effort: "
1130             (org-entry-get-multivalued-property (point) "Effort"))))
1131       (unless (equal effort "")
1132         (org-set-property "Effort" effort)))))
1133 #+end_src
1135 Or you can use a default effort for such a timer:
1137 #+begin_src emacs-lisp
1138 (add-hook 'org-clock-in-prepare-hook
1139           'my-org-mode-add-default-effort)
1141 (defvar org-clock-default-effort "1:00")
1143 (defun my-org-mode-add-default-effort ()
1144   "Add a default effort estimation."
1145   (unless (org-entry-get (point) "Effort")
1146     (org-set-property "Effort" org-clock-default-effort)))
1147 #+end_src
1149 *** Refresh the agenda view regurally
1151 Hack sent by Kiwon Um:
1153 #+begin_src emacs-lisp
1154 (defun kiwon/org-agenda-redo-in-other-window ()
1155   "Call org-agenda-redo function even in the non-agenda buffer."
1156   (interactive)
1157   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1158     (when agenda-window
1159       (with-selected-window agenda-window (org-agenda-redo)))))
1160 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1161 #+end_src
1163 *** Reschedule agenda items to today with a single command
1165 This was suggested by Carsten in reply to David Abrahams:
1167 #+begin_example emacs-lisp
1168 (defun org-agenda-reschedule-to-today ()
1169   (interactive)
1170   (flet ((org-read-date (&rest rest) (current-time)))
1171     (call-interactively 'org-agenda-schedule)))
1172 #+end_example
1174 * Hacking Org: Working with Org-mode and other Emacs Packages.
1175 ** org-remember-anything
1177 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1179 #+BEGIN_SRC emacs-lisp
1180 (defvar org-remember-anything
1181   '((name . "Org Remember")
1182     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1183     (action . (lambda (name)
1184                 (let* ((orig-template org-remember-templates)
1185                        (org-remember-templates
1186                         (list (assoc name orig-template))))
1187                   (call-interactively 'org-remember))))))
1188 #+END_SRC
1190 You can add it to your 'anything-sources' variable and open remember directly
1191 from anything. I imagine this would be more interesting for people with many
1192 remember templatesm, so that you are out of keys to assign those to. You should
1193 get something like this:
1195 [[file:images/thumbs/org-remember-anything.png]]
1197 ** Org-mode and saveplace.el
1199 Fix a problem with saveplace.el putting you back in a folded position:
1201 #+begin_src emacs-lisp
1202 (add-hook 'org-mode-hook
1203           (lambda ()
1204             (when (outline-invisible-p)
1205               (save-excursion
1206                 (outline-previous-visible-heading 1)
1207                 (org-show-subtree)))))
1208 #+end_src
1210 ** Using ido-completing-read to find attachments
1211 -- Matt Lundin
1213 Org-attach is great for quickly linking files to a project. But if you
1214 use org-attach extensively you might find yourself wanting to browse
1215 all the files you've attached to org headlines. This is not easy to do
1216 manually, since the directories containing the files are not human
1217 readable (i.e., they are based on automatically generated ids). Here's
1218 some code to browse those files using ido (obviously, you need to be
1219 using ido):
1221 #+begin_src emacs-lisp
1222 (load-library "find-lisp")
1224 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1226 (defun my-ido-find-org-attach ()
1227   "Find files in org-attachment directory"
1228   (interactive)
1229   (let* ((enable-recursive-minibuffers t)
1230          (files (find-lisp-find-files org-attach-directory "."))
1231          (file-assoc-list
1232           (mapcar (lambda (x)
1233                     (cons (file-name-nondirectory x)
1234                           x))
1235                   files))
1236          (filename-list
1237           (remove-duplicates (mapcar #'car file-assoc-list)
1238                              :test #'string=))
1239          (filename (ido-completing-read "Org attachments: " filename-list nil t))
1240          (longname (cdr (assoc filename file-assoc-list))))
1241     (ido-set-current-directory
1242      (if (file-directory-p longname)
1243          longname
1244        (file-name-directory longname)))
1245     (setq ido-exit 'refresh
1246           ido-text-init ido-text
1247           ido-rotate-temp t)
1248     (exit-minibuffer)))
1250 (add-hook 'ido-setup-hook 'ido-my-keys)
1252 (defun ido-my-keys ()
1253   "Add my keybindings for ido."
1254   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1255 #+end_src
1257 To browse your org attachments using ido fuzzy matching and/or the
1258 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1259 press =C-;=.
1261 ** Use idle timer for automatic agenda views
1263 From John Wiegley's mailing list post (March 18, 2010):
1265 #+begin_quote
1266 I have the following snippet in my .emacs file, which I find very
1267 useful. Basically what it does is that if I don't touch my Emacs for 5
1268 minutes, it displays the current agenda. This keeps my tasks "always
1269 in mind" whenever I come back to Emacs after doing something else,
1270 whereas before I had a tendency to forget that it was there.
1271 #+end_quote  
1273   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1275 #+begin_src emacs-lisp
1276 (defun jump-to-org-agenda ()
1277   (interactive)
1278   (let ((buf (get-buffer "*Org Agenda*"))
1279         wind)
1280     (if buf
1281         (if (setq wind (get-buffer-window buf))
1282             (select-window wind)
1283           (if (called-interactively-p)
1284               (progn
1285                 (select-window (display-buffer buf t t))
1286                 (org-fit-window-to-buffer)
1287                 ;; (org-agenda-redo)
1288                 )
1289             (with-selected-window (display-buffer buf)
1290               (org-fit-window-to-buffer)
1291               ;; (org-agenda-redo)
1292               )))
1293       (call-interactively 'org-agenda-list)))
1294   ;;(let ((buf (get-buffer "*Calendar*")))
1295   ;;  (unless (get-buffer-window buf)
1296   ;;    (org-agenda-goto-calendar)))
1297   )
1298   
1299 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1300 #+end_src
1302 #+results:
1303 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1305 ** Link to Gnus messages by Message-Id
1307 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1308 discussion about linking to Gnus messages without encoding the folder
1309 name in the link.  The following code hooks in to the store-link
1310 function in Gnus to capture links by Message-Id when in nnml folders,
1311 and then provides a link type "mid" which can open this link.  The
1312 =mde-org-gnus-open-message-link= function uses the
1313 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1314 scan.  It will go through them, in order, asking each to locate the
1315 message and opening it from the first one that reports success.
1317 It has only been tested with a single nnml backend, so there may be
1318 bugs lurking here and there.
1320 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1321 article]].
1323 #+begin_src emacs-lisp
1324 ;; Support for saving Gnus messages by Message-ID
1325 (defun mde-org-gnus-save-by-mid ()
1326   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1327     (when (eq major-mode 'gnus-article-mode)
1328       (gnus-article-show-summary))
1329     (let* ((group gnus-newsgroup-name)
1330            (method (gnus-find-method-for-group group)))
1331       (when (eq 'nnml (car method))
1332         (let* ((article (gnus-summary-article-number))
1333                (header (gnus-summary-article-header article))
1334                (from (mail-header-from header))
1335                (message-id
1336                 (save-match-data
1337                   (let ((mid (mail-header-id header)))
1338                     (if (string-match "<\\(.*\\)>" mid)
1339                         (match-string 1 mid)
1340                       (error "Malformed message ID header %s" mid)))))
1341                (date (mail-header-date header))
1342                (subject (gnus-summary-subject-string)))
1343           (org-store-link-props :type "mid" :from from :subject subject
1344                                 :message-id message-id :group group
1345                                 :link (org-make-link "mid:" message-id))
1346           (apply 'org-store-link-props
1347                  :description (org-email-link-description)
1348                  org-store-link-plist)
1349           t)))))
1351 (defvar mde-mid-resolve-methods '()
1352   "List of methods to try when resolving message ID's.  For Gnus,
1353 it is a cons of 'gnus and the select (type and name).")
1354 (setq mde-mid-resolve-methods
1355       '((gnus nnml "")))
1357 (defvar mde-org-gnus-open-level 1
1358   "Level at which Gnus is started when opening a link")
1359 (defun mde-org-gnus-open-message-link (msgid)
1360   "Open a message link with Gnus"
1361   (require 'gnus)
1362   (require 'org-table)
1363   (catch 'method-found
1364     (message "[MID linker] Resolving %s" msgid)
1365     (dolist (method mde-mid-resolve-methods)
1366       (cond
1367        ((and (eq (car method) 'gnus)
1368              (eq (cadr method) 'nnml))
1369         (funcall (cdr (assq 'gnus org-link-frame-setup))
1370                  mde-org-gnus-open-level)
1371         (when gnus-other-frame-object
1372           (select-frame gnus-other-frame-object))
1373         (let* ((msg-info (nnml-find-group-number
1374                           (concat "<" msgid ">")
1375                           (cdr method)))
1376                (group (and msg-info (car msg-info)))
1377                (message (and msg-info (cdr msg-info)))
1378                (qname (and group
1379                            (if (gnus-methods-equal-p
1380                                 (cdr method)
1381                                 gnus-select-method)
1382                                group
1383                              (gnus-group-full-name group (cdr method))))))
1384           (when msg-info
1385             (gnus-summary-read-group qname nil t)
1386             (gnus-summary-goto-article message nil t))
1387           (throw 'method-found t)))
1388        (t (error "Unknown link type"))))))
1390 (eval-after-load 'org-gnus
1391   '(progn
1392      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1393      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1394 #+end_src
1396 ** Store link upon sending a message in Gnus
1398 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1400 #+begin_src emacs-lisp
1401 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1402   "Send message with `message-send-and-exit' and store org link to message copy.
1403 If multiple groups appear in the Gcc header, the link refers to
1404 the copy in the last group."
1405   (interactive "P")
1406     (save-excursion
1407       (save-restriction
1408         (message-narrow-to-headers)
1409         (let ((gcc (car (last
1410                          (message-unquote-tokens
1411                           (message-tokenize-header
1412                            (mail-fetch-field "gcc" nil t) " ,")))))
1413               (buf (current-buffer))
1414               (message-kill-buffer-on-exit nil)
1415               id to from subject desc link newsgroup xarchive)
1416         (message-send-and-exit arg)
1417         (or
1418          ;; gcc group found ...
1419          (and gcc
1420               (save-current-buffer
1421                 (progn (set-buffer buf)
1422                        (setq id (org-remove-angle-brackets
1423                                  (mail-fetch-field "Message-ID")))
1424                        (setq to (mail-fetch-field "To"))
1425                        (setq from (mail-fetch-field "From"))
1426                        (setq subject (mail-fetch-field "Subject"))))
1427               (org-store-link-props :type "gnus" :from from :subject subject
1428                                     :message-id id :group gcc :to to)
1429               (setq desc (org-email-link-description))
1430               (setq link (org-gnus-article-link
1431                           gcc newsgroup id xarchive))
1432               (setq org-stored-links
1433                     (cons (list link desc) org-stored-links)))
1434          ;; no gcc group found ...
1435          (message "Can not create Org link: No Gcc header found."))))))
1437 (define-key message-mode-map [(control c) (control meta c)]
1438   'ulf-message-send-and-org-gnus-store-link)
1439 #+end_src
1441 ** Send html messages and attachments with Wanderlust
1442   -- David Maus
1444 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1445 similar functionality for both Wanderlust and Gnus.  The hack below is
1446 still somewhat different: It allows you to toggle sending of html
1447 messages within Wanderlust transparently.  I.e. html markup of the
1448 message body is created right before sending starts.
1450 *** Send HTML message
1452 Putting the code below in your .emacs adds following four functions:
1454 - dmj/wl-send-html-message
1456   Function that does the job: Convert everything between "--text
1457   follows this line--" and first mime entity (read: attachment) or
1458   end of buffer into html markup using `org-export-region-as-html'
1459   and replaces original body with a multipart MIME entity with the
1460   plain text version of body and the html markup version.  Thus a
1461   recipient that prefers html messages can see the html markup,
1462   recipients that prefer or depend on plain text can see the plain
1463   text.
1465   Cannot be called interactively: It is hooked into SEMI's
1466   `mime-edit-translate-hook' if message should be HTML message.
1468 - dmj/wl-send-html-message-draft-init
1470   Cannot be called interactively: It is hooked into WL's
1471   `wl-mail-setup-hook' and provides a buffer local variable to
1472   toggle.
1474 - dmj/wl-send-html-message-draft-maybe
1476   Cannot be called interactively: It is hooked into WL's
1477   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1478   `mime-edit-translate-hook' depending on whether HTML message is
1479   toggled on or off
1481 - dmj/wl-send-html-message-toggle
1483   Toggles sending of HTML message.  If toggled on, the letters
1484   "HTML" appear in the mode line.
1486   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1488 If you have to send HTML messages regularly you can set a global
1489 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1490 toggle on sending HTML message by default.
1492 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1493 Google's web front end.  As you can see you have the whole markup of
1494 Org at your service: *bold*, /italics/, tables, lists...
1496 So even if you feel uncomfortable with sending HTML messages at least
1497 you send HTML that looks quite good.
1499 #+begin_src emacs-lisp
1500 (defun dmj/wl-send-html-message ()
1501   "Send message as html message.
1502 Convert body of message to html using
1503   `org-export-region-as-html'."
1504   (require 'org)
1505   (save-excursion
1506     (let (beg end html text)
1507       (goto-char (point-min))
1508       (re-search-forward "^--text follows this line--$")
1509       ;; move to beginning of next line
1510       (beginning-of-line 2)
1511       (setq beg (point))
1512       (if (not (re-search-forward "^--\\[\\[" nil t))
1513           (setq end (point-max))
1514         ;; line up
1515         (end-of-line 0)
1516         (setq end (point)))
1517       ;; grab body
1518       (setq text (buffer-substring-no-properties beg end))
1519       ;; convert to html
1520       (with-temp-buffer
1521         (org-mode)
1522         (insert text)
1523         ;; handle signature
1524         (when (re-search-backward "^-- \n" nil t)
1525           ;; preserve link breaks in signature
1526           (insert "\n#+BEGIN_VERSE\n")
1527           (goto-char (point-max))
1528           (insert "\n#+END_VERSE\n")
1529           ;; grab html
1530           (setq html (org-export-region-as-html
1531                       (point-min) (point-max) t 'string))))
1532       (delete-region beg end)
1533       (insert
1534        (concat
1535         "--" "<<alternative>>-{\n"
1536         "--" "[[text/plain]]\n" text
1537         "--" "[[text/html]]\n"  html
1538         "--" "}-<<alternative>>\n")))))
1540 (defun dmj/wl-send-html-message-toggle ()
1541   "Toggle sending of html message."
1542   (interactive)
1543   (setq dmj/wl-send-html-message-toggled-p
1544         (if dmj/wl-send-html-message-toggled-p
1545             nil "HTML"))
1546   (message "Sending html message toggled %s"
1547            (if dmj/wl-send-html-message-toggled-p
1548                "on" "off")))
1550 (defun dmj/wl-send-html-message-draft-init ()
1551   "Create buffer local settings for maybe sending html message."
1552   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1553     (setq dmj/wl-send-html-message-toggled-p nil))
1554   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1555   (add-to-list 'global-mode-string
1556                '(:eval (if (eq major-mode 'wl-draft-mode)
1557                            dmj/wl-send-html-message-toggled-p))))
1559 (defun dmj/wl-send-html-message-maybe ()
1560   "Maybe send this message as html message.
1562 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1563 non-nil, add `dmj/wl-send-html-message' to
1564 `mime-edit-translate-hook'."
1565   (if dmj/wl-send-html-message-toggled-p
1566       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1567     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1569 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1570 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1571 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1572 #+end_src
1574 *** Attach HTML of region or subtree
1576 Instead of sending a complete HTML message you might only send parts
1577 of an Org file as HTML for the poor souls who are plagued with
1578 non-proportional fonts in their mail program that messes up pretty
1579 ASCII tables.
1581 This short function does the trick: It exports region or subtree to
1582 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1583 and clipboard.  If a region is active, it uses the region, the
1584 complete subtree otherwise.
1586 #+begin_src emacs-lisp
1587 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1588   "Export region between BEG and END as html attachment.
1589 If BEG and END are not set, use current subtree.  Region or
1590 subtree is exported to html without header and footer, prefixed
1591 with a mime entity string and pushed to clipboard and killring.
1592 When called with prefix, mime entity is not marked as
1593 attachment."
1594   (interactive "r\nP")
1595   (save-excursion
1596     (let* ((beg (if (region-active-p) (region-beginning)
1597                   (progn
1598                     (org-back-to-heading)
1599                     (point))))
1600            (end (if (region-active-p) (region-end)
1601                   (progn
1602                     (org-end-of-subtree)
1603                     (point))))
1604            (html (concat "--[[text/html"
1605                          (if arg "" "\nContent-Disposition: attachment")
1606                          "]]\n"
1607                          (org-export-region-as-html beg end t 'string))))
1608       (when (fboundp 'x-set-selection)
1609         (ignore-errors (x-set-selection 'PRIMARY html))
1610         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1611       (message "html export done, pushed to kill ring and clipboard"))))
1612 #+end_src
1614 *** Adopting for Gnus
1616 The whole magic lies in the special strings that mark a HTML
1617 attachment.  So you might just have to find out what these special
1618 strings are in message-mode and modify the functions accordingly.
1619 * Hacking Org: Working with Org-mode and External Programs.
1620 ** Use Org-mode with Screen [Andrew Hyatt]
1622 "The general idea is that you start a task in which all the work will
1623 take place in a shell.  This usually is not a leaf-task for me, but
1624 usually the parent of a leaf task.  From a task in your org-file, M-x
1625 ash-org-screen will prompt for the name of a session.  Give it a name,
1626 and it will insert a link.  Open the link at any time to go the screen
1627 session containing your work!"
1629 http://article.gmane.org/gmane.emacs.orgmode/5276
1631 #+BEGIN_SRC emacs-lisp
1632 (require 'term)
1634 (defun ash-org-goto-screen (name)
1635   "Open the screen with the specified name in the window"
1636   (interactive "MScreen name: ")
1637   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1638     (if (member screen-buffer-name
1639                 (mapcar 'buffer-name (buffer-list)))
1640         (switch-to-buffer screen-buffer-name)
1641       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1643 (defun ash-org-screen-buffer-name (name)
1644   "Returns the buffer name corresponding to the screen name given."
1645   (concat "*screen " name "*"))
1647 (defun ash-org-screen-helper (name arg)
1648   ;; Pick the name of the new buffer.
1649   (let ((term-ansi-buffer-name
1650          (generate-new-buffer-name
1651           (ash-org-screen-buffer-name name))))
1652     (setq term-ansi-buffer-name
1653           (term-ansi-make-term
1654            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1655     (set-buffer term-ansi-buffer-name)
1656     (term-mode)
1657     (term-char-mode)
1658     (term-set-escape-char ?\C-x)
1659     term-ansi-buffer-name))
1661 (defun ash-org-screen (name)
1662   "Start a screen session with name"
1663   (interactive "MScreen name: ")
1664   (save-excursion
1665     (ash-org-screen-helper name "-S"))
1666   (insert-string (concat "[[screen:" name "]]")))
1668 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1669 ;; \"%s\")") to org-link-abbrev-alist.
1670 #+END_SRC
1672 ** Org Agenda + Appt + Zenity
1674 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It make sure your agenda
1675 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1676 popup window.
1678 #+BEGIN_SRC emacs-lisp
1679 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1680 ; For org appointment reminders
1682 ;; Get appointments for today
1683 (defun my-org-agenda-to-appt ()
1684   (interactive)
1685   (setq appt-time-msg-list nil)
1686   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
1687         (org-agenda-to-appt)))
1689 ;; Run once, activate and schedule refresh
1690 (my-org-agenda-to-appt)
1691 (appt-activate t)
1692 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
1694 ; 5 minute warnings
1695 (setq appt-message-warning-time 15)
1696 (setq appt-display-interval 5)
1698 ; Update appt each time agenda opened.
1699 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
1701 ; Setup zenify, we tell appt to use window, and replace default function
1702 (setq appt-display-format 'window)
1703 (setq appt-disp-window-function (function my-appt-disp-window))
1705 (defun my-appt-disp-window (min-to-app new-time msg)
1706   (save-window-excursion (shell-command (concat
1707     "/usr/bin/zenity --info --title='Appointment' --text='"
1708     msg "' &") nil nil)))
1709 #+END_SRC
1711 ** Org-Mode + gnome-osd
1713 Richard Riley uses gnome-osd in interaction with Org-Mode to display
1714 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
1716 ** remind2org
1718 From Detlef Steuer
1720 http://article.gmane.org/gmane.emacs.orgmode/5073
1722 #+BEGIN_QUOTE
1723 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
1724 command line calendaring program. Its features superseed the possibilities
1725 of orgmode in the area of date specifying, so that I want to use it
1726 combined with orgmode.
1728 Using the script below I'm able use remind and incorporate its output in my
1729 agenda views.  The default of using 13 months look ahead is easily
1730 changed. It just happens I sometimes like to look a year into the
1731 future. :-)
1732 #+END_QUOTE
1734 ** Useful webjumps for conkeror
1736 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
1737 your =~/.conkerorrc= file:
1739 #+begin_example
1740 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
1741 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
1742 #+end_example
1744 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
1745 Org-mode mailing list.
1747 ** Use MathJax for HTML export without requiring JavaScript
1748 As of 2010-08-14, MathJax is the default method used to export math to HTML.
1750 If you like the results but do not want JavaScript in the exported pages,
1751 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
1752 HTML file from the exported version. It can also embed all referenced fonts
1753 within the HTML file itself, so there are no dependencies to external files.
1755 The download archive contains an elisp file which integrates it into the Org
1756 export process (configurable per file with a "#+StaticMathJax:" line).
1758 Read README.org and the comments in org-static-mathjax.el for usage instructions.
1759 ** Search Org files using lgrep
1761 Matt Lundi suggests this:
1763 #+begin_src emacs-lisp
1764   (defun my-org-grep (search &optional context)
1765     "Search for word in org files. 
1767 Prefix argument determines number of lines."
1768     (interactive "sSearch for: \nP")
1769     (let ((grep-find-ignored-files '("#*" ".#*"))
1770           (grep-template (concat "grep <X> -i -nH " 
1771                                  (when context
1772                                    (concat "-C" (number-to-string context)))
1773                                  " -e <R> <F>")))
1774       (lgrep search "*org*" "/home/matt/org/")))
1776   (global-set-key (kbd "<f8>") 'my-org-grep)
1777 #+end_src