org-contribute.org: Clarify what contributors can expect
[worg.git] / org-hacks.org
blob8d8d41b59008ca0175fc28714c0262474f171c44
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
11 #+HTML_LINK_UP:    index.html
12 #+HTML_LINK_HOME:  https://orgmode.org/worg/
14 # This file is the default header for new Org files in Worg.  Feel free
15 # to tailor it to your needs.
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 *** Colorize clocking tasks with a block
24 :PROPERTIES:
25 :DIR:      /home/stardiviner/Code/Emacs/worg/images/agenda/
26 :END:
28 Show Org Agenda tasks with heigh spacing based on clock time with ~org-agenda-log-mode~.
30 [[file:images/agenda/org-agenda-colorized-blocks.png]]
32 Here is original author's post https://emacs-china.org/t/org-agenda/8679.
34 Here is a hook function to use archive this effect:
36 #+begin_src emacs-lisp
37 ;; work with org-agenda dispatcher [c] "Today Clocked Tasks" to view today's clocked tasks.
38 (defun org-agenda-log-mode-colorize-block ()
39   "Set different line spacing based on clock time duration."
40   (save-excursion
41     (let* ((colors (cl-case (alist-get 'background-mode (frame-parameters))
42                                  ('light
43                                   (list "#F6B1C3" "#FFFF9D" "#BEEB9F" "#ADD5F7"))
44                                  ('dark
45                                   (list "#aa557f" "DarkGreen" "DarkSlateGray" "DarkSlateBlue"))))
46            pos
47            duration)
48       (nconc colors colors)
49       (goto-char (point-min))
50       (while (setq pos (next-single-property-change (point) 'duration))
51         (goto-char pos)
52         (when (and (not (equal pos (point-at-eol)))
53                    (setq duration (org-get-at-bol 'duration)))
54           ;; larger duration bar height
55           (let ((line-height (if (< duration 15) 1.0 (+ 0.5 (/ duration 30))))
56                 (ov (make-overlay (point-at-bol) (1+ (point-at-eol)))))
57             (overlay-put ov 'face `(:background ,(car colors) :foreground "black"))
58             (setq colors (cdr colors))
59             (overlay-put ov 'line-height line-height)
60             (overlay-put ov 'line-spacing (1- line-height))))))))
62 (add-hook 'org-agenda-finalize-hook #'org-agenda-log-mode-colorize-block)
63 #+end_src
65 *** Picking up a random task in the global TODO list
67 Tony day [[http://mid.gmane.org/m2zk19l1me.fsf@gmail.com][shared]] [[https://gist.github.com/4343164][this gist]] to pick up a
68 random task.
70 ** Building and Managing Org
71 *** Generating autoloads and Compiling Org without make
72     :PROPERTIES:
73     :CUSTOM_ID: compiling-org-without-make
74     :END:
76 #+index: Compilation!without make
78   Compilation is optional, but you _must_ update the autoloads file
79   each time you update org, even when you run org uncompiled!
81   Starting with Org 7.9 you'll find functions for creating the
82   autoload files and do byte-compilation in =mk/org-fixup.el=.  When
83   you execute the commands below, your current directory must be where
84   org has been unpacked into, in other words the file =README= should
85   be found in your current directory and the directories =lisp= and
86   =etc= should be subdirectories of it.  The command =emacs= should be
87   found in your =PATH= and start the Emacs version you are using.  To
88   make just the autoloads file do:
89   : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
90   To make the autoloads file and byte-compile org:
91   : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
92   To make the autoloads file and byte-compile all of org again:
93   : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
94   If you are not using Git, you'll have to make fake version strings
95   first if =org-version.el= is not already available (if it is, you
96   could also edit the version strings there).
97   : emacs -batch -Q -L lisp -l ../mk/org-fixup \
98   : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
99   : (org-make-autoloads))'
100   The above assumes a
101   POSIX shell for its quoting.  Windows =CMD.exe= has quite different
102   quoting rules and this won't work, so your other option is to start
103   Emacs like this
104   : emacs -Q -L lisp -l ../mk/org-fixup
105   then paste the following into the =*scratch*= buffer
106 #+BEGIN_SRC emacs-lisp
107   (let ((org-fake-release     "7.9.1")
108         (org-fake-git-version "7.9.1-fake"))
109     (org-make-autoloads))
110 #+END_SRC
111   position the cursor after the closing paren and press =C-j= or =C-x
112   C-e= to evaluate the form.  Of course you can replace
113   =org-make-autoloads= with =org-make-autoloads-compile= or even
114   =org-make-autoloads-compile-force= if you wish with both variants.
116   For *older org versions only* (that do not yet have
117   =mk/org-fixup.el=), you can use the definitions below.  To use
118   this function, adjust the variables =my/org-lisp-directory= and
119   =my/org-compile-sources= to suit your needs.  If you have
120   byte-compiled org, but want to run org uncompiled again, just remove
121   all =*.elc= files in the =lisp/= directory, set
122   =my/org-compile-sources= to =nil=.
124 #+BEGIN_SRC emacs-lisp
125   (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
126     "Directory where your org-mode files live.")
128   (defvar my/org-compile-sources t
129     "If `nil', never compile org-sources. `my/compile-org' will only create
130   the autoloads file `org-loaddefs.el' then. If `t', compile the sources, too.")
132   ;; Customize: (must end with a slash!)
133   (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")
135   ;; Customize:
136   (setq  my/org-compile-sources t)
138   (defun my/compile-org(&optional directory)
139     "Generate autoloads file org-loaddefs.el.  Optionally compile
140      all *.el files that come with org-mode."
141     (interactive)
142     (defun my/compile-org()
143       "Generate autoloads file org-loaddefs.el.  Optionally compile
144        all *.el files that come with org-mode."
145       (interactive)
146       (let ((dirlisp (file-name-directory my/org-lisp-directory)))
147         (add-to-list 'load-path dirlisp)
148         (require 'autoload)
149         (let ((generated-autoload-file (concat dirlisp "org-loaddefs.el")))
150           ;; create the org-loaddefs file
151           (update-directory-autoloads dirlisp)
152           (when my/org-compile-sources
153             ;; optionally byte-compile
154             (byte-recompile-directory dirlisp 0 'force)))))
155   #+END_SRC
156 *** Reload Org
158 #+index: Initialization!Reload
160 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
161 function to reload org files.
163 Normally you want to use the compiled files since they are faster.
164 If you update your org files you can easily reload them with
166 : M-x org-reload
168 If you run into a bug and want to generate a useful backtrace you can
169 reload the source files instead of the compiled files with
171 : C-u M-x org-reload
173 and turn on the "Enter Debugger On Error" option.  Redo the action
174 that generates the error and cut and paste the resulting backtrace.
175 To switch back to the compiled version just reload again with
177 : M-x org-reload
179 *** Check for possibly problematic old link escapes
180 :PROPERTIES:
181 :CUSTOM_ID: check-old-link-escapes
182 :END:
183 #+index: Link!Escape
184 Starting with version 7.5 Org uses [[https://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
185 and with a modified algorithm to determine which characters to escape
186 and how.
188 As a side effect this modified behaviour might break existing links if
189 they contain a sequence of characters that look like a percent escape
190 (e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.
192 The function below can be used to perform a preliminary check for such
193 links in an Org mode file.  It will run through all links in the file
194 and issue a warning if it finds a percent escape sequence which is not
195 in old Org's list of known percent escapes.
197 #+begin_src emacs-lisp
198   (defun dmaus/org-check-percent-escapes ()
199     "*Check buffer for possibly problematic old link escapes."
200     (interactive)
201     (when (eq major-mode 'org-mode)
202       (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
203                            "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
204         (unless (boundp 'warning-suppress-types)
205           (setq warning-suppress-types nil))
206         (widen)
207         (show-all)
208         (goto-char (point-min))
209         (while (re-search-forward org-any-link-re nil t)
210           (let ((end (match-end 0)))
211             (goto-char (match-beginning 0))
212             (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
213               (let ((escape (match-string-no-properties 0)))
214                 (unless (member (upcase escape) old-escapes)
215                   (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
216                         escape
217                         (buffer-name)
218                         (- (point) 3)))))
219             (goto-char end))))))
220 #+end_src
222 ** Structure Movement and Editing
223 *** Go back to the previous top-level heading
225 #+BEGIN_SRC emacs-lisp
226 (defun org-back-to-top-level-heading ()
227   "Go back to the current top level heading."
228   (interactive)
229   (or (re-search-backward "^\* " nil t)
230       (goto-char (point-min))))
231 #+END_SRC
233 *** Go to a child of the current heading
234     :PROPERTIES:
235     :CUSTOM_ID: org-jump-to-child
236     :END:
237 #+index: Navigation!Heading
238 - [[http://langec.wordpress.com][Christoph Lange]]
240 =org-jump-to-child= in [[file:code/elisp/org-jump.el::(defun%20org-jump-to-child][org-jump.el]] (keybinding suggested there: =C-c o c=) interactively prompts for the title of a child node, i.e. sub-heading, of the current heading and jumps to the child node having that title (in case of ambiguity: the /last/ such node).
242 In the absence of a readily accessible structural representation of the tree outline, this is ipmlemented by walking over all child nodes and collecting their titles and their positions in the file.
244 *** Go to a heading by its ID (=CUSTOM_ID= property)
245     :PROPERTIES:
246     :CUSTOM_ID: org-jump-to-id
247     :END:
248 #+index: Navigation!Heading
249 - [[http://langec.wordpress.com][Christoph Lange]]
251 =org-jump-to-id= in [[file:code/elisp/org-jump.el::(defun%20org-jump-to-id][org-jump.el]] (keybinding suggested there: =C-c o j=) interactively prompts for the one of the =CUSTOM_ID= property values in the current document and jumps to the [first] node that has this ID.
253 This implementation works efficiently in a 5 MB org file with 100 IDs. Together with ido or helm I find it a very user-friendly way of jumping to frequently used headings.
255 I noticed that =org-babel-ref-goto-headline-id= does something similar, so maybe some code could be shared among the two functions.
256 *** Show next/prev heading tidily
258 #+index: Navigation!Heading
259 - Dan Davison
260   These close the current heading and open the next/previous heading.
262 #+begin_src emacs-lisp
263 (defun ded/org-show-next-heading-tidily ()
264   "Show next entry, keeping other entries closed."
265   (if (save-excursion (end-of-line) (outline-invisible-p))
266       (progn (org-show-entry) (show-children))
267     (outline-next-heading)
268     (unless (and (bolp) (org-on-heading-p))
269       (org-up-heading-safe)
270       (hide-subtree)
271       (error "Boundary reached"))
272     (org-overview)
273     (org-reveal t)
274     (org-show-entry)
275     (show-children)))
277 (defun ded/org-show-previous-heading-tidily ()
278   "Show previous entry, keeping other entries closed."
279   (let ((pos (point)))
280     (outline-previous-heading)
281     (unless (and (< (point) pos) (bolp) (org-on-heading-p))
282       (goto-char pos)
283       (hide-subtree)
284       (error "Boundary reached"))
285     (org-overview)
286     (org-reveal t)
287     (org-show-entry)
288     (show-children)))
290 (setq org-use-speed-commands t)
291 (add-to-list 'org-speed-commands-user
292              '("n" ded/org-show-next-heading-tidily))
293 (add-to-list 'org-speed-commands-user
294              '("p" ded/org-show-previous-heading-tidily))
295 #+end_src
297 *** Promote all items in subtree
298 #+index: Structure Editing!Promote
299 - Matt Lundin
301 This function will promote all items in a subtree. Since I use
302 subtrees primarily to organize projects, the function is somewhat
303 unimaginatively called my-org-un-project:
305 #+begin_src emacs-lisp
306 (defun my-org-un-project ()
307   (interactive)
308   (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
309   (org-cycle t))
310 #+end_src
312 *** Turn a heading into an Org link
313     :PROPERTIES:
314     :CUSTOM_ID: heading-to-link
315     :END:
316 #+index: Structure Editing!Heading
317 #+index: Link!Turn a heading into a
318 From David Maus:
320 #+begin_src emacs-lisp
321   (defun dmj:turn-headline-into-org-mode-link ()
322     "Replace word at point by an Org mode link."
323     (interactive)
324     (when (org-at-heading-p)
325       (let ((hl-text (nth 4 (org-heading-components))))
326         (unless (or (null hl-text)
327                     (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
328           (beginning-of-line)
329           (search-forward hl-text (point-at-eol))
330           (replace-string
331            hl-text
332            (format "[[file:%s.org][%s]]"
333                    (org-link-escape hl-text)
334                    (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
335            nil (- (point) (length hl-text)) (point))))))
336 #+end_src
338 *** Using M-up and M-down to transpose paragraphs
339 #+index: Structure Editing!paragraphs
341 From Paul Sexton: By default, if used within ordinary paragraphs in
342 org mode, =M-up= and =M-down= transpose *lines* (not sentences).  The
343 following code makes these keys transpose paragraphs, keeping the
344 point at the start of the moved paragraph. Behavior in tables and
345 headings is unaffected. It would be easy to modify this to transpose
346 sentences.
348 #+begin_src emacs-lisp
349 (defun org-transpose-paragraphs (arg)
350  (interactive)
351  (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
352             (thing-at-point 'sentence))
353    (transpose-paragraphs arg)
354    (backward-paragraph)
355    (re-search-forward "[[:graph:]]")
356    (goto-char (match-beginning 0))
357    t))
359 (add-to-list 'org-metaup-hook
360  (lambda () (interactive) (org-transpose-paragraphs -1)))
361 (add-to-list 'org-metadown-hook
362  (lambda () (interactive) (org-transpose-paragraphs 1)))
363 #+end_src
364 *** Changelog support for org headers
365 #+index: Structure Editing!Heading
366 -- James TD Smith
368 Put the following in your =.emacs=, and =C-x 4 a= and other functions which
369 use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
370 headline as the "current function" if you add a changelog entry from an org
371 buffer.
373 #+BEGIN_SRC emacs-lisp
374   (defun org-log-current-defun ()
375     (save-excursion
376       (org-back-to-heading)
377       (if (looking-at org-complex-heading-regexp)
378           (match-string 4))))
380   (add-hook 'org-mode-hook
381             (lambda ()
382               (make-variable-buffer-local 'add-log-current-defun-function)
383               (setq add-log-current-defun-function 'org-log-current-defun)))
384 #+END_SRC
386 *** Different org-cycle-level behavior
387 #+index: Cycling!behavior
388 -- Ryan Thompson
390 In recent org versions, when your point (cursor) is at the end of an
391 empty header line (like after you first created the header), the TAB
392 key (=org-cycle=) has a special behavior: it cycles the headline through
393 all possible levels. However, I did not like the way it determined
394 "all possible levels," so I rewrote the whole function, along with a
395 couple of supporting functions.
397 The original function's definition of "all possible levels" was "every
398 level from 1 to one more than the initial level of the current
399 headline before you started cycling." My new definition is "every
400 level from 1 to one more than the previous headline's level." So, if
401 you have a headline at level 4 and you use ALT+RET to make a new
402 headline below it, it will cycle between levels 1 and 5, inclusive.
404 The main advantage of my custom =org-cycle-level= function is that it
405 is stateless: the next level in the cycle is determined entirely by
406 the contents of the buffer, and not what command you executed last.
407 This makes it more predictable, I hope.
409 #+BEGIN_SRC emacs-lisp
410 (require 'cl)
412 (defun org-point-at-end-of-empty-headline ()
413   "If point is at the end of an empty headline, return t, else nil."
414   (and (looking-at "[ \t]*$")
415        (save-excursion
416          (beginning-of-line 1)
417          (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
419 (defun org-level-increment ()
420   "Return the number of stars that will be added or removed at a
421 time to headlines when structure editing, based on the value of
422 `org-odd-levels-only'."
423   (if org-odd-levels-only 2 1))
425 (defvar org-previous-line-level-cached nil)
427 (defun org-recalculate-previous-line-level ()
428   "Same as `org-get-previous-line-level', but does not use cached
429 value. It does *set* the cached value, though."
430   (set 'org-previous-line-level-cached
431        (let ((current-level (org-current-level))
432              (prev-level (when (> (line-number-at-pos) 1)
433                            (save-excursion
434                              (previous-line)
435                              (org-current-level)))))
436          (cond ((null current-level) nil) ; Before first headline
437                ((null prev-level) 0)      ; At first headline
438                (prev-level)))))
440 (defun org-get-previous-line-level ()
441   "Return the outline depth of the last headline before the
442 current line. Returns 0 for the first headline in the buffer, and
443 nil if before the first headline."
444   ;; This calculation is quite expensive, with all the regex searching
445   ;; and stuff. Since org-cycle-level won't change lines, we can reuse
446   ;; the last value of this command.
447   (or (and (eq last-command 'org-cycle-level)
448            org-previous-line-level-cached)
449       (org-recalculate-previous-line-level)))
451 (defun org-cycle-level ()
452   (interactive)
453   (let ((org-adapt-indentation nil))
454     (when (org-point-at-end-of-empty-headline)
455       (setq this-command 'org-cycle-level) ;Only needed for caching
456       (let ((cur-level (org-current-level))
457             (prev-level (org-get-previous-line-level)))
458         (cond
459          ;; If first headline in file, promote to top-level.
460          ((= prev-level 0)
461           (loop repeat (/ (- cur-level 1) (org-level-increment))
462                 do (org-do-promote)))
463          ;; If same level as prev, demote one.
464          ((= prev-level cur-level)
465           (org-do-demote))
466          ;; If parent is top-level, promote to top level if not already.
467          ((= prev-level 1)
468           (loop repeat (/ (- cur-level 1) (org-level-increment))
469                 do (org-do-promote)))
470          ;; If top-level, return to prev-level.
471          ((= cur-level 1)
472           (loop repeat (/ (- prev-level 1) (org-level-increment))
473                 do (org-do-demote)))
474          ;; If less than prev-level, promote one.
475          ((< cur-level prev-level)
476           (org-do-promote))
477          ;; If deeper than prev-level, promote until higher than
478          ;; prev-level.
479          ((> cur-level prev-level)
480           (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
481                 do (org-do-promote))))
482         t))))
483 #+END_SRC
485 *** Count words in an Org buffer
486 # FIXME: Does not fit too well under Structure. Any idea where to put it?
487 Paul Sexton [[https://orgmode.org/list/loom.20110220T224023-532@post.gmane.org][posted]] this function to count words in an Org buffer:
489 #+begin_src emacs-lisp
490 (defun org-word-count (beg end
491                            &optional count-latex-macro-args?
492                            count-footnotes?)
493   "Report the number of words in the Org mode buffer or selected region.
494 Ignores:
495 - comments
496 - tables
497 - source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
498 - hyperlinks (but does count words in hyperlink descriptions)
499 - tags, priorities, and TODO keywords in headers
500 - sections tagged as 'not for export'.
502 The text of footnote definitions is ignored, unless the optional argument
503 COUNT-FOOTNOTES? is non-nil.
505 If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
506 includes LaTeX macro arguments (the material between {curly braces}).
507 Otherwise, and by default, every LaTeX macro counts as 1 word regardless
508 of its arguments."
509   (interactive "r")
510   (unless mark-active
511     (setf beg (point-min)
512           end (point-max)))
513   (let ((wc 0)
514         (latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
515     (save-excursion
516       (goto-char beg)
517       (while (< (point) end)
518         (cond
519          ;; Ignore comments.
520          ((or (org-in-commented-line) (org-at-table-p))
521           nil)
522          ;; Ignore hyperlinks. But if link has a description, count
523          ;; the words within the description.
524          ((looking-at org-bracket-link-analytic-regexp)
525           (when (match-string-no-properties 5)
526             (let ((desc (match-string-no-properties 5)))
527               (save-match-data
528                 (incf wc (length (remove "" (org-split-string
529                                              desc "\\W")))))))
530           (goto-char (match-end 0)))
531          ((looking-at org-any-link-re)
532           (goto-char (match-end 0)))
533          ;; Ignore source code blocks.
534          ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
535           nil)
536          ;; Ignore inline source blocks, counting them as 1 word.
537          ((save-excursion
538             (backward-char)
539             (looking-at org-babel-inline-src-block-regexp))
540           (goto-char (match-end 0))
541           (setf wc (+ 2 wc)))
542          ;; Count latex macros as 1 word, ignoring their arguments.
543          ((save-excursion
544             (backward-char)
545             (looking-at latex-macro-regexp))
546           (goto-char (if count-latex-macro-args?
547                          (match-beginning 2)
548                        (match-end 0)))
549           (setf wc (+ 2 wc)))
550          ;; Ignore footnotes.
551          ((and (not count-footnotes?)
552                (or (org-footnote-at-definition-p)
553                    (org-footnote-at-reference-p)))
554           nil)
555          (t
556           (let ((contexts (org-context)))
557             (cond
558              ;; Ignore tags and TODO keywords, etc.
559              ((or (assoc :todo-keyword contexts)
560                   (assoc :priority contexts)
561                   (assoc :keyword contexts)
562                   (assoc :checkbox contexts))
563               nil)
564              ;; Ignore sections marked with tags that are
565              ;; excluded from export.
566              ((assoc :tags contexts)
567               (if (intersection (org-get-tags-at) org-export-exclude-tags
568                                 :test 'equal)
569                   (org-forward-same-level 1)
570                 nil))
571              (t
572               (incf wc))))))
573         (re-search-forward "\\w+\\W*")))
574     (message (format "%d words in %s." wc
575                      (if mark-active "region" "buffer")))))
576 #+end_src
578 *** Check for misplaced SCHEDULED and DEADLINE cookies
579   :PROPERTIES:
580   :CUSTOM_ID: check-for-misplaced-timestamps
581   :END:
583 The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
584 below* the headline -- like this:
586 #+begin_src org
587 ,* A headline
588   SCHEDULED: <2012-04-09 lun.>
589 #+end_src
591 This is what =org-scheduled= and =org-deadline= (and other similar
592 commands) do.  And the manual explicitely tell people to stick to this
593 format (see the section "8.3.1 Inserting deadlines or schedules").
595 If you think you might have subtrees with misplaced =SCHEDULED= and
596 =DEADLINE= cookies, this command lets you check the current buffer:
598 #+begin_src emacs-lisp
599 (defun org-check-misformatted-subtree ()
600   "Check misformatted entries in the current buffer."
601   (interactive)
602   (show-all)
603   (org-map-entries
604    (lambda ()
605      (when (and (move-beginning-of-line 2)
606                 (not (looking-at org-heading-regexp)))
607        (if (or (and (org-get-scheduled-time (point))
608                     (not (looking-at (concat "^.*" org-scheduled-regexp))))
609                (and (org-get-deadline-time (point))
610                     (not (looking-at (concat "^.*" org-deadline-regexp)))))
611            (when (y-or-n-p "Fix this subtree? ")
612              (message "Call the function again when you're done fixing this subtree.")
613              (recursive-edit))
614          (message "All subtrees checked."))))))
615 #+end_src
617 *** Sorting list by checkbox type
619 #+index: checkbox!sorting
621 You can use a custom function to sort list by checkbox type.
622 Here is a function suggested by Carsten:
624 #+BEGIN_SRC emacs-lisp
625 (defun org-sort-list-by-checkbox-type ()
626   "Sort list items according to Checkbox state."
627   (interactive)
628   (org-sort-list
629    nil ?f
630    (lambda ()
631      (if (looking-at org-list-full-item-re)
632          (cdr (assoc (match-string 3)
633                      '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
634        4))))
635 #+END_SRC
637 Use the function above directly on the list.  If you want to use an
638 equivalent function after =C-c ^ f=, use this one instead:
640 #+BEGIN_SRC emacs-lisp
641   (defun org-sort-list-by-checkbox-type-1 ()
642     (lambda ()
643       (if (looking-at org-list-full-item-re)
644           (cdr (assoc (match-string 3)
645                       '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
646         4)))
647 #+END_SRC
649 *** Adding Licenses to org files
651 You can add pretty standard licenses, such as creative commons or gfdl
652 to org articles using =org-license.el=.
654 ** Org Table
655    :PROPERTIES:
656    :CUSTOM_ID: Tables
657    :END:
659 *** Align all tables in a file
660   :PROPERTIES:
661   :CUSTOM_ID: align-tables-in-file
662   :END:
664 Andrew Young provided this function in [[https://orgmode.org/list/502F4EDF.3080800@wilkesley.net][this thread]]:
666 #+begin_src emacs-lisp
667   (defun my-align-all-tables ()
668     (interactive)
669     (org-table-map-tables 'org-table-align 'quietly))
670 #+end_src
672 *** Transpose table
673     :PROPERTIES:
674     :CUSTOM_ID: transpose-table
675     :END:
676 #+index: Table!Calculation
678 Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
679 see.)  There are also other solutions:
681 - with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
682   list, see [[https://orgmode.org/list/4BBCE264.3000407@alumni.ethz.ch][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00239.html][gnu]]
684 - with org-babel and R: provided by Dan Davison in the mailing list (old
685   =#+TBLR:= syntax), see [[https://orgmode.org/list/20081230193550.GA7961@stats.ox.ac.uk][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2008-12/msg00454.html][gnu]]
687 - with field coordinates in formulas (=@#= and =$#=): see [[#field-coordinates-in-formulas-transpose-table][Worg]].
689 *** Manipulate hours/minutes/seconds in table formulas
690 #+index: Table!hours-minutes-seconds
691 Both Bastien and Martin Halder have posted code ([[https://orgmode.org/list/00BD91C6-C610-4CDD-B3E0-E9FECDAA372C@gmail.com][Bastien's code]] and
692 [[https://orgmode.org/list/00BD91C6-C610-4CDD-B3E0-E9FECDAA372C@gmail.com][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
693 "=d=" is any digit) as time values in Org-mode table formula.  These
694 functions have now been wrapped up into a =with-time= macro which can
695 be used in table formula to translate table cell values to and from
696 numerical values for algebraic manipulation.
698 Here is the code implementing this macro.
699 #+begin_src emacs-lisp :results silent
700   (defun org-time-string-to-seconds (s)
701     "Convert a string HH:MM:SS to a number of seconds."
702     (cond
703      ((and (stringp s)
704            (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
705       (let ((hour (string-to-number (match-string 1 s)))
706             (min (string-to-number (match-string 2 s)))
707             (sec (string-to-number (match-string 3 s))))
708         (+ (* hour 3600) (* min 60) sec)))
709      ((and (stringp s)
710            (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
711       (let ((min (string-to-number (match-string 1 s)))
712             (sec (string-to-number (match-string 2 s))))
713         (+ (* min 60) sec)))
714      ((stringp s) (string-to-number s))
715      (t s)))
717   (defun org-time-seconds-to-string (secs)
718     "Convert a number of seconds to a time string."
719     (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
720           ((>= secs 60) (format-seconds "%m:%.2s" secs))
721           (t (format-seconds "%s" secs))))
723   (defmacro with-time (time-output-p &rest exprs)
724     "Evaluate an org-table formula, converting all fields that look
725   like time data to integer seconds.  If TIME-OUTPUT-P then return
726   the result as a time value."
727     (list
728      (if time-output-p 'org-time-seconds-to-string 'identity)
729      (cons 'progn
730            (mapcar
731             (lambda (expr)
732               `,(cons (car expr)
733                       (mapcar
734                        (lambda (el)
735                          (if (listp el)
736                              (list 'with-time nil el)
737                            (org-time-string-to-seconds el)))
738                        (cdr expr))))
739             `,@exprs))))
740 #+end_src
742 Which allows the following forms of table manipulation such as adding
743 and subtracting time values.
744 : | Date             | Start | Lunch |  Back |   End |  Sum |
745 : |------------------+-------+-------+-------+-------+------|
746 : | [2011-03-01 Tue] |  8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
747 : #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))
749 and dividing time values by integers
750 : |  time | miles | minutes/mile |
751 : |-------+-------+--------------|
752 : | 34:43 |   2.9 |        11:58 |
753 : | 32:15 |  2.77 |        11:38 |
754 : | 33:56 |   3.0 |        11:18 |
755 : | 52:22 |  4.62 |        11:20 |
756 : #+TBLFM: $3='(with-time t (/ $1 $2))
758 *Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
759 Elisp formulas) to compute time durations.  For example:
761 : | Task 1 | Task 2 |   Total |
762 : |--------+--------+---------|
763 : |  35:00 |  35:00 | 1:10:00 |
764 : #+TBLFM: @2$3=$1+$2;T
766 *** Dates computation
767 #+index: Table!dates
768 Xin Shi [[https://orgmode.org/list/5236d6f90907211206y20951c9dtc711cf71afc520e2@mail.gmail.com][asked]] for a way to calculate the duration of
769 dates stored in an org table.
771 Nick Dokos [[https://orgmode.org/list/10926.1248205548@alphaville.usa.hp.com][suggested]]:
773 Try the following:
775 : | Start Date |   End Date | Duration |
776 : |------------+------------+----------|
777 : | 2004.08.07 | 2005.07.08 |      335 |
778 : #+TBLFM: $3=(date(<$2>)-date(<$1>))
780 See [[https://orgmode.org/list/17380.1218757692@alphaville.usa.hp.com][this thread]] as well as [[https://orgmode.org/list/48A5BADA.4070507@cs.tu-berlin.de][this post]] (which is really a followup on the
781 above).  The problem that this last article pointed out was solved in [[https://orgmode.org/list/18981.1220565299@alphaville.usa.hp.com][this
782 post]] and Chris Randle's original musings are [[https://orgmode.org/list/00be01c8a9f4$a310ca00$6580a8c0@CUBE][here]].
784 *** Hex computation
785 #+index: Table!Calculation
786 As with Times computation, the following code allows Computation with
787 Hex values in Org-mode tables using the =with-hex= macro.
789 Here is the code implementing this macro.
790 #+begin_src emacs-lisp
791   (defun org-hex-strip-lead (str)
792     (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
793         (substring str 2) str))
795   (defun org-hex-to-hex (int)
796     (format "0x%x" int))
798   (defun org-hex-to-dec (str)
799     (cond
800      ((and (stringp str)
801            (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
802       (let ((out 0))
803         (mapc
804          (lambda (ch)
805            (setf out (+ (* out 16)
806                         (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
807          (coerce (match-string 1 str) 'list))
808         out))
809      ((stringp str) (string-to-number str))
810      (t str)))
812   (defmacro with-hex (hex-output-p &rest exprs)
813     "Evaluate an org-table formula, converting all fields that look
814       like hexadecimal to decimal integers.  If HEX-OUTPUT-P then
815       return the result as a hex value."
816     (list
817      (if hex-output-p 'org-hex-to-hex 'identity)
818      (cons 'progn
819            (mapcar
820             (lambda (expr)
821               `,(cons (car expr)
822                       (mapcar (lambda (el)
823                                 (if (listp el)
824                                     (list 'with-hex nil el)
825                                   (org-hex-to-dec el)))
826                               (cdr expr))))
827             `,@exprs))))
828 #+end_src
830 Which allows the following forms of table manipulation such as adding
831 and subtracting hex values.
832 | 0x10 | 0x0 | #ERROR | #ERROR |
833 | 0x20 | 0x1 | #ERROR | #ERROR |
834 | 0x30 | 0x2 | #ERROR | #ERROR |
835 | 0xf0 | 0xf | #ERROR | #ERROR |
836 #+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))
838 *** Field coordinates in formulas (=@#= and =$#=)
839     :PROPERTIES:
840     :CUSTOM_ID: field-coordinates-in-formulas
841     :END:
842 #+index: Table!Field Coordinates
843 -- Michael Brand
845 Following are some use cases that can be implemented with the “field
846 coordinates in formulas” described in the corresponding chapter in the
847 [[https://orgmode.org/manual/References.html#References][Org manual]].
849 **** Copy a column from a remote table into a column
850      :PROPERTIES:
851      :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
852      :END:
854 current column =$3= = remote column =$2=:
855 : #+TBLFM: $3 = remote(FOO, @@#$2)
857 **** Copy a row from a remote table transposed into a column
858      :PROPERTIES:
859      :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
860      :END:
862 current column =$1= = transposed remote row =@1=:
863 : #+TBLFM: $1 = remote(FOO, @$#$@#)
865 **** Transpose table
866      :PROPERTIES:
867      :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
868      :END:
870 -- Michael Brand
872 This is more like a demonstration of using “field coordinates in formulas”
873 and is bound to be slow for large tables. See the discussion in the mailing
874 list on
875 [[https://orgmode.org/list/82e274891002251643k327135aajea270914244abff7@mail.gmail.com][gmane]] or
876 [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
877 For more efficient solutions see
878 [[#transpose-table][Worg]].
880 To transpose this 4x7 table
882 : #+TBLNAME: FOO
883 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
884 : |------+------+------+------+------+------+------|
885 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
886 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
887 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
889 start with a 7x4 table without any horizontal line (to have filled
890 also the column header) and yet empty:
892 : |   |   |   |   |
893 : |   |   |   |   |
894 : |   |   |   |   |
895 : |   |   |   |   |
896 : |   |   |   |   |
897 : |   |   |   |   |
898 : |   |   |   |   |
900 Then add the =TBLFM= line below.  After recalculation this will end up with
901 the transposed copy:
903 : | year | min | avg | max |
904 : | 2004 | 401 | 402 | 403 |
905 : | 2005 | 501 | 502 | 503 |
906 : | 2006 | 601 | 602 | 603 |
907 : | 2007 | 701 | 702 | 703 |
908 : | 2008 | 801 | 802 | 803 |
909 : | 2009 | 901 | 902 | 903 |
910 : #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)
912 The formula simply exchanges row and column numbers by taking
913 - the absolute remote row number =@$#= from the current column number =$#=
914 - the absolute remote column number =$@#= from the current row number =@#=
916 Formulas to be taken over from the remote table will have to be transformed
917 manually.
919 **** Dynamic variation of ranges
921 -- Michael Brand
923 In this example all columns next to =quote= are calculated from the column
924 =quote= and show the average change of the time series =quote[year]=
925 during the period of the preceding =1=, =2=, =3= or =4= years:
927 : | year | quote |   1 a |   2 a |   3 a |   4 a |
928 : |------+-------+-------+-------+-------+-------|
929 : | 2005 |    10 |       |       |       |       |
930 : | 2006 |    12 | 0.200 |       |       |       |
931 : | 2007 |    14 | 0.167 | 0.183 |       |       |
932 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
933 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
934 : #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3
936 The important part of the formula without the field blanking is:
938 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
940 which is the Emacs Calc implementation of the equation
942 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/
944 where /i/ is the current time and /a/ is the length of the preceding period.
946 *** Rearrange one or more field within the same row or column
947     :PROPERTIES:
948     :CUSTOM_ID: field-same-row-or-column
949     :END:
950 #+index: Table!Editing
952 -- Michael Brand
954 **** Rearrange the column sequence in one row only
955      :PROPERTIES:
956      :CUSTOM_ID: column-sequence-in-row
957      :END:
958 #+index: Table!Editing
960 The functions below can be used to change the column sequence in one
961 row only, without affecting the other rows above and below like with
962 =M-<left>= or =M-<right>= (=org-table-move-column=).  See also the
963 docstring of the functions for more explanations.  The original table
964 that serves as the starting point for the examples:
966 : | a | b | c  | d  |
967 : | e | 9 | 10 | 11 |
968 : | f | g | h  | i  |
970 ***** Move current field in row
971 ****** Left
973 1) place point at "10" in original table
974 2) =M-x f-org-table-move-field-in-row-left=
975 3) point is at moved "10"
977 : | a | b  | c | d  |
978 : | e | 10 | 9 | 11 |
979 : | f | g  | h | i  |
981 ****** Right
983 1) place point at "9" in original table
984 2) =M-x f-org-table-move-field-in-row-right=
985 3) point is at moved "9"
987 : | a | b  | c | d  |
988 : | e | 10 | 9 | 11 |
989 : | f | g  | h | i  |
991 ***** Rotate rest of row (range from current field to end of row)
992 ****** Left
994 1) place point at @2$2 in original table
995 2) =M-x f-org-table-rotate-rest-of-row-left=
996 3) point is still at @2$2
998 : | a | b  | c  | d |
999 : | e | 10 | 11 | 9 |
1000 : | f | g  | h  | i |
1002 ****** Right
1004 1) place point at @2$2 in original table
1005 2) =M-x f-org-table-rotate-rest-of-row-right=
1006 3) point is still at @2$2
1008 : | a | b  | c | d  |
1009 : | e | 11 | 9 | 10 |
1010 : | f | g  | h | i  |
1012 ***** Open field in row (table size grows)
1014 This is just for completeness, interactively the same as typing =|
1015 S-TAB=.
1017 1) place point at @2$2 in original table
1018 2) =M-x f-org-table-open-field-in-row-grow=
1019 3) point is still at @2$2
1021 : | a | b | c | d  |    |
1022 : | e |   | 9 | 10 | 11 |
1023 : | f | g | h | i  |    |
1025 **** Rearrange the row sequence in one column only
1026      :PROPERTIES:
1027      :CUSTOM_ID: row-sequence-in-column
1028      :END:
1029 #+index: Table!Editing
1031 The functions below can be used to change the column sequence in one
1032 column only, without affecting the other columns left and right like
1033 with =M-<up>= or =M-<down>= (=org-table-move-row=).  See also the
1034 docstring of the functions for more explanations.  The original table
1035 that serves as the starting point for the examples:
1037 : | a |  b | c |
1038 : |---+----+---|
1039 : | d |  9 | e |
1040 : | f | 10 | g |
1041 : |---+----+---|
1042 : | h | 11 | i |
1044 ***** Move current field in column
1045 ****** Up
1047 1) place point at "10" in original table
1048 2) =M-x f-org-table-move-field-in-column-up=
1049 3) point is at moved "10"
1051 : | a |  b | c |
1052 : |---+----+---|
1053 : | d | 10 | e |
1054 : | f |  9 | g |
1055 : |---+----+---|
1056 : | h | 11 | i |
1058 ****** Down
1060 1) place point at "9" in original table
1061 2) =M-x f-org-table-move-field-in-column-down=
1062 3) point is at moved "9"
1064 : | a |  b | c |
1065 : |---+----+---|
1066 : | d | 10 | e |
1067 : | f |  9 | g |
1068 : |---+----+---|
1069 : | h | 11 | i |
1071 ***** Rotate rest of column (range from current field to end of column)
1072 ****** Up
1074 1) place point at @2$2 in original table
1075 2) =M-x f-org-table-rotate-rest-of-column-up=
1076 3) point is still at @2$2
1078 : | a |  b | c |
1079 : |---+----+---|
1080 : | d | 10 | e |
1081 : | f | 11 | g |
1082 : |---+----+---|
1083 : | h |  9 | i |
1085 ****** Down
1087 1) place point at @2$2 in original table
1088 2) =M-x f-org-table-rotate-rest-of-column-down=
1089 3) point is still at @2$2
1091 : | a |  b | c |
1092 : |---+----+---|
1093 : | d | 11 | e |
1094 : | f |  9 | g |
1095 : |---+----+---|
1096 : | h | 10 | i |
1098 ***** Open field in column (table size grows)
1100 1) place point at @2$2 in original table
1101 2) =M-x f-org-table-open-field-in-column-grow=
1102 3) point is still at @2$2
1104 : | a |  b | c |
1105 : |---+----+---|
1106 : | d |    | e |
1107 : | f |  9 | g |
1108 : |---+----+---|
1109 : | h | 10 | i |
1110 : |   | 11 |   |
1112 **** Key bindings for some of the functions
1114 I have this in an Org buffer to change temporarily to the desired
1115 behavior with =C-c C-c= on one of the three code snippets:
1117 : - move in row:
1118 :   #+begin_src emacs-lisp :results silent
1119 :     (org-defkey org-mode-map [(meta left)]
1120 :                 'f-org-table-move-field-in-row-left)
1121 :     (org-defkey org-mode-map [(meta right)]
1122 :                 'f-org-table-move-field-in-row-right)
1123 :     (org-defkey org-mode-map [(left)]  'org-table-previous-field)
1124 :     (org-defkey org-mode-map [(right)] 'org-table-next-field)
1125 :   #+end_src
1127 : - rotate in row:
1128 :   #+begin_src emacs-lisp :results silent
1129 :     (org-defkey org-mode-map [(meta left)]
1130 :                 'f-org-table-rotate-rest-of-row-left)
1131 :     (org-defkey org-mode-map [(meta right)]
1132 :                 'f-org-table-rotate-rest-of-row-right)
1133 :     (org-defkey org-mode-map [(left)]  'org-table-previous-field)
1134 :     (org-defkey org-mode-map [(right)] 'org-table-next-field)
1135 :   #+end_src
1137 : - back to original:
1138 :   #+begin_src emacs-lisp :results silent
1139 :     (org-defkey org-mode-map [(meta left)]  'org-metaleft)
1140 :     (org-defkey org-mode-map [(meta right)] 'org-metaright)
1141 :     (org-defkey org-mode-map [(left)]  'backward-char)
1142 :     (org-defkey org-mode-map [(right)] 'forward-char)
1143 :   #+end_src
1145 **** Implementation
1147 The functions
1149 : f-org-table-move-field-in-column-up
1150 : f-org-table-move-field-in-column-down
1151 : f-org-table-rotate-rest-of-column-up
1152 : f-org-table-rotate-rest-of-column-down
1154 are not yet implemented.  They could be done similar to
1155 =f-org-table-open-field-in-column-grow=.  A workaround without keeping
1156 horizontal separator lines is to interactively or programmatically
1157 simply:
1159 1) Transpose the table, see
1160    [[#transpose-table][Org hacks]].
1161 2) Use =f-org-table-*-column-in-row-*=, see
1162    [[https://orgmode.org/worg/org-hacks.html#column-sequence-in-row][previous
1163    section]].
1164 3) Transpose the table.
1166 The other functions:
1168 #+BEGIN_SRC emacs-lisp
1169   (defun f-org-table-move-field-in-row-left ()
1170     "Move current field in row to the left."
1171     (interactive)
1172     (f-org-table-move-field-in-row 'left))
1173   (defun f-org-table-move-field-in-row-right ()
1174     "Move current field in row to the right."
1175     (interactive)
1176     (f-org-table-move-field-in-row nil))
1178   (defun f-org-table-move-field-in-row (&optional left)
1179     "Move current field in row to the right.
1180   With arg LEFT, move to the left.  For repeated invocation the
1181   point follows the moved field.  Does not fix formulas."
1182     ;; Derived from `org-table-move-column'
1183     (interactive "P")
1184     (if (not (org-at-table-p))
1185         (error "Not at a table"))
1186     (org-table-find-dataline)
1187     (org-table-check-inside-data-field)
1188     (let* ((col (org-table-current-column))
1189            (col1 (if left (1- col) col))
1190            ;; Current cursor position
1191            (colpos (if left (1- col) (1+ col))))
1192       (if (and left (= col 1))
1193           (error "Cannot move column further left"))
1194       (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1195           (error "Cannot move column further right"))
1196       (org-table-goto-column col1 t)
1197       (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1198            (replace-match "|\\2|\\1|"))
1199       (org-table-goto-column colpos)
1200       (org-table-align)))
1202   (defun f-org-table-rotate-rest-of-row-left ()
1203     "Rotate rest of row to the left."
1204     (interactive)
1205     (f-org-table-rotate-rest-of-row 'left))
1206   (defun f-org-table-rotate-rest-of-row-right ()
1207     "Rotate rest of row to the right."
1208     (interactive)
1209     (f-org-table-rotate-rest-of-row nil))
1211   (defun f-org-table-rotate-rest-of-row (&optional left)
1212     "Rotate rest of row to the right.
1213   With arg LEFT, rotate to the left.  For both directions the
1214   boundaries of the rotation range are the current field and the
1215   field at the end of the row.  For repeated invocation the point
1216   stays on the original current field.  Does not fix formulas."
1217     ;; Derived from `org-table-move-column'
1218     (interactive "P")
1219     (if (not (org-at-table-p))
1220         (error "Not at a table"))
1221     (org-table-find-dataline)
1222     (org-table-check-inside-data-field)
1223     (let ((col (org-table-current-column)))
1224       (org-table-goto-column col t)
1225       (and (looking-at (if left
1226                            "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
1227                          "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
1228            (replace-match "|\\2|\\1|"))
1229       (org-table-goto-column col)
1230       (org-table-align)))
1232   (defun f-org-table-open-field-in-row-grow ()
1233     "Open field in row, move fields to the right by growing table."
1234     (interactive)
1235     (insert "|")
1236     (backward-char)
1237     (org-table-align))
1239   (defun f-org-table-open-field-in-column-grow ()
1240     "Open field in column, move all fields downwards by growing table."
1241     (interactive)
1242     (let ((col (org-table-current-column))
1243           (p   (point)))
1244       ;; Cut all fields downwards in same column
1245       (goto-char (org-table-end))
1246       (forward-line -1)
1247       (while (org-at-table-hline-p) (forward-line -1))
1248       (org-table-goto-column col)
1249       (org-table-cut-region p (point))
1250       ;; Paste at one field below
1251       (goto-char p)
1252       (forward-line)
1253       (org-table-goto-column col)
1254       (org-table-paste-rectangle)
1255       (goto-char p)
1256       (org-table-align)))
1257 #+END_SRC
1259 **** Reasons why this is not put into the Org core
1261 I consider this as only a hack for several reasons:
1263 - Generalization: The existing function =org-table-move-column= could
1264   be enhanced with additional optional parameters to incorporate these
1265   functionalities and could be used as the only function for better
1266   maintainability.  Now it's only a copy/paste hack of several similar
1267   functions with simple modifications.
1268 - Bindings: Should be convenient for repetition like =M-<right>=.
1269   What should be bound where, what has to be left unbound?
1270 - Does not fix formulas.  Could be resolved for field formulas but
1271   most probably not for column or range formulas and this can lead to
1272   confusion.  AFAIK all table manipulations found in Org core fix
1273   formulas.
1274 - Completeness: Not all variations and combinations are covered yet
1275   - move, rotate with range to end, rotate with range to begin, rotate
1276     all
1277   - left-right, up-down
1279 ** Capture and Remember
1280 *** Customize the size of the frame for remember
1281 #+index: Remember!frame
1282 #+index: Customization!remember
1283 (Note: this hack is likely out of date due to the development of
1284 =org-capture=.)
1286 # FIXME: gmane link?
1287 On emacs-orgmode, Ryan C. Thompson suggested this:
1289 #+begin_quote
1290 I am using org-remember set to open a new frame when used,
1291 and the default frame size is much too large. To fix this, I have
1292 designed some advice and a custom variable to implement custom
1293 parameters for the remember frame:
1294 #+end_quote
1296 #+begin_src emacs-lisp
1297 (defcustom remember-frame-alist nil
1298   "Additional frame parameters for dedicated remember frame."
1299   :type 'alist
1300   :group 'remember)
1302 (defadvice remember (around remember-frame-parameters activate)
1303   "Set some frame parameters for the remember frame."
1304   (let ((default-frame-alist (append remember-frame-alist
1305                                      default-frame-alist)))
1306     ad-do-it))
1307 #+end_src
1309 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
1310 reasonable size for the frame.
1311 *** [[https://github.com/PhilHudson/org-capture-vars.el][User-defined capture template variables with prompt and completion list]]
1312 *** [[https://github.com/alphapapa/unpackaged.el#ensure-blank-lines-between-headings-and-before-contents][Ensure blank lines between headings and before contents]]
1313 ** Handling Links
1314 *** [[#heading-to-link][Turn a heading into an org link]]
1315 *** Quickaccess to the link part of hyperlinks
1316 #+index: Link!Referent
1317 Christian Moe [[https://orgmode.org/list/4E0307D5.8080105@christianmoe.com][asked]], if there is a simpler way to copy the link part
1318 of an org hyperling other than to use `C-c C-l C-a C-k C-g',
1319 which is indeed kind of cumbersome.
1321 The thread offered [[https://orgmode.org/list/871uy9ghdw.fsf@gnu.org][two ways]]:
1323 Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
1324 #+begin_src emacs-lisp
1325 (fset 'getlink
1326       (lambda (&optional arg)
1327         "Keyboard macro."
1328         (interactive "p")
1329         (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
1330 #+end_src
1332 or a function:
1333 #+begin_src emacs-lisp
1334 (defun my-org-extract-link ()
1335   "Extract the link location at point and put it on the killring."
1336   (interactive)
1337   (when (org-in-regexp org-bracket-link-regexp 1)
1338     (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
1339 #+end_src
1341 They put the link destination on the killring and can be easily bound to a key.
1343 *** Insert link with HTML title as default description
1344 When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
1345 from HTML <title> tag and use it as a default link description. Here is a way to
1346 accomplish this:
1348 #+begin_src emacs-lisp
1349 (require 'mm-url) ; to include mm-url-decode-entities-string
1351 (defun my-org-insert-link ()
1352   "Insert org link where default description is set to html title."
1353   (interactive)
1354   (let* ((url (read-string "URL: "))
1355          (title (get-html-title-from-url url)))
1356     (org-insert-link nil url title)))
1358 (defun get-html-title-from-url (url)
1359   "Return content in <title> tag."
1360   (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
1361     (save-excursion
1362       (set-buffer download-buffer)
1363       (beginning-of-buffer)
1364       (setq x1 (search-forward "<title>"))
1365       (search-forward "</title>")
1366       (setq x2 (search-backward "<"))
1367       (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
1368 #+end_src
1370 Then just use `M-x my-org-insert-link' instead of `org-insert-link'.
1372 ** Archiving Content in Org-Mode
1373   :PROPERTIES:
1374   :CUSTOM_ID: archiving
1375   :END:
1377 *** Preserve top level headings when archiving to a file
1378 #+index: Archiving!Preserve top level headings
1379 - Matt Lundin
1381 To preserve (somewhat) the integrity of your archive structure while
1382 archiving lower level items to a file, you can use the following
1383 defadvice:
1385 #+begin_src emacs-lisp
1386 (defadvice org-archive-subtree (around my-org-archive-subtree activate)
1387   (let ((org-archive-location
1388          (if (save-excursion (org-back-to-heading)
1389                              (> (org-outline-level) 1))
1390              (concat (car (split-string org-archive-location "::"))
1391                      "::* "
1392                      (car (org-get-outline-path)))
1393            org-archive-location)))
1394     ad-do-it))
1395 #+end_src
1397 Thus, if you have an outline structure such as...
1399 #+begin_src org
1400 ,* Heading
1401 ,** Subheading
1402 ,*** Subsubheading
1403 #+end_src
1405 ...archiving "Subsubheading" to a new file will set the location in
1406 the new file to the top level heading:
1408 #+begin_src org
1409 ,* Heading
1410 ,** Subsubheading
1411 #+end_src
1413 While this hack obviously destroys the outline hierarchy somewhat, it
1414 at least preserves the logic of level one groupings.
1416 A slightly more complex version of this hack will not only keep the
1417 archive organized by top-level headings, but will also preserve the
1418 tags found on those headings:
1420 #+begin_src emacs-lisp
1421   (defun my-org-inherited-no-file-tags ()
1422     (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
1423           (ltags (org-entry-get nil "TAGS")))
1424       (mapc (lambda (tag)
1425               (setq tags
1426                     (replace-regexp-in-string (concat tag ":") "" tags)))
1427             (append org-file-tags (when ltags (split-string ltags ":" t))))
1428       (if (string= ":" tags) nil tags)))
1430   (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
1431     (let ((tags (my-org-inherited-no-file-tags))
1432           (org-archive-location
1433            (if (save-excursion (org-back-to-heading)
1434                                (> (org-outline-level) 1))
1435                (concat (car (split-string org-archive-location "::"))
1436                        "::* "
1437                        (car (org-get-outline-path)))
1438              org-archive-location)))
1439       ad-do-it
1440       (with-current-buffer (find-file-noselect (org-extract-archive-file))
1441         (save-excursion
1442           (while (org-up-heading-safe))
1443           (org-set-tags-to tags)))))
1444 #+end_src
1446 *** Archive in a date tree
1447 #+index: Archiving!date tree
1448 Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].
1450 (Make sure org-datetree.el is loaded for this to work.)
1452 #+begin_src emacs-lisp
1453 ;; (setq org-archive-location "%s_archive::date-tree")
1454 (defadvice org-archive-subtree
1455   (around org-archive-subtree-to-data-tree activate)
1456   "org-archive-subtree to date-tree"
1457   (if
1458       (string= "date-tree"
1459                (org-extract-archive-heading
1460                 (org-get-local-archive-location)))
1461       (let* ((dct (decode-time (org-current-time)))
1462              (y (nth 5 dct))
1463              (m (nth 4 dct))
1464              (d (nth 3 dct))
1465              (this-buffer (current-buffer))
1466              (location (org-get-local-archive-location))
1467              (afile (org-extract-archive-file location))
1468              (org-archive-location
1469               (format "%s::*** %04d-%02d-%02d %s" afile y m d
1470                       (format-time-string "%A" (encode-time 0 0 0 d m y)))))
1471         (message "afile=%s" afile)
1472         (unless afile
1473           (error "Invalid `org-archive-location'"))
1474         (save-excursion
1475           (switch-to-buffer (find-file-noselect afile))
1476           (org-datetree-find-year-create y)
1477           (org-datetree-find-month-create y m)
1478           (org-datetree-find-day-create y m d)
1479           (widen)
1480           (switch-to-buffer this-buffer))
1481         ad-do-it)
1482     ad-do-it))
1483 #+end_src
1485 *** Add inherited tags to archived entries
1486 #+index: Archiving!Add inherited tags
1487 To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
1488 advise the function like this:
1490 #+begin_example
1491 (defadvice org-archive-subtree
1492   (before add-inherited-tags-before-org-archive-subtree activate)
1493     "add inherited tags before org-archive-subtree"
1494     (org-set-tags-to (org-get-tags-at)))
1495 #+end_example
1497 ** Using and Managing Org-Metadata
1498 *** Remove redundant tags of headlines
1499   :PROPERTIES:
1500   :CUSTOM_ID: remove-redundant-tags
1501   :END:
1502 #+index: Tag!Remove redundant
1503 -- David Maus
1505 A small function that processes all headlines in current buffer and
1506 removes tags that are local to a headline and inherited by a parent
1507 headline or the #+FILETAGS: statement.
1509 #+BEGIN_SRC emacs-lisp
1510   (defun dmj/org-remove-redundant-tags ()
1511     "Remove redundant tags of headlines in current buffer.
1513   A tag is considered redundant if it is local to a headline and
1514   inherited by a parent headline."
1515     (interactive)
1516     (when (eq major-mode 'org-mode)
1517       (save-excursion
1518         (org-map-entries
1519          (lambda ()
1520            (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
1521                  local inherited tag)
1522              (dolist (tag alltags)
1523                (if (get-text-property 0 'inherited tag)
1524                    (push tag inherited) (push tag local)))
1525              (dolist (tag local)
1526                (if (member tag inherited) (org-toggle-tag tag 'off)))))
1527          t nil))))
1528 #+END_SRC
1530 *** Remove empty property drawers
1531   :PROPERTIES:
1532   :CUSTOM_ID: remove-empty-property-drawers
1533   :END:
1534 #+index: Drawer!Empty
1535 David Maus proposed this:
1537 #+begin_src emacs-lisp
1538 (defun dmj:org:remove-empty-propert-drawers ()
1539   "*Remove all empty property drawers in current file."
1540   (interactive)
1541   (unless (eq major-mode 'org-mode)
1542     (error "You need to turn on Org mode for this function."))
1543   (save-excursion
1544     (goto-char (point-min))
1545     (while (re-search-forward ":PROPERTIES:" nil t)
1546       (save-excursion
1547         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
1548 #+end_src
1550 *** Group task list by a property
1551 #+index: Agenda!Group task list
1552 This advice allows you to group a task list in Org-Mode.  To use it,
1553 set the variable =org-agenda-group-by-property= to the name of a
1554 property in the option list for a TODO or TAGS search.  The resulting
1555 agenda view will group tasks by that property prior to searching.
1557 #+begin_src emacs-lisp
1558 (defvar org-agenda-group-by-property nil
1559   "Set this in org-mode agenda views to group tasks by property")
1561 (defun org-group-bucket-items (prop items)
1562   (let ((buckets ()))
1563     (dolist (item items)
1564       (let* ((marker (get-text-property 0 'org-marker item))
1565              (pvalue (org-entry-get marker prop t))
1566              (cell (assoc pvalue buckets)))
1567         (if cell
1568             (setcdr cell (cons item (cdr cell)))
1569           (setq buckets (cons (cons pvalue (list item))
1570                               buckets)))))
1571     (setq buckets (mapcar (lambda (bucket)
1572                             (cons (car bucket)
1573                                   (reverse (cdr bucket))))
1574                           buckets))
1575     (sort buckets (lambda (i1 i2)
1576                     (string< (car i1) (car i2))))))
1578 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
1579                                                (list &optional nosort))
1580   "Prepare bucketed agenda entry lists"
1581   (if org-agenda-group-by-property
1582       ;; bucketed, handle appropriately
1583       (let ((text ""))
1584         (dolist (bucket (org-group-bucket-items
1585                          org-agenda-group-by-property
1586                          list))
1587           (let ((header (concat "Property "
1588                                 org-agenda-group-by-property
1589                                 " is "
1590                                 (or (car bucket) "<nil>") ":\n")))
1591             (add-text-properties 0 (1- (length header))
1592                                  (list 'face 'org-agenda-structure)
1593                                  header)
1594             (setq text
1595                   (concat text header
1596                           ;; recursively process
1597                           (let ((org-agenda-group-by-property nil))
1598                             (org-finalize-agenda-entries
1599                              (cdr bucket) nosort))
1600                           "\n\n"))))
1601         (setq ad-return-value text))
1602     ad-do-it))
1603 (ad-activate 'org-finalize-agenda-entries)
1604 #+end_src
1605 *** A way to tag a task so that when clocking-out user is prompted to take a note.
1606 #+index: Tag!Clock
1607 #+index: Clock!Tag
1608     Thanks to Richard Riley (see [[https://orgmode.org/list/vuoc49jfwp.fsf@news.eternal-september.org][this post on the mailing list]]).
1610 A small hook run when clocking out of a task that prompts for a note
1611 when the tag "=clockout_note=" is found in a headline. It uses the tag
1612 ("=clockout_note=") so inheritance can also be used...
1614 #+begin_src emacs-lisp
1615   (defun rgr/check-for-clock-out-note()
1616         (interactive)
1617         (save-excursion
1618           (org-back-to-heading)
1619           (let ((tags (org-get-tags)))
1620             (and tags (message "tags: %s " tags)
1621                  (when (member "clocknote" tags)
1622                    (org-add-note))))))
1624   (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
1625 #+end_src
1626 *** Dynamically adjust tag position
1627 #+index: Tag!position
1628 Here is a bit of code that allows you to have the tags always
1629 right-adjusted in the buffer.
1631 This is useful when you have bigger window than default window-size
1632 and you dislike the aesthetics of having the tag in the middle of the
1633 line.
1635 This hack solves the problem of adjusting it whenever you change the
1636 window size.
1637 Before saving it will revert the file to having the tag position be
1638 left-adjusted so that if you track your files with version control,
1639 you won't run into artificial diffs just because the window-size
1640 changed.
1642 *IMPORTANT*: This is probably slow on very big files.
1644 #+begin_src emacs-lisp
1645 (setq ba/org-adjust-tags-column t)
1647 (defun ba/org-adjust-tags-column-reset-tags ()
1648   "In org-mode buffers it will reset tag position according to
1649 `org-tags-column'."
1650   (when (and
1651          (not (string= (buffer-name) "*Remember*"))
1652          (eql major-mode 'org-mode))
1653     (let ((b-m-p (buffer-modified-p)))
1654       (condition-case nil
1655           (save-excursion
1656             (goto-char (point-min))
1657             (command-execute 'outline-next-visible-heading)
1658             ;; disable (message) that org-set-tags generates
1659             (flet ((message (&rest ignored) nil))
1660               (org-set-tags 1 t))
1661             (set-buffer-modified-p b-m-p))
1662         (error nil)))))
1664 (defun ba/org-adjust-tags-column-now ()
1665   "Right-adjust `org-tags-column' value, then reset tag position."
1666   (set (make-local-variable 'org-tags-column)
1667        (- (- (window-width) (length org-ellipsis))))
1668   (ba/org-adjust-tags-column-reset-tags))
1670 (defun ba/org-adjust-tags-column-maybe ()
1671   "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
1672   (when ba/org-adjust-tags-column
1673     (ba/org-adjust-tags-column-now)))
1675 (defun ba/org-adjust-tags-column-before-save ()
1676   "Tags need to be left-adjusted when saving."
1677   (when ba/org-adjust-tags-column
1678      (setq org-tags-column 1)
1679      (ba/org-adjust-tags-column-reset-tags)))
1681 (defun ba/org-adjust-tags-column-after-save ()
1682   "Revert left-adjusted tag position done by before-save hook."
1683   (ba/org-adjust-tags-column-maybe)
1684   (set-buffer-modified-p nil))
1686 ; automatically align tags on right-hand side
1687 (add-hook 'window-configuration-change-hook
1688           'ba/org-adjust-tags-column-maybe)
1689 (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1690 (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1691 (add-hook 'org-agenda-mode-hook (lambda ()
1692                                   (setq org-agenda-tags-column (- (window-width)))))
1694 ; between invoking org-refile and displaying the prompt (which
1695 ; triggers window-configuration-change-hook) tags might adjust,
1696 ; which invalidates the org-refile cache
1697 (defadvice org-refile (around org-refile-disable-adjust-tags)
1698   "Disable dynamically adjusting tags"
1699   (let ((ba/org-adjust-tags-column nil))
1700     ad-do-it))
1701 (ad-activate 'org-refile)
1702 #+end_src
1703 *** Use an "attach" link type to open files without worrying about their location
1704 #+index: Link!Attach
1705 -- Darlan Cavalcante Moreira
1707 In the setup part in my org-files I put:
1709 #+begin_src org
1710 ,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
1711 #+end_src
1713 Now I can use the "attach" link type, but org will ask me if I want to
1714 allow executing the elisp code.  To avoid this you can even set
1715 org-confirm-elisp-link-function to nil (I don't like this because it allows
1716 any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
1717 appropriately.
1719 In my case I use
1721 : (setq org-confirm-elisp-link-not-regexp "org-open-file")
1723 This works very well.
1725 ** Org Agenda and Task Management
1726 *** Make it easier to set org-agenda-files from multiple directories
1727 #+index: Agenda!Files
1728 - Matt Lundin
1730 #+begin_src emacs-lisp
1731 (defun my-org-list-files (dirs ext)
1732   "Function to create list of org files in multiple subdirectories.
1733 This can be called to generate a list of files for
1734 org-agenda-files or org-refile-targets.
1736 DIRS is a list of directories.
1738 EXT is a list of the extensions of files to be included."
1739   (let ((dirs (if (listp dirs)
1740                   dirs
1741                 (list dirs)))
1742         (ext (if (listp ext)
1743                  ext
1744                (list ext)))
1745         files)
1746     (mapc
1747      (lambda (x)
1748        (mapc
1749         (lambda (y)
1750           (setq files
1751                 (append files
1752                         (file-expand-wildcards
1753                          (concat (file-name-as-directory x) "*" y)))))
1754         ext))
1755      dirs)
1756     (mapc
1757      (lambda (x)
1758        (when (or (string-match "/.#" x)
1759                  (string-match "#$" x))
1760          (setq files (delete x files))))
1761      files)
1762     files))
1764 (defvar my-org-agenda-directories '("~/org/")
1765   "List of directories containing org files.")
1766 (defvar my-org-agenda-extensions '(".org")
1767   "List of extensions of agenda files")
1769 (setq my-org-agenda-directories '("~/org/" "~/work/"))
1770 (setq my-org-agenda-extensions '(".org" ".ref"))
1772 (defun my-org-set-agenda-files ()
1773   (interactive)
1774   (setq org-agenda-files (my-org-list-files
1775                           my-org-agenda-directories
1776                           my-org-agenda-extensions)))
1778 (my-org-set-agenda-files)
1779 #+end_src
1781 The code above will set your "default" agenda files to all files
1782 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
1783 You can change these values by setting the variables
1784 my-org-agenda-extensions and my-org-agenda-directories. The function
1785 my-org-agenda-files-by-filetag uses these two variables to determine
1786 which files to search for filetags (i.e., the larger set from which
1787 the subset will be drawn).
1789 You can also easily use my-org-list-files to "mix and match"
1790 directories and extensions to generate different lists of agenda
1791 files.
1793 *** Restrict org-agenda-files by filetag
1794   :PROPERTIES:
1795   :CUSTOM_ID: set-agenda-files-by-filetag
1796   :END:
1797 #+index: Agenda!Files
1798 - Matt Lundin
1800 It is often helpful to limit yourself to a subset of your agenda
1801 files. For instance, at work, you might want to see only files related
1802 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
1803 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 agendacommands]]. These solutions, however, require reapplying a filter each
1804 time you call the agenda or writing several new custom agenda commands
1805 for each context. Another solution is to use directories for different
1806 types of tasks and to change your agenda files with a function that
1807 sets org-agenda-files to the appropriate directory. But this relies on
1808 hard and static boundaries between files.
1810 The following functions allow for a more dynamic approach to selecting
1811 a subset of files based on filetags:
1813 #+begin_src emacs-lisp
1814 (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
1815   "Restrict org agenda files only to those containing filetag."
1816   (interactive)
1817   (let* ((tagslist (my-org-get-all-filetags))
1818          (ftag (or tag
1819                    (completing-read "Tag: "
1820                                     (mapcar 'car tagslist)))))
1821     (org-agenda-remove-restriction-lock 'noupdate)
1822     (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
1823     (setq org-agenda-overriding-restriction 'files)))
1825 (defun my-org-get-all-filetags ()
1826   "Get list of filetags from all default org-files."
1827   (let ((files org-agenda-files)
1828         tagslist x)
1829     (save-window-excursion
1830       (while (setq x (pop files))
1831         (set-buffer (find-file-noselect x))
1832         (mapc
1833          (lambda (y)
1834            (let ((tagfiles (assoc y tagslist)))
1835              (if tagfiles
1836                  (setcdr tagfiles (cons x (cdr tagfiles)))
1837                (add-to-list 'tagslist (list y x)))))
1838          (my-org-get-filetags)))
1839       tagslist)))
1841 (defun my-org-get-filetags ()
1842   "Get list of filetags for current buffer"
1843   (let ((ftags org-file-tags)
1844         x)
1845     (mapcar
1846      (lambda (x)
1847        (org-no-properties x))
1848      ftags)))
1849 #+end_src
1851 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
1852 with all filetags in your "normal" agenda files. When you select a
1853 tag, org-agenda-files will be restricted to only those files
1854 containing the filetag. To release the restriction, type C-c C-x >
1855 (org-agenda-remove-restriction-lock).
1857 *** Highlight the agenda line under cursor
1858 #+index: Agenda!Highlight
1859 This is useful to make sure what task you are operating on.
1861 #+BEGIN_SRC emacs-lisp
1862 (add-hook 'org-agenda-mode-hook (lambda () (hl-line-mode 1)))
1863 #+END_SRC
1865 Under XEmacs:
1867 #+BEGIN_SRC emacs-lisp
1868 ;; hl-line seems to be only for emacs
1869 (require 'highline)
1870 (add-hook 'org-agenda-mode-hook (lambda () (highline-mode 1)))
1872 ;; highline-mode does not work straightaway in tty mode.
1873 ;; I use a black background
1874 (custom-set-faces
1875   '(highline-face ((((type tty) (class color))
1876                     (:background "white" :foreground "black")))))
1877 #+END_SRC
1879 *** Split frame horizontally for agenda
1880 #+index: Agenda!frame
1881 If you would like to split the frame into two side-by-side windows when
1882 displaying the agenda, try this hack from Jan Rehders, which uses the
1883 `toggle-window-split' from
1885 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
1887 #+BEGIN_SRC emacs-lisp
1888 ;; Patch org-mode to use vertical splitting
1889 (defadvice org-prepare-agenda (after org-fix-split)
1890   (toggle-window-split))
1891 (ad-activate 'org-prepare-agenda)
1892 #+END_SRC
1894 *** Automatically add an appointment when clocking in a task
1895 #+index: Clock!Automatically add an appointment when clocking in a task
1896 #+index: Appointment!Automatically add an appointment when clocking in a task
1897 #+BEGIN_SRC emacs-lisp
1898 ;; Make sure you have a sensible value for `appt-message-warning-time'
1899 (defvar bzg-org-clock-in-appt-delay 100
1900   "Number of minutes for setting an appointment by clocking-in")
1901 #+END_SRC
1903 This function let's you add an appointment for the current entry.
1904 This can be useful when you need a reminder.
1906 #+BEGIN_SRC emacs-lisp
1907 (defun bzg-org-clock-in-add-appt (&optional n)
1908   "Add an appointment for the Org entry at point in N minutes."
1909   (interactive)
1910   (save-excursion
1911     (org-back-to-heading t)
1912     (looking-at org-complex-heading-regexp)
1913     (let* ((msg (match-string-no-properties 4))
1914            (ct-time (decode-time))
1915            (appt-min (+ (cadr ct-time)
1916                         (or n bzg-org-clock-in-appt-delay)))
1917            (appt-time ; define the time for the appointment
1918             (progn (setf (cadr ct-time) appt-min) ct-time)))
1919       (appt-add (format-time-string
1920                  "%H:%M" (apply 'encode-time appt-time)) msg)
1921       (if (interactive-p) (message "New appointment for %s" msg)))))
1922 #+END_SRC
1924 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
1925 add an appointment:
1927 #+BEGIN_SRC emacs-lisp
1928 (defadvice org-clock-in (after org-clock-in-add-appt activate)
1929   "Add an appointment when clocking a task in."
1930   (bzg-org-clock-in-add-appt))
1931 #+END_SRC
1933 You may also want to delete the associated appointment when clocking
1934 out.  This function does this:
1936 #+BEGIN_SRC emacs-lisp
1937 (defun bzg-org-clock-out-delete-appt nil
1938   "When clocking out, delete any associated appointment."
1939   (interactive)
1940   (save-excursion
1941     (org-back-to-heading t)
1942     (looking-at org-complex-heading-regexp)
1943     (let* ((msg (match-string-no-properties 4)))
1944       (setq appt-time-msg-list
1945             (delete nil
1946                     (mapcar
1947                      (lambda (appt)
1948                        (if (not (string-match (regexp-quote msg)
1949                                               (cadr appt))) appt))
1950                      appt-time-msg-list)))
1951       (appt-check))))
1952 #+END_SRC
1954 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
1956 #+BEGIN_SRC emacs-lisp
1957 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
1958   "Delete an appointment when clocking a task out."
1959   (bzg-org-clock-out-delete-appt))
1960 #+END_SRC
1962 *IMPORTANT*: You can add appointment by clocking in in both an
1963 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
1964 agenda buffer with the advice above will bring an error.
1966 *** Using external programs for appointments reminders
1967 #+index: Appointment!reminders
1968 Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.
1970 *** Remove from agenda time grid lines that are in an appointment
1971 #+index: Agenda!time grid
1972 #+index: Appointment!Remove from agenda time grid lines
1973 The agenda shows lines for the time grid.  Some people think that
1974 these lines are a distraction when there are appointments at those
1975 times.  You can get rid of the lines which coincide exactly with the
1976 beginning of an appointment.  Michael Ekstrand has written a piece of
1977 advice that also removes lines that are somewhere inside an
1978 appointment:
1980 #+begin_src emacs-lisp
1981 (defun org-time-to-minutes (time)
1982   "Convert an HHMM time to minutes"
1983   (+ (* (/ time 100) 60) (% time 100)))
1985 (defun org-time-from-minutes (minutes)
1986   "Convert a number of minutes to an HHMM time"
1987   (+ (* (/ minutes 60) 100) (% minutes 60)))
1989 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
1990                                                   (list ndays todayp))
1991   (if (member 'remove-match (car org-agenda-time-grid))
1992       (flet ((extract-window
1993               (line)
1994               (let ((start (get-text-property 1 'time-of-day line))
1995                     (dur (get-text-property 1 'duration line)))
1996                 (cond
1997                  ((and start dur)
1998                   (cons start
1999                         (org-time-from-minutes
2000                          (+ dur (org-time-to-minutes start)))))
2001                  (start start)
2002                  (t nil)))))
2003         (let* ((windows (delq nil (mapcar 'extract-window list)))
2004                (org-agenda-time-grid
2005                 (list (car org-agenda-time-grid)
2006                       (cadr org-agenda-time-grid)
2007                       (remove-if
2008                        (lambda (time)
2009                          (find-if (lambda (w)
2010                                     (if (numberp w)
2011                                         (equal w time)
2012                                       (and (>= time (car w))
2013                                            (< time (cdr w)))))
2014                                   windows))
2015                        (caddr org-agenda-time-grid)))))
2016           ad-do-it))
2017     ad-do-it))
2018 (ad-activate 'org-agenda-add-time-grid-maybe)
2019 #+end_src
2020 *** Disable version control for Org mode agenda files
2021 #+index: Agenda!Files
2022 -- David Maus
2024 Even if you use Git to track your agenda files you might not need
2025 vc-mode to be enabled for these files.
2027 #+begin_src emacs-lisp
2028 (add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
2029 (defun dmj/disable-vc-for-agenda-files-hook ()
2030   "Disable vc-mode for Org agenda files."
2031   (if (and (fboundp 'org-agenda-file-p)
2032            (org-agenda-file-p (buffer-file-name)))
2033       (remove-hook 'find-file-hook 'vc-find-file-hook)
2034     (add-hook 'find-file-hook 'vc-find-file-hook)))
2035 #+end_src
2037 *** Easy customization of TODO colors
2038 #+index: Customization!Todo keywords
2039 #+index: Todo keywords!Customization
2041 -- Ryan C. Thompson
2043 Here is some code I came up with some code to make it easier to
2044 customize the colors of various TODO keywords. As long as you just
2045 want a different color and nothing else, you can customize the
2046 variable org-todo-keyword-faces and use just a string color (i.e. a
2047 string of the color name) as the face, and then org-get-todo-face
2048 will convert the color to a face, inheriting everything else from
2049 the standard org-todo face.
2051 To demonstrate, I currently have org-todo-keyword-faces set to
2053 #+BEGIN_SRC emacs-lisp
2054 (("IN PROGRESS" . "dark orange")
2055  ("WAITING" . "red4")
2056  ("CANCELED" . "saddle brown"))
2057 #+END_SRC
2059   Here's the code, in a form you can put in your =.emacs=
2061 #+BEGIN_SRC emacs-lisp
2062 (eval-after-load 'org-faces
2063  '(progn
2064     (defcustom org-todo-keyword-faces nil
2065       "Faces for specific TODO keywords.
2066 This is a list of cons cells, with TODO keywords in the car and
2067 faces in the cdr.  The face can be a symbol, a color, or a
2068 property list of attributes, like (:foreground \"blue\" :weight
2069 bold :underline t)."
2070       :group 'org-faces
2071       :group 'org-todo
2072       :type '(repeat
2073               (cons
2074                (string :tag "Keyword")
2075                (choice color (sexp :tag "Face")))))))
2077 (eval-after-load 'org
2078  '(progn
2079     (defun org-get-todo-face-from-color (color)
2080       "Returns a specification for a face that inherits from org-todo
2081  face and has the given color as foreground. Returns nil if
2082  color is nil."
2083       (when color
2084         `(:inherit org-warning :foreground ,color)))
2086     (defun org-get-todo-face (kwd)
2087       "Get the right face for a TODO keyword KWD.
2088 If KWD is a number, get the corresponding match group."
2089       (if (numberp kwd) (setq kwd (match-string kwd)))
2090       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
2091             (if (stringp face)
2092                 (org-get-todo-face-from-color face)
2093               face))
2094           (and (member kwd org-done-keywords) 'org-done)
2095           'org-todo))))
2096 #+END_SRC
2098 *** Add an effort estimate on the fly when clocking in
2099 #+index: Effort estimate!Add when clocking in
2100 #+index: Clock!Effort estimate
2101 You can use =org-clock-in-prepare-hook= to add an effort estimate.
2102 This way you can easily have a "tea-timer" for your tasks when they
2103 don't already have an effort estimate.
2105 #+begin_src emacs-lisp
2106 (add-hook 'org-clock-in-prepare-hook
2107           'my-org-mode-ask-effort)
2109 (defun my-org-mode-ask-effort ()
2110   "Ask for an effort estimate when clocking in."
2111   (unless (org-entry-get (point) "Effort")
2112     (let ((effort
2113            (completing-read
2114             "Effort: "
2115             (org-entry-get-multivalued-property (point) "Effort"))))
2116       (unless (equal effort "")
2117         (org-set-property "Effort" effort)))))
2118 #+end_src
2120 Or you can use a default effort for such a timer:
2122 #+begin_src emacs-lisp
2123 (add-hook 'org-clock-in-prepare-hook
2124           'my-org-mode-add-default-effort)
2126 (defvar org-clock-default-effort "1:00")
2128 (defun my-org-mode-add-default-effort ()
2129   "Add a default effort estimation."
2130   (unless (org-entry-get (point) "Effort")
2131     (org-set-property "Effort" org-clock-default-effort)))
2132 #+end_src
2134 *** Use idle timer for automatic agenda views
2135 #+index: Agenda view!Refresh
2136 From John Wiegley's mailing list post (March 18, 2010):
2138 #+begin_quote
2139 I have the following snippet in my .emacs file, which I find very
2140 useful. Basically what it does is that if I don't touch my Emacs for 5
2141 minutes, it displays the current agenda. This keeps my tasks "always
2142 in mind" whenever I come back to Emacs after doing something else,
2143 whereas before I had a tendency to forget that it was there.
2144 #+end_quote
2146   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
2148 #+begin_src emacs-lisp
2149 (defun jump-to-org-agenda ()
2150   (interactive)
2151   (let ((buf (get-buffer "*Org Agenda*"))
2152         wind)
2153     (if buf
2154         (if (setq wind (get-buffer-window buf))
2155             (select-window wind)
2156           (if (called-interactively-p)
2157               (progn
2158                 (select-window (display-buffer buf t t))
2159                 (org-fit-window-to-buffer)
2160                 ;; (org-agenda-redo)
2161                 )
2162             (with-selected-window (display-buffer buf)
2163               (org-fit-window-to-buffer)
2164               ;; (org-agenda-redo)
2165               )))
2166       (call-interactively 'org-agenda-list)))
2167   ;;(let ((buf (get-buffer "*Calendar*")))
2168   ;;  (unless (get-buffer-window buf)
2169   ;;    (org-agenda-goto-calendar)))
2170   )
2172 (run-with-idle-timer 300 t 'jump-to-org-agenda)
2173 #+end_src
2175 #+results:
2176 : [nil 0 300 0 t jump-to-org-agenda nil idle]
2178 *** Refresh the agenda view regularly
2179 #+index: Agenda view!Refresh
2180 Hack sent by Kiwon Um:
2182 #+begin_src emacs-lisp
2183 (defun kiwon/org-agenda-redo-in-other-window ()
2184   "Call org-agenda-redo function even in the non-agenda buffer."
2185   (interactive)
2186   (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
2187     (when agenda-window
2188       (with-selected-window agenda-window (org-agenda-redo)))))
2189 (run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
2190 #+end_src
2192 *** Reschedule agenda items to today with a single command
2193 #+index: Agenda!Reschedule
2194 This was suggested by Carsten in reply to David Abrahams:
2196 #+begin_example emacs-lisp
2197 (defun org-agenda-reschedule-to-today ()
2198   (interactive)
2199   (flet ((org-read-date (&rest rest) (current-time)))
2200     (call-interactively 'org-agenda-schedule)))
2201 #+end_example
2203 *** Mark subtree DONE along with all subheadings
2204 #+index: Subtree!subheadings
2205 Bernt Hansen [[https://orgmode.org/list/87aac7dnr6.fsf@norang.ca][suggested]] this command:
2207 #+begin_src emacs-lisp
2208 (defun bh/mark-subtree-done ()
2209   (interactive)
2210   (org-mark-subtree)
2211   (let ((limit (point)))
2212     (save-excursion
2213       (exchange-point-and-mark)
2214       (while (> (point) limit)
2215         (org-todo "DONE")
2216         (outline-previous-visible-heading 1))
2217       (org-todo "DONE"))))
2218 #+end_src
2220 Then M-x bh/mark-subtree-done.
2222 *** Mark heading done when all checkboxes are checked.
2223     :PROPERTIES:
2224     :CUSTOM_ID: mark-done-when-all-checkboxes-checked
2225     :END:
2227 #+index: Checkbox
2229 An item consists of a list with checkboxes.  When all of the
2230 checkboxes are checked, the item should be considered complete and its
2231 TODO state should be automatically changed to DONE. The code below
2232 does that. This version is slightly enhanced over the one in the
2233 mailing list (see
2234 https://orgmode.org/list/87r5718ytv.fsf@sputnik.localhost to
2235 reset the state back to TODO if a checkbox is unchecked.
2237 Note that the code requires that a checkbox statistics cookie (the [/]
2238 or [%] thingie in the headline - see the [[https://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
2239 manual) be present in order for it to work. Note also that it is too
2240 dumb to figure out whether the item has a TODO state in the first
2241 place: if there is a statistics cookie, a TODO/DONE state will be
2242 added willy-nilly any time that the statistics cookie is changed.
2244 #+begin_src emacs-lisp
2245   ;; see https://orgmode.org/list/87r5718ytv.fsf@sputnik.localhost
2246   (eval-after-load 'org-list
2247     '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
2249   (defun ndk/checkbox-list-complete ()
2250     (save-excursion
2251       (org-back-to-heading t)
2252       (let ((beg (point)) end)
2253         (end-of-line)
2254         (setq end (point))
2255         (goto-char beg)
2256         (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
2257               (if (match-end 1)
2258                   (if (equal (match-string 1) "100%")
2259                       ;; all done - do the state change
2260                       (org-todo 'done)
2261                     (org-todo 'todo))
2262                 (if (and (> (match-end 2) (match-beginning 2))
2263                          (equal (match-string 2) (match-string 3)))
2264                     (org-todo 'done)
2265                   (org-todo 'todo)))))))
2266 #+end_src
2268 *** Links to custom agenda views
2269     :PROPERTIES:
2270     :CUSTOM_ID: links-to-agenda-views
2271     :END:
2272 #+index: Agenda view!Links to
2273 This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.
2275 If you have custom agenda commands defined to some key, say w, then
2276 the following will serve as a link to the custom agenda buffer.
2277 : [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]
2279 Clicking on it will prompt if you want to execute the elisp code.  If
2280 you would rather not have the prompt or would want to respond with a
2281 single letter, ~y~ or ~n~, take a look at the docstrings of the
2282 variables =org-confirm-elisp-link-function= and
2283 =org-confirm-elisp-link-not-regexp=.  Please take special note of the
2284 security risk associated with completely disabling the prompting
2285 before you proceed.
2287 ** Exporting org files
2288 *** Ignoring headlines during export
2289     :PROPERTIES:
2290     :CUSTOM_ID: ignoreheadline
2291     :END:
2292 #+index: Export!ignore headlines
2293 Sometimes users want to ignore the headline text during export like in
2294 the Beamer exporter (=ox-beamer=).  In the [[https://orgmode.org/manual/Beamer-export.html#Beamer-export][Beamer exporter]] one can use
2295 the tag =ignoreheading= to disable the export of a certain headline,
2296 whilst still retaining the content of the headline.  We can imitate
2297 this feature in other export backends.  Note that this is not a
2298 particularly easy problem, as the Org exporter creates a static
2299 representation of section numbers, table of contents etc.
2301 Consider the following document:
2302 #+BEGIN_SRC org
2303   ,* head 1                    :noexport:
2304   ,* head 2                    :ignoreheading:
2305   ,* head 3
2306   ,* =head 4=                  :ignoreheading:
2308 #+END_SRC
2309 We want to remove heading 2 and 4.
2311 There are different strategies to accomplish this:
2312 1. The best option is to remove headings tagged with =ignoreheading=
2313    before export starts.  This can be accomplished with the hook
2314    =org-export-before-parsing-hook= that runs before the buffer has
2315    been parsed.  In the example above, however, =head 2= would not be
2316    exported as it becomes part of =head 1= which is not exporter.  To
2317    overcome this move perhaps =head 1= can be moved to the end of the
2318    buffer.  An example of a hook that removes headings is before
2319    parsing is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01459.html][here]].  Note, this solution is compatible with
2320    /all/ export formats!
2321 2. The problem is simple when exporting to LaTeX, as the LaTeX
2322    compiler determines numbers.  We can thus use
2323    =org-export-filter-headline-functions= to remove the offending
2324    headlines.  One regexp-based solution that looks for the word
2325    =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
2326    exporter Org v7 exporter and the current Org v8 exporter.  Note,
2327    however, that this filter will only work with LaTeX (numbering and
2328    the table of content may break in other exporters).  In the example
2329    above, this filer will work flawlessly in LaTeX, it will not work
2330    at all in HTML and it will fail to update section numbers, TOC and
2331    leave some auxiliary lines behind when exporting to plain text.
2332 3. Another solution that tries to recover the Org element
2333    representation is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01480.html][here]].  In the example above this filter
2334    will not remove =head 4= exporting to any backend, since verbatim
2335    strings do not retain the Org element representation.  It will
2336    remove the extra heading line when exporting to plain text, but
2337    will also fail to update section numbers.  It should be fairly
2338    simple to also make it work with HTML.
2340 *NOTE: another way to accomplish this behavior is to use the [[https://code.orgmode.org/bzg/org-mode/raw/master/contrib/lisp/ox-extra.el][=ox-extra.el=]] package:*
2341 To use this, add the following to your =.elisp= file:
2343 #+begin_src emacs-lisp
2344     (add-to-list 'load-path "path/to/contrib/lisp")
2345     (require 'ox-extra)
2346     (ox-extras-activate '(ignore-headlines))
2347 #+end_src
2349 After this is added, then any headlines having an =:ignore:= tag will
2350 be omitted from the export, but their contents will be included in the
2351 export.
2353 *** Export Org to Org and handle includes.
2354 #+index: Export!handle includes
2355 N.B: this does not apply to the "new" export engine (>= 8.0) - the function
2356 =org-export-handle-include-files-recurse= is only available in earlier versions.
2357 There is probably a way to do the same thing in the "new" exporter but nobody
2358 has stepped up to the plate yet.
2360 Nick Dokos came up with this useful function:
2362 #+begin_src emacs-lisp
2363 (defun org-to-org-handle-includes ()
2364   "Copy the contents of the current buffer to OUTFILE,
2365 recursively processing #+INCLUDEs."
2366   (let* ((s (buffer-string))
2367          (fname (buffer-file-name))
2368          (ofname (format "%s.I.org" (file-name-sans-extension fname))))
2369     (setq result
2370           (with-temp-buffer
2371             (insert s)
2372             (org-export-handle-include-files-recurse)
2373             (buffer-string)))
2374     (find-file ofname)
2375     (delete-region (point-min) (point-max))
2376     (insert result)
2377     (save-buffer)))
2378 #+end_src
2380 *** Specifying LaTeX commands to floating environments
2381     :PROPERTIES:
2382     :CUSTOM_ID: latex-command-for-floats
2383     :END:
2385 #+index: Export!LaTeX
2386 The keyword ~placement~ can be used to specify placement options to
2387 floating environments (like =\begin{figure}= and =\begin{table}=}) in
2388 LaTeX export. Org passes along everything passed in options as long as
2389 there are no spaces. One can take advantage of this to pass other
2390 LaTeX commands and have their scope limited to the floating
2391 environment.
2393 For example one can set the fontsize of a table different from the
2394 default normal size by putting something like =\footnotesize= right
2395 after the placement options. During LaTeX export using the
2396 ~#+ATTR_LaTeX:~ line below:
2398 #+begin_src org
2399 ,#+ATTR_LaTeX: placement=[<options>]\footnotesize
2400 #+end_src
2402 exports the associated floating environment as shown in the following
2403 block.
2405 #+begin_src latex
2406 \begin{table}[<options>]\footnotesize
2408 \end{table}
2409 #+end_src
2411 It should be noted that this hack does not work for beamer export of
2412 tables since the =table= environment is not used. As an ugly
2413 workaround, one can use the following:
2415 #+begin_src org
2416 ,#+LATEX: {\footnotesize
2417 ,#+ATTR_LaTeX: align=rr
2418 | some | table |
2419 |------+-------|
2420 | ..   | ..    |
2421 ,#+LATEX: }
2422 #+end_src
2424 *** Styling code sections with CSS
2426 #+index: HTML!Styling code sections with CSS
2428 Code sections (marked with =#+begin_src= and =#+end_src=) are exported
2429 to HTML using =<pre>= tags, and assigned CSS classes by their content
2430 type.  For example, Perl content will have an opening tag like
2431 =<pre class="src src-perl">=.  You can use those classes to add styling
2432 to the output, such as here where a small language tag is added at the
2433 top of each kind of code box:
2435 #+begin_src lisp
2436 (setq org-export-html-style
2437  "<style type=\"text/css\">
2438     <!--/*--><![CDATA[/*><!--*/
2439       .src             { background-color: #F5FFF5; position: relative; overflow: visible; }
2440       .src:before      { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
2441       .src-sh:before   { content: 'sh'; }
2442       .src-bash:before { content: 'sh'; }
2443       .src-R:before    { content: 'R'; }
2444       .src-perl:before { content: 'Perl'; }
2445       .src-sql:before  { content: 'SQL'; }
2446       .example         { background-color: #FFF5F5; }
2447     /*]]>*/-->
2448  </style>")
2449 #+end_src
2451 Additionally, we use color to distinguish code output (the =.example=
2452 class) from input (all the =.src-*= classes).
2454 *** Where can I find nice themes for HTML export?
2456 You can find great looking HTML themes (CSS + JS) at
2457 https://github.com/fniessen/org-html-themes, currently:
2459 - Bigblow, and
2461   [[file:images/org-html-themes/bigblow.png]]
2463 - ReadTheOrg, a clone of Read The Docs.
2465   [[file:images/org-html-themes/readtheorg.png]]
2467 See https://www.youtube.com/watch?v=DnSGSiXYuOk for a demo of the Org
2468 HTML theme Bigblow.
2470 *** Including external text fragments
2472 #+index: Export!including external text fragments
2474 I recently had to document some source code but could not modify the
2475 source files themselves. Here is a setup that lets you refer to
2476 fragments of external files, such that the fragments are inserted as
2477 source blocks in the current file during evaluation of the ~call~
2478 lines (thus during export as well).
2480 #+BEGIN_SRC org
2481   ,* Setup                                                            :noexport:
2482   ,#+name: fetchsrc
2483   ,#+BEGIN_SRC emacs-lisp :results raw :var f="foo" :var s="Definition" :var e="\\. *$" :var b=()
2484     (defvar coqfiles nil)
2486     (defun fetchlines (file-path search-string &optional end before)
2487       "Searches for the SEARCH-STRING in FILE-PATH and returns the matching line.
2488     If the optional argument END is provided as a number, then this
2489     number of lines is printed.  If END is a string, then it is a
2490     regular expression indicating the end of the expression to print.
2491     If END is omitted, then 10 lines are printed.  If BEFORE is set,
2492     then one fewer line is printed (this is useful when END is a
2493     string matching the first line that should not be printed)."
2494       (with-temp-buffer
2495         (insert-file-contents file-path nil nil nil t)
2496         (goto-char (point-min))
2497         (let ((result
2498                (if (search-forward search-string nil t)
2499                    (buffer-substring
2500                     (line-beginning-position)
2501                     (if end
2502                         (cond
2503                          ((integerp end)
2504                           (line-end-position (if before (- end 1) end)))
2505                          ((stringp end)
2506                           (let ((point (re-search-forward end nil t)))
2507                             (if before (line-end-position 0) point)))
2508                          (t (line-end-position 10)))
2509                       (line-end-position 10))))))
2510           (or result ""))))
2512     (fetchlines (concat coqfiles f ".v") s e b)
2513   ,#+END_SRC
2515   ,#+name: wrap-coq
2516   ,#+BEGIN_SRC emacs-lisp :var text="" :results raw
2517   (concat "#+BEGIN_SRC coq\n" text "\n#+END_SRC")
2518   ,#+END_SRC
2519 #+END_SRC
2521 This is specialized for Coq files (hence the ~coq~ language in the
2522 ~wrap-coq~ function, the ~.v~ extension in the ~fetch~ function, and
2523 the default value for ~end~ matching the syntax ending definitions in
2524 Coq). To use it, you need to:
2525 - set the ~coqfiles~ variable to where your source files reside;
2526 - call the function using lines of the form
2527   #+BEGIN_SRC org
2528     ,#+call: fetchsrc(f="JsSyntax", s="Inductive expr :=", e="^ *$", b=1) :results drawer :post wrap-coq(text=*this*)
2529   #+END_SRC
2530   In this example, we look inside the file ~JsSyntax.v~ in ~coqfiles~,
2531   search for a line matching ~Inductive expr :=~, and include the
2532   fragment until the first line consisting only of white space,
2533   excluded (as ~b=1~).
2535 I use drawers to store the results to avoid a bug leading to
2536 duplication during export when the code has already been evaluated in
2537 the buffer (see [[https://orgmode.org/list/m2k3fkbxec.fsf@polytechnique.org][this thread]] for a description of the problem). This
2538 has been fixed in recent versions of org-mode, so alternative
2539 approaches are possible.
2541 ** Babel
2543 *** How do I preview LaTeX fragments when in a LaTeX source block?
2545 When editing =LaTeX= source blocks, you may want to preview LaTeX fragments
2546 just like in an Org-mode buffer.  You can do this by using the usual
2547 keybinding =C-c C-x C-l= after loading this snipped:
2549 #+BEGIN_SRC emacs-lisp
2550 (define-key org-src-mode-map "\C-c\C-x\C-l" 'org-edit-preview-latex-fragment)
2552 (defun org-edit-preview-latex-fragment ()
2553   "Write latex fragment from source to parent buffer and preview it."
2554   (interactive)
2555   (org-src-in-org-buffer (org-preview-latex-fragment)))
2556 #+END_SRC
2558 Thanks to Sebastian Hofer for sharing this.
2560 * Hacking Org: Working with Org-mode and other Emacs Packages
2561 ** How to ediff folded Org files
2562 A rather often quip among Org users is when looking at chages with
2563 ediff.  Ediff tends to fold the Org buffers when comparing.  This can
2564 be very inconvenient when trying to determine what changed.  A recent
2565 discussion on the mailing list led to a [[https://orgmode.org/list/87wqo5fnxc.dlv@debian.org][neat solution]] from Ratish
2566 Punnoose.
2568 ** org-remember-anything
2570 #+index: Remember!Anything
2572 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
2574 #+BEGIN_SRC emacs-lisp
2575 (defvar org-remember-anything
2576   '((name . "Org Remember")
2577     (candidates . (lambda () (mapcar 'car org-remember-templates)))
2578     (action . (lambda (name)
2579                 (let* ((orig-template org-remember-templates)
2580                        (org-remember-templates
2581                         (list (assoc name orig-template))))
2582                   (call-interactively 'org-remember))))))
2583 #+END_SRC
2585 You can add it to your 'anything-sources' variable and open remember directly
2586 from anything. I imagine this would be more interesting for people with many
2587 remember templates, so that you are out of keys to assign those to.
2589 ** Org-mode and saveplace.el
2591 Fix a problem with =saveplace.el= putting you back in a folded position:
2593 #+begin_src emacs-lisp
2594 (add-hook 'org-mode-hook
2595           (lambda ()
2596             (when (outline-invisible-p)
2597               (save-excursion
2598                 (outline-previous-visible-heading 1)
2599                 (org-show-subtree)))))
2600 #+end_src
2602 ** Using ido-mode for org-refile (and archiving via refile)
2604 First set up ido-mode, for example using:
2606 #+begin_src emacs-lisp
2607 ; use ido mode for completion
2608 (setq ido-everywhere t)
2609 (setq ido-enable-flex-matching t)
2610 (setq ido-max-directory-size 100000)
2611 (ido-mode (quote both))
2612 #+end_src
2614 Now to enable it in org-mode, use the following:
2615 #+begin_src emacs-lisp
2616 (setq org-completion-use-ido t)
2617 (setq org-refile-use-outline-path nil)
2618 (setq org-refile-allow-creating-parent-nodes 'confirm)
2619 #+end_src
2620 The last line enables the creation of nodes on the fly.
2622 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):
2623 #+begin_src emacs-lisp
2624 (setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
2625 #+end_src
2627 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.
2628 #+begin_src emacs-lisp
2629 ; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
2630 ; added check to only include headlines, e.g. line must have at least one child
2631 (defun my/verify-refile-target ()
2632   "Exclude todo keywords with a DONE state from refile targets"
2633   (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
2634       (save-excursion (org-goto-first-child))
2635   )
2636 (setq org-refile-target-verify-function 'my/verify-refile-target)
2637 #+end_src
2638 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.
2640 ** Using ido-completing-read to find attachments
2642 #+index: Attachment!ido completion
2644 -- Matt Lundin.
2646 Org-attach is great for quickly linking files to a project. But if you
2647 use org-attach extensively you might find yourself wanting to browse
2648 all the files you've attached to org headlines. This is not easy to do
2649 manually, since the directories containing the files are not human
2650 readable (i.e., they are based on automatically generated ids). Here's
2651 some code to browse those files using ido (obviously, you need to be
2652 using ido):
2654 #+begin_src emacs-lisp
2655 (load-library "find-lisp")
2657 ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
2659 (defun my-ido-find-org-attach ()
2660   "Find files in org-attachment directory"
2661   (interactive)
2662   (let* ((enable-recursive-minibuffers t)
2663          (files (find-lisp-find-files org-attach-directory "."))
2664          (file-assoc-list
2665           (mapcar (lambda (x)
2666                     (cons (file-name-nondirectory x)
2667                           x))
2668                   files))
2669          (filename-list
2670           (remove-duplicates (mapcar #'car file-assoc-list)
2671                              :test #'string=))
2672          (filename (ido-completing-read "Org attachments: " filename-list nil t))
2673          (longname (cdr (assoc filename file-assoc-list))))
2674     (ido-set-current-directory
2675      (if (file-directory-p longname)
2676          longname
2677        (file-name-directory longname)))
2678     (setq ido-exit 'refresh
2679           ido-text-init ido-text
2680           ido-rotate-temp t)
2681     (exit-minibuffer)))
2683 (add-hook 'ido-setup-hook 'ido-my-keys)
2685 (defun ido-my-keys ()
2686   "Add my keybindings for ido."
2687   (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
2688 #+end_src
2690 To browse your org attachments using ido fuzzy matching and/or the
2691 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
2692 press =C-;=.
2694 ** Link to Gnus messages by Message-Id
2695 #+index: Link!Gnus message by Message-Id
2696 In a [[https://orgmode.org/list/871vy3tg9x.fsf@wolfram.com][recent thread]] on the Org-Mode mailing list, there was some
2697 discussion about linking to Gnus messages without encoding the folder
2698 name in the link.  The following code hooks in to the store-link
2699 function in Gnus to capture links by Message-Id when in nnml folders,
2700 and then provides a link type "mid" which can open this link.  The
2701 =mde-org-gnus-open-message-link= function uses the
2702 =mde-mid-resolve-methods= variable to determine what Gnus backends to
2703 scan.  It will go through them, in order, asking each to locate the
2704 message and opening it from the first one that reports success.
2706 It has only been tested with a single nnml backend, so there may be
2707 bugs lurking here and there.
2709 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
2710 article]].
2712 #+begin_src emacs-lisp
2713 ;; Support for saving Gnus messages by Message-ID
2714 (defun mde-org-gnus-save-by-mid ()
2715   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
2716     (when (eq major-mode 'gnus-article-mode)
2717       (gnus-article-show-summary))
2718     (let* ((group gnus-newsgroup-name)
2719            (method (gnus-find-method-for-group group)))
2720       (when (eq 'nnml (car method))
2721         (let* ((article (gnus-summary-article-number))
2722                (header (gnus-summary-article-header article))
2723                (from (mail-header-from header))
2724                (message-id
2725                 (save-match-data
2726                   (let ((mid (mail-header-id header)))
2727                     (if (string-match "<\\(.*\\)>" mid)
2728                         (match-string 1 mid)
2729                       (error "Malformed message ID header %s" mid)))))
2730                (date (mail-header-date header))
2731                (subject (gnus-summary-subject-string)))
2732           (org-store-link-props :type "mid" :from from :subject subject
2733                                 :message-id message-id :group group
2734                                 :link (org-make-link "mid:" message-id))
2735           (apply 'org-store-link-props
2736                  :description (org-email-link-description)
2737                  org-store-link-plist)
2738           t)))))
2740 (defvar mde-mid-resolve-methods '()
2741   "List of methods to try when resolving message ID's.  For Gnus,
2742 it is a cons of 'gnus and the select (type and name).")
2743 (setq mde-mid-resolve-methods
2744       '((gnus nnml "")))
2746 (defvar mde-org-gnus-open-level 1
2747   "Level at which Gnus is started when opening a link")
2748 (defun mde-org-gnus-open-message-link (msgid)
2749   "Open a message link with Gnus"
2750   (require 'gnus)
2751   (require 'org-table)
2752   (catch 'method-found
2753     (message "[MID linker] Resolving %s" msgid)
2754     (dolist (method mde-mid-resolve-methods)
2755       (cond
2756        ((and (eq (car method) 'gnus)
2757              (eq (cadr method) 'nnml))
2758         (funcall (cdr (assq 'gnus org-link-frame-setup))
2759                  mde-org-gnus-open-level)
2760         (when gnus-other-frame-object
2761           (select-frame gnus-other-frame-object))
2762         (let* ((msg-info (nnml-find-group-number
2763                           (concat "<" msgid ">")
2764                           (cdr method)))
2765                (group (and msg-info (car msg-info)))
2766                (message (and msg-info (cdr msg-info)))
2767                (qname (and group
2768                            (if (gnus-methods-equal-p
2769                                 (cdr method)
2770                                 gnus-select-method)
2771                                group
2772                              (gnus-group-full-name group (cdr method))))))
2773           (when msg-info
2774             (gnus-summary-read-group qname nil t)
2775             (gnus-summary-goto-article message nil t))
2776           (throw 'method-found t)))
2777        (t (error "Unknown link type"))))))
2779 (eval-after-load 'org-gnus
2780   '(progn
2781      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
2782      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
2783 #+end_src
2785 ** Store link to a message when sending in Gnus
2786 #+index: Link!Store link to a message when sending in Gnus
2787 Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):
2789 #+begin_src emacs-lisp
2790 (defun ulf-message-send-and-org-gnus-store-link (&optional arg)
2791   "Send message with `message-send-and-exit' and store org link to message copy.
2792 If multiple groups appear in the Gcc header, the link refers to
2793 the copy in the last group."
2794   (interactive "P")
2795     (save-excursion
2796       (save-restriction
2797         (message-narrow-to-headers)
2798         (let ((gcc (car (last
2799                          (message-unquote-tokens
2800                           (message-tokenize-header
2801                            (mail-fetch-field "gcc" nil t) " ,")))))
2802               (buf (current-buffer))
2803               (message-kill-buffer-on-exit nil)
2804               id to from subject desc link newsgroup xarchive)
2805         (message-send-and-exit arg)
2806         (or
2807          ;; gcc group found ...
2808          (and gcc
2809               (save-current-buffer
2810                 (progn (set-buffer buf)
2811                        (setq id (org-remove-angle-brackets
2812                                  (mail-fetch-field "Message-ID")))
2813                        (setq to (mail-fetch-field "To"))
2814                        (setq from (mail-fetch-field "From"))
2815                        (setq subject (mail-fetch-field "Subject"))))
2816               (org-store-link-props :type "gnus" :from from :subject subject
2817                                     :message-id id :group gcc :to to)
2818               (setq desc (org-email-link-description))
2819               (setq link (org-gnus-article-link
2820                           gcc newsgroup id xarchive))
2821               (setq org-stored-links
2822                     (cons (list link desc) org-stored-links)))
2823          ;; no gcc group found ...
2824          (message "Can not create Org link: No Gcc header found."))))))
2826 (define-key message-mode-map [(control c) (control meta c)]
2827   'ulf-message-send-and-org-gnus-store-link)
2828 #+end_src
2830 ** Link to visit a file and run occur
2831 #+index: Link!Visit a file and run occur
2832 Add the following bit of code to your startup (after loading org),
2833 and you can then use links like =occur:my-file.txt#regex= to open a
2834 file and run occur with the regex on it.
2836 #+BEGIN_SRC emacs-lisp
2837   (defun org-occur-open (uri)
2838     "Visit the file specified by URI, and run `occur' on the fragment
2839     \(anything after the first '#') in the uri."
2840     (let ((list (split-string uri "#")))
2841       (org-open-file (car list) t)
2842       (occur (mapconcat 'identity (cdr list) "#"))))
2843   (org-add-link-type "occur" 'org-occur-open)
2844 #+END_SRC
2845 ** Send html messages and attachments with Wanderlust
2846   -- David Maus
2848 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
2849 similar functionality for both Wanderlust and Gnus.  The hack below is
2850 still somewhat different: It allows you to toggle sending of html
2851 messages within Wanderlust transparently.  I.e. html markup of the
2852 message body is created right before sending starts.
2854 *** Send HTML message
2856 Putting the code below in your .emacs adds following four functions:
2858 - dmj/wl-send-html-message
2860   Function that does the job: Convert everything between "--text
2861   follows this line--" and first mime entity (read: attachment) or
2862   end of buffer into html markup using `org-export-region-as-html'
2863   and replaces original body with a multipart MIME entity with the
2864   plain text version of body and the html markup version.  Thus a
2865   recipient that prefers html messages can see the html markup,
2866   recipients that prefer or depend on plain text can see the plain
2867   text.
2869   Cannot be called interactively: It is hooked into SEMI's
2870   `mime-edit-translate-hook' if message should be HTML message.
2872 - dmj/wl-send-html-message-draft-init
2874   Cannot be called interactively: It is hooked into WL's
2875   `wl-mail-setup-hook' and provides a buffer local variable to
2876   toggle.
2878 - dmj/wl-send-html-message-draft-maybe
2880   Cannot be called interactively: It is hooked into WL's
2881   `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
2882   `mime-edit-translate-hook' depending on whether HTML message is
2883   toggled on or off
2885 - dmj/wl-send-html-message-toggle
2887   Toggles sending of HTML message.  If toggled on, the letters
2888   "HTML" appear in the mode line.
2890   Call it interactively!  Or bind it to a key in `wl-draft-mode'.
2892 If you have to send HTML messages regularly you can set a global
2893 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
2894 toggle on sending HTML message by default.
2896 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
2897 Google's web front end.  As you can see you have the whole markup of
2898 Org at your service: *bold*, /italics/, tables, lists...
2900 So even if you feel uncomfortable with sending HTML messages at least
2901 you send HTML that looks quite good.
2903 #+begin_src emacs-lisp
2904 (defun dmj/wl-send-html-message ()
2905   "Send message as html message.
2906 Convert body of message to html using
2907   `org-export-region-as-html'."
2908   (require 'org)
2909   (save-excursion
2910     (let (beg end html text)
2911       (goto-char (point-min))
2912       (re-search-forward "^--text follows this line--$")
2913       ;; move to beginning of next line
2914       (beginning-of-line 2)
2915       (setq beg (point))
2916       (if (not (re-search-forward "^--\\[\\[" nil t))
2917           (setq end (point-max))
2918         ;; line up
2919         (end-of-line 0)
2920         (setq end (point)))
2921       ;; grab body
2922       (setq text (buffer-substring-no-properties beg end))
2923       ;; convert to html
2924       (with-temp-buffer
2925         (org-mode)
2926         (insert text)
2927         ;; handle signature
2928         (when (re-search-backward "^-- \n" nil t)
2929           ;; preserve link breaks in signature
2930           (insert "\n#+BEGIN_VERSE\n")
2931           (goto-char (point-max))
2932           (insert "\n#+END_VERSE\n")
2933           ;; grab html
2934           (setq html (org-export-region-as-html
2935                       (point-min) (point-max) t 'string))))
2936       (delete-region beg end)
2937       (insert
2938        (concat
2939         "--" "<<alternative>>-{\n"
2940         "--" "[[text/plain]]\n" text
2941         "--" "[[text/html]]\n"  html
2942         "--" "}-<<alternative>>\n")))))
2944 (defun dmj/wl-send-html-message-toggle ()
2945   "Toggle sending of html message."
2946   (interactive)
2947   (setq dmj/wl-send-html-message-toggled-p
2948         (if dmj/wl-send-html-message-toggled-p
2949             nil "HTML"))
2950   (message "Sending html message toggled %s"
2951            (if dmj/wl-send-html-message-toggled-p
2952                "on" "off")))
2954 (defun dmj/wl-send-html-message-draft-init ()
2955   "Create buffer local settings for maybe sending html message."
2956   (unless (boundp 'dmj/wl-send-html-message-toggled-p)
2957     (setq dmj/wl-send-html-message-toggled-p nil))
2958   (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
2959   (add-to-list 'global-mode-string
2960                '(:eval (if (eq major-mode 'wl-draft-mode)
2961                            dmj/wl-send-html-message-toggled-p))))
2963 (defun dmj/wl-send-html-message-maybe ()
2964   "Maybe send this message as html message.
2966 If buffer local variable `dmj/wl-send-html-message-toggled-p' is
2967 non-nil, add `dmj/wl-send-html-message' to
2968 `mime-edit-translate-hook'."
2969   (if dmj/wl-send-html-message-toggled-p
2970       (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
2971     (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
2973 (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
2974 (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
2975 (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
2976 #+end_src
2978 *** Attach HTML of region or subtree
2980 Instead of sending a complete HTML message you might only send parts
2981 of an Org file as HTML for the poor souls who are plagued with
2982 non-proportional fonts in their mail program that messes up pretty
2983 ASCII tables.
2985 This short function does the trick: It exports region or subtree to
2986 HTML, prefixes it with a MIME entity delimiter and pushes to killring
2987 and clipboard.  If a region is active, it uses the region, the
2988 complete subtree otherwise.
2990 #+begin_src emacs-lisp
2991 (defun dmj/org-export-region-as-html-attachment (beg end arg)
2992   "Export region between BEG and END as html attachment.
2993 If BEG and END are not set, use current subtree.  Region or
2994 subtree is exported to html without header and footer, prefixed
2995 with a mime entity string and pushed to clipboard and killring.
2996 When called with prefix, mime entity is not marked as
2997 attachment."
2998   (interactive "r\nP")
2999   (save-excursion
3000     (let* ((beg (if (region-active-p) (region-beginning)
3001                   (progn
3002                     (org-back-to-heading)
3003                     (point))))
3004            (end (if (region-active-p) (region-end)
3005                   (progn
3006                     (org-end-of-subtree)
3007                     (point))))
3008            (html (concat "--[[text/html"
3009                          (if arg "" "\nContent-Disposition: attachment")
3010                          "]]\n"
3011                          (org-export-region-as-html beg end t 'string))))
3012       (when (fboundp 'x-set-selection)
3013         (ignore-errors (x-set-selection 'PRIMARY html))
3014         (ignore-errors (x-set-selection 'CLIPBOARD html)))
3015       (message "html export done, pushed to kill ring and clipboard"))))
3016 #+end_src
3018 *** Adopting for Gnus
3020 The whole magic lies in the special strings that mark a HTML
3021 attachment.  So you might just have to find out what these special
3022 strings are in message-mode and modify the functions accordingly.
3023 ** Add sunrise/sunset times to the agenda.
3024 #+index: Agenda!Diary s-expressions
3025   -- Nick Dokos
3027 The diary package provides the function =diary-sunrise-sunset= which can be used
3028 in a diary s-expression in some agenda file like this:
3030 #+begin_src org
3031 %%(diary-sunrise-sunset)
3032 #+end_src
3034 Seb Vauban asked if it is possible to put sunrise and sunset in
3035 separate lines. Here is a hack to do that. It adds two functions (they
3036 have to be available before the agenda is shown, so I add them early
3037 in my org-config file which is sourced from .emacs, but you'll have to
3038 suit yourself here) that just parse the output of
3039 diary-sunrise-sunset, instead of doing the right thing which would be
3040 to take advantage of the data structures that diary/solar.el provides.
3041 In short, a hack - so perfectly suited for inclusion here :-)
3043 The functions (and latitude/longitude settings which you have to modify for
3044 your location) are as follows:
3046 #+begin_src emacs-lisp
3047 (setq calendar-latitude 48.2)
3048 (setq calendar-longitude 16.4)
3049 (setq calendar-location-name "Vienna, Austria")
3051 (autoload 'solar-sunrise-sunset "solar.el")
3052 (autoload 'solar-time-string "solar.el")
3053 (defun diary-sunrise ()
3054   "Local time of sunrise as a diary entry.
3055 The diary entry can contain `%s' which will be replaced with
3056 `calendar-location-name'."
3057   (let ((l (solar-sunrise-sunset date)))
3058     (when (car l)
3059       (concat
3060        (if (string= entry "")
3061            "Sunrise"
3062          (format entry (eval calendar-location-name))) " "
3063          (solar-time-string (caar l) nil)))))
3065 (defun diary-sunset ()
3066   "Local time of sunset as a diary entry.
3067 The diary entry can contain `%s' which will be replaced with
3068 `calendar-location-name'."
3069   (let ((l (solar-sunrise-sunset date)))
3070     (when (cadr l)
3071       (concat
3072        (if (string= entry "")
3073            "Sunset"
3074          (format entry (eval calendar-location-name))) " "
3075          (solar-time-string (caadr l) nil)))))
3076 #+end_src
3078 You also need to add a couple of diary s-expressions in one of your agenda
3079 files:
3081 #+begin_src org
3082 %%(diary-sunrise)Sunrise in %s
3083 %%(diary-sunset)
3084 #+end_src
3086 This will show sunrise with the location and sunset without it.
3088 The thread on the mailing list that started this can be found [[https://orgmode.org/list/87oc5rlwc4.wl%lists@700c.org][here]].
3089 In comparison to the version posted on the mailing list, this one
3090 gets rid of the timezone information and can show the location.
3091 ** Add lunar phases to the agenda.
3092 #+index: Agenda!Diary s-expressions
3093    -- Rüdiger
3095 Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
3096 This can be used to display lunar phases in the agenda display with the
3097 following function:
3099 #+begin_src emacs-lisp
3100 (require 'cl-lib)
3102 (org-no-warnings (defvar date))
3103 (defun org-lunar-phases ()
3104   "Show lunar phase in Agenda buffer."
3105   (require 'lunar)
3106   (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
3107          (phase (cl-find-if (lambda (phase) (equal (car phase) date))
3108                             phase-list)))
3109     (when phase
3110       (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
3111                         (substring (nth 1 phase) 0 5))))))
3112 #+end_src
3114 Add the following line to an agenda file:
3116 #+begin_src org
3117 ,* Lunar phase
3118 ,#+CATEGORY: Lunar
3119 %%(org-lunar-phases)
3120 #+end_src
3122 This should display an entry on new moon, first/last quarter moon, and on full
3123 moon.  You can customize the entries by customizing =lunar-phase-names=.
3125 E.g., to add Unicode symbols:
3127 #+begin_src emacs-lisp
3128 (setq lunar-phase-names
3129       '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
3130         "☽ First Quarter Moon"
3131         "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
3132         "☾ Last Quarter Moon"))
3133 #+end_src
3135 Unicode 6 even provides symbols for the Moon with nice faces.  But those
3136 symbols are currently barely supported in fonts.
3137 See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].
3139 ** Export BBDB contacts to org-contacts.el
3140 #+index: Address Book!BBDB to org-contacts
3141 Try this tool by Wes Hardaker:
3143 http://www.hardakers.net/code/bbdb-to-org-contacts/
3145 ** Calculating date differences - how to write a simple elisp function
3146 #+index: Timestamp!date calculations
3147 #+index: Elisp!technique
3149 Alexander Wingård asked how to calculate the number of days between a
3150 time stamp in his org file and today (see
3151 https://orgmode.org/list/064758C1-8D27-4647-A3C2-AB35FB8C6215@gmail.com  Although the
3152 resulting answer is probably not of general interest, the method might
3153 be useful to a budding Elisp programmer.
3155 Alexander started from an already existing org function,
3156 =org-evaluate-time-range=.  When this function is called in the context
3157 of a time range (two time stamps separated by "=--="), it calculates the
3158 number of days between the two dates and outputs the result in Emacs's
3159 echo area. What he wanted was a similar function that, when called from
3160 the context of a single time stamp, would calculate the number of days
3161 between the date in the time stamp and today. The result should go to
3162 the same place: Emacs's echo area.
3164 The solution presented in the mail thread is as follows:
3166 #+begin_src emacs-lisp
3167 (defun aw/org-evaluate-time-range (&optional to-buffer)
3168   (interactive)
3169   (if (org-at-date-range-p t)
3170       (org-evaluate-time-range to-buffer)
3171     ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
3172     (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
3173       (with-temp-buffer
3174         (insert headline)
3175         (goto-char (point-at-bol))
3176         (re-search-forward org-ts-regexp (point-at-eol) t)
3177         (if (not (org-at-timestamp-p t))
3178             (error "No timestamp here"))
3179         (goto-char (match-beginning 0))
3180         (org-insert-time-stamp (current-time) nil nil)
3181         (insert "--")
3182         (org-evaluate-time-range to-buffer)))))
3183 #+end_src
3185 The function assumes that point is on some line with some time stamp
3186 (or a date range) in it. Note that =org-evaluate-time-range= does not care
3187 whether the first date is earlier than the second: it will always output
3188 the number of days between the earlier date and the later date.
3190 As stated before, the function itself is of limited interest (although
3191 it satisfied Alexander's need).The *method* used might be of wider
3192 interest however, so here is a short explanation.
3194 The idea is that we want =org-evaluate-time-range= to do all the
3195 heavy lifting, but that function requires that it be in a date-range
3196 context. So the function first checks whether it's in a date range
3197 context already: if so, it calls =org-evaluate-time-range= directly
3198 to do the work. The trick now is to arrange things so we can call this
3199 same function in the case where we do *not* have a date range
3200 context. In that case, we manufacture one: we create a temporary
3201 buffer, copy the line with the purported time stamp to the temp
3202 buffer, find the time stamp (signal an error if no time stamp is
3203 found) and insert a new time stamp with the current time before the
3204 existing time stamp, followed by "=--=": voilà, we now have a time range
3205 on which we can apply our old friend =org-evaluate-time-range= to
3206 produce the answer. Because of the above-mentioned property
3207 of =org-evaluate-time-range=, it does not matter if the existing
3208 time stamp is earlier or later than the current time: the correct
3209 number of days is output.
3211 Note that at the end of the call to =with-temp-buffer=, the temporary
3212 buffer goes away.  It was just used as a scratch pad for the function
3213 to do some figuring.
3215 The idea of using a temp buffer as a scratch pad has wide
3216 applicability in Emacs programming. The rest of the work is knowing
3217 enough about facilities provided by Emacs (e.g. regexp searching) and
3218 by Org (e.g. checking for time stamps and generating a time stamp) so
3219 that you don't reinvent the wheel, and impedance-matching between the
3220 various pieces.
3222 ** ibuffer and org files
3224 Neil Smithline posted this snippet to let you browse org files with
3225 =ibuffer=:
3227 #+BEGIN_SRC emacs-lisp
3228 (require 'ibuffer)
3230 (defun org-ibuffer ()
3231   "Open an `ibuffer' window showing only `org-mode' buffers."
3232   (interactive)
3233   (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
3234 #+END_SRC
3236 ** Enable org-mode links in other modes
3238 Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].
3240 See the relevant discussion [[https://orgmode.org/list/CAOXM+eX-xkGu4B8c=9RLQ+959Sn050wtqSHO2fqhFQX4X5c53A@mail.gmail.com][here]].
3242 ** poporg.el: edit comments in org-mode
3244 [[https://github.com/QBobWatson/poporg/blob/master/poporg.el][poporg.el]] is a library by François Pinard which lets you edit comments
3245 and strings from your code using a separate org-mode buffer.
3247 ** Convert a .csv file to an Org-mode table
3249 Nicolas Richard has a [[https://orgmode.org/list/87a9rpy1x2.fsf@yahoo.fr][nice recipe]] using the pcsv library ([[http://marmalade-repo.org/packages/pcsv][available]] from
3250 the Marmelade ELPA repository):
3252 #+BEGIN_SRC emacs-lisp
3253 (defun yf/lisp-table-to-org-table (table &optional function)
3254   "Convert a lisp table to `org-mode' syntax, applying FUNCTION to each of its elements.
3255 The elements should not have any more newlines in them after
3256 applying FUNCTION ; the default converts them to spaces. Return
3257 value is a string containg the unaligned `org-mode' table."
3258   (unless (functionp function)
3259     (setq function (lambda (x) (replace-regexp-in-string "\n" " " x))))
3260   (mapconcat (lambda (x)                ; x is a line.
3261                (concat "| " (mapconcat function x " | ") " |"))
3262              table "\n"))
3264 (defun yf/csv-to-table (beg end)
3265 "Convert a csv file to an `org-mode' table."
3266   (interactive "r")
3267   (require 'pcsv)
3268   (insert (yf/lisp-table-to-org-table (pcsv-parse-region beg end)))
3269   (delete-region beg end)
3270   (org-table-align))
3271 #+END_SRC
3273 ** Don't let visual-line-mode shadow org special commands
3275 =M-x visual-line-mode RET= will use ~beginning-of-visual-line~,
3276 ~end-of-visual-line~, and ~kill-visual-line~ instead of
3277 ~org-beginning-of-line~, ~org-end-of-line~, and ~org-kill-line~, while 
3278 those might be preferred in an Org buffer.
3280 To avoid this, you can use this hack:
3282 #+begin_src emacs-lisp
3283 (add-hook 'visual-line-mode-hook
3284           (lambda () (when (derived-mode-p 'org-mode)
3285                        (local-set-key (kbd "C-a") #'org-beginning-of-line)
3286                        (local-set-key (kbd "C-e") #'org-end-of-line)
3287                        (local-set-key (kbd "C-k") #'org-kill-line))))
3288 #+end_src
3290 See [[https://orgmode.org/list/87zh7jfyal.fsf@gmail.com/][this discussion]].
3292 ** foldout.el
3294 ~foldout.el~, which is part of Emacs, is a nice little companion for
3295 ~outline-mode~.  With ~foldout.el~ one can narrow to a subtree and
3296 later unnarrow.  ~foldout.el~ is useful for Org mode out of the box.
3298 There is one annoyance though (at least for me):
3299 ~foldout-zoom-subtree~ opens the drawers.
3301 This can be fixed e.g. by using the following slightly modified
3302 version of ~foldout-zoom-subtree~ which uses function ~org-show-entry~
3303 instead of ~outline-show-entry~.
3305 #+begin_src emacs-lisp
3306 (defun foldout-zoom-org-subtree (&optional exposure)
3307   "Same as `foldout-zoom-subtree' with often nicer zoom in Org mode."
3308   (interactive "P")
3309   (cl-letf
3310       (((symbol-function #'outline-show-entry) (lambda () (org-show-entry))))
3311     (foldout-zoom-subtree exposure)))
3312 #+end_src
3313 ** Integrate Org Capture with YASnippet and Yankpad
3315 Org Capture allows you to quickly store a note. You can mix the Org
3316 Capture template system with those of [[https://github.com/joaotavora/yasnippet][YASnippet]] and [[https://github.com/Kungsgeten/yankpad][Yankpad]].
3318 Check out the repository for how to do it: https://github.com/ag91/ya-org-capture.
3320 A screencast that show the hack in action is [[https://github.com/ag91/ya-org-capture/blob/master/ya-org-capture-screehcast.gif][here]]. And a blog post
3321 describing this in more detail is [[https://ag91.github.io/blog/2020/07/28/how-to-integrate-yasnippet-and-yankpad-with-org-capture/][here]].
3323 ** Slack messages as TODOs in your Org Agenda
3325 Too many Slack messages reach you? Keep track of them in your Org
3326 Agenda! With this hack you can mix the power of the [[https://github.com/yuya373/emacs-slack][Emacs Slack]] client
3327 and the order of Org mode.
3329 Try this by running the code at:
3330 https://github.com/ag91/emacs-slack-org-mode-example
3332 Also a blog post that describes in detail how this works is [[https://ag91.github.io/blog/2020/08/14/slack-messages-in-your-org-agenda/][here]].
3334 * Hacking Org: Working with Org-mode and External Programs
3335 ** Use Org-mode with Screen [Andrew Hyatt]
3336 #+index: Link!to screen session
3337 "The general idea is that you start a task in which all the work will
3338 take place in a shell.  This usually is not a leaf-task for me, but
3339 usually the parent of a leaf task.  From a task in your org-file, M-x
3340 ash-org-screen will prompt for the name of a session.  Give it a name,
3341 and it will insert a link.  Open the link at any time to go the screen
3342 session containing your work!"
3344 https://orgmode.org/list/c8389b600801271541h4c68e70du589547ea5e8bd52f@mail.gmail.com
3346 #+BEGIN_SRC emacs-lisp
3347 (require 'term)
3349 (defun ash-org-goto-screen (name)
3350   "Open the screen with the specified name in the window"
3351   (interactive "MScreen name: ")
3352   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
3353     (if (member screen-buffer-name
3354                 (mapcar 'buffer-name (buffer-list)))
3355         (switch-to-buffer screen-buffer-name)
3356       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
3358 (defun ash-org-screen-buffer-name (name)
3359   "Returns the buffer name corresponding to the screen name given."
3360   (concat "*screen " name "*"))
3362 (defun ash-org-screen-helper (name arg)
3363   ;; Pick the name of the new buffer.
3364   (let ((term-ansi-buffer-name
3365          (generate-new-buffer-name
3366           (ash-org-screen-buffer-name name))))
3367     (setq term-ansi-buffer-name
3368           (term-ansi-make-term
3369            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
3370     (set-buffer term-ansi-buffer-name)
3371     (term-mode)
3372     (term-char-mode)
3373     (term-set-escape-char ?\C-x)
3374     term-ansi-buffer-name))
3376 (defun ash-org-screen (name)
3377   "Start a screen session with name"
3378   (interactive "MScreen name: ")
3379   (save-excursion
3380     (ash-org-screen-helper name "-S"))
3381   (insert-string (concat "[[screen:" name "]]")))
3383 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
3384 ;; \"%s\")") to org-link-abbrev-alist.
3385 #+END_SRC
3387 ** Org Agenda + Appt + Zenity
3388     :PROPERTIES:
3389     :CUSTOM_ID: org-agenda-appt-zenity
3390     :END:
3392 #+index: Appointment!reminders
3393 #+index: Appt!Zenity
3394 #+BEGIN_EXPORT HTML
3395 <a name="agenda-appt-zenity"></a>
3396 #+END_EXPORT
3397 Russell Adams posted this setup [[https://orgmode.org/list/20080302101346.GB18852@odin.demosthenes.org][on the list]].  It makes sure your agenda
3398 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
3399 popup window.
3401 #+BEGIN_SRC emacs-lisp
3402 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3403 ; For org appointment reminders
3405 ;; Get appointments for today
3406 (defun my-org-agenda-to-appt ()
3407   (interactive)
3408   (setq appt-time-msg-list nil)
3409   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
3410         (org-agenda-to-appt)))
3412 ;; Run once, activate and schedule refresh
3413 (my-org-agenda-to-appt)
3414 (appt-activate t)
3415 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
3417 ; 5 minute warnings
3418 (setq appt-message-warning-time 15)
3419 (setq appt-display-interval 5)
3421 ; Update appt each time agenda opened.
3422 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
3424 ; Setup zenify, we tell appt to use window, and replace default function
3425 (setq appt-display-format 'window)
3426 (setq appt-disp-window-function (function my-appt-disp-window))
3428 (defun my-appt-disp-window (min-to-app new-time msg)
3429   (save-window-excursion (shell-command (concat
3430     "/usr/bin/zenity --info --title='Appointment' --text='"
3431     msg "' &") nil nil)))
3432 #+END_SRC
3434 ** Org and appointment notifications on Mac OS 10.8
3436 Sarah Bagby [[http://mid.gmane.org/EA76104A-9ACD-4141-8D33-2E4D810D9B5A@geol.ucsb.edu][posted some code]] on how to get appointments notifications on
3437 Mac OS 10.8 with [[https://github.com/alloy/terminal-notifier][terminal-notifier]].
3439 ** Org-Mode + gnome-osd
3440 #+index: Appointment!reminders
3441 #+index: Appt!gnome-osd
3442 Richard Riley uses gnome-osd in interaction with Org-Mode to display
3443 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
3445 ** txt2org convert text data to org-mode tables
3446 From Eric Schulte
3448 I often find it useful to generate Org-mode tables on the command line
3449 from tab-separated data.  The following awk script makes this easy to
3450 do.  Text data is read from STDIN on a pipe and any command line
3451 arguments are interpreted as rows at which to insert hlines.
3453 Here are two usage examples.
3454 1. running the following
3455    : $ cat <<EOF|~/src/config/bin/txt2org
3456    : one 1
3457    : two 2
3458    : three 3
3459    : twenty 20
3460    : EOF
3461    results in
3462    : |    one |  1 |
3463    : |    two |  2 |
3464    : |  three |  3 |
3465    : | twenty | 20 |
3467 2. and the following (notice the command line argument)
3468    : $ cat <<EOF|~/src/config/bin/txt2org 1
3469    : strings numbers
3470    : one 1
3471    : two 2
3472    : three 3
3473    : twenty 20
3474    : EOF
3475    results in
3476    : | strings | numbers |
3477    : |---------+---------|
3478    : |     one |       1 |
3479    : |     two |       2 |
3480    : |   three |       3 |
3481    : |  twenty |      20 |
3483 Here is the script itself
3484 #+begin_src awk
3485   #!/usr/bin/gawk -f
3486   #
3487   # Read tab separated data from STDIN and output an Org-mode table.
3488   #
3489   # Optional command line arguments specify row numbers at which to
3490   # insert hlines.
3491   #
3492   BEGIN {
3493       for(i=1; i<ARGC; i++){
3494           hlines[ARGV[i]+1]=1; ARGV[i] = "-"; } }
3496   {
3497       if(NF > max_nf){ max_nf = NF; };
3498       for(f=1; f<=NF; f++){
3499           if(length($f) > lengths[f]){ lengths[f] = length($f); };
3500           row[NR][f]=$f; } }
3502   END {
3503       hline_str="|"
3504       for(f=1; f<=max_nf; f++){
3505           for(i=0; i<(lengths[f] + 2); i++){ hline_str=hline_str "-"; }
3506           if( f != max_nf){ hline_str=hline_str "+"; }
3507           else            { hline_str=hline_str "|"; } }
3509       for(r=1; r<=NR; r++){ # rows
3510           if(hlines[r] == 1){ print hline_str; }
3511           printf "|";
3512           for(f=1; f<=max_nf; f++){ # columns
3513               cell=row[r][f]; padding=""
3514               for(i=0; i<(lengths[f] - length(cell)); i++){ padding=padding " "; }
3515               # for now just print everything right-aligned
3516               # if(cell ~ /[0-9.]/){ printf " %s%s |", cell, padding; }
3517               # else{                printf " %s%s |", padding, cell; }
3518               printf " %s%s |", padding, cell; }
3519           printf "\n"; }
3521       if(hlines[NR+1]){ print hline_str; } }
3522 #+end_src
3524 ** remind2org
3525 #+index: Agenda!Views
3526 #+index: Agenda!and Remind (external program)
3527 From Detlef Steuer
3529 https://orgmode.org/list/20080112175502.0fb06b66@linux.site
3531 #+BEGIN_QUOTE
3532 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
3533 command line calendaring program. Its features supersede the possibilities
3534 of orgmode in the area of date specifying, so that I want to use it
3535 combined with orgmode.
3537 Using the script below I'm able use remind and incorporate its output in my
3538 agenda views.  The default of using 13 months look ahead is easily
3539 changed. It just happens I sometimes like to look a year into the
3540 future. :-)
3541 #+END_QUOTE
3543 ** Useful webjumps for conkeror
3544 #+index: Shortcuts!conkeror
3545 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
3546 your =~/.conkerorrc= file:
3548 #+begin_example
3549 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
3550 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
3551 #+end_example
3553 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
3554 Org-mode mailing list.
3556 ** Use MathJax for HTML export without requiring JavaScript
3557 #+index: Export!MathJax
3558 As of 2010-08-14, MathJax is the default method used to export math to HTML.
3560 If you like the results but do not want JavaScript in the exported pages,
3561 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
3562 HTML file from the exported version. It can also embed all referenced fonts
3563 within the HTML file itself, so there are no dependencies to external files.
3565 The download archive contains an elisp file which integrates it into the Org
3566 export process (configurable per file with a "#+StaticMathJax:" line).
3568 Read README.org and the comments in org-static-mathjax.el for usage instructions.
3570 ** Use checkboxes and progress cookies in HTML generated from Org
3571 #+index: Export!HTML!Checkboxes
3572 If you want to have dynamically-updated progress cookies for lists
3573 with checkboxes in an HTML document exported from Org, [[https://lists.gnu.org/archive/html/emacs-orgmode/2020-06/msg00323.html][this mailing
3574 list thread]] contains a (partial) Javascript solution.
3576 Note that the Javascript depends on the default HTML structure
3577 generated by Org at the time (the maint branch somewhere between 9.3
3578 and 9.4), so the code won't work without modification if you customize
3579 HTML output or if Org's default HTML export changes.
3581 ** Search Org files using lgrep
3582 #+index: search!lgrep
3583 Matt Lundin suggests this:
3585 #+begin_src emacs-lisp
3586   (defun my-org-grep (search &optional context)
3587     "Search for word in org files.
3589 Prefix argument determines number of lines."
3590     (interactive "sSearch for: \nP")
3591     (let ((grep-find-ignored-files '("#*" ".#*"))
3592           (grep-template (concat "grep <X> -i -nH "
3593                                  (when context
3594                                    (concat "-C" (number-to-string context)))
3595                                  " -e <R> <F>")))
3596       (lgrep search "*org*" "/home/matt/org/")))
3598   (global-set-key (kbd "<f8>") 'my-org-grep)
3599 #+end_src
3601 ** Automatic screenshot insertion
3602 #+index: Link!screenshot
3603 Suggested by Russell Adams
3605 #+begin_src emacs-lisp
3606   (defun my-org-screenshot ()
3607     "Take a screenshot into a time stamped unique-named file in the
3608   same directory as the org-buffer and insert a link to this file."
3609     (interactive)
3610     (setq filename
3611           (concat
3612            (make-temp-name
3613             (concat (buffer-file-name)
3614                     "_"
3615                     (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
3616     (call-process "import" nil nil nil filename)
3617     (insert (concat "[[" filename "]]"))
3618     (org-display-inline-images))
3619 #+end_src
3621 ** Capture invitations/appointments from MS Exchange emails
3622 #+index: Appointment!MS Exchange
3623 Dirk-Jan C.Binnema [[https://orgmode.org/list/20100718104515.4C21039C72A@djcbsoftware.nl][provided]] code to do this.  Please check
3624 [[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]
3626 ** Audio/video file playback within org mode
3627 #+index: Link!audio/video
3628 Paul Sexton provided code that makes =file:= links to audio or video files
3629 (MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
3630 media player library. The user can pause, skip forward and backward in the
3631 track, and so on from without leaving Emacs. Links can also contain a time
3632 after a double colon -- when this is present, playback will begin at that
3633 position in the track.
3635 See the file [[file:code/elisp/org-player.el][org-player.el]]
3637 ** Under X11 Keep a window with the current agenda items at all time
3638 #+index: Agenda!dedicated window
3639 I struggle to keep (in emacs) a window with the agenda at all times.
3640 For a long time I have wanted a sticky window that keeps this
3641 information, and then use my window manager to place it and remove its
3642 decorations (I can also force its placement in the stack: top always,
3643 for example).
3645 I wrote a small program in qt that simply monitors an HTML file and
3646 displays it. Nothing more. It does the work for me, and maybe somebody
3647 else will find it useful. It relies on exporting the agenda as HTML
3648 every time the org file is saved, and then this little program
3649 displays the html file. The window manager is responsible of removing
3650 decorations, making it sticky, and placing it in same place always.
3652 Here is a screenshot (see window to the bottom right). The decorations
3653 are removed by the window manager:
3655 http://turingmachine.org/hacking/org-mode/orgdisplay.png
3657 Here is the code. As I said, very, very simple, but maybe somebody will
3658 find if useful.
3660 http://turingmachine.org/hacking/org-mode/
3662 --daniel german
3664 ** Script (thru procmail) to output emails to an Org file
3665 #+index: Conversion!email to org file
3666 Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:
3668 : I've [...] created some procmail and shell glue that takes emails and
3669 : inserts them into an org-file so that I can capture stuff on the go using
3670 : the email program.
3672 Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3674 ** Save File With Different Format for Headings (fileconversion)
3675    :PROPERTIES:
3676    :CUSTOM_ID: fileconversion
3677    :END:
3678 #+index: Conversion!fileconversion
3680 Using hooks and on the fly
3681 - When writing a buffer to the file: Replace the leading stars from
3682   headings with a file char.
3683 - When reading a file into the buffer: Replace the file chars with
3684   leading stars for headings.
3686 To change the file format just add or remove the keyword in the
3687 ~#+STARTUP:~ line in the Org buffer and save.
3689 Now you can also change to Fundamental mode to see how the file looks
3690 like on the level of the file, can go back to Org mode, reenter Org
3691 mode or change to any other major mode and the conversion gets done
3692 whenever necessary.
3694 *** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
3695     :PROPERTIES:
3696     :CUSTOM_ID: hidestarsfile
3697     :END:
3698 #+index: Conversion!fileconversion hidestarsfile
3700 This is like "a cleaner outline view":
3701 https://orgmode.org/manual/Clean-view.html
3703 Example of the *file content* first with leading stars as usual and
3704 below without leading stars through ~#+STARTUP: odd hidestars
3705 hidestarsfile~:
3707 #+BEGIN_SRC org
3708   ,#+STARTUP: odd hidestars
3709   [...]
3710   ***** TODO section
3711   ******* subsection
3712   ********* subsubsec
3713             - bla bla
3714   ***** section
3715         - bla bla
3716   ******* subsection
3717 #+END_SRC
3719 #+BEGIN_SRC org
3720   ,#+STARTUP: odd hidestars hidestarsfile
3721   [...]
3722       * TODO section
3723         * subsection
3724           * subsubsec
3725             - bla bla
3726       * section
3727         - bla bla
3728         * subsection
3729 #+END_SRC
3731 The latter is convenient for better human readability when an Org file,
3732 additionally to Emacs, is read with a file viewer or, for smaller edits,
3733 with an editor not capable of the Org file format.
3735 ~hidestarsfile~ is a hack and can not become part of the Org core:
3736 - An Org file with ~hidestarsfile~ can not contain list items with a
3737   star as bullet due to the syntax conflict at read time. Mark
3738   E. Shoulson suggested to use the non-breaking space which is now
3739   implemented in fileconversion as ~nbspstarsfile~ as an alternative
3740   for ~hidestarsfile~. Although I don't recommend it because an editor
3741   like typically e. g. Emacs may render the non-breaking space
3742   differently from the space ~0x20~.
3743 - An Org file with ~hidestarsfile~ can almost not be edited with an
3744   Org mode without added functionality of hidestarsfile as long as the
3745   file is not converted back.
3747 *** Headings in Markdown Format (markdownstarsfile)
3748     :PROPERTIES:
3749     :CUSTOM_ID: markdownstarsfile
3750     :END:
3751 #+index: Conversion!fileconversion markdownstarsfile
3753 Together with ~oddeven~ you can use ~markdownstarsfile~ to be readable
3754 or even basically editable with Markdown (does not make much sense
3755 with ~odd~, see ~org-convert-to-odd-levels~ and
3756 ~org-convert-to-oddeven-levels~ for how to convert).
3758 Example of the *file content*:
3760 #+BEGIN_SRC org
3761   ,#+STARTUP: oddeven markdownstarsfile
3762   # section level 1
3763     1. first item of numbered list (same format in Org and Markdown)
3764   ## section level 2
3765      - first item of unordered list (same format in Org and Markdown)
3766   ### section level 3
3767       + first item of unordered list (same format in Org and Markdown)
3768   #### section level 4
3769        * first item of unordered list (same format in Org and Markdown)
3770        * avoid this item type to be compatible with Org hidestarsfile
3771 #+END_SRC
3773 An Org file with ~markdownstarsfile~ can not contain code comment
3774 lines prefixed with ~#~, even not when within source blocks.
3776 *** emacs-lisp code
3777     :PROPERTIES:
3778     :CUSTOM_ID: fileconversion-code
3779     :END:
3780 #+index: Conversion!fileconversion emacs-lisp code
3782 #+BEGIN_SRC emacs-lisp
3783   ;; - fileconversion version 0.10
3784   ;; - DISCLAIMER: Make a backup of your Org files before trying
3785   ;;   `f-org-fileconv-*'. It is recommended to use a version control
3786   ;;   system like git and to review and commit the changes in the Org
3787   ;;   files regularly.
3788   ;; - Supported "#+STARTUP:" formats: "hidestarsfile",
3789   ;;   "nbspstarsfile", "markdownstarsfile".
3791   ;; Design summary: fileconversion is a round robin of two states linked by
3792   ;; two actions:
3793   ;; - State `v-org-fileconv-level-org-p' is nil: The level is "file"
3794   ;;   (encoded).
3795   ;; - Action `f-org-fileconv-decode': Replace file char with "*".
3796   ;; - State `v-org-fileconv-level-org-p' is non-nil: The level is "Org"
3797   ;;   (decoded).
3798   ;; - Action `f-org-fileconv-encode': Replace "*" with file char.
3799   ;;
3800   ;; Naming convention of prefix:
3801   ;; - f-[...]: "my function", instead of the unspecific prefix `my-*'.
3802   ;; - v-[...]: "my variable", instead of the unspecific prefix `my-*'.
3804   (defvar v-org-fileconv-level-org-p nil
3805     "Whether level of buffer is Org or only file.
3806   nil: level is file (encoded), non-nil: level is Org (decoded).")
3807   (make-variable-buffer-local 'v-org-fileconv-level-org-p)
3808   ;; Survive a change of major mode that does `kill-all-local-variables', e.
3809   ;; g. when reentering Org mode through "C-c C-c" on a #+STARTUP: line.
3810   (put 'v-org-fileconv-level-org-p 'permanent-local t)
3812   ;; * Callback `f-org-fileconv-org-mode-beg' before `org-mode'
3813   (defadvice org-mode (before org-mode-advice-before-fileconv)
3814     (f-org-fileconv-org-mode-beg))
3815   (ad-activate 'org-mode)
3816   (defun f-org-fileconv-org-mode-beg ()
3817     ;; - Reason to test `buffer-file-name': Only when converting really
3818     ;;   from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3819     ;;   file.
3820     ;; - No `message' to not wipe a possible "File mode specification error:".
3821     ;; - `f-org-fileconv-decode' in org-mode-hook would be too late for
3822     ;;   performance reasons, see
3823     ;;   http://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00920.html
3824     (when (buffer-file-name) (f-org-fileconv-decode)))
3826   ;; * Callback `f-org-fileconv-org-mode-end' after `org-mode'
3827   (add-hook 'org-mode-hook 'f-org-fileconv-org-mode-end
3828             nil   ; _Prepend_ to hook to have it first.
3829             nil)  ; Hook addition global.
3830   (defun f-org-fileconv-org-mode-end ()
3831     ;; - Reason to test `buffer-file-name': only when converting really
3832     ;;   from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
3833     ;;   file.
3834     ;; - No `message' to not wipe a possible "File mode specification error:".
3835     (when (buffer-file-name)
3836       ;; - Adding this to `change-major-mode-hook' or "defadvice before" of
3837       ;;   org-mode would be too early and already trigger during find-file.
3838       ;; - Argument 4: t to limit hook addition to buffer locally, this way
3839       ;;   and as required the hook addition will disappear when the major
3840       ;;   mode of the buffer changes.
3841       (add-hook 'change-major-mode-hook 'f-org-fileconv-encode nil t)
3842       (add-hook 'before-save-hook       'f-org-fileconv-encode nil t)
3843       (add-hook 'after-save-hook        'f-org-fileconv-decode nil t)))
3845   (defun f-org-fileconv-re ()
3846     "Check whether there is a #+STARTUP: line for fileconversion.
3847   If found then return the expressions required for the conversion."
3848     (save-excursion
3849       (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3850       (let (re-list (count 0))
3851         (while (re-search-forward "^[ \t]*#\\+STARTUP:" nil t)
3852           ;; #+STARTUP: hidestarsfile
3853           (when (string-match-p "\\bhidestarsfile\\b" (thing-at-point 'line))
3854             ;; Exclude e. g.:
3855             ;; - Line starting with star for bold emphasis.
3856             ;; - Line of stars to underline section title in loosely quoted
3857             ;;   ASCII style (star at end of line).
3858             (setq re-list '("\\(\\* \\)"  ; common-re
3859                             ?\ ))         ; file-char
3860             (setq count (1+ count)))
3861           ;; #+STARTUP: nbspstarsfile
3862           (when (string-match-p "\\bnbspstarsfile\\b" (thing-at-point 'line))
3863             (setq re-list '("\\(\\* \\)"  ; common-re
3864                             ?\xa0))       ; file-char non-breaking space
3865             (setq count (1+ count)))
3866           ;; #+STARTUP: markdownstarsfile
3867           (when (string-match-p "\\bmarkdownstarsfile\\b"
3868                                 (thing-at-point 'line))
3869             ;; Exclude e. g. "#STARTUP:".
3870             (setq re-list '("\\( \\)"  ; common-re
3871                             ?#))       ; file-char
3872             (setq count (1+ count))))
3873         (when (> count 1) (error "More than one fileconversion found."))
3874         re-list)))
3876   (defun f-org-fileconv-decode ()
3877     "In headings replace file char with '*'."
3878     (let ((re-list (f-org-fileconv-re)))
3879       (when (and re-list (not v-org-fileconv-level-org-p))
3880         ;; No `save-excursion' to be able to keep point in case of error.
3881         (let* ((common-re (nth 0 re-list))
3882                (file-char (nth 1 re-list))
3883                (file-re   (concat "^" (string file-char) "+" common-re))
3884                (org-re    (concat "^\\*+" common-re))
3885                len
3886                (p         (point)))
3887           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3888           ;; Syntax check.
3889           (when (re-search-forward org-re nil t)
3890             (goto-char (match-beginning 0))
3891             (org-reveal)
3892             (error "Org fileconversion decode: Syntax conflict at point."))
3893           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3894           ;; Substitution.
3895           (with-silent-modifications
3896             (while (re-search-forward file-re nil t)
3897               (goto-char (match-beginning 0))
3898               ;; Faster than a lisp call of insert and delete on each single
3899               ;; char.
3900               (setq len (- (match-beginning 1) (match-beginning 0)))
3901               (insert-char ?* len)
3902               (delete-char len)))
3903           (goto-char p))))
3905           ;; Notes for ediff when only one file has fileconversion:
3906           ;; - The changes to the buffer with fileconversion until here are
3907           ;;   not regarded by `ediff-files' because the first call to diff is
3908           ;;   made with the bare files directly. Only `ediff-update-diffs'
3909           ;;   and `ediff-buffers' write the decoded buffers to temp files and
3910           ;;   then call diff with them.
3911           ;; - Workarounds (choose one):
3912           ;;   - After ediff-files first do a "!" (ediff-update-diffs) in the
3913           ;;     "*Ediff Control Panel*".
3914           ;;   - Instead of using `ediff-files' first open the files and then
3915           ;;     run `ediff-buffers' (better for e. g. a script that takes two
3916           ;;     files as arguments and uses "emacs --eval").
3918     ;; The level is Org most of all when no fileconversion is in effect.
3919     (setq v-org-fileconv-level-org-p t))
3921   (defun f-org-fileconv-encode ()
3922     "In headings replace '*' with file char."
3923     (let ((re-list (f-org-fileconv-re)))
3924       (when (and re-list v-org-fileconv-level-org-p)
3925         ;; No `save-excursion' to be able to keep point in case of error.
3926         (let* ((common-re (nth 0 re-list))
3927                (file-char (nth 1 re-list))
3928                (file-re   (concat "^" (string file-char) "+" common-re))
3929                (org-re    (concat "^\\*+" common-re))
3930                len
3931                (p         (point)))
3932           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3933           ;; Syntax check.
3934           (when (re-search-forward file-re nil t)
3935             (goto-char (match-beginning 0))
3936             (org-reveal)
3937             (error "Org fileconversion encode: Syntax conflict at point."))
3938           (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
3939           ;; Substitution.
3940           (with-silent-modifications
3941             (while (re-search-forward org-re nil t)
3942               (goto-char (match-beginning 0))
3943               ;; Faster than a lisp call of insert and delete on each single
3944               ;; char.
3945               (setq len (- (match-beginning 1) (match-beginning 0)))
3946               (insert-char file-char len)
3947               (delete-char len)))
3948           (goto-char p)
3949           (setq v-org-fileconv-level-org-p nil))))
3950     nil)  ; For the hook.
3951 #+END_SRC
3953 Michael Brand
3955 ** Meaningful diff for org files in a git repository
3956 #+index: git!diff org files
3957 Since most diff utilities are primarily meant for source code, it is
3958 difficult to read diffs of text files like ~.org~ files easily. If you
3959 version your org directory with a SCM like git you will know what I
3960 mean. However for git, there is a way around. You can use
3961 =gitattributes= to define a custom diff driver for org files. Then a
3962 regular expression can be used to configure how the diff driver
3963 recognises a "function".
3965 Put the following in your =<org_dir>/.gitattributes=.
3966 : *.org diff=org
3967 Then put the following lines in =<org_dir>/.git/config=
3968 : [diff "org"]
3969 :       xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
3971 This will let you see diffs for org files with each hunk identified by
3972 the unmodified headline closest to the changes. After the
3973 configuration a diff should look something like the example below.
3975 #+begin_example
3976 diff --git a/org-hacks.org b/org-hacks.org
3977 index a0672ea..92a08f7 100644
3978 --- a/org-hacks.org
3979 +++ b/org-hacks.org
3980 @@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file
3982  Everything is documented [[http://tychoish.com/code/org-mail/][here]].
3984 +** Meaningful diff for org files in a git repository
3986 +Since most diff utilities are primarily meant for source code, it is
3987 +difficult to read diffs of text files like ~.org~ files easily. If you
3988 +version your org directory with a SCM like git you will know what I
3989 +mean. However for git, there is a way around. You can use
3990 +=gitattributes= to define a custom diff driver for org files. Then a
3991 +regular expression can be used to configure how the diff driver
3992 +recognises a "function".
3994 +Put the following in your =<org_dir>/.gitattributes=.
3995 +: *.org        diff=org
3996 +Then put the following lines in =<org_dir>/.git/config=
3997 +: [diff "org"]
3998 +:      xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
4000  * Musings
4002  ** Cooking?  Brewing?
4003 #+end_example
4005 ** Opening devonthink links
4007 John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
4008 links from org-mode.
4010 ** Memacs - Org-mode collecting meta-data from the disk and cloud
4012 Karl Voit designed Memacs ([[https://en.wikipedia.org/wiki/Memex][Memex]] and Emacs) which is a collection of
4013 modules that are able to get meta-data from different kind of
4014 sources. Memacs then generates output files containing meta-data in
4015 Org-mode format. Those files a most likely integrated as ~*.org_archive~
4016 files in your agenda.
4018 This way, you can get a pretty decent overview of your (digital) life:
4019 - file name timestamps ([[https://en.wikipedia.org/wiki/Iso_date][ISO 8601]]; like "2013-10-11 Product Demonstration.odp")
4020 - emails (IMAP, POP, Maildir, mbox)
4021 - RSS feeds (blog updates, ... *lots* of possibilities there!)
4022 - version system commits (SVN, git)
4023 - calendar (iCal, CSV)
4024 - text messages from your phone (Android)
4025 - phone calls (Android)
4026 - photographs (EXIF)
4027 - bank accounts ([[http://easybank.at][easybank]])
4028 - usenet postings (slrn, mbox, ...)
4029 - XML (a sub-set of easy-to-parse XML files can be parsed with minimal
4030   effort)
4032 General idea: you set up the module(s) you would like to use once and
4033 they are running in the background. As long as the data source does
4034 not change, you should not have to worry about the module again.
4036 It is hard to explain the vast amount of (small) benefits you get once
4037 you have set up your Memacs modules.
4039 There is [[http://arxiv.org/abs/1304.1332][a whitepaper which describes Memacs]] and its implications.
4041 Memacs is [[https://github.com/novoid/Memacs][hosted on github]] and is written in Python.
4043 You can use Memacs to write your own Memacs module: an example module
4044 demonstrates how to write modules with very low effort. Please
4045 consider a pull request on github so that other people can use your
4046 module as well!
4048 [[https://github.com/novoid/twitter-json_to_orgmode][Twitter JSON to Org-mode]] generates Memacs-like output files for
4049 [[https://blog.twitter.com/2012/your-twitter-archive][Twitter export archives]] (JSON) but is independent of Memacs.
4051 ** Displaying Vega and Vega lite graphs with org
4053 See [[https://github.com/vladkotu/vladkotu.github.io/blob/source/blog/org-clj-plot/clj-plot.org#vega-vega-lite-wrappers][this example]].
4055 ** Emacs as an Org capture server
4057 #+begin_quote
4058 The general idea is to run an Emacs server as a daemon which clients
4059 can quickly connect to via a bash script. The client executes
4060 org-capture and the frame closes upon finalizing or aborting the
4061 capture.
4062 #+end_quote
4064 See No Wayman's [[https://orgmode.org/list/87a6xz3lnd.fsf@gmail.com/][message on the list]] and [[https://gist.github.com/progfolio/af627354f87542879de3ddc30a31adc1][this gist]] for details.
4066 * Musings
4068 ** Cooking?  Brewing?
4069 #+index: beer!brewing
4070 #+index: cooking!conversions
4071 See [[https://orgmode.org/list/87livkco7y.wl%egh@e6h.org][this message]] from Erik Hetzner:
4073 It currently does metric/english conversion, and a few other tricks.
4074 Basically I just use calc’s units code.  I think scaling recipes, or
4075 turning percentages into weights would be pretty easy.
4077   https://gitorious.org/org-cook/org-cook
4079 There is also, for those interested:
4081   https://gitorious.org/org-brew/org-brew
4083 for brewing beer. This is again, mostly just calc functions, including
4084 hydrometer correction, abv calculation, priming sugar for a given CO_2
4085 volume, etc. More integration with org-mode should be possible: for
4086 instance it would be nice to be able to use a lookup table (of ingredients)
4087 to calculate target original gravity, IBUs, etc.