Add Marco Wahl to the list of signed contributors
[worg.git] / org-hacks.org
blobfa8eb7ddad2c51bbc2fdf6cc8e0b2888a6b71184
1 #+TITLE:      Org ad hoc code, quick hacks and workarounds
2 #+AUTHOR:     Worg people
3 #+EMAIL:      mdl AT imapmail DOT org
4 #+OPTIONS:    H:3 num:nil toc:t \n:nil ::t |:t ^:t -:t f:t *:t tex:t d:(HIDE) tags:not-in-toc
5 #+STARTUP:    align fold nodlcheck hidestars oddeven lognotestate
6 #+SEQ_TODO:   TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
7 #+TAGS:       Write(w) Update(u) Fix(f) Check(c)
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 ** Org Agenda
23 *** Picking up a random task in the global TODO list
25 Tony day [[http://mid.gmane.org/m2zk19l1me.fsf@gmail.com][shared]] [[https://gist.github.com/4343164][this gist]] to pick up a
26 random task.
28 ** Building and Managing Org
29 *** Generating autoloads and Compiling Org without make
30     :PROPERTIES:
31     :CUSTOM_ID: compiling-org-without-make
32     :END:
34 #+index: Compilation!without make
36   Compilation is optional, but you _must_ update the autoloads file
37   each time you update org, even when you run org uncompiled!
39   Starting with Org 7.9 you'll find functions for creating the
40   autoload files and do byte-compilation in =mk/org-fixup.el=.  When
41   you execute the commands below, your current directory must be where
42   org has been unpacked into, in other words the file =README= should
43   be found in your current directory and the directories =lisp= and
44   =etc= should be subdirectories of it.  The command =emacs= should be
45   found in your =PATH= and start the Emacs version you are using.  To
46   make just the autoloads file do:
47   : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
48   To make the autoloads file and byte-compile org:
49   : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
50   To make the autoloads file and byte-compile all of org again:
51   : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
52   If you are not using Git, you'll have to make fake version strings
53   first if =org-version.el= is not already available (if it is, you
54   could also edit the version strings there).
55   : emacs -batch -Q -L lisp -l ../mk/org-fixup \
56   : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
57   : (org-make-autoloads))'
58   The above assumes a
59   POSIX shell for its quoting.  Windows =CMD.exe= has quite different
60   quoting rules and this won't work, so your other option is to start
61   Emacs like this
62   : emacs -Q -L lisp -l ../mk/org-fixup
63   then paste the following into the =*scratch*= buffer
64 #+BEGIN_SRC emacs-lisp
65   (let ((org-fake-release     "7.9.1")
66         (org-fake-git-version "7.9.1-fake"))
67     (org-make-autoloads))
68 #+END_SRC
69   position the cursor after the closing paren and press =C-j= or =C-x
70   C-e= to evaluate the form.  Of course you can replace
71   =org-make-autoloads= with =org-make-autoloads-compile= or even
72   =org-make-autoloads-compile-force= if you wish with both variants.
74   For *older org versions only* (that do not yet have
75   =mk/org-fixup.el=), you can use the definitions below.  To use
76   this function, adjust the variables =my/org-lisp-directory= and
77   =my/org-compile-sources= to suit your needs.  If you have
78   byte-compiled org, but want to run org uncompiled again, just remove
79   all =*.elc= files in the =lisp/= directory, set
80   =my/org-compile-sources= to =nil=.
82 #+BEGIN_SRC emacs-lisp
83   (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
84     "Directory where your org-mode files live.")
85   
86   (defvar my/org-compile-sources t
87     "If `nil', never compile org-sources. `my/compile-org' will only create
88   the autoloads file `org-loaddefs.el' then. If `t', compile the sources, too.")
89   
90   ;; Customize: (must end with a slash!)
91   (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")
92   
93   ;; Customize:
94   (setq  my/org-compile-sources t)
95   
96   (defun my/compile-org(&optional directory)
97     "Generate autoloads file org-loaddefs.el.  Optionally compile
98      all *.el files that come with org-mode."
99     (interactive)
100     (defun my/compile-org()
101       "Generate autoloads file org-loaddefs.el.  Optionally compile
102        all *.el files that come with org-mode."
103       (interactive)
104       (let ((dirlisp (file-name-directory my/org-lisp-directory)))
105         (add-to-list 'load-path dirlisp)
106         (require 'autoload)
107         (let ((generated-autoload-file (concat dirlisp "org-loaddefs.el")))
108           ;; create the org-loaddefs file
109           (update-directory-autoloads dirlisp)
110           (when my/org-compile-sources
111             ;; optionally byte-compile
112             (byte-recompile-directory dirlisp 0 'force)))))
113   #+END_SRC
114 *** Reload Org
116 #+index: Initialization!Reload
118 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
119 function to reload org files.
121 Normally you want to use the compiled files since they are faster.
122 If you update your org files you can easily reload them with
124 : M-x org-reload
126 If you run into a bug and want to generate a useful backtrace you can
127 reload the source files instead of the compiled files with
129 : C-u M-x org-reload
131 and turn on the "Enter Debugger On Error" option.  Redo the action
132 that generates the error and cut and paste the resulting backtrace.
133 To switch back to the compiled version just reload again with
135 : M-x org-reload
137 *** Check for possibly problematic old link escapes
138 :PROPERTIES:
139 :CUSTOM_ID: check-old-link-escapes
140 :END:
141 #+index: Link!Escape
142 Starting with version 7.5 Org uses [[http://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
143 and with a modified algorithm to determine which characters to escape
144 and how.
146 As a side effect this modified behaviour might break existing links if
147 they contain a sequence of characters that look like a percent escape
148 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
150 The function below can be used to perform a preliminary check for such
151 links in an Org mode file.  It will run through all links in the file
152 and issue a warning if it finds a percent escape sequence which is not
153 in old Org's list of known percent escapes.
155 #+begin_src emacs-lisp
156   (defun dmaus/org-check-percent-escapes ()
157     "*Check buffer for possibly problematic old link escapes."
158     (interactive)
159     (when (eq major-mode 'org-mode)
160       (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
161                            "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
162         (unless (boundp 'warning-suppress-types)
163           (setq warning-suppress-types nil))
164         (widen)
165         (show-all)
166         (goto-char (point-min))
167         (while (re-search-forward org-any-link-re nil t)
168           (let ((end (match-end 0)))
169             (goto-char (match-beginning 0))
170             (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
171               (let ((escape (match-string-no-properties 0)))
172                 (unless (member (upcase escape) old-escapes)
173                   (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
174                         escape
175                         (buffer-name)
176                         (- (point) 3)))))
177             (goto-char end))))))
178 #+end_src
180 ** Structure Movement and Editing
181 *** Go back to the previous top-level heading
183 #+BEGIN_SRC emacs-lisp
184 (defun org-back-to-top-level-heading ()
185   "Go back to the current top level heading."
186   (interactive)
187   (or (re-search-backward "^\* " nil t)
188       (goto-char (point-min))))
189 #+END_SRC
191 *** Show next/prev heading tidily
193 #+index: Navigation!Heading
194 - Dan Davison
195   These close the current heading and open the next/previous heading.
197 #+begin_src emacs-lisp
198 (defun ded/org-show-next-heading-tidily ()
199   "Show next entry, keeping other entries closed."
200   (if (save-excursion (end-of-line) (outline-invisible-p))
201       (progn (org-show-entry) (show-children))
202     (outline-next-heading)
203     (unless (and (bolp) (org-on-heading-p))
204       (org-up-heading-safe)
205       (hide-subtree)
206       (error "Boundary reached"))
207     (org-overview)
208     (org-reveal t)
209     (org-show-entry)
210     (show-children)))
212 (defun ded/org-show-previous-heading-tidily ()
213   "Show previous entry, keeping other entries closed."
214   (let ((pos (point)))
215     (outline-previous-heading)
216     (unless (and (< (point) pos) (bolp) (org-on-heading-p))
217       (goto-char pos)
218       (hide-subtree)
219       (error "Boundary reached"))
220     (org-overview)
221     (org-reveal t)
222     (org-show-entry)
223     (show-children)))
225 (setq org-use-speed-commands t)
226 (add-to-list 'org-speed-commands-user
227              '("n" ded/org-show-next-heading-tidily))
228 (add-to-list 'org-speed-commands-user
229              '("p" ded/org-show-previous-heading-tidily))
230 #+end_src
232 *** Promote all items in subtree
233 #+index: Structure Editing!Promote
234 - Matt Lundin
236 This function will promote all items in a subtree. Since I use
237 subtrees primarily to organize projects, the function is somewhat
238 unimaginatively called my-org-un-project:
240 #+begin_src emacs-lisp
241 (defun my-org-un-project ()
242   (interactive)
243   (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
244   (org-cycle t))
245 #+end_src
247 *** Turn a heading into an Org link
248     :PROPERTIES:
249     :CUSTOM_ID: heading-to-link
250     :END:
251 #+index: Structure Editing!Heading
252 #+index: Link!Turn a heading into a
253 From David Maus:
255 #+begin_src emacs-lisp
256   (defun dmj:turn-headline-into-org-mode-link ()
257     "Replace word at point by an Org mode link."
258     (interactive)
259     (when (org-at-heading-p)
260       (let ((hl-text (nth 4 (org-heading-components))))
261         (unless (or (null hl-text)
262                     (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
263           (beginning-of-line)
264           (search-forward hl-text (point-at-eol))
265           (replace-string
266            hl-text
267            (format "[[file:%s.org][%s]]"
268                    (org-link-escape hl-text)
269                    (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
270            nil (- (point) (length hl-text)) (point))))))
271 #+end_src
273 *** Using M-up and M-down to transpose paragraphs
274 #+index: Structure Editing!paragraphs
276 From Paul Sexton: By default, if used within ordinary paragraphs in
277 org mode, =M-up= and =M-down= transpose *lines* (not sentences).  The
278 following code makes these keys transpose paragraphs, keeping the
279 point at the start of the moved paragraph. Behavior in tables and
280 headings is unaffected. It would be easy to modify this to transpose
281 sentences.
283 #+begin_src emacs-lisp
284 (defun org-transpose-paragraphs (arg)
285  (interactive)
286  (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
287             (thing-at-point 'sentence))
288    (transpose-paragraphs arg)
289    (backward-paragraph)
290    (re-search-forward "[[:graph:]]")
291    (goto-char (match-beginning 0))
292    t))
294 (add-to-list 'org-metaup-hook 
295  (lambda () (interactive) (org-transpose-paragraphs -1)))
296 (add-to-list 'org-metadown-hook 
297  (lambda () (interactive) (org-transpose-paragraphs 1)))
298 #+end_src
299 *** Changelog support for org headers
300 #+index: Structure Editing!Heading
301 -- James TD Smith
303 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
304 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
305 headline as the "current function" if you add a changelog entry from an org
306 buffer.
308 #+BEGIN_SRC emacs-lisp
309   (defun org-log-current-defun ()
310     (save-excursion
311       (org-back-to-heading)
312       (if (looking-at org-complex-heading-regexp)
313           (match-string 4))))
315   (add-hook 'org-mode-hook
316             (lambda ()
317               (make-variable-buffer-local 'add-log-current-defun-function)
318               (setq add-log-current-defun-function 'org-log-current-defun)))
319 #+END_SRC
321 *** Different org-cycle-level behavior
322 #+index: Cycling!behavior
323 -- Ryan Thompson
325 In recent org versions, when your point (cursor) is at the end of an
326 empty header line (like after you first created the header), the TAB
327 key (=org-cycle=) has a special behavior: it cycles the headline through
328 all possible levels. However, I did not like the way it determined
329 "all possible levels," so I rewrote the whole function, along with a
330 couple of supporting functions.
332 The original function's definition of "all possible levels" was "every
333 level from 1 to one more than the initial level of the current
334 headline before you started cycling." My new definition is "every
335 level from 1 to one more than the previous headline's level." So, if
336 you have a headline at level 4 and you use ALT+RET to make a new
337 headline below it, it will cycle between levels 1 and 5, inclusive.
339 The main advantage of my custom =org-cycle-level= function is that it
340 is stateless: the next level in the cycle is determined entirely by
341 the contents of the buffer, and not what command you executed last.
342 This makes it more predictable, I hope.
344 #+BEGIN_SRC emacs-lisp
345 (require 'cl)
347 (defun org-point-at-end-of-empty-headline ()
348   "If point is at the end of an empty headline, return t, else nil."
349   (and (looking-at "[ \t]*$")
350        (save-excursion
351          (beginning-of-line 1)
352          (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
354 (defun org-level-increment ()
355   "Return the number of stars that will be added or removed at a
356 time to headlines when structure editing, based on the value of
357 `org-odd-levels-only'."
358   (if org-odd-levels-only 2 1))
360 (defvar org-previous-line-level-cached nil)
362 (defun org-recalculate-previous-line-level ()
363   "Same as `org-get-previous-line-level', but does not use cached
364 value. It does *set* the cached value, though."
365   (set 'org-previous-line-level-cached
366        (let ((current-level (org-current-level))
367              (prev-level (when (> (line-number-at-pos) 1)
368                            (save-excursion
369                              (previous-line)
370                              (org-current-level)))))
371          (cond ((null current-level) nil) ; Before first headline
372                ((null prev-level) 0)      ; At first headline
373                (prev-level)))))
375 (defun org-get-previous-line-level ()
376   "Return the outline depth of the last headline before the
377 current line. Returns 0 for the first headline in the buffer, and
378 nil if before the first headline."
379   ;; This calculation is quite expensive, with all the regex searching
380   ;; and stuff. Since org-cycle-level won't change lines, we can reuse
381   ;; the last value of this command.
382   (or (and (eq last-command 'org-cycle-level)
383            org-previous-line-level-cached)
384       (org-recalculate-previous-line-level)))
386 (defun org-cycle-level ()
387   (interactive)
388   (let ((org-adapt-indentation nil))
389     (when (org-point-at-end-of-empty-headline)
390       (setq this-command 'org-cycle-level) ;Only needed for caching
391       (let ((cur-level (org-current-level))
392             (prev-level (org-get-previous-line-level)))
393         (cond
394          ;; If first headline in file, promote to top-level.
395          ((= prev-level 0)
396           (loop repeat (/ (- cur-level 1) (org-level-increment))
397                 do (org-do-promote)))
398          ;; If same level as prev, demote one.
399          ((= prev-level cur-level)
400           (org-do-demote))
401          ;; If parent is top-level, promote to top level if not already.
402          ((= prev-level 1)
403           (loop repeat (/ (- cur-level 1) (org-level-increment))
404                 do (org-do-promote)))
405          ;; If top-level, return to prev-level.
406          ((= cur-level 1)
407           (loop repeat (/ (- prev-level 1) (org-level-increment))
408                 do (org-do-demote)))
409          ;; If less than prev-level, promote one.
410          ((< cur-level prev-level)
411           (org-do-promote))
412          ;; If deeper than prev-level, promote until higher than
413          ;; prev-level.
414          ((> cur-level prev-level)
415           (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
416                 do (org-do-promote))))
417         t))))
418 #+END_SRC
420 *** Count words in an Org buffer
421 # FIXME: Does not fit too well under Structure. Any idea where to put it?
422 Paul Sexton [[http://article.gmane.org/gmane.emacs.orgmode/38014][posted]] this function to count words in an Org buffer:
424 #+begin_src emacs-lisp
425 (defun org-word-count (beg end
426                            &optional count-latex-macro-args?
427                            count-footnotes?)
428   "Report the number of words in the Org mode buffer or selected region.
429 Ignores:
430 - comments
431 - tables
432 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
433 - hyperlinks (but does count words in hyperlink descriptions)
434 - tags, priorities, and TODO keywords in headers
435 - sections tagged as 'not for export'.
437 The text of footnote definitions is ignored, unless the optional argument
438 COUNT-FOOTNOTES? is non-nil.
440 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
441 includes LaTeX macro arguments (the material between {curly braces}).
442 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
443 of its arguments."
444   (interactive "r")
445   (unless mark-active
446     (setf beg (point-min)
447           end (point-max)))
448   (let ((wc 0)
449         (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
450     (save-excursion
451       (goto-char beg)
452       (while (< (point) end)
453         (cond
454          ;; Ignore comments.
455          ((or (org-in-commented-line) (org-at-table-p))
456           nil)
457          ;; Ignore hyperlinks. But if link has a description, count
458          ;; the words within the description.
459          ((looking-at org-bracket-link-analytic-regexp)
460           (when (match-string-no-properties 5)
461             (let ((desc (match-string-no-properties 5)))
462               (save-match-data
463                 (incf wc (length (remove "" (org-split-string
464                                              desc "\\W")))))))
465           (goto-char (match-end 0)))
466          ((looking-at org-any-link-re)
467           (goto-char (match-end 0)))
468          ;; Ignore source code blocks.
469          ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
470           nil)
471          ;; Ignore inline source blocks, counting them as 1 word.
472          ((save-excursion
473             (backward-char)
474             (looking-at org-babel-inline-src-block-regexp))
475           (goto-char (match-end 0))
476           (setf wc (+ 2 wc)))
477          ;; Count latex macros as 1 word, ignoring their arguments.
478          ((save-excursion
479             (backward-char)
480             (looking-at latex-macro-regexp))
481           (goto-char (if count-latex-macro-args?
482                          (match-beginning 2)
483                        (match-end 0)))
484           (setf wc (+ 2 wc)))
485          ;; Ignore footnotes.
486          ((and (not count-footnotes?)
487                (or (org-footnote-at-definition-p)
488                    (org-footnote-at-reference-p)))
489           nil)
490          (t
491           (let ((contexts (org-context)))
492             (cond
493              ;; Ignore tags and TODO keywords, etc.
494              ((or (assoc :todo-keyword contexts)
495                   (assoc :priority contexts)
496                   (assoc :keyword contexts)
497                   (assoc :checkbox contexts))
498               nil)
499              ;; Ignore sections marked with tags that are
500              ;; excluded from export.
501              ((assoc :tags contexts)
502               (if (intersection (org-get-tags-at) org-export-exclude-tags
503                                 :test 'equal)
504                   (org-forward-same-level 1)
505                 nil))
506              (t
507               (incf wc))))))
508         (re-search-forward "\\w+\\W*")))
509     (message (format "%d words in %s." wc
510                      (if mark-active "region" "buffer")))))
511 #+end_src
513 *** Check for misplaced SCHEDULED and DEADLINE cookies
515 The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
516 below* the headline -- like this:
518 #+begin_src org
519 ,* A headline
520   SCHEDULED: <2012-04-09 lun.>
521 #+end_src
523 This is what =org-scheduled= and =org-deadline= (and other similar
524 commands) do.  And the manual explicitely tell people to stick to this
525 format (see the section "8.3.1 Inserting deadlines or schedules").
527 If you think you might have subtrees with misplaced =SCHEDULED= and
528 =DEADLINE= cookies, this command lets you check the current buffer:
530 #+begin_src emacs-lisp
531 (defun org-check-misformatted-subtree ()
532   "Check misformatted entries in the current buffer."
533   (interactive)
534   (show-all)
535   (org-map-entries
536    (lambda ()
537      (when (and (move-beginning-of-line 2)
538                 (not (looking-at org-heading-regexp)))
539        (if (or (and (org-get-scheduled-time (point))
540                     (not (looking-at (concat "^.*" org-scheduled-regexp))))
541                (and (org-get-deadline-time (point))
542                     (not (looking-at (concat "^.*" org-deadline-regexp)))))
543            (when (y-or-n-p "Fix this subtree? ")
544              (message "Call the function again when you're done fixing this subtree.")
545              (recursive-edit))
546          (message "All subtrees checked."))))))
547 #+end_src
549 *** Sorting list by checkbox type
551 #+index: checkbox!sorting
553 You can use a custom function to sort list by checkbox type.
554 Here is a function suggested by Carsten:
556 #+BEGIN_SRC emacs-lisp
557 (defun org-sort-list-by-checkbox-type ()
558   "Sort list items according to Checkbox state."
559   (interactive)
560   (org-sort-list
561    nil ?f
562    (lambda ()
563      (if (looking-at org-list-full-item-re)
564          (cdr (assoc (match-string 3)
565                      '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
566        4))))
567 #+END_SRC
569 Use the function above directly on the list.  If you want to use an
570 equivalent function after =C-c ^ f=, use this one instead:
572 #+BEGIN_SRC emacs-lisp
573   (defun org-sort-list-by-checkbox-type-1 ()
574     (lambda ()
575       (if (looking-at org-list-full-item-re)
576           (cdr (assoc (match-string 3)
577                       '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
578         4)))
579 #+END_SRC
581 *** Adding Licenses to org files
582   You can add pretty standard licenses, such as creative commons or gfdl to org articles using [[file:code/elisp/org-license.el][org-license.el]].
583 ** Org Table
584    :PROPERTIES:
585    :CUSTOM_ID: Tables
586    :END:
588 *** Align all tables in a file
590 Andrew Young provided this function in [[http://thread.gmane.org/gmane.emacs.orgmode/58974/focus%3D58976][this thread]]:
592 #+begin_src emacs-lisp
593   (defun my-align-all-tables ()
594     (interactive)
595     (org-table-map-tables 'org-table-align 'quietly))
596 #+end_src
598 *** Transpose table
599 #+index: Table!Calculation
600     :PROPERTIES:
601     :CUSTOM_ID: transpose-table
602     :END:
604 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
605 see.)  There are also other solutions:
607 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
608   list, see [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00239.html][gnu]]
610 - with org-babel and R: provided by Dan Davison in the mailing list (old
611   =#+TBLR:= syntax), see [[http://thread.gmane.org/gmane.emacs.orgmode/10159/focus=10159][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2008-12/msg00454.html][gnu]]
613 - with field coordinates in formulas (=@#= and =$#=): see [[file:org-hacks.org::#field-coordinates-in-formulas-transpose-table][Worg]].
615 *** Manipulate hours/minutes/seconds in table formulas
616 #+index: Table!hours-minutes-seconds
617 Both Bastien and Martin Halder have posted code ([[http://article.gmane.org/gmane.emacs.orgmode/39519][Bastien's code]] and
618 [[http://article.gmane.org/gmane.emacs.orgmode/39519][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
619 "=d=" is any digit) as time values in Org-mode table formula.  These
620 functions have now been wrapped up into a =with-time= macro which can
621 be used in table formula to translate table cell values to and from
622 numerical values for algebraic manipulation.
624 Here is the code implementing this macro.
625 #+begin_src emacs-lisp :results silent
626   (defun org-time-string-to-seconds (s)
627     "Convert a string HH:MM:SS to a number of seconds."
628     (cond
629      ((and (stringp s)
630            (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
631       (let ((hour (string-to-number (match-string 1 s)))
632             (min (string-to-number (match-string 2 s)))
633             (sec (string-to-number (match-string 3 s))))
634         (+ (* hour 3600) (* min 60) sec)))
635      ((and (stringp s)
636            (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
637       (let ((min (string-to-number (match-string 1 s)))
638             (sec (string-to-number (match-string 2 s))))
639         (+ (* min 60) sec)))
640      ((stringp s) (string-to-number s))
641      (t s)))
643   (defun org-time-seconds-to-string (secs)
644     "Convert a number of seconds to a time string."
645     (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
646           ((>= secs 60) (format-seconds "%m:%.2s" secs))
647           (t (format-seconds "%s" secs))))
649   (defmacro with-time (time-output-p &rest exprs)
650     "Evaluate an org-table formula, converting all fields that look
651   like time data to integer seconds.  If TIME-OUTPUT-P then return
652   the result as a time value."
653     (list
654      (if time-output-p 'org-time-seconds-to-string 'identity)
655      (cons 'progn
656            (mapcar
657             (lambda (expr)
658               `,(cons (car expr)
659                       (mapcar
660                        (lambda (el)
661                          (if (listp el)
662                              (list 'with-time nil el)
663                            (org-time-string-to-seconds el)))
664                        (cdr expr))))
665             `,@exprs))))
666 #+end_src
668 Which allows the following forms of table manipulation such as adding
669 and subtracting time values.
670 : | Date             | Start | Lunch |  Back |   End |  Sum |
671 : |------------------+-------+-------+-------+-------+------|
672 : | [2011-03-01 Tue] |  8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
673 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
675 and dividing time values by integers
676 : |  time | miles | minutes/mile |
677 : |-------+-------+--------------|
678 : | 34:43 |   2.9 |        11:58 |
679 : | 32:15 |  2.77 |        11:38 |
680 : | 33:56 |   3.0 |        11:18 |
681 : | 52:22 |  4.62 |        11:20 |
682 : #+TBLFM: $3='(with-time t (/ $1 $2))
684 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
685 Elisp formulas) to compute time durations.  For example:
687 : | Task 1 | Task 2 |   Total |
688 : |--------+--------+---------|
689 : |  35:00 |  35:00 | 1:10:00 |
690 : #+TBLFM: @2$3=$1+$2;T
692 *** Dates computation
693 #+index: Table!dates
694 Xin Shi [[http://article.gmane.org/gmane.emacs.orgmode/15692][asked]] for a way to calculate the duration of 
695 dates stored in an org table.
697 Nick Dokos [[http://article.gmane.org/gmane.emacs.orgmode/15694][suggested]]:
699 Try the following:
701 : | Start Date |   End Date | Duration |
702 : |------------+------------+----------|
703 : | 2004.08.07 | 2005.07.08 |      335 |
704 : #+TBLFM: $3=(date(<$2>)-date(<$1>))
706 See [[http://thread.gmane.org/gmane.emacs.orgmode/7741][this thread]] as well as [[http://article.gmane.org/gmane.emacs.orgmode/7753][this post]] (which is really a followup on the
707 above).  The problem that this last article pointed out was solved in [[http://article.gmane.org/gmane.emacs.orgmode/8001][this
708 post]] and Chris Randle's original musings are [[http://article.gmane.org/gmane.emacs.orgmode/6536/][here]].
710 *** Hex computation
711 #+index: Table!Calculation
712 As with Times computation, the following code allows Computation with
713 Hex values in Org-mode tables using the =with-hex= macro.
715 Here is the code implementing this macro.
716 #+begin_src emacs-lisp
717   (defun org-hex-strip-lead (str)
718     (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
719         (substring str 2) str))
721   (defun org-hex-to-hex (int)
722     (format "0x%x" int))
724   (defun org-hex-to-dec (str)
725     (cond
726      ((and (stringp str)
727            (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
728       (let ((out 0))
729         (mapc
730          (lambda (ch)
731            (setf out (+ (* out 16)
732                         (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
733          (coerce (match-string 1 str) 'list))
734         out))
735      ((stringp str) (string-to-number str))
736      (t str)))
738   (defmacro with-hex (hex-output-p &rest exprs)
739     "Evaluate an org-table formula, converting all fields that look
740       like hexadecimal to decimal integers.  If HEX-OUTPUT-P then
741       return the result as a hex value."
742     (list
743      (if hex-output-p 'org-hex-to-hex 'identity)
744      (cons 'progn
745            (mapcar
746             (lambda (expr)
747               `,(cons (car expr)
748                       (mapcar (lambda (el)
749                                 (if (listp el)
750                                     (list 'with-hex nil el)
751                                   (org-hex-to-dec el)))
752                               (cdr expr))))
753             `,@exprs))))
754 #+end_src
756 Which allows the following forms of table manipulation such as adding
757 and subtracting hex values.
758 | 0x10 | 0x0 | 0x10 |  16 |
759 | 0x20 | 0x1 | 0x21 |  33 |
760 | 0x30 | 0x2 | 0x32 |  50 |
761 | 0xf0 | 0xf | 0xff | 255 |
762 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
764 *** Field coordinates in formulas (=@#= and =$#=)
765     :PROPERTIES:
766     :CUSTOM_ID: field-coordinates-in-formulas
767     :END:
768 #+index: Table!Field Coordinates
769 -- Michael Brand
771 Following are some use cases that can be implemented with the “field
772 coordinates in formulas” described in the corresponding chapter in the
773 [[http://orgmode.org/manual/References.html#References][Org manual]].
775 **** Copy a column from a remote table into a column
776      :PROPERTIES:
777      :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
778      :END:
780 current column =$3= = remote column =$2=:
781 : #+TBLFM: $3 = remote(FOO, @@#$2)
783 **** Copy a row from a remote table transposed into a column
784      :PROPERTIES:
785      :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
786      :END:
788 current column =$1= = transposed remote row =@1=:
789 : #+TBLFM: $1 = remote(FOO, @$#$@#)
791 **** Transpose table
792      :PROPERTIES:
793      :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
794      :END:
796 -- Michael Brand
798 This is more like a demonstration of using “field coordinates in formulas”
799 and is bound to be slow for large tables. See the discussion in the mailing
800 list on
801 [[http://thread.gmane.org/gmane.emacs.orgmode/22610/focus=23662][gmane]] or
802 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
803 For more efficient solutions see
804 [[file:org-hacks.org::#transpose-table][Worg]].
806 To transpose this 4x7 table
808 : #+TBLNAME: FOO
809 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
810 : |------+------+------+------+------+------+------|
811 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
812 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
813 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
815 start with a 7x4 table without any horizontal line (to have filled
816 also the column header) and yet empty:
818 : |   |   |   |   |
819 : |   |   |   |   |
820 : |   |   |   |   |
821 : |   |   |   |   |
822 : |   |   |   |   |
823 : |   |   |   |   |
824 : |   |   |   |   |
826 Then add the =TBLFM= line below.  After recalculation this will end up with
827 the transposed copy:
829 : | year | min | avg | max |
830 : | 2004 | 401 | 402 | 403 |
831 : | 2005 | 501 | 502 | 503 |
832 : | 2006 | 601 | 602 | 603 |
833 : | 2007 | 701 | 702 | 703 |
834 : | 2008 | 801 | 802 | 803 |
835 : | 2009 | 901 | 902 | 903 |
836 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
838 The formula simply exchanges row and column numbers by taking
839 - the absolute remote row number =@$#= from the current column number =$#=
840 - the absolute remote column number =$@#= from the current row number =@#=
842 Formulas to be taken over from the remote table will have to be transformed
843 manually.
845 **** Dynamic variation of ranges
847 -- Michael Brand
849 In this example all columns next to =quote= are calculated from the column
850 =quote= and show the average change of the time series =quote[year]=
851 during the period of the preceding =1=, =2=, =3= or =4= years:
853 : | year | quote |   1 a |   2 a |   3 a |   4 a |
854 : |------+-------+-------+-------+-------+-------|
855 : | 2005 |    10 |       |       |       |       |
856 : | 2006 |    12 | 0.200 |       |       |       |
857 : | 2007 |    14 | 0.167 | 0.183 |       |       |
858 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
859 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
860 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
862 The important part of the formula without the field blanking is:
864 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
866 which is the Emacs Calc implementation of the equation
868 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
870 where /i/ is the current time and /a/ is the length of the preceding period.
872 *** Rearrange one or more field within the same row or column
873 #+index: Table!Editing
874     :PROPERTIES:
875     :CUSTOM_ID: field-same-row-or-column
876     :END:
878 -- Michael Brand
880 **** Rearrange the column sequence in one row only
881 #+index: Table!Editing
882      :PROPERTIES:
883      :CUSTOM_ID: column-sequence-in-row
884      :END:
886 The functions below can be used to change the column sequence in one
887 row only, without affecting the other rows above and below like with
888 =M-<left>= or =M-<right>= (=org-table-move-column=).  See also the
889 docstring of the functions for more explanations.  The original table
890 that serves as the starting point for the examples:
892 : | a | b | c  | d  |
893 : | e | 9 | 10 | 11 |
894 : | f | g | h  | i  |
896 ***** Move current field in row
897 ****** Left
899 1) place point at "10" in original table
900 2) =M-x f-org-table-move-field-in-row-left=
901 3) point is at moved "10"
903 : | a | b  | c | d  |
904 : | e | 10 | 9 | 11 |
905 : | f | g  | h | i  |
907 ****** Right
909 1) place point at "9" in original table
910 2) =M-x f-org-table-move-field-in-row-right=
911 3) point is at moved "9"
913 : | a | b  | c | d  |
914 : | e | 10 | 9 | 11 |
915 : | f | g  | h | i  |
917 ***** Rotate rest of row (range from current field to end of row)
918 ****** Left
920 1) place point at @2$2 in original table
921 2) =M-x f-org-table-rotate-rest-of-row-left=
922 3) point is still at @2$2
924 : | a | b  | c  | d |
925 : | e | 10 | 11 | 9 |
926 : | f | g  | h  | i |
928 ****** Right
930 1) place point at @2$2 in original table
931 2) =M-x f-org-table-rotate-rest-of-row-right=
932 3) point is still at @2$2
934 : | a | b  | c | d  |
935 : | e | 11 | 9 | 10 |
936 : | f | g  | h | i  |
938 ***** Open field in row (table size grows)
940 This is just for completeness, interactively the same as typing =|
941 S-TAB=.
943 1) place point at @2$2 in original table
944 2) =M-x f-org-table-open-field-in-row-grow=
945 3) point is still at @2$2
947 : | a | b | c | d  |    |
948 : | e |   | 9 | 10 | 11 |
949 : | f | g | h | i  |    |
951 **** Rearrange the row sequence in one column only
952 #+index: Table!Editing
953      :PROPERTIES:
954      :CUSTOM_ID: row-sequence-in-column
955      :END:
957 The functions below can be used to change the column sequence in one
958 column only, without affecting the other columns left and right like
959 with =M-<up>= or =M-<down>= (=org-table-move-row=).  See also the
960 docstring of the functions for more explanations.  The original table
961 that serves as the starting point for the examples:
963 : | a |  b | c |
964 : |---+----+---|
965 : | d |  9 | e |
966 : | f | 10 | g |
967 : |---+----+---|
968 : | h | 11 | i |
970 ***** Move current field in column
971 ****** Up
973 1) place point at "10" in original table
974 2) =M-x f-org-table-move-field-in-column-up=
975 3) point is at moved "10"
977 : | a |  b | c |
978 : |---+----+---|
979 : | d | 10 | e |
980 : | f |  9 | g |
981 : |---+----+---|
982 : | h | 11 | i |
984 ****** Down
986 1) place point at "9" in original table
987 2) =M-x f-org-table-move-field-in-column-down=
988 3) point is at moved "9"
990 : | a |  b | c |
991 : |---+----+---|
992 : | d | 10 | e |
993 : | f |  9 | g |
994 : |---+----+---|
995 : | h | 11 | i |
997 ***** Rotate rest of column (range from current field to end of column)
998 ****** Up
1000 1) place point at @2$2 in original table
1001 2) =M-x f-org-table-rotate-rest-of-column-up=
1002 3) point is still at @2$2
1004 : | a |  b | c |
1005 : |---+----+---|
1006 : | d | 10 | e |
1007 : | f | 11 | g |
1008 : |---+----+---|
1009 : | h |  9 | i |
1011 ****** Down
1013 1) place point at @2$2 in original table
1014 2) =M-x f-org-table-rotate-rest-of-column-down=
1015 3) point is still at @2$2
1017 : | a |  b | c |
1018 : |---+----+---|
1019 : | d | 11 | e |
1020 : | f |  9 | g |
1021 : |---+----+---|
1022 : | h | 10 | i |
1024 ***** Open field in column (table size grows)
1026 1) place point at @2$2 in original table
1027 2) =M-x f-org-table-open-field-in-column-grow=
1028 3) point is still at @2$2
1030 : | a |  b | c |
1031 : |---+----+---|
1032 : | d |    | e |
1033 : | f |  9 | g |
1034 : |---+----+---|
1035 : | h | 10 | i |
1036 : |   | 11 |   |
1038 **** Key bindings for some of the functions
1040 I have this in an Org buffer to change temporarily to the desired
1041 behavior with =C-c C-c= on one of the three code snippets:
1043 : - move in row:
1044 :   #+begin_src emacs-lisp :results silent
1045 :     (org-defkey org-mode-map [(meta left)]
1046 :                 'f-org-table-move-field-in-row-left)
1047 :     (org-defkey org-mode-map [(meta right)]
1048 :                 'f-org-table-move-field-in-row-right)
1049 :     (org-defkey org-mode-map [(left)]  'org-table-previous-field)
1050 :     (org-defkey org-mode-map [(right)] 'org-table-next-field)
1051 :   #+end_src
1053 : - rotate in row:
1054 :   #+begin_src emacs-lisp :results silent
1055 :     (org-defkey org-mode-map [(meta left)]
1056 :                 'f-org-table-rotate-rest-of-row-left)
1057 :     (org-defkey org-mode-map [(meta right)]
1058 :                 'f-org-table-rotate-rest-of-row-right)
1059 :     (org-defkey org-mode-map [(left)]  'org-table-previous-field)
1060 :     (org-defkey org-mode-map [(right)] 'org-table-next-field)
1061 :   #+end_src
1063 : - back to original:
1064 :   #+begin_src emacs-lisp :results silent
1065 :     (org-defkey org-mode-map [(meta left)]  'org-metaleft)
1066 :     (org-defkey org-mode-map [(meta right)] 'org-metaright)
1067 :     (org-defkey org-mode-map [(left)]  'backward-char)
1068 :     (org-defkey org-mode-map [(right)] 'forward-char)
1069 :   #+end_src
1071 **** Implementation
1073 The functions
1075 : f-org-table-move-field-in-column-up
1076 : f-org-table-move-field-in-column-down
1077 : f-org-table-rotate-rest-of-column-up
1078 : f-org-table-rotate-rest-of-column-down
1080 are not yet implemented.  They could be done similar to
1081 =f-org-table-open-field-in-column-grow=.  A workaround without keeping
1082 horizontal separator lines is to interactively or programmatically
1083 simply:
1085 1) Transpose the table, see
1086    [[http://orgmode.org/worg/org-hacks.html#transpose-table][Org hacks]].
1087 2) Use =f-org-table-*-column-in-row-*=, see
1088    [[http://orgmode.org/worg/org-hacks.html#column-sequence-in-row][previous
1089    section]].
1090 3) Transpose the table.
1092 The other functions:
1094 #+BEGIN_SRC emacs-lisp
1095   (defun f-org-table-move-field-in-row-left ()
1096     "Move current field in row to the left."
1097     (interactive)
1098     (f-org-table-move-field-in-row 'left))
1099   (defun f-org-table-move-field-in-row-right ()
1100     "Move current field in row to the right."
1101     (interactive)
1102     (f-org-table-move-field-in-row nil))
1104   (defun f-org-table-move-field-in-row (&optional left)
1105     "Move current field in row to the right.
1106   With arg LEFT, move to the left.  For repeated invocation the
1107   point follows the moved field.  Does not fix formulas."
1108     ;; Derived from `org-table-move-column'
1109     (interactive "P")
1110     (if (not (org-at-table-p))
1111         (error "Not at a table"))
1112     (org-table-find-dataline)
1113     (org-table-check-inside-data-field)
1114     (let* ((col (org-table-current-column))
1115            (col1 (if left (1- col) col))
1116            ;; Current cursor position
1117            (colpos (if left (1- col) (1+ col))))
1118       (if (and left (= col 1))
1119           (error "Cannot move column further left"))
1120       (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1121           (error "Cannot move column further right"))
1122       (org-table-goto-column col1 t)
1123       (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1124            (replace-match "|\\2|\\1|"))
1125       (org-table-goto-column colpos)
1126       (org-table-align)))
1128   (defun f-org-table-rotate-rest-of-row-left ()
1129     "Rotate rest of row to the left."
1130     (interactive)
1131     (f-org-table-rotate-rest-of-row 'left))
1132   (defun f-org-table-rotate-rest-of-row-right ()
1133     "Rotate rest of row to the right."
1134     (interactive)
1135     (f-org-table-rotate-rest-of-row nil))
1137   (defun f-org-table-rotate-rest-of-row (&optional left)
1138     "Rotate rest of row to the right.
1139   With arg LEFT, rotate to the left.  For both directions the
1140   boundaries of the rotation range are the current field and the
1141   field at the end of the row.  For repeated invocation the point
1142   stays on the original current field.  Does not fix formulas."
1143     ;; Derived from `org-table-move-column'
1144     (interactive "P")
1145     (if (not (org-at-table-p))
1146         (error "Not at a table"))
1147     (org-table-find-dataline)
1148     (org-table-check-inside-data-field)
1149     (let ((col (org-table-current-column)))
1150       (org-table-goto-column col t)
1151       (and (looking-at (if left
1152                            "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
1153                          "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
1154            (replace-match "|\\2|\\1|"))
1155       (org-table-goto-column col)
1156       (org-table-align)))
1158   (defun f-org-table-open-field-in-row-grow ()
1159     "Open field in row, move fields to the right by growing table."
1160     (interactive)
1161     (insert "|")
1162     (backward-char)
1163     (org-table-align))
1165   (defun f-org-table-open-field-in-column-grow ()
1166     "Open field in column, move all fields downwards by growing table."
1167     (interactive)
1168     (let ((col (org-table-current-column))
1169           (p   (point)))
1170       ;; Cut all fields downwards in same column
1171       (goto-char (org-table-end))
1172       (forward-line -1)
1173       (while (org-at-table-hline-p) (forward-line -1))
1174       (org-table-goto-column col)
1175       (org-table-cut-region p (point))
1176       ;; Paste at one field below
1177       (goto-char p)
1178       (forward-line)
1179       (org-table-goto-column col)
1180       (org-table-paste-rectangle)
1181       (goto-char p)
1182       (org-table-align)))
1183 #+END_SRC
1185 **** Reasons why this is not put into the Org core
1187 I consider this as only a hack for several reasons:
1189 - Generalization: The existing function =org-table-move-column= could
1190   be enhanced with additional optional parameters to incorporate these
1191   functionalities and could be used as the only function for better
1192   maintainability.  Now it's only a copy/paste hack of several similar
1193   functions with simple modifications.
1194 - Bindings: Should be convenient for repetition like =M-<right>=.
1195   What should be bound where, what has to be left unbound?
1196 - Does not fix formulas.  Could be resolved for field formulas but
1197   most probably not for column or range formulas and this can lead to
1198   confusion.  AFAIK all table manipulations found in Org core fix
1199   formulas.
1200 - Completeness: Not all variations and combinations are covered yet
1201   - move, rotate with range to end, rotate with range to begin, rotate
1202     all
1203   - left-right, up-down
1205 ** Capture and Remember
1206 *** Customize the size of the frame for remember
1207 #+index: Remember!frame
1208 #+index: Customization!remember
1209 (Note: this hack is likely out of date due to the development of
1210 [[org-capture]].)
1212 # FIXME: gmane link?
1213 On emacs-orgmode, Ryan C. Thompson suggested this:
1215 #+begin_quote
1216 I am using org-remember set to open a new frame when used,
1217 and the default frame size is much too large. To fix this, I have
1218 designed some advice and a custom variable to implement custom
1219 parameters for the remember frame:
1220 #+end_quote
1222 #+begin_src emacs-lisp
1223 (defcustom remember-frame-alist nil
1224   "Additional frame parameters for dedicated remember frame."
1225   :type 'alist
1226   :group 'remember)
1228 (defadvice remember (around remember-frame-parameters activate)
1229   "Set some frame parameters for the remember frame."
1230   (let ((default-frame-alist (append remember-frame-alist
1231                                      default-frame-alist)))
1232     ad-do-it))
1233 #+end_src
1235 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1236 reasonable size for the frame.
1237 ** Handling Links
1238 *** [[#heading-to-link][Turn a heading into an org link]] 
1239 *** Quickaccess to the link part of hyperlinks
1240 #+index: Link!Referent
1241 Christian Moe [[http://permalink.gmane.org/gmane.emacs.orgmode/43122][asked]], if there is a simpler way to copy the link part
1242 of an org hyperling other than to use `C-c C-l C-a C-k C-g', 
1243 which is indeed kind of cumbersome.
1245 The thread offered [[http://permalink.gmane.org/gmane.emacs.orgmode/43606][two ways]]:
1247 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1248 #+begin_src emacs-lisp
1249 (fset 'getlink
1250       (lambda (&optional arg) 
1251         "Keyboard macro." 
1252         (interactive "p") 
1253         (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1254 #+end_src
1256 or a function: 
1257 #+begin_src emacs-lisp
1258 (defun my-org-extract-link ()
1259   "Extract the link location at point and put it on the killring."
1260   (interactive)
1261   (when (org-in-regexp org-bracket-link-regexp 1)
1262     (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1263 #+end_src
1265 They put the link destination on the killring and can be easily bound to a key.
1267 *** Insert link with HTML title as default description
1268 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1269 from HTML <title> tag and use it as a default link description. Here is a way to
1270 accomplish this:
1272 #+begin_src emacs-lisp
1273 (require 'mm-url) ; to include mm-url-decode-entities-string
1275 (defun my-org-insert-link ()
1276   "Insert org link where default description is set to html title."
1277   (interactive)
1278   (let* ((url (read-string "URL: "))
1279          (title (get-html-title-from-url url)))
1280     (org-insert-link nil url title)))
1282 (defun get-html-title-from-url (url)
1283   "Return content in <title> tag."
1284   (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1285     (save-excursion
1286       (set-buffer download-buffer)
1287       (beginning-of-buffer)
1288       (setq x1 (search-forward "<title>"))
1289       (search-forward "</title>")
1290       (setq x2 (search-backward "<"))
1291       (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1292 #+end_src
1294 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1296 ** Archiving Content in Org-Mode
1297 *** Preserve top level headings when archiving to a file
1298 #+index: Archiving!Preserve top level headings
1299 - Matt Lundin
1301 To preserve (somewhat) the integrity of your archive structure while
1302 archiving lower level items to a file, you can use the following
1303 defadvice:
1305 #+begin_src emacs-lisp
1306 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1307   (let ((org-archive-location
1308          (if (save-excursion (org-back-to-heading)
1309                              (> (org-outline-level) 1))
1310              (concat (car (split-string org-archive-location "::"))
1311                      "::* "
1312                      (car (org-get-outline-path)))
1313            org-archive-location)))
1314     ad-do-it))
1315 #+end_src
1317 Thus, if you have an outline structure such as...
1319 #+begin_src org
1320 ,* Heading
1321 ,** Subheading
1322 ,*** Subsubheading
1323 #+end_src
1325 ...archiving "Subsubheading" to a new file will set the location in
1326 the new file to the top level heading:
1328 #+begin_src org
1329 ,* Heading
1330 ,** Subsubheading
1331 #+end_src
1333 While this hack obviously destroys the outline hierarchy somewhat, it
1334 at least preserves the logic of level one groupings.
1336 A slightly more complex version of this hack will not only keep the
1337 archive organized by top-level headings, but will also preserve the
1338 tags found on those headings:
1340 #+begin_src emacs-lisp
1341   (defun my-org-inherited-no-file-tags ()
1342     (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1343           (ltags (org-entry-get nil "TAGS")))
1344       (mapc (lambda (tag)
1345               (setq tags
1346                     (replace-regexp-in-string (concat tag ":") "" tags)))
1347             (append org-file-tags (when ltags (split-string ltags ":" t))))
1348       (if (string= ":" tags) nil tags)))
1350   (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1351     (let ((tags (my-org-inherited-no-file-tags))
1352           (org-archive-location
1353            (if (save-excursion (org-back-to-heading)
1354                                (> (org-outline-level) 1))
1355                (concat (car (split-string org-archive-location "::"))
1356                        "::* "
1357                        (car (org-get-outline-path)))
1358              org-archive-location)))
1359       ad-do-it
1360       (with-current-buffer (find-file-noselect (org-extract-archive-file))
1361         (save-excursion
1362           (while (org-up-heading-safe))
1363           (org-set-tags-to tags)))))
1364 #+end_src
1366 *** Archive in a date tree
1367 #+index: Archiving!date tree
1368 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1370 (Make sure org-datetree.el is loaded for this to work.)
1372 #+begin_src emacs-lisp
1373 ;; (setq org-archive-location "%s_archive::date-tree")
1374 (defadvice org-archive-subtree
1375   (around org-archive-subtree-to-data-tree activate)
1376   "org-archive-subtree to date-tree"
1377   (if
1378       (string= "date-tree"
1379                (org-extract-archive-heading
1380                 (org-get-local-archive-location)))
1381       (let* ((dct (decode-time (org-current-time)))
1382              (y (nth 5 dct))
1383              (m (nth 4 dct))
1384              (d (nth 3 dct))
1385              (this-buffer (current-buffer))
1386              (location (org-get-local-archive-location))
1387              (afile (org-extract-archive-file location))
1388              (org-archive-location
1389               (format "%s::*** %04d-%02d-%02d %s" afile y m d
1390                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1391         (message "afile=%s" afile)
1392         (unless afile
1393           (error "Invalid `org-archive-location'"))
1394         (save-excursion
1395           (switch-to-buffer (find-file-noselect afile))
1396           (org-datetree-find-year-create y)
1397           (org-datetree-find-month-create y m)
1398           (org-datetree-find-day-create y m d)
1399           (widen)
1400           (switch-to-buffer this-buffer))
1401         ad-do-it)
1402     ad-do-it))
1403 #+end_src
1405 *** Add inherited tags to archived entries
1406 #+index: Archiving!Add inherited tags
1407 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1408 advise the function like this:
1410 #+begin_example
1411 (defadvice org-archive-subtree
1412   (before add-inherited-tags-before-org-archive-subtree activate)
1413     "add inherited tags before org-archive-subtree"
1414     (org-set-tags-to (org-get-tags-at)))
1415 #+end_example
1417 ** Using and Managing Org-Metadata
1418 *** Remove redundant tags of headlines
1419 #+index: Tag!Remove redundant
1420 -- David Maus
1422 A small function that processes all headlines in current buffer and
1423 removes tags that are local to a headline and inherited by a parent
1424 headline or the #+FILETAGS: statement.
1426 #+BEGIN_SRC emacs-lisp
1427   (defun dmj/org-remove-redundant-tags ()
1428     "Remove redundant tags of headlines in current buffer.
1430   A tag is considered redundant if it is local to a headline and
1431   inherited by a parent headline."
1432     (interactive)
1433     (when (eq major-mode 'org-mode)
1434       (save-excursion
1435         (org-map-entries
1436          (lambda ()
1437            (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1438                  local inherited tag)
1439              (dolist (tag alltags)
1440                (if (get-text-property 0 'inherited tag)
1441                    (push tag inherited) (push tag local)))
1442              (dolist (tag local)
1443                (if (member tag inherited) (org-toggle-tag tag 'off)))))
1444          t nil))))
1445 #+END_SRC
1447 *** Remove empty property drawers
1448 #+index: Drawer!Empty
1449 David Maus proposed this:
1451 #+begin_src emacs-lisp
1452 (defun dmj:org:remove-empty-propert-drawers ()
1453   "*Remove all empty property drawers in current file."
1454   (interactive)
1455   (unless (eq major-mode 'org-mode)
1456     (error "You need to turn on Org mode for this function."))
1457   (save-excursion
1458     (goto-char (point-min))
1459     (while (re-search-forward ":PROPERTIES:" nil t)
1460       (save-excursion
1461         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1462 #+end_src
1464 *** Group task list by a property
1465 #+index: Agenda!Group task list
1466 This advice allows you to group a task list in Org-Mode.  To use it,
1467 set the variable =org-agenda-group-by-property= to the name of a
1468 property in the option list for a TODO or TAGS search.  The resulting
1469 agenda view will group tasks by that property prior to searching.
1471 #+begin_src emacs-lisp
1472 (defvar org-agenda-group-by-property nil
1473   "Set this in org-mode agenda views to group tasks by property")
1475 (defun org-group-bucket-items (prop items)
1476   (let ((buckets ()))
1477     (dolist (item items)
1478       (let* ((marker (get-text-property 0 'org-marker item))
1479              (pvalue (org-entry-get marker prop t))
1480              (cell (assoc pvalue buckets)))
1481         (if cell
1482             (setcdr cell (cons item (cdr cell)))
1483           (setq buckets (cons (cons pvalue (list item))
1484                               buckets)))))
1485     (setq buckets (mapcar (lambda (bucket)
1486                             (cons (car bucket)
1487                                   (reverse (cdr bucket))))
1488                           buckets))
1489     (sort buckets (lambda (i1 i2)
1490                     (string< (car i1) (car i2))))))
1492 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1493                                                (list &optional nosort))
1494   "Prepare bucketed agenda entry lists"
1495   (if org-agenda-group-by-property
1496       ;; bucketed, handle appropriately
1497       (let ((text ""))
1498         (dolist (bucket (org-group-bucket-items
1499                          org-agenda-group-by-property
1500                          list))
1501           (let ((header (concat "Property "
1502                                 org-agenda-group-by-property
1503                                 " is "
1504                                 (or (car bucket) "<nil>") ":\n")))
1505             (add-text-properties 0 (1- (length header))
1506                                  (list 'face 'org-agenda-structure)
1507                                  header)
1508             (setq text
1509                   (concat text header
1510                           ;; recursively process
1511                           (let ((org-agenda-group-by-property nil))
1512                             (org-finalize-agenda-entries
1513                              (cdr bucket) nosort))
1514                           "\n\n"))))
1515         (setq ad-return-value text))
1516     ad-do-it))
1517 (ad-activate 'org-finalize-agenda-entries)
1518 #+end_src
1519 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1520 #+index: Tag!Clock
1521 #+index: Clock!Tag
1522     Thanks to Richard Riley (see [[http://permalink.gmane.org/gmane.emacs.orgmode/40896][this post on the mailing list]]).
1524 A small hook run when clocking out of a task that prompts for a note
1525 when the tag "=clockout_note=" is found in a headline. It uses the tag
1526 ("=clockout_note=") so inheritance can also be used...
1528 #+begin_src emacs-lisp
1529   (defun rgr/check-for-clock-out-note()
1530         (interactive)
1531         (save-excursion
1532           (org-back-to-heading)
1533           (let ((tags (org-get-tags)))
1534             (and tags (message "tags: %s " tags)
1535                  (when (member "clocknote" tags)
1536                    (org-add-note))))))
1538   (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1539 #+end_src
1540 *** Dynamically adjust tag position
1541 #+index: Tag!position
1542 Here is a bit of code that allows you to have the tags always
1543 right-adjusted in the buffer.
1545 This is useful when you have bigger window than default window-size
1546 and you dislike the aesthetics of having the tag in the middle of the
1547 line.
1549 This hack solves the problem of adjusting it whenever you change the
1550 window size.
1551 Before saving it will revert the file to having the tag position be
1552 left-adjusted so that if you track your files with version control,
1553 you won't run into artificial diffs just because the window-size
1554 changed.
1556 *IMPORTANT*: This is probably slow on very big files.
1558 #+begin_src emacs-lisp
1559 (setq ba/org-adjust-tags-column t)
1561 (defun ba/org-adjust-tags-column-reset-tags ()
1562   "In org-mode buffers it will reset tag position according to
1563 `org-tags-column'."
1564   (when (and
1565          (not (string= (buffer-name) "*Remember*"))
1566          (eql major-mode 'org-mode))
1567     (let ((b-m-p (buffer-modified-p)))
1568       (condition-case nil
1569           (save-excursion
1570             (goto-char (point-min))
1571             (command-execute 'outline-next-visible-heading)
1572             ;; disable (message) that org-set-tags generates
1573             (flet ((message (&rest ignored) nil))
1574               (org-set-tags 1 t))
1575             (set-buffer-modified-p b-m-p))
1576         (error nil)))))
1578 (defun ba/org-adjust-tags-column-now ()
1579   "Right-adjust `org-tags-column' value, then reset tag position."
1580   (set (make-local-variable 'org-tags-column)
1581        (- (- (window-width) (length org-ellipsis))))
1582   (ba/org-adjust-tags-column-reset-tags))
1584 (defun ba/org-adjust-tags-column-maybe ()
1585   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1586   (when ba/org-adjust-tags-column
1587     (ba/org-adjust-tags-column-now)))
1589 (defun ba/org-adjust-tags-column-before-save ()
1590   "Tags need to be left-adjusted when saving."
1591   (when ba/org-adjust-tags-column
1592      (setq org-tags-column 1)
1593      (ba/org-adjust-tags-column-reset-tags)))
1595 (defun ba/org-adjust-tags-column-after-save ()
1596   "Revert left-adjusted tag position done by before-save hook."
1597   (ba/org-adjust-tags-column-maybe)
1598   (set-buffer-modified-p nil))
1600 ; automatically align tags on right-hand side
1601 (add-hook 'window-configuration-change-hook
1602           'ba/org-adjust-tags-column-maybe)
1603 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1604 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1605 (add-hook 'org-agenda-mode-hook (lambda ()
1606                                   (setq org-agenda-tags-column (- (window-width)))))
1608 ; between invoking org-refile and displaying the prompt (which
1609 ; triggers window-configuration-change-hook) tags might adjust,
1610 ; which invalidates the org-refile cache
1611 (defadvice org-refile (around org-refile-disable-adjust-tags)
1612   "Disable dynamically adjusting tags"
1613   (let ((ba/org-adjust-tags-column nil))
1614     ad-do-it))
1615 (ad-activate 'org-refile)
1616 #+end_src
1617 *** Use an "attach" link type to open files without worrying about their location
1618 #+index: Link!Attach
1619 -- Darlan Cavalcante Moreira
1621 In the setup part in my org-files I put:
1623 #+begin_src org
1624 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1625 #+end_src
1627 Now I can use the "attach" link type, but org will ask me if I want to
1628 allow executing the elisp code.  To avoid this you can even set
1629 org-confirm-elisp-link-function to nil (I don't like this because it allows
1630 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1631 appropriately.
1633 In my case I use
1635 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1637 This works very well.
1639 ** Org Agenda and Task Management
1640 *** Make it easier to set org-agenda-files from multiple directories
1641 #+index: Agenda!Files
1642 - Matt Lundin
1644 #+begin_src emacs-lisp
1645 (defun my-org-list-files (dirs ext)
1646   "Function to create list of org files in multiple subdirectories.
1647 This can be called to generate a list of files for
1648 org-agenda-files or org-refile-targets.
1650 DIRS is a list of directories.
1652 EXT is a list of the extensions of files to be included."
1653   (let ((dirs (if (listp dirs)
1654                   dirs
1655                 (list dirs)))
1656         (ext (if (listp ext)
1657                  ext
1658                (list ext)))
1659         files)
1660     (mapc
1661      (lambda (x)
1662        (mapc
1663         (lambda (y)
1664           (setq files
1665                 (append files
1666                         (file-expand-wildcards
1667                          (concat (file-name-as-directory x) "*" y)))))
1668         ext))
1669      dirs)
1670     (mapc
1671      (lambda (x)
1672        (when (or (string-match "/.#" x)
1673                  (string-match "#$" x))
1674          (setq files (delete x files))))
1675      files)
1676     files))
1678 (defvar my-org-agenda-directories '("~/org/")
1679   "List of directories containing org files.")
1680 (defvar my-org-agenda-extensions '(".org")
1681   "List of extensions of agenda files")
1683 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1684 (setq my-org-agenda-extensions '(".org" ".ref"))
1686 (defun my-org-set-agenda-files ()
1687   (interactive)
1688   (setq org-agenda-files (my-org-list-files
1689                           my-org-agenda-directories
1690                           my-org-agenda-extensions)))
1692 (my-org-set-agenda-files)
1693 #+end_src
1695 The code above will set your "default" agenda files to all files
1696 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1697 You can change these values by setting the variables
1698 my-org-agenda-extensions and my-org-agenda-directories. The function
1699 my-org-agenda-files-by-filetag uses these two variables to determine
1700 which files to search for filetags (i.e., the larger set from which
1701 the subset will be drawn).
1703 You can also easily use my-org-list-files to "mix and match"
1704 directories and extensions to generate different lists of agenda
1705 files.
1707 *** Restrict org-agenda-files by filetag
1708 #+index: Agenda!Files
1709   :PROPERTIES:
1710   :CUSTOM_ID: set-agenda-files-by-filetag
1711   :END:
1712 - Matt Lundin
1714 It is often helpful to limit yourself to a subset of your agenda
1715 files. For instance, at work, you might want to see only files related
1716 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1717 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
1718 commands]]. These solutions, however, require reapplying a filter each
1719 time you call the agenda or writing several new custom agenda commands
1720 for each context. Another solution is to use directories for different
1721 types of tasks and to change your agenda files with a function that
1722 sets org-agenda-files to the appropriate directory. But this relies on
1723 hard and static boundaries between files.
1725 The following functions allow for a more dynamic approach to selecting
1726 a subset of files based on filetags:
1728 #+begin_src emacs-lisp
1729 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1730   "Restrict org agenda files only to those containing filetag."
1731   (interactive)
1732   (let* ((tagslist (my-org-get-all-filetags))
1733          (ftag (or tag
1734                    (completing-read "Tag: "
1735                                     (mapcar 'car tagslist)))))
1736     (org-agenda-remove-restriction-lock 'noupdate)
1737     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1738     (setq org-agenda-overriding-restriction 'files)))
1740 (defun my-org-get-all-filetags ()
1741   "Get list of filetags from all default org-files."
1742   (let ((files org-agenda-files)
1743         tagslist x)
1744     (save-window-excursion
1745       (while (setq x (pop files))
1746         (set-buffer (find-file-noselect x))
1747         (mapc
1748          (lambda (y)
1749            (let ((tagfiles (assoc y tagslist)))
1750              (if tagfiles
1751                  (setcdr tagfiles (cons x (cdr tagfiles)))
1752                (add-to-list 'tagslist (list y x)))))
1753          (my-org-get-filetags)))
1754       tagslist)))
1756 (defun my-org-get-filetags ()
1757   "Get list of filetags for current buffer"
1758   (let ((ftags org-file-tags)
1759         x)
1760     (mapcar
1761      (lambda (x)
1762        (org-substring-no-properties x))
1763      ftags)))
1764 #+end_src
1766 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1767 with all filetags in your "normal" agenda files. When you select a
1768 tag, org-agenda-files will be restricted to only those files
1769 containing the filetag. To release the restriction, type C-c C-x >
1770 (org-agenda-remove-restriction-lock).
1772 *** Highlight the agenda line under cursor
1773 #+index: Agenda!Highlight
1774 This is useful to make sure what task you are operating on.
1776 #+BEGIN_SRC emacs-lisp
1777 (add-hook 'org-agenda-mode-hook (lambda () (hl-line-mode 1)))
1778 #+END_SRC
1780 Under XEmacs:
1782 #+BEGIN_SRC emacs-lisp
1783 ;; hl-line seems to be only for emacs
1784 (require 'highline)
1785 (add-hook 'org-agenda-mode-hook (lambda () (highline-mode 1)))
1787 ;; highline-mode does not work straightaway in tty mode.
1788 ;; I use a black background
1789 (custom-set-faces
1790   '(highline-face ((((type tty) (class color))
1791                     (:background "white" :foreground "black")))))
1792 #+END_SRC
1794 *** Split frame horizontally for agenda
1795 #+index: Agenda!frame
1796 If you would like to split the frame into two side-by-side windows when
1797 displaying the agenda, try this hack from Jan Rehders, which uses the
1798 `toggle-window-split' from
1800 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1802 #+BEGIN_SRC emacs-lisp
1803 ;; Patch org-mode to use vertical splitting
1804 (defadvice org-prepare-agenda (after org-fix-split)
1805   (toggle-window-split))
1806 (ad-activate 'org-prepare-agenda)
1807 #+END_SRC
1809 *** Automatically add an appointment when clocking in a task
1810 #+index: Clock!Automatically add an appointment when clocking in a task
1811 #+index: Appointment!Automatically add an appointment when clocking in a task
1812 #+BEGIN_SRC emacs-lisp
1813 ;; Make sure you have a sensible value for `appt-message-warning-time'
1814 (defvar bzg-org-clock-in-appt-delay 100
1815   "Number of minutes for setting an appointment by clocking-in")
1816 #+END_SRC
1818 This function let's you add an appointment for the current entry.
1819 This can be useful when you need a reminder.
1821 #+BEGIN_SRC emacs-lisp
1822 (defun bzg-org-clock-in-add-appt (&optional n)
1823   "Add an appointment for the Org entry at point in N minutes."
1824   (interactive)
1825   (save-excursion
1826     (org-back-to-heading t)
1827     (looking-at org-complex-heading-regexp)
1828     (let* ((msg (match-string-no-properties 4))
1829            (ct-time (decode-time))
1830            (appt-min (+ (cadr ct-time)
1831                         (or n bzg-org-clock-in-appt-delay)))
1832            (appt-time ; define the time for the appointment
1833             (progn (setf (cadr ct-time) appt-min) ct-time)))
1834       (appt-add (format-time-string
1835                  "%H:%M" (apply 'encode-time appt-time)) msg)
1836       (if (interactive-p) (message "New appointment for %s" msg)))))
1837 #+END_SRC
1839 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1840 add an appointment:
1842 #+BEGIN_SRC emacs-lisp
1843 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1844   "Add an appointment when clocking a task in."
1845   (bzg-org-clock-in-add-appt))
1846 #+END_SRC
1848 You may also want to delete the associated appointment when clocking
1849 out.  This function does this:
1851 #+BEGIN_SRC emacs-lisp
1852 (defun bzg-org-clock-out-delete-appt nil
1853   "When clocking out, delete any associated appointment."
1854   (interactive)
1855   (save-excursion
1856     (org-back-to-heading t)
1857     (looking-at org-complex-heading-regexp)
1858     (let* ((msg (match-string-no-properties 4)))
1859       (setq appt-time-msg-list
1860             (delete nil
1861                     (mapcar
1862                      (lambda (appt)
1863                        (if (not (string-match (regexp-quote msg)
1864                                               (cadr appt))) appt))
1865                      appt-time-msg-list)))
1866       (appt-check))))
1867 #+END_SRC
1869 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1871 #+BEGIN_SRC emacs-lisp
1872 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1873   "Delete an appointment when clocking a task out."
1874   (bzg-org-clock-out-delete-appt))
1875 #+END_SRC
1877 *IMPORTANT*: You can add appointment by clocking in in both an
1878 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
1879 agenda buffer with the advice above will bring an error.
1881 *** Using external programs for appointments reminders
1882 #+index: Appointment!reminders
1883 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1885 *** Remove from agenda time grid lines that are in an appointment
1886 #+index: Agenda!time grid
1887 #+index: Appointment!Remove from agenda time grid lines
1888 The agenda shows lines for the time grid.  Some people think that
1889 these lines are a distraction when there are appointments at those
1890 times.  You can get rid of the lines which coincide exactly with the
1891 beginning of an appointment.  Michael Ekstrand has written a piece of
1892 advice that also removes lines that are somewhere inside an
1893 appointment:
1895 #+begin_src emacs-lisp
1896 (defun org-time-to-minutes (time)
1897   "Convert an HHMM time to minutes"
1898   (+ (* (/ time 100) 60) (% time 100)))
1900 (defun org-time-from-minutes (minutes)
1901   "Convert a number of minutes to an HHMM time"
1902   (+ (* (/ minutes 60) 100) (% minutes 60)))
1904 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1905                                                   (list ndays todayp))
1906   (if (member 'remove-match (car org-agenda-time-grid))
1907       (flet ((extract-window
1908               (line)
1909               (let ((start (get-text-property 1 'time-of-day line))
1910                     (dur (get-text-property 1 'duration line)))
1911                 (cond
1912                  ((and start dur)
1913                   (cons start
1914                         (org-time-from-minutes
1915                          (+ dur (org-time-to-minutes start)))))
1916                  (start start)
1917                  (t nil)))))
1918         (let* ((windows (delq nil (mapcar 'extract-window list)))
1919                (org-agenda-time-grid
1920                 (list (car org-agenda-time-grid)
1921                       (cadr org-agenda-time-grid)
1922                       (remove-if
1923                        (lambda (time)
1924                          (find-if (lambda (w)
1925                                     (if (numberp w)
1926                                         (equal w time)
1927                                       (and (>= time (car w))
1928                                            (< time (cdr w)))))
1929                                   windows))
1930                        (caddr org-agenda-time-grid)))))
1931           ad-do-it))
1932     ad-do-it))
1933 (ad-activate 'org-agenda-add-time-grid-maybe)
1934 #+end_src
1935 *** Disable version control for Org mode agenda files
1936 #+index: Agenda!Files
1937 -- David Maus
1939 Even if you use Git to track your agenda files you might not need
1940 vc-mode to be enabled for these files.
1942 #+begin_src emacs-lisp
1943 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
1944 (defun dmj/disable-vc-for-agenda-files-hook ()
1945   "Disable vc-mode for Org agenda files."
1946   (if (and (fboundp 'org-agenda-file-p)
1947            (org-agenda-file-p (buffer-file-name)))
1948       (remove-hook 'find-file-hook 'vc-find-file-hook)
1949     (add-hook 'find-file-hook 'vc-find-file-hook)))
1950 #+end_src
1952 *** Easy customization of TODO colors
1953 #+index: Customization!Todo keywords
1954 #+index: Todo keywords!Customization
1956 -- Ryan C. Thompson
1958 Here is some code I came up with some code to make it easier to
1959 customize the colors of various TODO keywords. As long as you just
1960 want a different color and nothing else, you can customize the
1961 variable org-todo-keyword-faces and use just a string color (i.e. a
1962 string of the color name) as the face, and then org-get-todo-face
1963 will convert the color to a face, inheriting everything else from
1964 the standard org-todo face.
1966 To demonstrate, I currently have org-todo-keyword-faces set to
1968 #+BEGIN_SRC emacs-lisp
1969 (("IN PROGRESS" . "dark orange")
1970  ("WAITING" . "red4")
1971  ("CANCELED" . "saddle brown"))
1972 #+END_SRC
1974   Here's the code, in a form you can put in your =.emacs=
1976 #+BEGIN_SRC emacs-lisp
1977 (eval-after-load 'org-faces
1978  '(progn
1979     (defcustom org-todo-keyword-faces nil
1980       "Faces for specific TODO keywords.
1981 This is a list of cons cells, with TODO keywords in the car and
1982 faces in the cdr.  The face can be a symbol, a color, or a
1983 property list of attributes, like (:foreground \"blue\" :weight
1984 bold :underline t)."
1985       :group 'org-faces
1986       :group 'org-todo
1987       :type '(repeat
1988               (cons
1989                (string :tag "Keyword")
1990                (choice color (sexp :tag "Face")))))))
1992 (eval-after-load 'org
1993  '(progn
1994     (defun org-get-todo-face-from-color (color)
1995       "Returns a specification for a face that inherits from org-todo
1996  face and has the given color as foreground. Returns nil if
1997  color is nil."
1998       (when color
1999         `(:inherit org-warning :foreground ,color)))
2001     (defun org-get-todo-face (kwd)
2002       "Get the right face for a TODO keyword KWD.
2003 If KWD is a number, get the corresponding match group."
2004       (if (numberp kwd) (setq kwd (match-string kwd)))
2005       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
2006             (if (stringp face)
2007                 (org-get-todo-face-from-color face)
2008               face))
2009           (and (member kwd org-done-keywords) 'org-done)
2010           'org-todo))))
2011 #+END_SRC
2013 *** Add an effort estimate on the fly when clocking in
2014 #+index: Effort estimate!Add when clocking in
2015 #+index: Clock!Effort estimate
2016 You can use =org-clock-in-prepare-hook= to add an effort estimate.
2017 This way you can easily have a "tea-timer" for your tasks when they
2018 don't already have an effort estimate.
2020 #+begin_src emacs-lisp
2021 (add-hook 'org-clock-in-prepare-hook
2022           'my-org-mode-ask-effort)
2024 (defun my-org-mode-ask-effort ()
2025   "Ask for an effort estimate when clocking in."
2026   (unless (org-entry-get (point) "Effort")
2027     (let ((effort
2028            (completing-read
2029             "Effort: "
2030             (org-entry-get-multivalued-property (point) "Effort"))))
2031       (unless (equal effort "")
2032         (org-set-property "Effort" effort)))))
2033 #+end_src
2035 Or you can use a default effort for such a timer:
2037 #+begin_src emacs-lisp
2038 (add-hook 'org-clock-in-prepare-hook
2039           'my-org-mode-add-default-effort)
2041 (defvar org-clock-default-effort "1:00")
2043 (defun my-org-mode-add-default-effort ()
2044   "Add a default effort estimation."
2045   (unless (org-entry-get (point) "Effort")
2046     (org-set-property "Effort" org-clock-default-effort)))
2047 #+end_src
2049 *** Use idle timer for automatic agenda views
2050 #+index: Agenda view!Refresh
2051 From John Wiegley's mailing list post (March 18, 2010):
2053 #+begin_quote
2054 I have the following snippet in my .emacs file, which I find very
2055 useful. Basically what it does is that if I don't touch my Emacs for 5
2056 minutes, it displays the current agenda. This keeps my tasks "always
2057 in mind" whenever I come back to Emacs after doing something else,
2058 whereas before I had a tendency to forget that it was there.
2059 #+end_quote
2061   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
2063 #+begin_src emacs-lisp
2064 (defun jump-to-org-agenda ()
2065   (interactive)
2066   (let ((buf (get-buffer "*Org Agenda*"))
2067         wind)
2068     (if buf
2069         (if (setq wind (get-buffer-window buf))
2070             (select-window wind)
2071           (if (called-interactively-p)
2072               (progn
2073                 (select-window (display-buffer buf t t))
2074                 (org-fit-window-to-buffer)
2075                 ;; (org-agenda-redo)
2076                 )
2077             (with-selected-window (display-buffer buf)
2078               (org-fit-window-to-buffer)
2079               ;; (org-agenda-redo)
2080               )))
2081       (call-interactively 'org-agenda-list)))
2082   ;;(let ((buf (get-buffer "*Calendar*")))
2083   ;;  (unless (get-buffer-window buf)
2084   ;;    (org-agenda-goto-calendar)))
2085   )
2087 (run-with-idle-timer 300 t 'jump-to-org-agenda)
2088 #+end_src
2090 #+results:
2091 : [nil 0 300 0 t jump-to-org-agenda nil idle]
2093 *** Refresh the agenda view regularly
2094 #+index: Agenda view!Refresh
2095 Hack sent by Kiwon Um:
2097 #+begin_src emacs-lisp
2098 (defun kiwon/org-agenda-redo-in-other-window ()
2099   "Call org-agenda-redo function even in the non-agenda buffer."
2100   (interactive)
2101   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
2102     (when agenda-window
2103       (with-selected-window agenda-window (org-agenda-redo)))))
2104 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
2105 #+end_src
2107 *** Reschedule agenda items to today with a single command
2108 #+index: Agenda!Reschedule
2109 This was suggested by Carsten in reply to David Abrahams:
2111 #+begin_example emacs-lisp
2112 (defun org-agenda-reschedule-to-today ()
2113   (interactive)
2114   (flet ((org-read-date (&rest rest) (current-time)))
2115     (call-interactively 'org-agenda-schedule)))
2116 #+end_example
2118 *** Mark subtree DONE along with all subheadings
2119 #+index: Subtree!subheadings
2120 Bernt Hansen [[http://permalink.gmane.org/gmane.emacs.orgmode/44693][suggested]] this command:
2122 #+begin_src emacs-lisp
2123 (defun bh/mark-subtree-done ()
2124   (interactive)
2125   (org-mark-subtree)
2126   (let ((limit (point)))
2127     (save-excursion
2128       (exchange-point-and-mark)
2129       (while (> (point) limit)
2130         (org-todo "DONE")
2131         (outline-previous-visible-heading 1))
2132       (org-todo "DONE"))))
2133 #+end_src
2135 Then M-x bh/mark-subtree-done.
2137 *** Mark heading done when all checkboxes are checked.
2138     :PROPERTIES:
2139     :CUSTOM_ID: mark-done-when-all-checkboxes-checked
2140     :END:
2142 #+index: Checkbox
2144 An item consists of a list with checkboxes.  When all of the
2145 checkboxes are checked, the item should be considered complete and its
2146 TODO state should be automatically changed to DONE. The code below
2147 does that. This version is slightly enhanced over the one in the
2148 mailing list (see
2149 http://thread.gmane.org/gmane.emacs.orgmode/42715/focus=42721) to
2150 reset the state back to TODO if a checkbox is unchecked.
2152 Note that the code requires that a checkbox statistics cookie (the [/]
2153 or [%] thingie in the headline - see the [[http://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
2154 manual) be present in order for it to work. Note also that it is too
2155 dumb to figure out whether the item has a TODO state in the first
2156 place: if there is a statistics cookie, a TODO/DONE state will be
2157 added willy-nilly any time that the statistics cookie is changed.
2159 #+begin_src emacs-lisp
2160   ;; see http://thread.gmane.org/gmane.emacs.orgmode/42715
2161   (eval-after-load 'org-list
2162     '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
2163   
2164   (defun ndk/checkbox-list-complete ()
2165     (save-excursion
2166       (org-back-to-heading t)
2167       (let ((beg (point)) end)
2168         (end-of-line)
2169         (setq end (point))
2170         (goto-char beg)
2171         (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
2172               (if (match-end 1)
2173                   (if (equal (match-string 1) "100%")
2174                       ;; all done - do the state change
2175                       (org-todo 'done)
2176                     (org-todo 'todo))
2177                 (if (and (> (match-end 2) (match-beginning 2))
2178                          (equal (match-string 2) (match-string 3)))
2179                     (org-todo 'done)
2180                   (org-todo 'todo)))))))
2181 #+end_src
2183 *** Links to custom agenda views
2184     :PROPERTIES:
2185     :CUSTOM_ID: links-to-agenda-views
2186     :END:
2187 #+index: Agenda view!Links to
2188 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
2190 If you have custom agenda commands defined to some key, say w, then
2191 the following will serve as a link to the custom agenda buffer.
2192 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
2194 Clicking on it will prompt if you want to execute the elisp code.  If
2195 you would rather not have the prompt or would want to respond with a
2196 single letter, ~y~ or ~n~, take a look at the docstrings of the
2197 variables =org-confirm-elisp-link-function= and
2198 =org-confirm-elisp-link-not-regexp=.  Please take special note of the
2199 security risk associated with completely disabling the prompting
2200 before you proceed.
2202 ** Exporting org files
2203 *** Ignoring headlines during export
2204     :PROPERTIES:
2205     :CUSTOM_ID: ignoreheadline
2206     :END:
2207 #+index: Export!ignore headlines
2208 Sometimes users want to ignore the headline text during export like in
2209 the Beamer exporter (=ox-beamer=).  In the [[http://orgmode.org/manual/Beamer-export.html#Beamer-export][Beamer exporter]] one can use
2210 the tag =ignoreheading= to disable the export of a certain headline,
2211 whilst still retaining the content of the headline.  We can imitate
2212 this feature in other export backends.  Note that this is not a
2213 particularly easy problem, as the Org exporter creates a static
2214 representation of section numbers, table of contents etc.
2216 Consider the following document:
2217 #+BEGIN_SRC org
2218   ,* head 1                    :noexport:
2219   ,* head 2                    :ignoreheading:
2220   ,* head 3
2221   ,* =head 4=                  :ignoreheading:
2223 #+END_SRC
2224 We want to remove heading 2 and 4.
2226 There are different strategies to accomplish this:
2227 1. The best option is to remove headings tagged with =ignoreheading=
2228    before export starts.  This can be accomplished with the hook
2229    =org-export-before-parsing-hook= that runs before the buffer has
2230    been parsed.  In the example above, however, =head 2= would not be
2231    exported as it becomes part of =head 1= which is not exporter.  To
2232    overcome this move perhaps =head 1= can be moved to the end of the
2233    buffer.  An example of a hook that removes headings is before
2234    parsing is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01459.html][here]].  Note, this solution is compatible with
2235    /all/ export formats!
2236 2. The problem is simple when exporting to LaTeX, as the LaTeX
2237    compiler determines numbers.  We can thus use
2238    =org-export-filter-headline-functions= to remove the offending
2239    headlines.  One regexp-based solution that looks for the word
2240    =ignoreheading= is available on [[https://stackoverflow.com/questions/10295177/is-there-an-equivalent-of-org-modes-b-ignoreheading-for-non-beamer-documents][StackOverflow]] for both the legacy
2241    exporter Org v7 exporter and the current Org v8 exporter.  Note,
2242    however, that this filter will only work with LaTeX (numbering and
2243    the table of content may break in other exporters).  In the example
2244    above, this filer will work flawlessly in LaTeX, it will not work
2245    at all in HTML and it will fail to update section numbers, TOC and
2246    leave some auxiliary lines behind when exporting to plain text.
2247 3. Another solution that tries to recover the Org element
2248    representation is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01480.html][here]].  In the example above this filter
2249    will not remove =head 4= exporting to any backend, since verbatim
2250    strings do not retain the Org element representation.  It will
2251    remove the extra heading line when exporting to plain text, but
2252    will also fail to update section numbers.  It should be fairly
2253    simple to also make it work with HTML.
2255 *** Export Org to Org and handle includes.
2256 #+index: Export!handle includes
2257 Nick Dokos came up with this useful function:
2259 #+begin_src emacs-lisp
2260 (defun org-to-org-handle-includes ()
2261   "Copy the contents of the current buffer to OUTFILE,
2262 recursively processing #+INCLUDEs."
2263   (let* ((s (buffer-string))
2264          (fname (buffer-file-name))
2265          (ofname (format "%s.I.org" (file-name-sans-extension fname))))
2266     (setq result
2267           (with-temp-buffer
2268             (insert s)
2269             (org-export-handle-include-files-recurse)
2270             (buffer-string)))
2271     (find-file ofname)
2272     (delete-region (point-min) (point-max))
2273     (insert result)
2274     (save-buffer)))
2275 #+end_src
2277 *** Specifying LaTeX commands to floating environments
2278     :PROPERTIES:
2279     :CUSTOM_ID: latex-command-for-floats
2280     :END:
2282 #+index: Export!LaTeX
2283 The keyword ~placement~ can be used to specify placement options to
2284 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2285 LaTeX export. Org passes along everything passed in options as long as
2286 there are no spaces. One can take advantage of this to pass other
2287 LaTeX commands and have their scope limited to the floating
2288 environment.
2290 For example one can set the fontsize of a table different from the
2291 default normal size by putting something like =\footnotesize= right
2292 after the placement options. During LaTeX export using the
2293 ~#+ATTR_LaTeX:~ line below:
2295 #+begin_src org
2296 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2297 #+end_src
2299 exports the associated floating environment as shown in the following
2300 block.
2302 #+begin_src latex
2303 \begin{table}[<options>]\footnotesize
2305 \end{table}
2306 #+end_src
2308 It should be noted that this hack does not work for beamer export of
2309 tables since the =table= environment is not used. As an ugly
2310 workaround, one can use the following:
2312 #+begin_src org
2313 ,#+LATEX: {\footnotesize
2314 ,#+ATTR_LaTeX: align=rr
2315 | some | table |
2316 |------+-------|
2317 | ..   | ..    |
2318 ,#+LATEX: }
2319 #+end_src
2321 *** Styling code sections with CSS
2323 #+index: HTML!Styling code sections with CSS
2325 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2326 to HTML using =<pre>= tags, and assigned CSS classes by their content
2327 type.  For example, Perl content will have an opening tag like
2328 =<pre class="src src-perl">=.  You can use those classes to add styling
2329 to the output, such as here where a small language tag is added at the
2330 top of each kind of code box:
2332 #+begin_src lisp
2333 (setq org-export-html-style
2334  "<style type=\"text/css\">
2335     <!--/*--><![CDATA[/*><!--*/
2336       .src             { background-color: #F5FFF5; position: relative; overflow: visible; }
2337       .src:before      { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2338       .src-sh:before   { content: 'sh'; }
2339       .src-bash:before { content: 'sh'; }
2340       .src-R:before    { content: 'R'; }
2341       .src-perl:before { content: 'Perl'; }
2342       .src-sql:before  { content: 'SQL'; }
2343       .example         { background-color: #FFF5F5; }
2344     /*]]>*/-->
2345  </style>")
2346 #+end_src
2348 Additionally, we use color to distinguish code output (the =.example=
2349 class) from input (all the =.src-*= classes).
2351 *** Including external text fragments
2353 #+index: Export!including external text fragments
2355 I recently had to document some source code but could not modify the
2356 source files themselves. Here is a setup that lets you refer to
2357 fragments of external files, such that the fragments are inserted as
2358 source blocks in the current file during evaluation of the ~call~
2359 lines (thus during export as well).
2361 #+BEGIN_SRC org
2362   ,* Setup                                                            :noexport:
2363   ,#+name: fetchsrc
2364   ,#+BEGIN_SRC emacs-lisp :results raw :var f="foo" :var s="Definition" :var e="\\. *$" :var b=()
2365     (defvar coqfiles nil)
2366   
2367     (defun fetchlines (file-path search-string &optional end before)
2368       "Searches for the SEARCH-STRING in FILE-PATH and returns the matching line.
2369     If the optional argument END is provided as a number, then this
2370     number of lines is printed.  If END is a string, then it is a
2371     regular expression indicating the end of the expression to print.
2372     If END is omitted, then 10 lines are printed.  If BEFORE is set,
2373     then one fewer line is printed (this is useful when END is a
2374     string matching the first line that should not be printed)."
2375       (with-temp-buffer
2376         (insert-file-contents file-path nil nil nil t)
2377         (goto-char (point-min))
2378         (let ((result
2379                (if (search-forward search-string nil t)
2380                    (buffer-substring
2381                     (line-beginning-position)
2382                     (if end
2383                         (cond
2384                          ((integerp end)
2385                           (line-end-position (if before (- end 1) end)))
2386                          ((stringp end)
2387                           (let ((point (re-search-forward end nil t)))
2388                             (if before (line-end-position 0) point)))
2389                          (t (line-end-position 10)))
2390                       (line-end-position 10))))))
2391           (or result ""))))
2392     
2393     (fetchlines (concat coqfiles f ".v") s e b)
2394   ,#+END_SRC
2395   
2396   ,#+name: wrap-coq
2397   ,#+BEGIN_SRC emacs-lisp :var text="" :results raw
2398   (concat "#+BEGIN_SRC coq\n" text "\n#+END_SRC")
2399   ,#+END_SRC
2400 #+END_SRC
2402 This is specialized for Coq files (hence the ~coq~ language in the
2403 ~wrap-coq~ function, the ~.v~ extension in the ~fetch~ function, and
2404 the default value for ~end~ matching the syntax ending definitions in
2405 Coq). To use it, you need to:
2406 - set the ~coqfiles~ variable to where your source files reside;
2407 - call the function using lines of the form
2408   #+BEGIN_SRC org
2409     ,#+call: fetchsrc(f="JsSyntax", s="Inductive expr :=", e="^ *$", b=1) :results drawer :post wrap-coq(text=*this*)
2410   #+END_SRC
2411   In this example, we look inside the file ~JsSyntax.v~ in ~coqfiles~,
2412   search for a line matching ~Inductive expr :=~, and include the
2413   fragment until the first line consisting only of white space,
2414   excluded (as ~b=1~).
2416 I use drawers to store the results to avoid a bug leading to
2417 duplication during export when the code has already been evaluated in
2418 the buffer (see [[http://thread.gmane.org/gmane.emacs.orgmode/79520][this thread]] for a description of the problem). This
2419 has been fixed in recent versions of org-mode, so alternative
2420 approaches are possible.
2422 ** Babel
2424 *** How do I preview LaTeX fragments when in a LaTeX source block?
2426 When editing =LaTeX= source blocks, you may want to preview LaTeX fragments
2427 just like in an Org-mode buffer.  You can do this by using the usual
2428 keybinding =C-c C-x C-l= after loading this snipped:
2430 #+BEGIN_SRC emacs-lisp
2431 (define-key org-src-mode-map "\C-c\C-x\C-l" 'org-edit-preview-latex-fragment)
2433 (defun org-edit-preview-latex-fragment ()
2434   "Write latex fragment from source to parent buffer and preview it."
2435   (interactive)
2436   (org-src-in-org-buffer (org-preview-latex-fragment)))
2437 #+END_SRC
2439 Thanks to Sebastian Hofer for sharing this.
2441 * Hacking Org: Working with Org-mode and other Emacs Packages.
2442 ** How to ediff folded Org files
2443 A rather often quip among Org users is when looking at chages with
2444 ediff.  Ediff tends to fold the Org buffers when comparing.  This can
2445 be very inconvenient when trying to determine what changed.  A recent
2446 discussion on the mailing list led to a [[http://article.gmane.org/gmane.emacs.orgmode/75222][neat solution]] from Ratish
2447 Punnoose.
2449 ** org-remember-anything
2451 #+index: Remember!Anything
2453 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2455 #+BEGIN_SRC emacs-lisp
2456 (defvar org-remember-anything
2457   '((name . "Org Remember")
2458     (candidates . (lambda () (mapcar 'car org-remember-templates)))
2459     (action . (lambda (name)
2460                 (let* ((orig-template org-remember-templates)
2461                        (org-remember-templates
2462                         (list (assoc name orig-template))))
2463                   (call-interactively 'org-remember))))))
2464 #+END_SRC
2466 You can add it to your 'anything-sources' variable and open remember directly
2467 from anything. I imagine this would be more interesting for people with many
2468 remember templates, so that you are out of keys to assign those to.
2470 ** Org-mode and saveplace.el
2472 Fix a problem with =saveplace.el= putting you back in a folded position:
2474 #+begin_src emacs-lisp
2475 (add-hook 'org-mode-hook
2476           (lambda ()
2477             (when (outline-invisible-p)
2478               (save-excursion
2479                 (outline-previous-visible-heading 1)
2480                 (org-show-subtree)))))
2481 #+end_src
2483 ** Using ido-mode for org-refile (and archiving via refile)
2485 First set up ido-mode, for example using:
2487 #+begin_src emacs-lisp
2488 ; use ido mode for completion
2489 (setq ido-everywhere t)
2490 (setq ido-enable-flex-matching t)
2491 (setq ido-max-directory-size 100000)
2492 (ido-mode (quote both))
2493 #+end_src
2495 Now to enable it in org-mode, use the following:
2496 #+begin_src emacs-lisp
2497 (setq org-completion-use-ido t)
2498 (setq org-refile-use-outline-path nil)
2499 (setq org-refile-allow-creating-parent-nodes 'confirm)
2500 #+end_src
2501 The last line enables the creation of nodes on the fly.
2503 If you refile into files that are not in your agenda file list, you can add them as target like this (replace file1\_done, etc with your files):
2504 #+begin_src emacs-lisp
2505 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2506 #+end_src
2508 For refiling it is often not useful to include targets that have a DONE state. It's easy to remove them by using the verify-refile-target hook.
2509 #+begin_src emacs-lisp
2510 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2511 ; added check to only include headlines, e.g. line must have at least one child
2512 (defun my/verify-refile-target ()
2513   "Exclude todo keywords with a DONE state from refile targets"
2514   (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2515       (save-excursion (org-goto-first-child))
2516   )
2517 (setq org-refile-target-verify-function 'my/verify-refile-target)
2518 #+end_src
2519 Now when looking for a refile target, you can use the full power of ido to find them. Ctrl-R can be used to switch between different options that ido offers.
2521 ** Using ido-completing-read to find attachments
2523 #+index: Attachment!ido completion
2525 -- Matt Lundin.
2527 Org-attach is great for quickly linking files to a project. But if you
2528 use org-attach extensively you might find yourself wanting to browse
2529 all the files you've attached to org headlines. This is not easy to do
2530 manually, since the directories containing the files are not human
2531 readable (i.e., they are based on automatically generated ids). Here's
2532 some code to browse those files using ido (obviously, you need to be
2533 using ido):
2535 #+begin_src emacs-lisp
2536 (load-library "find-lisp")
2538 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2540 (defun my-ido-find-org-attach ()
2541   "Find files in org-attachment directory"
2542   (interactive)
2543   (let* ((enable-recursive-minibuffers t)
2544          (files (find-lisp-find-files org-attach-directory "."))
2545          (file-assoc-list
2546           (mapcar (lambda (x)
2547                     (cons (file-name-nondirectory x)
2548                           x))
2549                   files))
2550          (filename-list
2551           (remove-duplicates (mapcar #'car file-assoc-list)
2552                              :test #'string=))
2553          (filename (ido-completing-read "Org attachments: " filename-list nil t))
2554          (longname (cdr (assoc filename file-assoc-list))))
2555     (ido-set-current-directory
2556      (if (file-directory-p longname)
2557          longname
2558        (file-name-directory longname)))
2559     (setq ido-exit 'refresh
2560           ido-text-init ido-text
2561           ido-rotate-temp t)
2562     (exit-minibuffer)))
2564 (add-hook 'ido-setup-hook 'ido-my-keys)
2566 (defun ido-my-keys ()
2567   "Add my keybindings for ido."
2568   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2569 #+end_src
2571 To browse your org attachments using ido fuzzy matching and/or the
2572 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2573 press =C-;=.
2575 ** Link to Gnus messages by Message-Id
2576 #+index: Link!Gnus message by Message-Id
2577 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
2578 discussion about linking to Gnus messages without encoding the folder
2579 name in the link.  The following code hooks in to the store-link
2580 function in Gnus to capture links by Message-Id when in nnml folders,
2581 and then provides a link type "mid" which can open this link.  The
2582 =mde-org-gnus-open-message-link= function uses the
2583 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2584 scan.  It will go through them, in order, asking each to locate the
2585 message and opening it from the first one that reports success.
2587 It has only been tested with a single nnml backend, so there may be
2588 bugs lurking here and there.
2590 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2591 article]].
2593 #+begin_src emacs-lisp
2594 ;; Support for saving Gnus messages by Message-ID
2595 (defun mde-org-gnus-save-by-mid ()
2596   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2597     (when (eq major-mode 'gnus-article-mode)
2598       (gnus-article-show-summary))
2599     (let* ((group gnus-newsgroup-name)
2600            (method (gnus-find-method-for-group group)))
2601       (when (eq 'nnml (car method))
2602         (let* ((article (gnus-summary-article-number))
2603                (header (gnus-summary-article-header article))
2604                (from (mail-header-from header))
2605                (message-id
2606                 (save-match-data
2607                   (let ((mid (mail-header-id header)))
2608                     (if (string-match "<\\(.*\\)>" mid)
2609                         (match-string 1 mid)
2610                       (error "Malformed message ID header %s" mid)))))
2611                (date (mail-header-date header))
2612                (subject (gnus-summary-subject-string)))
2613           (org-store-link-props :type "mid" :from from :subject subject
2614                                 :message-id message-id :group group
2615                                 :link (org-make-link "mid:" message-id))
2616           (apply 'org-store-link-props
2617                  :description (org-email-link-description)
2618                  org-store-link-plist)
2619           t)))))
2621 (defvar mde-mid-resolve-methods '()
2622   "List of methods to try when resolving message ID's.  For Gnus,
2623 it is a cons of 'gnus and the select (type and name).")
2624 (setq mde-mid-resolve-methods
2625       '((gnus nnml "")))
2627 (defvar mde-org-gnus-open-level 1
2628   "Level at which Gnus is started when opening a link")
2629 (defun mde-org-gnus-open-message-link (msgid)
2630   "Open a message link with Gnus"
2631   (require 'gnus)
2632   (require 'org-table)
2633   (catch 'method-found
2634     (message "[MID linker] Resolving %s" msgid)
2635     (dolist (method mde-mid-resolve-methods)
2636       (cond
2637        ((and (eq (car method) 'gnus)
2638              (eq (cadr method) 'nnml))
2639         (funcall (cdr (assq 'gnus org-link-frame-setup))
2640                  mde-org-gnus-open-level)
2641         (when gnus-other-frame-object
2642           (select-frame gnus-other-frame-object))
2643         (let* ((msg-info (nnml-find-group-number
2644                           (concat "<" msgid ">")
2645                           (cdr method)))
2646                (group (and msg-info (car msg-info)))
2647                (message (and msg-info (cdr msg-info)))
2648                (qname (and group
2649                            (if (gnus-methods-equal-p
2650                                 (cdr method)
2651                                 gnus-select-method)
2652                                group
2653                              (gnus-group-full-name group (cdr method))))))
2654           (when msg-info
2655             (gnus-summary-read-group qname nil t)
2656             (gnus-summary-goto-article message nil t))
2657           (throw 'method-found t)))
2658        (t (error "Unknown link type"))))))
2660 (eval-after-load 'org-gnus
2661   '(progn
2662      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2663      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2664 #+end_src
2666 ** Store link to a message when sending in Gnus
2667 #+index: Link!Store link to a message when sending in Gnus
2668 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2670 #+begin_src emacs-lisp
2671 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2672   "Send message with `message-send-and-exit' and store org link to message copy.
2673 If multiple groups appear in the Gcc header, the link refers to
2674 the copy in the last group."
2675   (interactive "P")
2676     (save-excursion
2677       (save-restriction
2678         (message-narrow-to-headers)
2679         (let ((gcc (car (last
2680                          (message-unquote-tokens
2681                           (message-tokenize-header
2682                            (mail-fetch-field "gcc" nil t) " ,")))))
2683               (buf (current-buffer))
2684               (message-kill-buffer-on-exit nil)
2685               id to from subject desc link newsgroup xarchive)
2686         (message-send-and-exit arg)
2687         (or
2688          ;; gcc group found ...
2689          (and gcc
2690               (save-current-buffer
2691                 (progn (set-buffer buf)
2692                        (setq id (org-remove-angle-brackets
2693                                  (mail-fetch-field "Message-ID")))
2694                        (setq to (mail-fetch-field "To"))
2695                        (setq from (mail-fetch-field "From"))
2696                        (setq subject (mail-fetch-field "Subject"))))
2697               (org-store-link-props :type "gnus" :from from :subject subject
2698                                     :message-id id :group gcc :to to)
2699               (setq desc (org-email-link-description))
2700               (setq link (org-gnus-article-link
2701                           gcc newsgroup id xarchive))
2702               (setq org-stored-links
2703                     (cons (list link desc) org-stored-links)))
2704          ;; no gcc group found ...
2705          (message "Can not create Org link: No Gcc header found."))))))
2707 (define-key message-mode-map [(control c) (control meta c)]
2708   'ulf-message-send-and-org-gnus-store-link)
2709 #+end_src
2711 ** Link to visit a file and run occur
2712 #+index: Link!Visit a file and run occur
2713 Add the following bit of code to your startup (after loading org),
2714 and you can then use links like =occur:my-file.txt#regex= to open a
2715 file and run occur with the regex on it.
2717 #+BEGIN_SRC emacs-lisp
2718   (defun org-occur-open (uri)
2719     "Visit the file specified by URI, and run `occur' on the fragment
2720     \(anything after the first '#') in the uri."
2721     (let ((list (split-string uri "#")))
2722       (org-open-file (car list) t)
2723       (occur (mapconcat 'identity (cdr list) "#"))))
2724   (org-add-link-type "occur" 'org-occur-open)
2725 #+END_SRC
2726 ** Send html messages and attachments with Wanderlust
2727   -- David Maus
2729 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2730 similar functionality for both Wanderlust and Gnus.  The hack below is
2731 still somewhat different: It allows you to toggle sending of html
2732 messages within Wanderlust transparently.  I.e. html markup of the
2733 message body is created right before sending starts.
2735 *** Send HTML message
2737 Putting the code below in your .emacs adds following four functions:
2739 - dmj/wl-send-html-message
2741   Function that does the job: Convert everything between "--text
2742   follows this line--" and first mime entity (read: attachment) or
2743   end of buffer into html markup using `org-export-region-as-html'
2744   and replaces original body with a multipart MIME entity with the
2745   plain text version of body and the html markup version.  Thus a
2746   recipient that prefers html messages can see the html markup,
2747   recipients that prefer or depend on plain text can see the plain
2748   text.
2750   Cannot be called interactively: It is hooked into SEMI's
2751   `mime-edit-translate-hook' if message should be HTML message.
2753 - dmj/wl-send-html-message-draft-init
2755   Cannot be called interactively: It is hooked into WL's
2756   `wl-mail-setup-hook' and provides a buffer local variable to
2757   toggle.
2759 - dmj/wl-send-html-message-draft-maybe
2761   Cannot be called interactively: It is hooked into WL's
2762   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2763   `mime-edit-translate-hook' depending on whether HTML message is
2764   toggled on or off
2766 - dmj/wl-send-html-message-toggle
2768   Toggles sending of HTML message.  If toggled on, the letters
2769   "HTML" appear in the mode line.
2771   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
2773 If you have to send HTML messages regularly you can set a global
2774 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2775 toggle on sending HTML message by default.
2777 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2778 Google's web front end.  As you can see you have the whole markup of
2779 Org at your service: *bold*, /italics/, tables, lists...
2781 So even if you feel uncomfortable with sending HTML messages at least
2782 you send HTML that looks quite good.
2784 #+begin_src emacs-lisp
2785 (defun dmj/wl-send-html-message ()
2786   "Send message as html message.
2787 Convert body of message to html using
2788   `org-export-region-as-html'."
2789   (require 'org)
2790   (save-excursion
2791     (let (beg end html text)
2792       (goto-char (point-min))
2793       (re-search-forward "^--text follows this line--$")
2794       ;; move to beginning of next line
2795       (beginning-of-line 2)
2796       (setq beg (point))
2797       (if (not (re-search-forward "^--\\[\\[" nil t))
2798           (setq end (point-max))
2799         ;; line up
2800         (end-of-line 0)
2801         (setq end (point)))
2802       ;; grab body
2803       (setq text (buffer-substring-no-properties beg end))
2804       ;; convert to html
2805       (with-temp-buffer
2806         (org-mode)
2807         (insert text)
2808         ;; handle signature
2809         (when (re-search-backward "^-- \n" nil t)
2810           ;; preserve link breaks in signature
2811           (insert "\n#+BEGIN_VERSE\n")
2812           (goto-char (point-max))
2813           (insert "\n#+END_VERSE\n")
2814           ;; grab html
2815           (setq html (org-export-region-as-html
2816                       (point-min) (point-max) t 'string))))
2817       (delete-region beg end)
2818       (insert
2819        (concat
2820         "--" "<<alternative>>-{\n"
2821         "--" "[[text/plain]]\n" text
2822         "--" "[[text/html]]\n"  html
2823         "--" "}-<<alternative>>\n")))))
2825 (defun dmj/wl-send-html-message-toggle ()
2826   "Toggle sending of html message."
2827   (interactive)
2828   (setq dmj/wl-send-html-message-toggled-p
2829         (if dmj/wl-send-html-message-toggled-p
2830             nil "HTML"))
2831   (message "Sending html message toggled %s"
2832            (if dmj/wl-send-html-message-toggled-p
2833                "on" "off")))
2835 (defun dmj/wl-send-html-message-draft-init ()
2836   "Create buffer local settings for maybe sending html message."
2837   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2838     (setq dmj/wl-send-html-message-toggled-p nil))
2839   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2840   (add-to-list 'global-mode-string
2841                '(:eval (if (eq major-mode 'wl-draft-mode)
2842                            dmj/wl-send-html-message-toggled-p))))
2844 (defun dmj/wl-send-html-message-maybe ()
2845   "Maybe send this message as html message.
2847 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2848 non-nil, add `dmj/wl-send-html-message' to
2849 `mime-edit-translate-hook'."
2850   (if dmj/wl-send-html-message-toggled-p
2851       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2852     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2854 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2855 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2856 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2857 #+end_src
2859 *** Attach HTML of region or subtree
2861 Instead of sending a complete HTML message you might only send parts
2862 of an Org file as HTML for the poor souls who are plagued with
2863 non-proportional fonts in their mail program that messes up pretty
2864 ASCII tables.
2866 This short function does the trick: It exports region or subtree to
2867 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2868 and clipboard.  If a region is active, it uses the region, the
2869 complete subtree otherwise.
2871 #+begin_src emacs-lisp
2872 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2873   "Export region between BEG and END as html attachment.
2874 If BEG and END are not set, use current subtree.  Region or
2875 subtree is exported to html without header and footer, prefixed
2876 with a mime entity string and pushed to clipboard and killring.
2877 When called with prefix, mime entity is not marked as
2878 attachment."
2879   (interactive "r\nP")
2880   (save-excursion
2881     (let* ((beg (if (region-active-p) (region-beginning)
2882                   (progn
2883                     (org-back-to-heading)
2884                     (point))))
2885            (end (if (region-active-p) (region-end)
2886                   (progn
2887                     (org-end-of-subtree)
2888                     (point))))
2889            (html (concat "--[[text/html"
2890                          (if arg "" "\nContent-Disposition: attachment")
2891                          "]]\n"
2892                          (org-export-region-as-html beg end t 'string))))
2893       (when (fboundp 'x-set-selection)
2894         (ignore-errors (x-set-selection 'PRIMARY html))
2895         (ignore-errors (x-set-selection 'CLIPBOARD html)))
2896       (message "html export done, pushed to kill ring and clipboard"))))
2897 #+end_src
2899 *** Adopting for Gnus
2901 The whole magic lies in the special strings that mark a HTML
2902 attachment.  So you might just have to find out what these special
2903 strings are in message-mode and modify the functions accordingly.
2904 ** Add sunrise/sunset times to the agenda.
2905 #+index: Agenda!Diary s-expressions
2906   -- Nick Dokos
2908 The diary package provides the function =diary-sunrise-sunset= which can be used
2909 in a diary s-expression in some agenda file like this:
2911 #+begin_src org
2912 %%(diary-sunrise-sunset)
2913 #+end_src
2915 Seb Vauban asked if it is possible to put sunrise and sunset in
2916 separate lines. Here is a hack to do that. It adds two functions (they
2917 have to be available before the agenda is shown, so I add them early
2918 in my org-config file which is sourced from .emacs, but you'll have to
2919 suit yourself here) that just parse the output of
2920 diary-sunrise-sunset, instead of doing the right thing which would be
2921 to take advantage of the data structures that diary/solar.el provides.
2922 In short, a hack - so perfectly suited for inclusion here :-)
2924 The functions (and latitude/longitude settings which you have to modify for
2925 your location) are as follows:
2927 #+begin_src emacs-lisp
2928 (setq calendar-latitude 48.2)
2929 (setq calendar-longitude 16.4)
2930 (setq calendar-location-name "Vienna, Austria")
2932 (autoload 'solar-sunrise-sunset "solar.el")
2933 (autoload 'solar-time-string "solar.el")
2934 (defun diary-sunrise ()
2935   "Local time of sunrise as a diary entry.
2936 The diary entry can contain `%s' which will be replaced with
2937 `calendar-location-name'."
2938   (let ((l (solar-sunrise-sunset date)))
2939     (when (car l)
2940       (concat
2941        (if (string= entry "")
2942            "Sunrise"
2943          (format entry (eval calendar-location-name))) " "
2944          (solar-time-string (caar l) nil)))))
2946 (defun diary-sunset ()
2947   "Local time of sunset as a diary entry.
2948 The diary entry can contain `%s' which will be replaced with
2949 `calendar-location-name'."
2950   (let ((l (solar-sunrise-sunset date)))
2951     (when (cadr l)
2952       (concat
2953        (if (string= entry "")
2954            "Sunset"
2955          (format entry (eval calendar-location-name))) " "
2956          (solar-time-string (caadr l) nil)))))
2957 #+end_src
2959 You also need to add a couple of diary s-expressions in one of your agenda
2960 files:
2962 #+begin_src org
2963 %%(diary-sunrise)Sunrise in %s
2964 %%(diary-sunset)
2965 #+end_src
2967 This will show sunrise with the location and sunset without it.
2969 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]].
2970 In comparison to the version posted on the mailing list, this one
2971 gets rid of the timezone information and can show the location.
2972 ** Add lunar phases to the agenda.
2973 #+index: Agenda!Diary s-expressions
2974    -- Rüdiger
2976 Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
2977 This can be used to display lunar phases in the agenda display with the
2978 following function:
2980 #+begin_src emacs-lisp
2981 (require 'cl-lib)
2983 (org-no-warnings (defvar date))
2984 (defun org-lunar-phases ()
2985   "Show lunar phase in Agenda buffer."
2986   (require 'lunar)
2987   (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
2988          (phase (cl-find-if (lambda (phase) (equal (car phase) date))
2989                             phase-list)))
2990     (when phase
2991       (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
2992                         (substring (nth 1 phase) 0 5))))))
2993 #+end_src
2995 Add the following line to an agenda file:
2997 #+begin_src org
2998 ,* Lunar phase
2999 ,#+CATEGORY: Lunar
3000 %%(org-lunar-phases)
3001 #+end_src
3003 This should display an entry on new moon, first/last quarter moon, and on full
3004 moon.  You can customize the entries by customizing =lunar-phase-names=.
3006 E.g., to add Unicode symbols:
3008 #+begin_src emacs-lisp
3009 (setq lunar-phase-names
3010       '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
3011         "☽ First Quarter Moon"
3012         "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
3013         "☾ Last Quarter Moon"))
3014 #+end_src
3016 Unicode 6 even provides symbols for the Moon with nice faces.  But those
3017 symbols are currently barely supported in fonts.
3018 See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].
3020 ** Export BBDB contacts to org-contacts.el
3021 #+index: Address Book!BBDB to org-contacts
3022 Try this tool by Wes Hardaker:
3024 http://www.hardakers.net/code/bbdb-to-org-contacts/
3026 ** Calculating date differences - how to write a simple elisp function
3027 #+index: Timestamp!date calculations
3028 #+index: Elisp!technique
3030 Alexander Wingård asked how to calculate the number of days between a
3031 time stamp in his org file and today (see
3032 http://thread.gmane.org/gmane.emacs.orgmode/46881).  Although the
3033 resulting answer is probably not of general interest, the method might
3034 be useful to a budding Elisp programmer.
3036 Alexander started from an already existing org function,
3037 =org-evaluate-time-range=.  When this function is called in the context
3038 of a time range (two time stamps separated by "=--="), it calculates the
3039 number of days between the two dates and outputs the result in Emacs's
3040 echo area. What he wanted was a similar function that, when called from
3041 the context of a single time stamp, would calculate the number of days
3042 between the date in the time stamp and today. The result should go to
3043 the same place: Emacs's echo area.
3045 The solution presented in the mail thread is as follows:
3047 #+begin_src emacs-lisp
3048 (defun aw/org-evaluate-time-range (&optional to-buffer)
3049   (interactive)
3050   (if (org-at-date-range-p t)
3051       (org-evaluate-time-range to-buffer)
3052     ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
3053     (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
3054       (with-temp-buffer
3055         (insert headline)
3056         (goto-char (point-at-bol))
3057         (re-search-forward org-ts-regexp (point-at-eol) t)
3058         (if (not (org-at-timestamp-p t))
3059             (error "No timestamp here"))
3060         (goto-char (match-beginning 0))
3061         (org-insert-time-stamp (current-time) nil nil)
3062         (insert "--")
3063         (org-evaluate-time-range to-buffer)))))
3064 #+end_src
3066 The function assumes that point is on some line with some time stamp
3067 (or a date range) in it. Note that =org-evaluate-time-range= does not care
3068 whether the first date is earlier than the second: it will always output
3069 the number of days between the earlier date and the later date.
3071 As stated before, the function itself is of limited interest (although
3072 it satisfied Alexander's need).The *method* used might be of wider
3073 interest however, so here is a short explanation.
3075 The idea is that we want =org-evaluate-time-range= to do all the
3076 heavy lifting, but that function requires that it be in a date-range
3077 context. So the function first checks whether it's in a date range
3078 context already: if so, it calls =org-evaluate-time-range= directly
3079 to do the work. The trick now is to arrange things so we can call this
3080 same function in the case where we do *not* have a date range
3081 context. In that case, we manufacture one: we create a temporary
3082 buffer, copy the line with the purported time stamp to the temp
3083 buffer, find the time stamp (signal an error if no time stamp is
3084 found) and insert a new time stamp with the current time before the
3085 existing time stamp, followed by "=--=": voilà, we now have a time range
3086 on which we can apply our old friend =org-evaluate-time-range= to
3087 produce the answer. Because of the above-mentioned property
3088 of =org-evaluate-time-range=, it does not matter if the existing
3089 time stamp is earlier or later than the current time: the correct
3090 number of days is output.
3092 Note that at the end of the call to =with-temp-buffer=, the temporary
3093 buffer goes away.  It was just used as a scratch pad for the function
3094 to do some figuring.
3096 The idea of using a temp buffer as a scratch pad has wide
3097 applicability in Emacs programming. The rest of the work is knowing
3098 enough about facilities provided by Emacs (e.g. regexp searching) and
3099 by Org (e.g. checking for time stamps and generating a time stamp) so
3100 that you don't reinvent the wheel, and impedance-matching between the
3101 various pieces.
3103 ** ibuffer and org files
3105 Neil Smithline posted this snippet to let you browse org files with
3106 =ibuffer=:
3108 #+BEGIN_SRC emacs-lisp
3109 (require 'ibuffer)
3111 (defun org-ibuffer ()
3112   "Open an `ibuffer' window showing only `org-mode' buffers."
3113   (interactive)
3114   (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
3115 #+END_SRC
3117 ** Enable org-mode links in other modes
3119 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
3121 See the relevant discussion [[http://thread.gmane.org/gmane.emacs.orgmode/58715/focus%3D58794][here]].
3123 ** poporg.el: edit comments in org-mode
3125 [[https://github.com/QBobWatson/poporg/blob/master/poporg.el][poporg.el]] is a library by François Pinard which lets you edit comments
3126 and strings from your code using a separate org-mode buffer.
3128 ** Convert a .csv file to an Org-mode table
3130 Nicolas Richard has a [[http://article.gmane.org/gmane.emacs.orgmode/65456][nice recipe]] using the pcsv library ([[http://marmalade-repo.org/packages/pcsv][available]] from
3131 the Marmelade ELPA repository):
3133 #+BEGIN_SRC emacs-lisp
3134 (defun yf/lisp-table-to-org-table (table &optional function)
3135   "Convert a lisp table to `org-mode' syntax, applying FUNCTION to each of its elements.
3136 The elements should not have any more newlines in them after
3137 applying FUNCTION ; the default converts them to spaces. Return
3138 value is a string containg the unaligned `org-mode' table."
3139   (unless (functionp function)
3140     (setq function (lambda (x) (replace-regexp-in-string "\n" " " x))))
3141   (mapconcat (lambda (x)                ; x is a line.
3142                (concat "| " (mapconcat function x " | ") " |"))
3143              table "\n"))
3145 (defun yf/csv-to-table (beg end)
3146 "Convert a csv file to an `org-mode' table."
3147   (interactive "r")
3148   (require 'pcsv)
3149   (insert (yf/lisp-table-to-org-table (pcsv-parse-region beg end)))
3150   (delete-region beg end)
3151   (org-table-align))
3152 #+END_SRC
3154 * Hacking Org: Working with Org-mode and External Programs.
3155 ** Use Org-mode with Screen [Andrew Hyatt]
3156 #+index: Link!to screen session
3157 "The general idea is that you start a task in which all the work will
3158 take place in a shell.  This usually is not a leaf-task for me, but
3159 usually the parent of a leaf task.  From a task in your org-file, M-x
3160 ash-org-screen will prompt for the name of a session.  Give it a name,
3161 and it will insert a link.  Open the link at any time to go the screen
3162 session containing your work!"
3164 http://article.gmane.org/gmane.emacs.orgmode/5276
3166 #+BEGIN_SRC emacs-lisp
3167 (require 'term)
3169 (defun ash-org-goto-screen (name)
3170   "Open the screen with the specified name in the window"
3171   (interactive "MScreen name: ")
3172   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
3173     (if (member screen-buffer-name
3174                 (mapcar 'buffer-name (buffer-list)))
3175         (switch-to-buffer screen-buffer-name)
3176       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
3178 (defun ash-org-screen-buffer-name (name)
3179   "Returns the buffer name corresponding to the screen name given."
3180   (concat "*screen " name "*"))
3182 (defun ash-org-screen-helper (name arg)
3183   ;; Pick the name of the new buffer.
3184   (let ((term-ansi-buffer-name
3185          (generate-new-buffer-name
3186           (ash-org-screen-buffer-name name))))
3187     (setq term-ansi-buffer-name
3188           (term-ansi-make-term
3189            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
3190     (set-buffer term-ansi-buffer-name)
3191     (term-mode)
3192     (term-char-mode)
3193     (term-set-escape-char ?\C-x)
3194     term-ansi-buffer-name))
3196 (defun ash-org-screen (name)
3197   "Start a screen session with name"
3198   (interactive "MScreen name: ")
3199   (save-excursion
3200     (ash-org-screen-helper name "-S"))
3201   (insert-string (concat "[[screen:" name "]]")))
3203 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
3204 ;; \"%s\")") to org-link-abbrev-alist.
3205 #+END_SRC
3207 ** Org Agenda + Appt + Zenity
3208     :PROPERTIES:
3209     :CUSTOM_ID: org-agenda-appt-zenity
3210     :END:
3212 #+index: Appointment!reminders
3213 #+index: Appt!Zenity
3214 #+BEGIN_HTML
3215 <a name="agenda-appt-zenity"></a>
3216 #+END_HTML
3217 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It makes sure your agenda
3218 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
3219 popup window.
3221 #+BEGIN_SRC emacs-lisp
3222 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3223 ; For org appointment reminders
3225 ;; Get appointments for today
3226 (defun my-org-agenda-to-appt ()
3227   (interactive)
3228   (setq appt-time-msg-list nil)
3229   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
3230         (org-agenda-to-appt)))
3232 ;; Run once, activate and schedule refresh
3233 (my-org-agenda-to-appt)
3234 (appt-activate t)
3235 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
3237 ; 5 minute warnings
3238 (setq appt-message-warning-time 15)
3239 (setq appt-display-interval 5)
3241 ; Update appt each time agenda opened.
3242 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
3244 ; Setup zenify, we tell appt to use window, and replace default function
3245 (setq appt-display-format 'window)
3246 (setq appt-disp-window-function (function my-appt-disp-window))
3248 (defun my-appt-disp-window (min-to-app new-time msg)
3249   (save-window-excursion (shell-command (concat
3250     "/usr/bin/zenity --info --title='Appointment' --text='"
3251     msg "' &") nil nil)))
3252 #+END_SRC
3254 ** Org and appointment notifications on Mac OS 10.8
3256 Sarah Bagby [[http://mid.gmane.org/EA76104A-9ACD-4141-8D33-2E4D810D9B5A@geol.ucsb.edu][posted some code]] on how to get appointments notifications on
3257 Mac OS 10.8 with [[https://github.com/alloy/terminal-notifier][terminal-notifier]].
3259 ** Org-Mode + gnome-osd
3260 #+index: Appointment!reminders
3261 #+index: Appt!gnome-osd
3262 Richard Riley uses gnome-osd in interaction with Org-Mode to display
3263 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
3265 ** txt2org convert text data to org-mode tables
3266 From Eric Schulte
3268 I often find it useful to generate Org-mode tables on the command line
3269 from tab-separated data.  The following awk script makes this easy to
3270 do.  Text data is read from STDIN on a pipe and any command line
3271 arguments are interpreted as rows at which to insert hlines.
3273 Here are two usage examples.
3274 1. running the following
3275    : $ cat <<EOF|~/src/config/bin/txt2org
3276    : one 1
3277    : two 2
3278    : three 3
3279    : twenty 20
3280    : EOF                  
3281    results in
3282    : |    one |  1 |
3283    : |    two |  2 |
3284    : |  three |  3 |
3285    : | twenty | 20 |
3287 2. and the following (notice the command line argument)
3288    : $ cat <<EOF|~/src/config/bin/txt2org 1
3289    : strings numbers                                          
3290    : one 1
3291    : two 2
3292    : three 3
3293    : twenty 20
3294    : EOF 
3295    results in
3296    : | strings | numbers |
3297    : |---------+---------|
3298    : |     one |       1 |
3299    : |     two |       2 |
3300    : |   three |       3 |
3301    : |  twenty |      20 |
3303 Here is the script itself
3304 #+begin_src awk
3305   #!/usr/bin/gawk -f
3306   #
3307   # Read tab separated data from STDIN and output an Org-mode table.
3308   #
3309   # Optional command line arguments specify row numbers at which to
3310   # insert hlines.
3311   #
3312   BEGIN {
3313       for(i=1; i<ARGC; i++){
3314           hlines[ARGV[i]+1]=1; ARGV[i] = "-"; } }
3315   
3316   {
3317       if(NF > max_nf){ max_nf = NF; };
3318       for(f=1; f<=NF; f++){
3319           if(length($f) > lengths[f]){ lengths[f] = length($f); };
3320           row[NR][f]=$f; } }
3321   
3322   END {
3323       hline_str="|"
3324       for(f=1; f<=max_nf; f++){
3325           for(i=0; i<(lengths[f] + 2); i++){ hline_str=hline_str "-"; }
3326           if( f != max_nf){ hline_str=hline_str "+"; }
3327           else            { hline_str=hline_str "|"; } }
3328   
3329       for(r=1; r<=NR; r++){ # rows
3330           if(hlines[r] == 1){ print hline_str; }
3331           printf "|";
3332           for(f=1; f<=max_nf; f++){ # columns
3333               cell=row[r][f]; padding=""
3334               for(i=0; i<(lengths[f] - length(cell)); i++){ padding=padding " "; }
3335               # for now just print everything right-aligned
3336               # if(cell ~ /[0-9.]/){ printf " %s%s |", cell, padding; }
3337               # else{                printf " %s%s |", padding, cell; }
3338               printf " %s%s |", padding, cell; }
3339           printf "\n"; }
3340       
3341       if(hlines[NR+1]){ print hline_str; } }
3342 #+end_src
3344 ** remind2org
3345 #+index: Agenda!Views
3346 #+index: Agenda!and Remind (external program)
3347 From Detlef Steuer
3349 http://article.gmane.org/gmane.emacs.orgmode/5073
3351 #+BEGIN_QUOTE
3352 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
3353 command line calendaring program. Its features supersede the possibilities
3354 of orgmode in the area of date specifying, so that I want to use it
3355 combined with orgmode.
3357 Using the script below I'm able use remind and incorporate its output in my
3358 agenda views.  The default of using 13 months look ahead is easily
3359 changed. It just happens I sometimes like to look a year into the
3360 future. :-)
3361 #+END_QUOTE
3363 ** Useful webjumps for conkeror
3364 #+index: Shortcuts!conkeror
3365 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
3366 your =~/.conkerorrc= file:
3368 #+begin_example
3369 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
3370 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
3371 #+end_example
3373 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
3374 Org-mode mailing list.
3376 ** Use MathJax for HTML export without requiring JavaScript
3377 #+index: Export!MathJax
3378 As of 2010-08-14, MathJax is the default method used to export math to HTML.
3380 If you like the results but do not want JavaScript in the exported pages,
3381 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
3382 HTML file from the exported version. It can also embed all referenced fonts
3383 within the HTML file itself, so there are no dependencies to external files.
3385 The download archive contains an elisp file which integrates it into the Org
3386 export process (configurable per file with a "#+StaticMathJax:" line).
3388 Read README.org and the comments in org-static-mathjax.el for usage instructions.
3389 ** Search Org files using lgrep
3390 #+index: search!lgrep
3391 Matt Lundin suggests this:
3393 #+begin_src emacs-lisp
3394   (defun my-org-grep (search &optional context)
3395     "Search for word in org files.
3397 Prefix argument determines number of lines."
3398     (interactive "sSearch for: \nP")
3399     (let ((grep-find-ignored-files '("#*" ".#*"))
3400           (grep-template (concat "grep <X> -i -nH "
3401                                  (when context
3402                                    (concat "-C" (number-to-string context)))
3403                                  " -e <R> <F>")))
3404       (lgrep search "*org*" "/home/matt/org/")))
3406   (global-set-key (kbd "<f8>") 'my-org-grep)
3407 #+end_src
3409 ** Automatic screenshot insertion
3410 #+index: Link!screenshot
3411 Suggested by Russell Adams
3413 #+begin_src emacs-lisp
3414   (defun my-org-screenshot ()
3415     "Take a screenshot into a time stamped unique-named file in the
3416   same directory as the org-buffer and insert a link to this file."
3417     (interactive)
3418     (setq filename
3419           (concat
3420            (make-temp-name
3421             (concat (buffer-file-name)
3422                     "_"
3423                     (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
3424     (call-process "import" nil nil nil filename)
3425     (insert (concat "[[" filename "]]"))
3426     (org-display-inline-images))
3427 #+end_src
3429 ** Capture invitations/appointments from MS Exchange emails
3430 #+index: Appointment!MS Exchange
3431 Dirk-Jan C.Binnema [[http://article.gmane.org/gmane.emacs.orgmode/27684/][provided]] code to do this.  Please check
3432 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
3434 ** Audio/video file playback within org mode
3435 #+index: Link!audio/video
3436 Paul Sexton provided code that makes =file:= links to audio or video files
3437 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
3438 media player library. The user can pause, skip forward and backward in the
3439 track, and so on from without leaving Emacs. Links can also contain a time
3440 after a double colon -- when this is present, playback will begin at that
3441 position in the track.
3443 See the file [[file:code/elisp/org-player.el][org-player.el]]
3445 ** Under X11 Keep a window with the current agenda items at all time
3446 #+index: Agenda!dedicated window
3447 I struggle to keep (in emacs) a window with the agenda at all times.
3448 For a long time I have wanted a sticky window that keeps this
3449 information, and then use my window manager to place it and remove its
3450 decorations (I can also force its placement in the stack: top always,
3451 for example).
3453 I wrote a small program in qt that simply monitors an HTML file and
3454 displays it. Nothing more. It does the work for me, and maybe somebody
3455 else will find it useful. It relies on exporting the agenda as HTML
3456 every time the org file is saved, and then this little program
3457 displays the html file. The window manager is responsible of removing
3458 decorations, making it sticky, and placing it in same place always.
3460 Here is a screenshot (see window to the bottom right). The decorations
3461 are removed by the window manager:
3463 http://turingmachine.org/hacking/org-mode/orgdisplay.png
3465 Here is the code. As I said, very, very simple, but maybe somebody will
3466 find if useful.
3468 http://turingmachine.org/hacking/org-mode/
3470 --daniel german
3472 ** Script (thru procmail) to output emails to an Org file
3473 #+index: Conversion!email to org file
3474 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
3476 : I've [...] created some procmail and shell glue that takes emails and
3477 : inserts them into an org-file so that I can capture stuff on the go using
3478 : the email program.
3480 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3482 ** Save File With Different Format for Headings (fileconversion)
3483    :PROPERTIES:
3484    :CUSTOM_ID: fileconversion
3485    :END:
3486 #+index: Conversion!fileconversion
3488 Using hooks and on the fly
3489 - When writing a buffer to the file: Replace the leading stars from
3490   headings with a file char.
3491 - When reading a file into the buffer: Replace the file chars with
3492   leading stars for headings.
3494 To change the file format just add or remove the keyword in the
3495 ~#+STARTUP:~ line in the Org buffer and save.
3497 Now you can also change to Fundamental mode to see how the file looks
3498 like on the level of the file, can go back to Org mode, reenter Org
3499 mode or change to any other major mode and the conversion gets done
3500 whenever necessary.
3502 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
3503     :PROPERTIES:
3504     :CUSTOM_ID: hidestarsfile
3505     :END:
3506 #+index: Conversion!fileconversion hidestarsfile
3508 This is like "a cleaner outline view":
3509 http://orgmode.org/manual/Clean-view.html
3511 Example of the *file content* first with leading stars as usual and
3512 below without leading stars through ~#+STARTUP: odd hidestars
3513 hidestarsfile~:
3515 #+BEGIN_SRC org
3516   ,#+STARTUP: odd hidestars
3517   [...]
3518   ***** TODO section
3519   ******* subsection
3520   ********* subsubsec
3521             - bla bla
3522   ***** section
3523         - bla bla
3524   ******* subsection
3525 #+END_SRC
3527 #+BEGIN_SRC org
3528   ,#+STARTUP: odd hidestars hidestarsfile
3529   [...]
3530       * TODO section
3531         * subsection
3532           * subsubsec
3533             - bla bla
3534       * section
3535         - bla bla
3536         * subsection
3537 #+END_SRC
3539 The latter is convenient for better human readability when an Org file,
3540 additionally to Emacs, is read with a file viewer or, for smaller edits,
3541 with an editor not capable of the Org file format.
3543 ~hidestarsfile~ is a hack and can not become part of the Org core:
3544 - An Org file with ~hidestarsfile~ can not contain list items with a
3545   star as bullet due to the syntax conflict at read time. Mark
3546   E. Shoulson suggested to use the non-breaking space which is now
3547   implemented in fileconversion as ~nbspstarsfile~ as an alternative
3548   for ~hidestarsfile~. Although I don't recommend it because an editor
3549   like typically e. g. Emacs may render the non-breaking space
3550   differently from the space ~0x20~.
3551 - An Org file with ~hidestarsfile~ can almost not be edited with an
3552   Org mode without added functionality of hidestarsfile as long as the
3553   file is not converted back.
3555 *** Headings in Markdown Format (markdownstarsfile)
3556     :PROPERTIES:
3557     :CUSTOM_ID: markdownstarsfile
3558     :END:
3559 #+index: Conversion!fileconversion markdownstarsfile
3561 Together with ~oddeven~ you can use ~markdownstarsfile~ to be readable
3562 or even basically editable with Markdown (does not make much sense
3563 with ~odd~, see ~org-convert-to-odd-levels~ and
3564 ~org-convert-to-oddeven-levels~ for how to convert).
3566 Example of the *file content*:
3568 #+BEGIN_SRC org
3569   ,#+STARTUP: oddeven markdownstarsfile
3570   # section level 1
3571     1. first item of numbered list (same format in Org and Markdown)
3572   ## section level 2
3573      - first item of unordered list (same format in Org and Markdown)
3574   ### section level 3
3575       + first item of unordered list (same format in Org and Markdown)
3576   #### section level 4
3577        * first item of unordered list (same format in Org and Markdown)
3578        * avoid this item type to be compatible with Org hidestarsfile
3579 #+END_SRC
3581 An Org file with ~markdownstarsfile~ can not contain code comment
3582 lines prefixed with ~#~, even not when within source blocks.
3584 *** emacs-lisp code
3585     :PROPERTIES:
3586     :CUSTOM_ID: fileconversion-code
3587     :END:
3588 #+index: Conversion!fileconversion emacs-lisp code
3590 #+BEGIN_SRC emacs-lisp
3591   ;; - fileconversion version 0.10
3592   ;; - DISCLAIMER: Make a backup of your Org files before trying
3593   ;;   `f-org-fileconv-*'. It is recommended to use a version control
3594   ;;   system like git and to review and commit the changes in the Org
3595   ;;   files regularly.
3596   ;; - Supported "#+STARTUP:" formats: "hidestarsfile",
3597   ;;   "nbspstarsfile", "markdownstarsfile".
3599   ;; Design summary: fileconversion is a round robin of two states linked by
3600   ;; two actions:
3601   ;; - State `v-org-fileconv-level-org-p' is nil: The level is "file"
3602   ;;   (encoded).
3603   ;; - Action `f-org-fileconv-decode': Replace file char with "*".
3604   ;; - State `v-org-fileconv-level-org-p' is non-nil: The level is "Org"
3605   ;;   (decoded).
3606   ;; - Action `f-org-fileconv-encode': Replace "*" with file char.
3607   ;;
3608   ;; Naming convention of prefix:
3609   ;; - f-[...]: "my function", instead of the unspecific prefix `my-*'.
3610   ;; - v-[...]: "my variable", instead of the unspecific prefix `my-*'.
3612   (defvar v-org-fileconv-level-org-p nil
3613     "Whether level of buffer is Org or only file.
3614   nil: level is file (encoded), non-nil: level is Org (decoded).")
3615   (make-variable-buffer-local 'v-org-fileconv-level-org-p)
3616   ;; Survive a change of major mode that does `kill-all-local-variables', e.
3617   ;; g. when reentering Org mode through "C-c C-c" on a #+STARTUP: line.
3618   (put 'v-org-fileconv-level-org-p 'permanent-local t)
3620   ;; * Callback `f-org-fileconv-org-mode-beg' before `org-mode'
3621   (defadvice org-mode (before org-mode-advice-before-fileconv)
3622     (f-org-fileconv-org-mode-beg))
3623   (ad-activate 'org-mode)
3624   (defun f-org-fileconv-org-mode-beg ()
3625     ;; - Reason to test `buffer-file-name': Only when converting really
3626     ;;   from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3627     ;;   file.
3628     ;; - No `message' to not wipe a possible "File mode specification error:".
3629     ;; - `f-org-fileconv-decode' in org-mode-hook would be too late for
3630     ;;   performance reasons, see
3631     ;;   http://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00920.html
3632     (when (buffer-file-name) (f-org-fileconv-decode)))
3634   ;; * Callback `f-org-fileconv-org-mode-end' after `org-mode'
3635   (add-hook 'org-mode-hook 'f-org-fileconv-org-mode-end
3636             nil   ; _Prepend_ to hook to have it first.
3637             nil)  ; Hook addition global.
3638   (defun f-org-fileconv-org-mode-end ()
3639     ;; - Reason to test `buffer-file-name': only when converting really
3640     ;;   from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3641     ;;   file.
3642     ;; - No `message' to not wipe a possible "File mode specification error:".
3643     (when (buffer-file-name)
3644       ;; - Adding this to `change-major-mode-hook' or "defadvice before" of
3645       ;;   org-mode would be too early and already trigger during find-file.
3646       ;; - Argument 4: t to limit hook addition to buffer locally, this way
3647       ;;   and as required the hook addition will disappear when the major
3648       ;;   mode of the buffer changes.
3649       (add-hook 'change-major-mode-hook 'f-org-fileconv-encode nil t)
3650       (add-hook 'before-save-hook       'f-org-fileconv-encode nil t)
3651       (add-hook 'after-save-hook        'f-org-fileconv-decode nil t)))
3653   (defun f-org-fileconv-re ()
3654     "Check whether there is a #+STARTUP: line for fileconversion.
3655   If found then return the expressions required for the conversion."
3656     (save-excursion
3657       (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3658       (let (re-list (count 0))
3659         (while (re-search-forward "^[ \t]*#\\+STARTUP:" nil t)
3660           ;; #+STARTUP: hidestarsfile
3661           (when (string-match-p "\\bhidestarsfile\\b" (thing-at-point 'line))
3662             ;; Exclude e. g.:
3663             ;; - Line starting with star for bold emphasis.
3664             ;; - Line of stars to underline section title in loosely quoted
3665             ;;   ASCII style (star at end of line).
3666             (setq re-list '("\\(\\* \\)"  ; common-re
3667                             ?\ ))         ; file-char
3668             (setq count (1+ count)))
3669           ;; #+STARTUP: nbspstarsfile
3670           (when (string-match-p "\\bnbspstarsfile\\b" (thing-at-point 'line))
3671             (setq re-list '("\\(\\* \\)"  ; common-re
3672                             ?\xa0))       ; file-char non-breaking space
3673             (setq count (1+ count)))
3674           ;; #+STARTUP: markdownstarsfile
3675           (when (string-match-p "\\bmarkdownstarsfile\\b"
3676                                 (thing-at-point 'line))
3677             ;; Exclude e. g. "#STARTUP:".
3678             (setq re-list '("\\( \\)"  ; common-re
3679                             ?#))       ; file-char
3680             (setq count (1+ count))))
3681         (when (> count 1) (error "More than one fileconversion found."))
3682         re-list)))
3684   (defun f-org-fileconv-decode ()
3685     "In headings replace file char with '*'."
3686     (let ((re-list (f-org-fileconv-re)))
3687       (when (and re-list (not v-org-fileconv-level-org-p))
3688         ;; No `save-excursion' to be able to keep point in case of error.
3689         (let* ((common-re (nth 0 re-list))
3690                (file-char (nth 1 re-list))
3691                (file-re   (concat "^" (string file-char) "+" common-re))
3692                (org-re    (concat "^\\*+" common-re))
3693                len
3694                (p         (point)))
3695           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3696           ;; Syntax check.
3697           (when (re-search-forward org-re nil t)
3698             (goto-char (match-beginning 0))
3699             (org-reveal)
3700             (error "Org fileconversion decode: Syntax conflict at point."))
3701           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3702           ;; Substitution.
3703           (with-silent-modifications
3704             (while (re-search-forward file-re nil t)
3705               (goto-char (match-beginning 0))
3706               ;; Faster than a lisp call of insert and delete on each single
3707               ;; char.
3708               (setq len (- (match-beginning 1) (match-beginning 0)))
3709               (insert-char ?* len)
3710               (delete-char len)))
3711           (goto-char p))))
3713           ;; Notes for ediff when only one file has fileconversion:
3714           ;; - The changes to the buffer with fileconversion until here are
3715           ;;   not regarded by `ediff-files' because the first call to diff is
3716           ;;   made with the bare files directly. Only `ediff-update-diffs'
3717           ;;   and `ediff-buffers' write the decoded buffers to temp files and
3718           ;;   then call diff with them.
3719           ;; - Workarounds (choose one):
3720           ;;   - After ediff-files first do a "!" (ediff-update-diffs) in the
3721           ;;     "*Ediff Control Panel*".
3722           ;;   - Instead of using `ediff-files' first open the files and then
3723           ;;     run `ediff-buffers' (better for e. g. a script that takes two
3724           ;;     files as arguments and uses "emacs --eval").
3726     ;; The level is Org most of all when no fileconversion is in effect.
3727     (setq v-org-fileconv-level-org-p t))
3729   (defun f-org-fileconv-encode ()
3730     "In headings replace '*' with file char."
3731     (let ((re-list (f-org-fileconv-re)))
3732       (when (and re-list v-org-fileconv-level-org-p)
3733         ;; No `save-excursion' to be able to keep point in case of error.
3734         (let* ((common-re (nth 0 re-list))
3735                (file-char (nth 1 re-list))
3736                (file-re   (concat "^" (string file-char) "+" common-re))
3737                (org-re    (concat "^\\*+" common-re))
3738                len
3739                (p         (point)))
3740           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3741           ;; Syntax check.
3742           (when (re-search-forward file-re nil t)
3743             (goto-char (match-beginning 0))
3744             (org-reveal)
3745             (error "Org fileconversion encode: Syntax conflict at point."))
3746           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3747           ;; Substitution.
3748           (with-silent-modifications
3749             (while (re-search-forward org-re nil t)
3750               (goto-char (match-beginning 0))
3751               ;; Faster than a lisp call of insert and delete on each single
3752               ;; char.
3753               (setq len (- (match-beginning 1) (match-beginning 0)))
3754               (insert-char file-char len)
3755               (delete-char len)))
3756           (goto-char p)
3757           (setq v-org-fileconv-level-org-p nil))))
3758     nil)  ; For the hook.
3759 #+END_SRC
3761 Michael Brand
3763 ** Meaningful diff for org files in a git repository
3764 #+index: git!diff org files
3765 Since most diff utilities are primarily meant for source code, it is
3766 difficult to read diffs of text files like ~.org~ files easily. If you
3767 version your org directory with a SCM like git you will know what I
3768 mean. However for git, there is a way around. You can use
3769 =gitattributes= to define a custom diff driver for org files. Then a
3770 regular expression can be used to configure how the diff driver
3771 recognises a "function".
3773 Put the following in your =<org_dir>/.gitattributes=.
3774 : *.org diff=org
3775 Then put the following lines in =<org_dir>/.git/config=
3776 : [diff "org"]
3777 :       xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3779 This will let you see diffs for org files with each hunk identified by
3780 the unmodified headline closest to the changes. After the
3781 configuration a diff should look something like the example below.
3783 #+begin_example
3784 diff --git a/org-hacks.org b/org-hacks.org
3785 index a0672ea..92a08f7 100644
3786 --- a/org-hacks.org
3787 +++ b/org-hacks.org
3788 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3790  Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3792 +** Meaningful diff for org files in a git repository
3794 +Since most diff utilities are primarily meant for source code, it is
3795 +difficult to read diffs of text files like ~.org~ files easily. If you
3796 +version your org directory with a SCM like git you will know what I
3797 +mean. However for git, there is a way around. You can use
3798 +=gitattributes= to define a custom diff driver for org files. Then a
3799 +regular expression can be used to configure how the diff driver
3800 +recognises a "function".
3802 +Put the following in your =<org_dir>/.gitattributes=.
3803 +: *.org        diff=org
3804 +Then put the following lines in =<org_dir>/.git/config=
3805 +: [diff "org"]
3806 +:      xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3808  * Musings
3810  ** Cooking?  Brewing?
3811 #+end_example
3813 ** Opening devonthink links
3815 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
3816 links from org-mode.
3818 ** Memacs - Org-mode collecting meta-data from the disk and cloud
3820 Karl Voit designed Memacs ([[https://en.wikipedia.org/wiki/Memex][Memex]] and Emacs) which is a collection of
3821 modules that are able to get meta-data from different kind of
3822 sources. Memacs then generates output files containing meta-data in
3823 Org-mode format. Those files a most likely integrated as ~*.org_archive~
3824 files in your agenda.
3826 This way, you can get a pretty decent overview of your (digital) life:
3827 - file name timestamps ([[https://en.wikipedia.org/wiki/Iso_date][ISO 8601]]; like "2013-10-11 Product Demonstration.odp")
3828 - emails (IMAP, POP, Maildir, mbox)
3829 - RSS feeds (blog updates, ... *lots* of possibilities there!)
3830 - version system commits (SVN, git)
3831 - calendar (iCal, CSV)
3832 - text messages from your phone (Android)
3833 - phone calls (Android)
3834 - photographs (EXIF)
3835 - bank accounts ([[http://easybank.at][easybank]])
3836 - usenet postings (slrn, mbox, ...)
3837 - XML (a sub-set of easy-to-parse XML files can be parsed with minimal
3838   effort)
3840 General idea: you set up the module(s) you would like to use once and
3841 they are running in the background. As long as the data source does
3842 not change, you should not have to worry about the module again.
3844 It is hard to explain the vast amount of (small) benefits you get once
3845 you have set up your Memacs modules.
3847 There is [[http://arxiv.org/abs/1304.1332][a whitepaper which describes Memacs]] and its implications.
3849 Memacs is [[https://github.com/novoid/Memacs][hosted on github]] and is written in Python.
3851 You can use Memacs to write your own Memacs module: an example module
3852 demonstrates how to write modules with very low effort. Please
3853 consider a pull request on github so that other people can use your
3854 module as well!
3856 [[https://github.com/novoid/twitter-json_to_orgmode][Twitter JSON to Org-mode]] generates Memacs-like output files for
3857 [[https://blog.twitter.com/2012/your-twitter-archive][Twitter export archives]] (JSON) but is independent of Memacs.
3859 * Musings
3861 ** Cooking?  Brewing?
3862 #+index: beer!brewing
3863 #+index: cooking!conversions
3864 See [[http://article.gmane.org/gmane.emacs.orgmode/44981][this message]] from Erik Hetzner:
3866 It currently does metric/english conversion, and a few other tricks.
3867 Basically I just use calc’s units code.  I think scaling recipes, or
3868 turning percentages into weights would be pretty easy.
3870   https://gitorious.org/org-cook/org-cook
3872 There is also, for those interested:
3874   https://gitorious.org/org-brew/org-brew
3876 for brewing beer. This is again, mostly just calc functions, including
3877 hydrometer correction, abv calculation, priming sugar for a given CO_2
3878 volume, etc. More integration with org-mode should be possible: for
3879 instance it would be nice to be able to use a lookup table (of ingredients)
3880 to calculate target original gravity, IBUs, etc.