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