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
7 #+EMAIL: mdl AT imapmail DOT org
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
20 * Hacking Org: Working within Org-mode.
21 ** Building and Managing Org
22 *** Compiling Org without make
24 :CUSTOM_ID: compiling-org-without-make
27 This file is the result of [[http://article.gmane.org/gmane.emacs.orgmode/15264][one of our discussions]] on the mailing list.
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.")
42 (setq my/org-lisp-directory "~/.emacs.d/org/lisp")
45 (setq my/org-compile-sources t)
47 (defun my/compile-org(&optional directory)
48 "Compile all *.el files that come with org-mode."
50 (setq directory (concat
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
60 (setq esf/org-install-file (concat directory "org-install.el"))
61 (find-file esf/org-install-file)
64 (generate-file-autoloads x))
66 (insert "\n(provide (quote org-install))\n")
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)))))
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
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
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
98 *** Check for possibly problematic old link escapes
100 :CUSTOM_ID: check-old-link-escapes
103 Starting with version 7.5 Org uses [[http://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
104 and with a modified algorithm to determine which characters to escape
107 As a side effect this modified behaviour might break existing links if
108 they contain a sequence of characters that look like a percent esage
109 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
111 The function below can be used to perform a preliminary check for such
112 links in an Org mode file. It will run through all links in the file
113 and issue a warning if it finds a percent escape sequence which is not
114 in old Org's list of known percent escapes.
116 #+begin_src emacs-lisp
117 (defun dmaus/org-check-percent-escapes ()
118 "*Check buffer for possibly problematic old link escapes."
120 (when (eq major-mode 'org-mode)
121 (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
122 "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
123 (unless (boundp 'warning-suppress-types)
124 (setq warning-suppress-types nil))
127 (goto-char (point-min))
128 (while (re-search-forward org-any-link-re nil t)
129 (let ((end (match-end 0)))
130 (goto-char (match-beginning 0))
131 (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
132 (let ((escape (match-string-no-properties 0)))
133 (unless (member (upcase escape) old-escapes)
134 (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
137 (- (point) 3))))))))))
140 ** Enhancing the Org experience.
142 Speed commands are described [[http://orgmode.org/manual/Speed-keys.html#Speed-keys][here]] in the manual. Add your own speed
144 *** Show next/prev heading tidily
146 These close the current heading and open the next/previous heading.
148 #+begin_src emacs-lisp
149 (defun ded/org-show-next-heading-tidily ()
150 "Show next entry, keeping other entries closed."
151 (if (save-excursion (end-of-line) (outline-invisible-p))
152 (progn (org-show-entry) (show-children))
153 (outline-next-heading)
154 (unless (and (bolp) (org-on-heading-p))
155 (org-up-heading-safe)
157 (error "Boundary reached"))
163 (defun ded/org-show-previous-heading-tidily ()
164 "Show previous entry, keeping other entries closed."
166 (outline-previous-heading)
167 (unless (and (< (point) pos) (bolp) (org-on-heading-p))
170 (error "Boundary reached"))
176 (setq org-use-speed-commands t)
177 (add-to-list 'org-speed-commands-user
178 '("n" ded/org-show-next-heading-tidily))
179 (add-to-list 'org-speed-commands-user
180 '("p" ded/org-show-previous-heading-tidily))
183 *** Changelog support for org headers
186 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
187 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
188 headline as the "current function" if you add a changelog entry from an org
191 #+BEGIN_SRC emacs-lisp
192 (defun org-log-current-defun ()
194 (org-back-to-heading)
195 (if (looking-at org-complex-heading-regexp)
198 (add-hook 'org-mode-hook
200 (make-variable-buffer-local 'add-log-current-defun-function)
201 (setq add-log-current-defun-function 'org-log-current-defun)))
204 *** Different org-cycle-level behavior
207 In recent org versions, when your point (cursor) is at the end of an
208 empty header line (like after you first created the header), the TAB
209 key (=org-cycle=) has a special behavior: it cycles the headline through
210 all possible levels. However, I did not like the way it determined
211 "all possible levels," so I rewrote the whole function, along with a
212 couple of supporting functions.
214 The original function's definition of "all possible levels" was "every
215 level from 1 to one more than the initial level of the current
216 headline before you started cycling." My new definition is "every
217 level from 1 to one more than the previous headline's level." So, if
218 you have a headline at level 4 and you use ALT+RET to make a new
219 headline below it, it will cycle between levels 1 and 5, inclusive.
221 The main advantage of my custom =org-cycle-level= function is that it
222 is stateless: the next level in the cycle is determined entirely by
223 the contents of the buffer, and not what command you executed last.
224 This makes it more predictable, I hope.
226 #+BEGIN_SRC emacs-lisp
229 (defun org-point-at-end-of-empty-headline ()
230 "If point is at the end of an empty headline, return t, else nil."
231 (and (looking-at "[ \t]*$")
233 (beginning-of-line 1)
234 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
236 (defun org-level-increment ()
237 "Return the number of stars that will be added or removed at a
238 time to headlines when structure editing, based on the value of
239 `org-odd-levels-only'."
240 (if org-odd-levels-only 2 1))
242 (defvar org-previous-line-level-cached nil)
244 (defun org-recalculate-previous-line-level ()
245 "Same as `org-get-previous-line-level', but does not use cached
246 value. It does *set* the cached value, though."
247 (set 'org-previous-line-level-cached
248 (let ((current-level (org-current-level))
249 (prev-level (when (> (line-number-at-pos) 1)
252 (org-current-level)))))
253 (cond ((null current-level) nil) ; Before first headline
254 ((null prev-level) 0) ; At first headline
257 (defun org-get-previous-line-level ()
258 "Return the outline depth of the last headline before the
259 current line. Returns 0 for the first headline in the buffer, and
260 nil if before the first headline."
261 ;; This calculation is quite expensive, with all the regex searching
262 ;; and stuff. Since org-cycle-level won't change lines, we can reuse
263 ;; the last value of this command.
264 (or (and (eq last-command 'org-cycle-level)
265 org-previous-line-level-cached)
266 (org-recalculate-previous-line-level)))
268 (defun org-cycle-level ()
270 (let ((org-adapt-indentation nil))
271 (when (org-point-at-end-of-empty-headline)
272 (setq this-command 'org-cycle-level) ;Only needed for caching
273 (let ((cur-level (org-current-level))
274 (prev-level (org-get-previous-line-level)))
276 ;; If first headline in file, promote to top-level.
278 (loop repeat (/ (- cur-level 1) (org-level-increment))
279 do (org-do-promote)))
280 ;; If same level as prev, demote one.
281 ((= prev-level cur-level)
283 ;; If parent is top-level, promote to top level if not already.
285 (loop repeat (/ (- cur-level 1) (org-level-increment))
286 do (org-do-promote)))
287 ;; If top-level, return to prev-level.
289 (loop repeat (/ (- prev-level 1) (org-level-increment))
291 ;; If less than prev-level, promote one.
292 ((< cur-level prev-level)
294 ;; If deeper than prev-level, promote until higher than
296 ((> cur-level prev-level)
297 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
298 do (org-do-promote))))
303 **** Transpose tables (Juan Pechiar)
305 This function by Juan Pechiar will transpose a table:
307 #+begin_src emacs-lisp
308 (defun org-transpose-table-at-point ()
309 "Transpose orgmode table at point, eliminate hlines"
312 (apply #'mapcar* #'list
313 ;; remove 'hline from list
314 (remove-if-not 'listp
315 ;; signals error if not table
316 (org-table-to-lisp)))))
317 (delete-region (org-table-begin) (org-table-end))
318 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
330 will be transposed as
337 (Note that horizontal lines disappeared.)
339 *** Dates computation
341 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
343 I have a table in org which stores the date, I'm wondering if there is
344 any function to calculate the duration? For example:
346 | Start Date | End Date | Duration |
347 |------------+------------+----------|
348 | 2004.08.07 | 2005.07.08 | |
350 I tried to use B&-C&, but failed ...
352 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
356 | Start Date | End Date | Duration |
357 |------------+------------+----------|
358 | 2004.08.07 | 2005.07.08 | 335 |
359 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
363 http://thread.gmane.org/gmane.emacs.orgmode/7741
365 as well as this post (which is really a followup on the
368 http://article.gmane.org/gmane.emacs.orgmode/7753
370 The problem that this last article pointed out was solved
373 http://article.gmane.org/gmane.emacs.orgmode/8001
375 and Chris Randle's original musings are at
377 http://article.gmane.org/gmane.emacs.orgmode/6536/
379 *** Field coordinates in formulas (=@#= and =$#=)
383 Following are some use cases that can be implemented with the
384 _field coordinates in formulas_ described in the corresponding
385 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
387 **** Copy a column from a remote table into a column
389 current column =$3= = remote column =$2=:
390 : #+TBLFM: $3 = remote(FOO, @@#$2)
392 **** Copy a row from a remote table transposed into a column
394 current column =$1= = transposed remote row =@1=:
395 : #+TBLFM: $1 = remote(FOO, @$#$@#)
397 **** Transpose a table
401 This is more like a demonstration of using _field coordinates in formulas_
402 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel. The efficient
403 and simple solution for this with the help of org-babel and Emacs Lisp has
404 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
406 To transpose this 4x7 table
409 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
410 : |------+------+------+------+------+------+------|
411 : | min | 401 | 501 | 601 | 701 | 801 | 901 |
412 : | avg | 402 | 502 | 602 | 702 | 802 | 902 |
413 : | max | 403 | 503 | 603 | 703 | 803 | 903 |
415 start with a 7x4 table without any horizontal line (to have filled
416 also the column header) and yet empty:
426 Then add the =TBLFM= below with the same formula repeated for each column.
427 After recalculation this will end up with the transposed copy:
429 : | year | min | avg | max |
430 : | 2004 | 401 | 402 | 403 |
431 : | 2005 | 501 | 502 | 503 |
432 : | 2006 | 601 | 602 | 603 |
433 : | 2007 | 701 | 702 | 703 |
434 : | 2008 | 801 | 802 | 803 |
435 : | 2009 | 901 | 902 | 903 |
436 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
438 The formulas simply exchange row and column numbers by taking
439 - the absolute remote row number =@$#= from the current column number =$#=
440 - the absolute remote column number =$@#= from the current row number =@#=
442 Possible field formulas from the remote table will have to be transferred
443 manually. Since there are no row formulas yet there is no need to transfer
444 column formulas to row formulas or vice versa.
446 **** Dynamic variation of ranges
450 In this example all columns next to =quote= are calculated from the column
451 =quote= and show the average change of the time series =quote[year]=
452 during the period of the preceding =1=, =2=, =3= or =4= years:
454 : | year | quote | 1 a | 2 a | 3 a | 4 a |
455 : |------+-------+-------+-------+-------+-------|
456 : | 2005 | 10 | | | | |
457 : | 2006 | 12 | 0.200 | | | |
458 : | 2007 | 14 | 0.167 | 0.183 | | |
459 : | 2008 | 16 | 0.143 | 0.155 | 0.170 | |
460 : | 2009 | 18 | 0.125 | 0.134 | 0.145 | 0.158 |
461 : #+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
463 The formula is the same for each column =$3= through =$6=. This can easily
464 be seen with the great formula editor invoked by C-c ' on the
465 table. The important part of the formula without the field blanking is:
467 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
469 which is the Emacs Calc implementation of the equation
471 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
473 where /i/ is the current time and /a/ is the length of the preceding period.
475 *** Customize the size of the frame for remember
476 (Note: this hack is likely out of date due to the development of
480 On emacs-orgmode, Ryan C. Thompson suggested this:
483 I am using org-remember set to open a new frame when used,
484 and the default frame size is much too large. To fix this, I have
485 designed some advice and a custom variable to implement custom
486 parameters for the remember frame:
489 #+begin_src emacs-lisp
490 (defcustom remember-frame-alist nil
491 "Additional frame parameters for dedicated remember frame."
495 (defadvice remember (around remember-frame-parameters activate)
496 "Set some frame parameters for the remember frame."
497 (let ((default-frame-alist (append remember-frame-alist
498 default-frame-alist)))
502 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
503 reasonable size for the frame.
504 *** Promote all items in subtree
507 This function will promote all items in a subtree. Since I use
508 subtrees primarily to organize projects, the function is somewhat
509 unimaginatively called my-org-un-project:
511 #+begin_src emacs-lisp
512 (defun my-org-un-project ()
514 (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
518 *** Turn a heading into an Org link
522 #+begin_src emacs-lisp
523 (defun dmj:turn-headline-into-org-mode-link ()
524 "Replace word at point by an Org mode link."
526 (when (org-at-heading-p)
527 (let ((hl-text (nth 4 (org-heading-components))))
528 (unless (or (null hl-text)
529 (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
531 (search-forward hl-text (point-at-eol))
534 (format "[[file:%s.org][%s]]"
535 (org-link-escape hl-text)
536 (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
537 nil (- (point) (length hl-text)) (point))))))
540 *** Count words in an Org buffer
542 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
544 #+begin_src emacs-lisp
545 (defun org-word-count (beg end
546 &optional count-latex-macro-args?
548 "Report the number of words in the Org mode buffer or selected region.
552 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
553 - hyperlinks (but does count words in hyperlink descriptions)
554 - tags, priorities, and TODO keywords in headers
555 - sections tagged as 'not for export'.
557 The text of footnote definitions is ignored, unless the optional argument
558 COUNT-FOOTNOTES? is non-nil.
560 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
561 includes LaTeX macro arguments (the material between {curly braces}).
562 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
566 (setf beg (point-min)
569 (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
572 (while (< (point) end)
575 ((or (org-in-commented-line) (org-at-table-p))
577 ;; Ignore hyperlinks. But if link has a description, count
578 ;; the words within the description.
579 ((looking-at org-bracket-link-analytic-regexp)
580 (when (match-string-no-properties 5)
581 (let ((desc (match-string-no-properties 5)))
583 (incf wc (length (remove "" (org-split-string
585 (goto-char (match-end 0)))
586 ((looking-at org-any-link-re)
587 (goto-char (match-end 0)))
588 ;; Ignore source code blocks.
589 ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
591 ;; Ignore inline source blocks, counting them as 1 word.
594 (looking-at org-babel-inline-src-block-regexp))
595 (goto-char (match-end 0))
597 ;; Count latex macros as 1 word, ignoring their arguments.
600 (looking-at latex-macro-regexp))
601 (goto-char (if count-latex-macro-args?
606 ((and (not count-footnotes?)
607 (or (org-footnote-at-definition-p)
608 (org-footnote-at-reference-p)))
611 (let ((contexts (org-context)))
613 ;; Ignore tags and TODO keywords, etc.
614 ((or (assoc :todo-keyword contexts)
615 (assoc :priority contexts)
616 (assoc :keyword contexts)
617 (assoc :checkbox contexts))
619 ;; Ignore sections marked with tags that are
620 ;; excluded from export.
621 ((assoc :tags contexts)
622 (if (intersection (org-get-tags-at) org-export-exclude-tags
624 (org-forward-same-level 1)
628 (re-search-forward "\\w+\\W*")))
629 (message (format "%d words in %s." wc
630 (if mark-active "region" "buffer")))))
633 ** Archiving Content in Org-Mode
634 *** Preserve top level headings when archiving to a file
637 To preserve (somewhat) the integrity of your archive structure while
638 archiving lower level items to a file, you can use the following
641 #+begin_src emacs-lisp
642 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
643 (let ((org-archive-location
644 (if (save-excursion (org-back-to-heading)
645 (> (org-outline-level) 1))
646 (concat (car (split-string org-archive-location "::"))
648 (car (org-get-outline-path)))
649 org-archive-location)))
653 Thus, if you have an outline structure such as...
661 ...archiving "Subsubheading" to a new file will set the location in
662 the new file to the top level heading:
669 While this hack obviously destroys the outline hierarchy somewhat, it
670 at least preserves the logic of level one groupings.
672 *** Archive in a date tree
674 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
676 (Make sure org-datetree.el is loaded for this to work.)
678 #+begin_src emacs-lisp
679 ;; (setq org-archive-location "%s_archive::date-tree")
680 (defadvice org-archive-subtree
681 (around org-archive-subtree-to-data-tree activate)
682 "org-archive-subtree to date-tree"
685 (org-extract-archive-heading
686 (org-get-local-archive-location)))
687 (let* ((dct (decode-time (org-current-time)))
691 (this-buffer (current-buffer))
692 (location (org-get-local-archive-location))
693 (afile (org-extract-archive-file location))
694 (org-archive-location
695 (format "%s::*** %04d-%02d-%02d %s" afile y m d
696 (format-time-string "%A" (encode-time 0 0 0 d m y)))))
697 (message "afile=%s" afile)
699 (error "Invalid `org-archive-location'"))
701 (switch-to-buffer (find-file-noselect afile))
702 (org-datetree-find-year-create y)
703 (org-datetree-find-month-create y m)
704 (org-datetree-find-day-create y m d)
706 (switch-to-buffer this-buffer))
711 *** Add inherited tags to archived entries
713 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
714 advise the function like this:
717 (defadvice org-archive-subtree
718 (before add-inherited-tags-before-org-archive-subtree activate)
719 "add inherited tags before org-archive-subtree"
720 (org-set-tags-to (org-get-tags-at)))
723 ** Using and Managing Org-Metadata
724 *** Remove redundant tags of headlines
727 A small function that processes all headlines in current buffer and
728 removes tags that are local to a headline and inherited by a parent
729 headline or the #+FILETAGS: statement.
731 #+BEGIN_SRC emacs-lisp
732 (defun dmj/org-remove-redundant-tags ()
733 "Remove redundant tags of headlines in current buffer.
735 A tag is considered redundant if it is local to a headline and
736 inherited by a parent headline."
738 (when (eq major-mode 'org-mode)
742 (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
744 (dolist (tag alltags)
745 (if (get-text-property 0 'inherited tag)
746 (push tag inherited) (push tag local)))
748 (if (member tag inherited) (org-toggle-tag tag 'off)))))
752 *** Remove empty property drawers
754 David Maus proposed this:
756 #+begin_src emacs-lisp
757 (defun dmj:org:remove-empty-propert-drawers ()
758 "*Remove all empty property drawers in current file."
760 (unless (eq major-mode 'org-mode)
761 (error "You need to turn on Org mode for this function."))
763 (goto-char (point-min))
764 (while (re-search-forward ":PROPERTIES:" nil t)
766 (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
769 *** Group task list by a property
771 This advice allows you to group a task list in Org-Mode. To use it,
772 set the variable =org-agenda-group-by-property= to the name of a
773 property in the option list for a TODO or TAGS search. The resulting
774 agenda view will group tasks by that property prior to searching.
776 #+begin_src emacs-lisp
777 (defvar org-agenda-group-by-property nil
778 "Set this in org-mode agenda views to group tasks by property")
780 (defun org-group-bucket-items (prop items)
783 (let* ((marker (get-text-property 0 'org-marker item))
784 (pvalue (org-entry-get marker prop t))
785 (cell (assoc pvalue buckets)))
787 (setcdr cell (cons item (cdr cell)))
788 (setq buckets (cons (cons pvalue (list item))
790 (setq buckets (mapcar (lambda (bucket)
792 (reverse (cdr bucket))))
794 (sort buckets (lambda (i1 i2)
795 (string< (car i1) (car i2))))))
797 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
798 (list &optional nosort))
799 "Prepare bucketed agenda entry lists"
800 (if org-agenda-group-by-property
801 ;; bucketed, handle appropriately
803 (dolist (bucket (org-group-bucket-items
804 org-agenda-group-by-property
806 (let ((header (concat "Property "
807 org-agenda-group-by-property
809 (or (car bucket) "<nil>") ":\n")))
810 (add-text-properties 0 (1- (length header))
811 (list 'face 'org-agenda-structure)
815 ;; recursively process
816 (let ((org-agenda-group-by-property nil))
817 (org-finalize-agenda-entries
818 (cdr bucket) nosort))
820 (setq ad-return-value text))
822 (ad-activate 'org-finalize-agenda-entries)
824 *** Dynamically adjust tag position
825 Here is a bit of code that allows you to have the tags always
826 right-adjusted in the buffer.
828 This is useful when you have bigger window than default window-size
829 and you dislike the aesthetics of having the tag in the middle of the
832 This hack solves the problem of adjusting it whenever you change the
834 Before saving it will revert the file to having the tag position be
835 left-adjusted so that if you track your files with version control,
836 you won't run into artificial diffs just because the window-size
839 *IMPORTANT*: This is probably slow on very big files.
841 #+begin_src emacs-lisp
842 (setq ba/org-adjust-tags-column t)
844 (defun ba/org-adjust-tags-column-reset-tags ()
845 "In org-mode buffers it will reset tag position according to
848 (not (string= (buffer-name) "*Remember*"))
849 (eql major-mode 'org-mode))
850 (let ((b-m-p (buffer-modified-p)))
853 (goto-char (point-min))
854 (command-execute 'outline-next-visible-heading)
855 ;; disable (message) that org-set-tags generates
856 (flet ((message (&rest ignored) nil))
858 (set-buffer-modified-p b-m-p))
861 (defun ba/org-adjust-tags-column-now ()
862 "Right-adjust `org-tags-column' value, then reset tag position."
863 (set (make-local-variable 'org-tags-column)
864 (- (- (window-width) (length org-ellipsis))))
865 (ba/org-adjust-tags-column-reset-tags))
867 (defun ba/org-adjust-tags-column-maybe ()
868 "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
869 (when ba/org-adjust-tags-column
870 (ba/org-adjust-tags-column-now)))
872 (defun ba/org-adjust-tags-column-before-save ()
873 "Tags need to be left-adjusted when saving."
874 (when ba/org-adjust-tags-column
875 (setq org-tags-column 1)
876 (ba/org-adjust-tags-column-reset-tags)))
878 (defun ba/org-adjust-tags-column-after-save ()
879 "Revert left-adjusted tag position done by before-save hook."
880 (ba/org-adjust-tags-column-maybe)
881 (set-buffer-modified-p nil))
883 ; automatically align tags on right-hand side
884 (add-hook 'window-configuration-change-hook
885 'ba/org-adjust-tags-column-maybe)
886 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
887 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
888 (add-hook 'org-agenda-mode-hook '(lambda ()
889 (setq org-agenda-tags-column (- (window-width)))))
891 ; between invoking org-refile and displaying the prompt (which
892 ; triggers window-configuration-change-hook) tags might adjust,
893 ; which invalidates the org-refile cache
894 (defadvice org-refile (around org-refile-disable-adjust-tags)
895 "Disable dynamically adjusting tags"
896 (let ((ba/org-adjust-tags-column nil))
898 (ad-activate 'org-refile)
900 ** Org Agenda and Task Management
901 *** Make it easier to set org-agenda-files from multiple directories
904 #+begin_src emacs-lisp
905 (defun my-org-list-files (dirs ext)
906 "Function to create list of org files in multiple subdirectories.
907 This can be called to generate a list of files for
908 org-agenda-files or org-refile-targets.
910 DIRS is a list of directories.
912 EXT is a list of the extensions of files to be included."
913 (let ((dirs (if (listp dirs)
926 (file-expand-wildcards
927 (concat (file-name-as-directory x) "*" y)))))
932 (when (or (string-match "/.#" x)
933 (string-match "#$" x))
934 (setq files (delete x files))))
938 (defvar my-org-agenda-directories '("~/org/")
939 "List of directories containing org files.")
940 (defvar my-org-agenda-extensions '(".org")
941 "List of extensions of agenda files")
943 (setq my-org-agenda-directories '("~/org/" "~/work/"))
944 (setq my-org-agenda-extensions '(".org" ".ref"))
946 (defun my-org-set-agenda-files ()
948 (setq org-agenda-files (my-org-list-files
949 my-org-agenda-directories
950 my-org-agenda-extensions)))
952 (my-org-set-agenda-files)
955 The code above will set your "default" agenda files to all files
956 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
957 You can change these values by setting the variables
958 my-org-agenda-extensions and my-org-agenda-directories. The function
959 my-org-agenda-files-by-filetag uses these two variables to determine
960 which files to search for filetags (i.e., the larger set from which
961 the subset will be drawn).
963 You can also easily use my-org-list-files to "mix and match"
964 directories and extensions to generate different lists of agenda
967 *** Restrict org-agenda-files by filetag
969 :CUSTOM_ID: set-agenda-files-by-filetag
973 It is often helpful to limit yourself to a subset of your agenda
974 files. For instance, at work, you might want to see only files related
975 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
976 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
977 commands]]. These solutions, however, require reapplying a filter each
978 time you call the agenda or writing several new custom agenda commands
979 for each context. Another solution is to use directories for different
980 types of tasks and to change your agenda files with a function that
981 sets org-agenda-files to the appropriate directory. But this relies on
982 hard and static boundaries between files.
984 The following functions allow for a more dynamic approach to selecting
985 a subset of files based on filetags:
987 #+begin_src emacs-lisp
988 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
989 "Restrict org agenda files only to those containing filetag."
991 (let* ((tagslist (my-org-get-all-filetags))
993 (completing-read "Tag: "
994 (mapcar 'car tagslist)))))
995 (org-agenda-remove-restriction-lock 'noupdate)
996 (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
997 (setq org-agenda-overriding-restriction 'files)))
999 (defun my-org-get-all-filetags ()
1000 "Get list of filetags from all default org-files."
1001 (let ((files org-agenda-files)
1003 (save-window-excursion
1004 (while (setq x (pop files))
1005 (set-buffer (find-file-noselect x))
1008 (let ((tagfiles (assoc y tagslist)))
1010 (setcdr tagfiles (cons x (cdr tagfiles)))
1011 (add-to-list 'tagslist (list y x)))))
1012 (my-org-get-filetags)))
1015 (defun my-org-get-filetags ()
1016 "Get list of filetags for current buffer"
1017 (let ((ftags org-file-tags)
1021 (org-substring-no-properties x))
1025 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1026 with all filetags in your "normal" agenda files. When you select a
1027 tag, org-agenda-files will be restricted to only those files
1028 containing the filetag. To release the restriction, type C-c C-x >
1029 (org-agenda-remove-restriction-lock).
1031 *** Highlight the agenda line under cursor
1033 This is useful to make sure what task you are operating on.
1035 #+BEGIN_SRC emacs-lisp
1036 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
1037 #+END_SRC emacs-lisp
1041 #+BEGIN_SRC emacs-lisp
1042 ;; hl-line seems to be only for emacs
1044 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
1046 ;; highline-mode does not work straightaway in tty mode.
1047 ;; I use a black background
1049 '(highline-face ((((type tty) (class color))
1050 (:background "white" :foreground "black")))))
1051 #+END_SRC emacs-lisp
1053 *** Split horizontally for agenda
1055 If you would like to split the frame into two side-by-side windows when
1056 displaying the agenda, try this hack from Jan Rehders, which uses the
1057 `toggle-window-split' from
1059 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1061 #+BEGIN_SRC emacs-lisp
1062 ;; Patch org-mode to use vertical splitting
1063 (defadvice org-prepare-agenda (after org-fix-split)
1064 (toggle-window-split))
1065 (ad-activate 'org-prepare-agenda)
1068 *** Automatically add an appointment when clocking in a task
1070 #+BEGIN_SRC emacs-lisp
1071 ;; Make sure you have a sensible value for `appt-message-warning-time'
1072 (defvar bzg-org-clock-in-appt-delay 100
1073 "Number of minutes for setting an appointment by clocking-in")
1076 This function let's you add an appointment for the current entry.
1077 This can be useful when you need a reminder.
1079 #+BEGIN_SRC emacs-lisp
1080 (defun bzg-org-clock-in-add-appt (&optional n)
1081 "Add an appointment for the Org entry at point in N minutes."
1084 (org-back-to-heading t)
1085 (looking-at org-complex-heading-regexp)
1086 (let* ((msg (match-string-no-properties 4))
1087 (ct-time (decode-time))
1088 (appt-min (+ (cadr ct-time)
1089 (or n bzg-org-clock-in-appt-delay)))
1090 (appt-time ; define the time for the appointment
1091 (progn (setf (cadr ct-time) appt-min) ct-time)))
1092 (appt-add (format-time-string
1093 "%H:%M" (apply 'encode-time appt-time)) msg)
1094 (if (interactive-p) (message "New appointment for %s" msg)))))
1097 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1100 #+BEGIN_SRC emacs-lisp
1101 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1102 "Add an appointment when clocking a task in."
1103 (bzg-org-clock-in-add-appt))
1106 You may also want to delete the associated appointment when clocking
1107 out. This function does this:
1109 #+BEGIN_SRC emacs-lisp
1110 (defun bzg-org-clock-out-delete-appt nil
1111 "When clocking out, delete any associated appointment."
1114 (org-back-to-heading t)
1115 (looking-at org-complex-heading-regexp)
1116 (let* ((msg (match-string-no-properties 4)))
1117 (setq appt-time-msg-list
1121 (if (not (string-match (regexp-quote msg)
1122 (cadr appt))) appt))
1123 appt-time-msg-list)))
1127 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1129 #+BEGIN_SRC emacs-lisp
1130 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1131 "Delete an appointment when clocking a task out."
1132 (bzg-org-clock-out-delete-appt))
1135 *IMPORTANT*: You can add appointment by clocking in in both an
1136 =org-mode= and an =org-agenda-mode= buffer. But clocking out from
1137 agenda buffer with the advice above will bring an error.
1139 *** Remove time grid lines that are in an appointment
1141 The agenda shows lines for the time grid. Some people think that
1142 these lines are a distraction when there are appointments at those
1143 times. You can get rid of the lines which coincide exactly with the
1144 beginning of an appointment. Michael Ekstrand has written a piece of
1145 advice that also removes lines that are somewhere inside an
1148 #+begin_src emacs-lisp
1149 (defun org-time-to-minutes (time)
1150 "Convert an HHMM time to minutes"
1151 (+ (* (/ time 100) 60) (% time 100)))
1153 (defun org-time-from-minutes (minutes)
1154 "Convert a number of minutes to an HHMM time"
1155 (+ (* (/ minutes 60) 100) (% minutes 60)))
1157 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1158 (list ndays todayp))
1159 (if (member 'remove-match (car org-agenda-time-grid))
1160 (flet ((extract-window
1162 (let ((start (get-text-property 1 'time-of-day line))
1163 (dur (get-text-property 1 'duration line)))
1167 (org-time-from-minutes
1168 (+ dur (org-time-to-minutes start)))))
1171 (let* ((windows (delq nil (mapcar 'extract-window list)))
1172 (org-agenda-time-grid
1173 (list (car org-agenda-time-grid)
1174 (cadr org-agenda-time-grid)
1177 (find-if (lambda (w)
1180 (and (>= time (car w))
1183 (caddr org-agenda-time-grid)))))
1186 (ad-activate 'org-agenda-add-time-grid-maybe)
1188 *** Disable vc for Org mode agenda files
1191 Even if you use Git to track your agenda files you might not need
1192 vc-mode to be enabled for these files.
1194 #+begin_src emacs-lisp
1195 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1196 (defun dmj/disable-vc-for-agenda-files-hook ()
1197 "Disable vc-mode for Org agenda files."
1198 (if (and (fboundp 'org-agenda-file-p)
1199 (org-agenda-file-p (buffer-file-name)))
1200 (remove-hook 'find-file-hook 'vc-find-file-hook)
1201 (add-hook 'find-file-hook 'vc-find-file-hook)))
1204 *** Easy customization of TODO colors
1207 Here is some code I came up with some code to make it easier to
1208 customize the colors of various TODO keywords. As long as you just
1209 want a different color and nothing else, you can customize the
1210 variable org-todo-keyword-faces and use just a string color (i.e. a
1211 string of the color name) as the face, and then org-get-todo-face
1212 will convert the color to a face, inheriting everything else from
1213 the standard org-todo face.
1215 To demonstrate, I currently have org-todo-keyword-faces set to
1217 #+BEGIN_SRC emacs-lisp
1218 (("IN PROGRESS" . "dark orange")
1219 ("WAITING" . "red4")
1220 ("CANCELED" . "saddle brown"))
1221 #+END_SRC emacs-lisp
1223 Here's the code, in a form you can put in your =.emacs=
1225 #+BEGIN_SRC emacs-lisp
1226 (eval-after-load 'org-faces
1228 (defcustom org-todo-keyword-faces nil
1229 "Faces for specific TODO keywords.
1230 This is a list of cons cells, with TODO keywords in the car and
1231 faces in the cdr. The face can be a symbol, a color, or a
1232 property list of attributes, like (:foreground \"blue\" :weight
1233 bold :underline t)."
1238 (string :tag "Keyword")
1239 (choice color (sexp :tag "Face")))))))
1241 (eval-after-load 'org
1243 (defun org-get-todo-face-from-color (color)
1244 "Returns a specification for a face that inherits from org-todo
1245 face and has the given color as foreground. Returns nil if
1248 `(:inherit org-warning :foreground ,color)))
1250 (defun org-get-todo-face (kwd)
1251 "Get the right face for a TODO keyword KWD.
1252 If KWD is a number, get the corresponding match group."
1253 (if (numberp kwd) (setq kwd (match-string kwd)))
1254 (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
1256 (org-get-todo-face-from-color face)
1258 (and (member kwd org-done-keywords) 'org-done)
1260 #+END_SRC emacs-lisp
1262 *** Add an effort estimate on the fly when clocking in
1264 You can use =org-clock-in-prepare-hook= to add an effort estimate.
1265 This way you can easily have a "tea-timer" for your tasks when they
1266 don't already have an effort estimate.
1268 #+begin_src emacs-lisp
1269 (add-hook 'org-clock-in-prepare-hook
1270 'my-org-mode-ask-effort)
1272 (defun my-org-mode-ask-effort ()
1273 "Ask for an effort estimate when clocking in."
1274 (unless (org-entry-get (point) "Effort")
1278 (org-entry-get-multivalued-property (point) "Effort"))))
1279 (unless (equal effort "")
1280 (org-set-property "Effort" effort)))))
1283 Or you can use a default effort for such a timer:
1285 #+begin_src emacs-lisp
1286 (add-hook 'org-clock-in-prepare-hook
1287 'my-org-mode-add-default-effort)
1289 (defvar org-clock-default-effort "1:00")
1291 (defun my-org-mode-add-default-effort ()
1292 "Add a default effort estimation."
1293 (unless (org-entry-get (point) "Effort")
1294 (org-set-property "Effort" org-clock-default-effort)))
1297 *** Refresh the agenda view regurally
1299 Hack sent by Kiwon Um:
1301 #+begin_src emacs-lisp
1302 (defun kiwon/org-agenda-redo-in-other-window ()
1303 "Call org-agenda-redo function even in the non-agenda buffer."
1305 (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
1307 (with-selected-window agenda-window (org-agenda-redo)))))
1308 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
1311 *** Reschedule agenda items to today with a single command
1313 This was suggested by Carsten in reply to David Abrahams:
1315 #+begin_example emacs-lisp
1316 (defun org-agenda-reschedule-to-today ()
1318 (flet ((org-read-date (&rest rest) (current-time)))
1319 (call-interactively 'org-agenda-schedule)))
1322 * Hacking Org: Working with Org-mode and other Emacs Packages.
1323 ** org-remember-anything
1325 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1327 #+BEGIN_SRC emacs-lisp
1328 (defvar org-remember-anything
1329 '((name . "Org Remember")
1330 (candidates . (lambda () (mapcar 'car org-remember-templates)))
1331 (action . (lambda (name)
1332 (let* ((orig-template org-remember-templates)
1333 (org-remember-templates
1334 (list (assoc name orig-template))))
1335 (call-interactively 'org-remember))))))
1338 You can add it to your 'anything-sources' variable and open remember directly
1339 from anything. I imagine this would be more interesting for people with many
1340 remember templatesm, so that you are out of keys to assign those to. You should
1341 get something like this:
1343 [[file:images/thumbs/org-remember-anything.png]]
1345 ** Org-mode and saveplace.el
1347 Fix a problem with saveplace.el putting you back in a folded position:
1349 #+begin_src emacs-lisp
1350 (add-hook 'org-mode-hook
1352 (when (outline-invisible-p)
1354 (outline-previous-visible-heading 1)
1355 (org-show-subtree)))))
1358 ** Using ido-completing-read to find attachments
1361 Org-attach is great for quickly linking files to a project. But if you
1362 use org-attach extensively you might find yourself wanting to browse
1363 all the files you've attached to org headlines. This is not easy to do
1364 manually, since the directories containing the files are not human
1365 readable (i.e., they are based on automatically generated ids). Here's
1366 some code to browse those files using ido (obviously, you need to be
1369 #+begin_src emacs-lisp
1370 (load-library "find-lisp")
1372 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1374 (defun my-ido-find-org-attach ()
1375 "Find files in org-attachment directory"
1377 (let* ((enable-recursive-minibuffers t)
1378 (files (find-lisp-find-files org-attach-directory "."))
1381 (cons (file-name-nondirectory x)
1385 (remove-duplicates (mapcar #'car file-assoc-list)
1387 (filename (ido-completing-read "Org attachments: " filename-list nil t))
1388 (longname (cdr (assoc filename file-assoc-list))))
1389 (ido-set-current-directory
1390 (if (file-directory-p longname)
1392 (file-name-directory longname)))
1393 (setq ido-exit 'refresh
1394 ido-text-init ido-text
1398 (add-hook 'ido-setup-hook 'ido-my-keys)
1400 (defun ido-my-keys ()
1401 "Add my keybindings for ido."
1402 (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1405 To browse your org attachments using ido fuzzy matching and/or the
1406 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1409 ** Use idle timer for automatic agenda views
1411 From John Wiegley's mailing list post (March 18, 2010):
1414 I have the following snippet in my .emacs file, which I find very
1415 useful. Basically what it does is that if I don't touch my Emacs for 5
1416 minutes, it displays the current agenda. This keeps my tasks "always
1417 in mind" whenever I come back to Emacs after doing something else,
1418 whereas before I had a tendency to forget that it was there.
1421 - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1423 #+begin_src emacs-lisp
1424 (defun jump-to-org-agenda ()
1426 (let ((buf (get-buffer "*Org Agenda*"))
1429 (if (setq wind (get-buffer-window buf))
1430 (select-window wind)
1431 (if (called-interactively-p)
1433 (select-window (display-buffer buf t t))
1434 (org-fit-window-to-buffer)
1435 ;; (org-agenda-redo)
1437 (with-selected-window (display-buffer buf)
1438 (org-fit-window-to-buffer)
1439 ;; (org-agenda-redo)
1441 (call-interactively 'org-agenda-list)))
1442 ;;(let ((buf (get-buffer "*Calendar*")))
1443 ;; (unless (get-buffer-window buf)
1444 ;; (org-agenda-goto-calendar)))
1447 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1451 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1453 ** Link to Gnus messages by Message-Id
1455 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1456 discussion about linking to Gnus messages without encoding the folder
1457 name in the link. The following code hooks in to the store-link
1458 function in Gnus to capture links by Message-Id when in nnml folders,
1459 and then provides a link type "mid" which can open this link. The
1460 =mde-org-gnus-open-message-link= function uses the
1461 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1462 scan. It will go through them, in order, asking each to locate the
1463 message and opening it from the first one that reports success.
1465 It has only been tested with a single nnml backend, so there may be
1466 bugs lurking here and there.
1468 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1471 #+begin_src emacs-lisp
1472 ;; Support for saving Gnus messages by Message-ID
1473 (defun mde-org-gnus-save-by-mid ()
1474 (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1475 (when (eq major-mode 'gnus-article-mode)
1476 (gnus-article-show-summary))
1477 (let* ((group gnus-newsgroup-name)
1478 (method (gnus-find-method-for-group group)))
1479 (when (eq 'nnml (car method))
1480 (let* ((article (gnus-summary-article-number))
1481 (header (gnus-summary-article-header article))
1482 (from (mail-header-from header))
1485 (let ((mid (mail-header-id header)))
1486 (if (string-match "<\\(.*\\)>" mid)
1487 (match-string 1 mid)
1488 (error "Malformed message ID header %s" mid)))))
1489 (date (mail-header-date header))
1490 (subject (gnus-summary-subject-string)))
1491 (org-store-link-props :type "mid" :from from :subject subject
1492 :message-id message-id :group group
1493 :link (org-make-link "mid:" message-id))
1494 (apply 'org-store-link-props
1495 :description (org-email-link-description)
1496 org-store-link-plist)
1499 (defvar mde-mid-resolve-methods '()
1500 "List of methods to try when resolving message ID's. For Gnus,
1501 it is a cons of 'gnus and the select (type and name).")
1502 (setq mde-mid-resolve-methods
1505 (defvar mde-org-gnus-open-level 1
1506 "Level at which Gnus is started when opening a link")
1507 (defun mde-org-gnus-open-message-link (msgid)
1508 "Open a message link with Gnus"
1510 (require 'org-table)
1511 (catch 'method-found
1512 (message "[MID linker] Resolving %s" msgid)
1513 (dolist (method mde-mid-resolve-methods)
1515 ((and (eq (car method) 'gnus)
1516 (eq (cadr method) 'nnml))
1517 (funcall (cdr (assq 'gnus org-link-frame-setup))
1518 mde-org-gnus-open-level)
1519 (when gnus-other-frame-object
1520 (select-frame gnus-other-frame-object))
1521 (let* ((msg-info (nnml-find-group-number
1522 (concat "<" msgid ">")
1524 (group (and msg-info (car msg-info)))
1525 (message (and msg-info (cdr msg-info)))
1527 (if (gnus-methods-equal-p
1531 (gnus-group-full-name group (cdr method))))))
1533 (gnus-summary-read-group qname nil t)
1534 (gnus-summary-goto-article message nil t))
1535 (throw 'method-found t)))
1536 (t (error "Unknown link type"))))))
1538 (eval-after-load 'org-gnus
1540 (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1541 (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1544 ** Store link upon sending a message in Gnus
1546 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
1548 #+begin_src emacs-lisp
1549 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
1550 "Send message with `message-send-and-exit' and store org link to message copy.
1551 If multiple groups appear in the Gcc header, the link refers to
1552 the copy in the last group."
1556 (message-narrow-to-headers)
1557 (let ((gcc (car (last
1558 (message-unquote-tokens
1559 (message-tokenize-header
1560 (mail-fetch-field "gcc" nil t) " ,")))))
1561 (buf (current-buffer))
1562 (message-kill-buffer-on-exit nil)
1563 id to from subject desc link newsgroup xarchive)
1564 (message-send-and-exit arg)
1566 ;; gcc group found ...
1568 (save-current-buffer
1569 (progn (set-buffer buf)
1570 (setq id (org-remove-angle-brackets
1571 (mail-fetch-field "Message-ID")))
1572 (setq to (mail-fetch-field "To"))
1573 (setq from (mail-fetch-field "From"))
1574 (setq subject (mail-fetch-field "Subject"))))
1575 (org-store-link-props :type "gnus" :from from :subject subject
1576 :message-id id :group gcc :to to)
1577 (setq desc (org-email-link-description))
1578 (setq link (org-gnus-article-link
1579 gcc newsgroup id xarchive))
1580 (setq org-stored-links
1581 (cons (list link desc) org-stored-links)))
1582 ;; no gcc group found ...
1583 (message "Can not create Org link: No Gcc header found."))))))
1585 (define-key message-mode-map [(control c) (control meta c)]
1586 'ulf-message-send-and-org-gnus-store-link)
1589 ** Send html messages and attachments with Wanderlust
1592 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1593 similar functionality for both Wanderlust and Gnus. The hack below is
1594 still somewhat different: It allows you to toggle sending of html
1595 messages within Wanderlust transparently. I.e. html markup of the
1596 message body is created right before sending starts.
1598 *** Send HTML message
1600 Putting the code below in your .emacs adds following four functions:
1602 - dmj/wl-send-html-message
1604 Function that does the job: Convert everything between "--text
1605 follows this line--" and first mime entity (read: attachment) or
1606 end of buffer into html markup using `org-export-region-as-html'
1607 and replaces original body with a multipart MIME entity with the
1608 plain text version of body and the html markup version. Thus a
1609 recipient that prefers html messages can see the html markup,
1610 recipients that prefer or depend on plain text can see the plain
1613 Cannot be called interactively: It is hooked into SEMI's
1614 `mime-edit-translate-hook' if message should be HTML message.
1616 - dmj/wl-send-html-message-draft-init
1618 Cannot be called interactively: It is hooked into WL's
1619 `wl-mail-setup-hook' and provides a buffer local variable to
1622 - dmj/wl-send-html-message-draft-maybe
1624 Cannot be called interactively: It is hooked into WL's
1625 `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1626 `mime-edit-translate-hook' depending on whether HTML message is
1629 - dmj/wl-send-html-message-toggle
1631 Toggles sending of HTML message. If toggled on, the letters
1632 "HTML" appear in the mode line.
1634 Call it interactively! Or bind it to a key in `wl-draft-mode'.
1636 If you have to send HTML messages regularly you can set a global
1637 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1638 toggle on sending HTML message by default.
1640 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1641 Google's web front end. As you can see you have the whole markup of
1642 Org at your service: *bold*, /italics/, tables, lists...
1644 So even if you feel uncomfortable with sending HTML messages at least
1645 you send HTML that looks quite good.
1647 #+begin_src emacs-lisp
1648 (defun dmj/wl-send-html-message ()
1649 "Send message as html message.
1650 Convert body of message to html using
1651 `org-export-region-as-html'."
1654 (let (beg end html text)
1655 (goto-char (point-min))
1656 (re-search-forward "^--text follows this line--$")
1657 ;; move to beginning of next line
1658 (beginning-of-line 2)
1660 (if (not (re-search-forward "^--\\[\\[" nil t))
1661 (setq end (point-max))
1666 (setq text (buffer-substring-no-properties beg end))
1672 (when (re-search-backward "^-- \n" nil t)
1673 ;; preserve link breaks in signature
1674 (insert "\n#+BEGIN_VERSE\n")
1675 (goto-char (point-max))
1676 (insert "\n#+END_VERSE\n")
1678 (setq html (org-export-region-as-html
1679 (point-min) (point-max) t 'string))))
1680 (delete-region beg end)
1683 "--" "<<alternative>>-{\n"
1684 "--" "[[text/plain]]\n" text
1685 "--" "[[text/html]]\n" html
1686 "--" "}-<<alternative>>\n")))))
1688 (defun dmj/wl-send-html-message-toggle ()
1689 "Toggle sending of html message."
1691 (setq dmj/wl-send-html-message-toggled-p
1692 (if dmj/wl-send-html-message-toggled-p
1694 (message "Sending html message toggled %s"
1695 (if dmj/wl-send-html-message-toggled-p
1698 (defun dmj/wl-send-html-message-draft-init ()
1699 "Create buffer local settings for maybe sending html message."
1700 (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1701 (setq dmj/wl-send-html-message-toggled-p nil))
1702 (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1703 (add-to-list 'global-mode-string
1704 '(:eval (if (eq major-mode 'wl-draft-mode)
1705 dmj/wl-send-html-message-toggled-p))))
1707 (defun dmj/wl-send-html-message-maybe ()
1708 "Maybe send this message as html message.
1710 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1711 non-nil, add `dmj/wl-send-html-message' to
1712 `mime-edit-translate-hook'."
1713 (if dmj/wl-send-html-message-toggled-p
1714 (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1715 (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1717 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1718 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1719 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1722 *** Attach HTML of region or subtree
1724 Instead of sending a complete HTML message you might only send parts
1725 of an Org file as HTML for the poor souls who are plagued with
1726 non-proportional fonts in their mail program that messes up pretty
1729 This short function does the trick: It exports region or subtree to
1730 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1731 and clipboard. If a region is active, it uses the region, the
1732 complete subtree otherwise.
1734 #+begin_src emacs-lisp
1735 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1736 "Export region between BEG and END as html attachment.
1737 If BEG and END are not set, use current subtree. Region or
1738 subtree is exported to html without header and footer, prefixed
1739 with a mime entity string and pushed to clipboard and killring.
1740 When called with prefix, mime entity is not marked as
1742 (interactive "r\nP")
1744 (let* ((beg (if (region-active-p) (region-beginning)
1746 (org-back-to-heading)
1748 (end (if (region-active-p) (region-end)
1750 (org-end-of-subtree)
1752 (html (concat "--[[text/html"
1753 (if arg "" "\nContent-Disposition: attachment")
1755 (org-export-region-as-html beg end t 'string))))
1756 (when (fboundp 'x-set-selection)
1757 (ignore-errors (x-set-selection 'PRIMARY html))
1758 (ignore-errors (x-set-selection 'CLIPBOARD html)))
1759 (message "html export done, pushed to kill ring and clipboard"))))
1762 *** Adopting for Gnus
1764 The whole magic lies in the special strings that mark a HTML
1765 attachment. So you might just have to find out what these special
1766 strings are in message-mode and modify the functions accordingly.
1767 ** Add sunrise/sunset times to the agenda.
1770 The diary package provides the function =diary-sunrise-sunset= which can be used
1771 in a diary s-expression in some agenda file like this:
1774 %%(diary-sunrise-sunset)
1777 Seb Vauban asked if it is possible to put sunrise and sunset in
1778 separate lines. Here is a hack to do that. It adds two functions (they
1779 have to be available before the agenda is shown, so I add them early
1780 in my org-config file which is sourced from .emacs, but you'll have to
1781 suit yourself here) that just parse the output of
1782 diary-sunrise-sunset, instead of doing the right thing which would be
1783 to take advantage of the data structures that diary/solar.el provides.
1784 In short, a hack - so perfectly suited for inclusion here :-)
1786 The functions (and latitude/longitude settings which you have to modify for
1787 your location) are as follows:
1789 #begin_src emacs-lisp
1790 (setq calendar-latitude 40.3)
1791 (setq calendar-longitude -71.0)
1792 (defun diary-sunrise ()
1793 (let ((dss (diary-sunrise-sunset)))
1796 (goto-char (point-min))
1797 (while (re-search-forward " ([^)]*)" nil t)
1798 (replace-match "" nil nil))
1799 (goto-char (point-min))
1800 (search-forward ",")
1801 (buffer-substring (point-min) (match-beginning 0)))))
1803 (defun diary-sunset ()
1804 (let ((dss (diary-sunrise-sunset))
1808 (goto-char (point-min))
1809 (while (re-search-forward " ([^)]*)" nil t)
1810 (replace-match "" nil nil))
1811 (goto-char (point-min))
1812 (search-forward ", ")
1813 (setq start (match-end 0))
1814 (search-forward " at")
1815 (setq end (match-beginning 0))
1818 (buffer-substring start end))))
1821 You also need to add a couple of diary s-expressions in one of your agenda
1829 The thread on the mailing list that started this can be found [[http://thread.gmane.org/gmane.emacs.orgmode/38723Here%20is%20a%20pointer%20to%20the%20thread%20on%20the%20mailing%20list][here]].
1830 In comparison to the version posted on the mailing list, this one
1831 gets rid of the timezone information.
1832 * Hacking Org: Working with Org-mode and External Programs.
1833 ** Use Org-mode with Screen [Andrew Hyatt]
1835 "The general idea is that you start a task in which all the work will
1836 take place in a shell. This usually is not a leaf-task for me, but
1837 usually the parent of a leaf task. From a task in your org-file, M-x
1838 ash-org-screen will prompt for the name of a session. Give it a name,
1839 and it will insert a link. Open the link at any time to go the screen
1840 session containing your work!"
1842 http://article.gmane.org/gmane.emacs.orgmode/5276
1844 #+BEGIN_SRC emacs-lisp
1847 (defun ash-org-goto-screen (name)
1848 "Open the screen with the specified name in the window"
1849 (interactive "MScreen name: ")
1850 (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1851 (if (member screen-buffer-name
1852 (mapcar 'buffer-name (buffer-list)))
1853 (switch-to-buffer screen-buffer-name)
1854 (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1856 (defun ash-org-screen-buffer-name (name)
1857 "Returns the buffer name corresponding to the screen name given."
1858 (concat "*screen " name "*"))
1860 (defun ash-org-screen-helper (name arg)
1861 ;; Pick the name of the new buffer.
1862 (let ((term-ansi-buffer-name
1863 (generate-new-buffer-name
1864 (ash-org-screen-buffer-name name))))
1865 (setq term-ansi-buffer-name
1866 (term-ansi-make-term
1867 term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1868 (set-buffer term-ansi-buffer-name)
1871 (term-set-escape-char ?\C-x)
1872 term-ansi-buffer-name))
1874 (defun ash-org-screen (name)
1875 "Start a screen session with name"
1876 (interactive "MScreen name: ")
1878 (ash-org-screen-helper name "-S"))
1879 (insert-string (concat "[[screen:" name "]]")))
1881 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1882 ;; \"%s\")") to org-link-abbrev-alist.
1885 ** Org Agenda + Appt + Zenity
1887 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]]. It make sure your agenda
1888 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1891 #+BEGIN_SRC emacs-lisp
1892 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1893 ; For org appointment reminders
1895 ;; Get appointments for today
1896 (defun my-org-agenda-to-appt ()
1898 (setq appt-time-msg-list nil)
1899 (let ((org-deadline-warning-days 0)) ;; will be automatic in org 5.23
1900 (org-agenda-to-appt)))
1902 ;; Run once, activate and schedule refresh
1903 (my-org-agenda-to-appt)
1905 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
1908 (setq appt-message-warning-time 15)
1909 (setq appt-display-interval 5)
1911 ; Update appt each time agenda opened.
1912 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
1914 ; Setup zenify, we tell appt to use window, and replace default function
1915 (setq appt-display-format 'window)
1916 (setq appt-disp-window-function (function my-appt-disp-window))
1918 (defun my-appt-disp-window (min-to-app new-time msg)
1919 (save-window-excursion (shell-command (concat
1920 "/usr/bin/zenity --info --title='Appointment' --text='"
1921 msg "' &") nil nil)))
1924 ** Org-Mode + gnome-osd
1926 Richard Riley uses gnome-osd in interaction with Org-Mode to display
1927 appointments. You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
1933 http://article.gmane.org/gmane.emacs.orgmode/5073
1936 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
1937 command line calendaring program. Its features superseed the possibilities
1938 of orgmode in the area of date specifying, so that I want to use it
1939 combined with orgmode.
1941 Using the script below I'm able use remind and incorporate its output in my
1942 agenda views. The default of using 13 months look ahead is easily
1943 changed. It just happens I sometimes like to look a year into the
1947 ** Useful webjumps for conkeror
1949 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
1950 your =~/.conkerorrc= file:
1953 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
1954 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
1957 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
1958 Org-mode mailing list.
1960 ** Use MathJax for HTML export without requiring JavaScript
1961 As of 2010-08-14, MathJax is the default method used to export math to HTML.
1963 If you like the results but do not want JavaScript in the exported pages,
1964 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
1965 HTML file from the exported version. It can also embed all referenced fonts
1966 within the HTML file itself, so there are no dependencies to external files.
1968 The download archive contains an elisp file which integrates it into the Org
1969 export process (configurable per file with a "#+StaticMathJax:" line).
1971 Read README.org and the comments in org-static-mathjax.el for usage instructions.
1972 ** Search Org files using lgrep
1974 Matt Lundin suggests this:
1976 #+begin_src emacs-lisp
1977 (defun my-org-grep (search &optional context)
1978 "Search for word in org files.
1980 Prefix argument determines number of lines."
1981 (interactive "sSearch for: \nP")
1982 (let ((grep-find-ignored-files '("#*" ".#*"))
1983 (grep-template (concat "grep <X> -i -nH "
1985 (concat "-C" (number-to-string context)))
1987 (lgrep search "*org*" "/home/matt/org/")))
1989 (global-set-key (kbd "<f8>") 'my-org-grep)
1992 ** Automatic screenshot insertion
1994 Suggested by Jonathan Bisson:
1996 #+begin_src emacs-lisp
1997 (defun my-screenshot ()
1998 "Take a screenshot into a unique-named file in the current buffer file
1999 directory and insert a link to this file."
2004 (file-name-directory (buffer-file-name))) ".jpg"))
2005 (call-process "import" nil nil nil filename)
2006 (insert (concat "[[" filename "]]"))
2007 (org-display-inline-images))
2010 ** Capture invitations/appointments from MS Exchange emails
2012 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this. Please check
2013 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]