Mention Russian translation of tutorial
[Worg.git] / org-hacks.org
blobbabe7b3a13d5433e94c6c12ca5e0ed82d12803f7
1 #+OPTIONS:    H:3 num:nil toc:t \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+STARTUP:    align fold nodlcheck hidestars oddeven lognotestate
3 #+SEQ_TODO:   TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
4 #+TAGS:       Write(w) Update(u) Fix(f) Check(c)
5 #+TITLE:      Org ad hoc code, quick hacks and workarounds
6 #+AUTHOR:     Worg people
7 #+EMAIL:      bzg AT altern DOT org
8 #+LANGUAGE:   en
9 #+PRIORITIES: A C B
10 #+CATEGORY:   worg
12 # This file is the default header for new Org files in Worg.  Feel free
13 # to tailor it to your needs.
15 [[file:index.org][{Back to Worg's index}]]
17 This page is for ad hoc bits of code.  Feel free to add quick hacks and
18 workaround.  Go crazy.
20 * Hacking Org: Modifying orgmode itself
21 ** Compiling Org without make
22    :PROPERTIES:
23    :CUSTOM_ID: compiling-org-without-make
24    :END:
26    This file is the result of  [[http://article.gmane.org/gmane.emacs.orgmode/15264][one of our discussions]] on the mailing list.
27    Enhancements wellcome.
29    To use this function, adjust the variables =my/org-lisp-directory= and
30    =my/org-compile-sources= to suite your needs.
32    #+BEGIN_SRC emacs-lisp
33    (defvar my/org-lisp-directory "~/.emacs.d/org/lisp"
34      "Directory where your org-mode files live.")
36    (defvar my/org-compile-sources t
37      "If `nil', never compile org-sources. `my/compile-org' will only create
38    the autoloads file `org-install.el' then. If `t', compile the sources, too.")
40    ;; Customize:
41    (setq my/org-lisp-directory "~/.emacs.d/org/lisp")
43    ;; Customize:
44    (setq  my/org-compile-sources t)
46    (defun my/compile-org(&optional directory)
47      "Compile all *.el files that come with org-mode."
48      (interactive)
49      (setq directory (concat
50                         (file-truename
51                        (or directory my/org-lisp-directory)) "/"))
53      (add-to-list 'load-path directory)
55      (let ((list-of-org-files (file-expand-wildcards (concat directory "*.el"))))
57        ;; create the org-install file
58        (require 'autoload)
59        (setq esf/org-install-file (concat directory "org-install.el"))
60        (find-file esf/org-install-file)
61        (erase-buffer)
62        (mapc (lambda (x)
63                (generate-file-autoloads x))
64              list-of-org-files)
65        (insert "\n(provide (quote org-install))\n")
66        (save-buffer)
67        (kill-buffer)
68        (byte-compile-file esf/org-install-file t)
70        (dolist (f list-of-org-files)
71          (if (file-exists-p (concat f "c")) ; delete compiled files
72              (delete-file (concat f "c")))
73          (if my/org-compile-sources     ; Compile, if `my/org-compile-sources' is t
74              (byte-compile-file f)))))
75    #+END_SRC
76 ** Reload Org
78 As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
79 function to reload org files.
81 Normally you want to use the compiled files since they are faster.
82 If you update your org files you can easily reload them with
84 : M-x org-reload
86 If you run into a bug and want to generate a useful backtrace you can
87 reload the source files instead of the compiled files with
89 : C-u M-x org-reload
91 and turn on the "Enter Debugger On Error" option.  Redo the action
92 that generates the error and cut and paste the resulting backtrace.
93 To switch back to the compiled version just reload again with
95 : M-x org-reload
97 ** Speed Commands
98    Speed commands are described [[http://orgmode.org/manual/Speed-keys.html#Speed-keys][here]] in the manual. Add your own speed
99    commands here.
100 *** Show next/prev heading tidily
101    - Dan Davison
102      These close the current heading and open the next/previous heading.
104 #+begin_src emacs-lisp
105 (defun ded/org-show-next-heading-tidily ()
106   "Show next entry, keeping other entries closed."
107   (if (save-excursion (end-of-line) (outline-invisible-p))
108       (progn (org-show-entry) (show-children))
109     (outline-next-heading)
110     (unless (and (bolp) (org-on-heading-p))
111       (org-up-heading-safe)
112       (hide-subtree)
113       (error "Boundary reached"))
114     (org-overview)
115     (org-reveal t)
116     (org-show-entry)
117     (show-children)))
119 (defun ded/org-show-previous-heading-tidily ()
120   "Show previous entry, keeping other entries closed."
121   (let ((pos (point)))
122     (outline-previous-heading)
123     (unless (and (< (point) pos) (bolp) (org-on-heading-p))
124       (goto-char pos)
125       (hide-subtree)
126       (error "Boundary reached"))
127     (org-overview)
128     (org-reveal t)
129     (org-show-entry)
130     (show-children)))
132 (setq org-use-speed-commands t)
133 (add-to-list 'org-speed-commands-user
134              '("n" ded/org-show-next-heading-tidily))
135 (add-to-list 'org-speed-commands-user 
136              '("p" ded/org-show-previous-heading-tidily))
137 #+end_src
139 ** Easy customization of TODO colors
140   -- Ryan C. Thompson
142   Here is some code I came up with some code to make it easier to
143   customize the colors of various TODO keywords. As long as you just
144   want a different color and nothing else, you can customize the
145   variable org-todo-keyword-faces and use just a string color (i.e. a
146   string of the color name) as the face, and then org-get-todo-face
147   will convert the color to a face, inheriting everything else from
148   the standard org-todo face.
150   To demonstrate, I currently have org-todo-keyword-faces set to
152 #+BEGIN_SRC emacs-lisp
153 (("IN PROGRESS" . "dark orange")
154  ("WAITING" . "red4")
155  ("CANCELED" . "saddle brown"))
156 #+END_SRC emacs-lisp
158   Here's the code, in a form you can put in your =.emacs=
160 #+BEGIN_SRC emacs-lisp
161 (eval-after-load 'org-faces
162  '(progn
163     (defcustom org-todo-keyword-faces nil
164       "Faces for specific TODO keywords.
165 This is a list of cons cells, with TODO keywords in the car and
166 faces in the cdr.  The face can be a symbol, a color, or a
167 property list of attributes, like (:foreground \"blue\" :weight
168 bold :underline t)."
169       :group 'org-faces
170       :group 'org-todo
171       :type '(repeat
172               (cons
173                (string :tag "Keyword")
174                (choice color (sexp :tag "Face")))))))
176 (eval-after-load 'org
177  '(progn
178     (defun org-get-todo-face-from-color (color)
179       "Returns a specification for a face that inherits from org-todo
180  face and has the given color as foreground. Returns nil if
181  color is nil."
182       (when color
183         `(:inherit org-warning :foreground ,color)))
185     (defun org-get-todo-face (kwd)
186       "Get the right face for a TODO keyword KWD.
187 If KWD is a number, get the corresponding match group."
188       (if (numberp kwd) (setq kwd (match-string kwd)))
189       (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
190             (if (stringp face)
191                 (org-get-todo-face-from-color face)
192               face))
193           (and (member kwd org-done-keywords) 'org-done)
194           'org-todo))))
195 #+END_SRC emacs-lisp
197 ** Changelog support for org headers
198    -- James TD Smith
200    Put the following in your =.emacs=, and =C-x 4 a= and other functions which
201    use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
202    headline as the "current function" if you add a changelog entry from an org
203    buffer.
205    #+BEGIN_SRC emacs-lisp
206      (defun org-log-current-defun ()
207        (save-excursion
208          (org-back-to-heading)
209          (if (looking-at org-complex-heading-regexp)
210              (match-string 4))))
211      
212      (add-hook 'org-mode-hook
213                (lambda ()
214                  (make-variable-buffer-local 'add-log-current-defun-function)
215                  (setq add-log-current-defun-function 'org-log-current-defun)))
216    #+END_SRC
218 ** Remove redundant tags of headlines
219   -- David Maus
221 A small function that processes all headlines in current buffer and
222 removes tags that are local to a headline and inherited by a parent
223 headline or the #+FILETAGS: statement.
225 #+BEGIN_SRC emacs-lisp
226   (defun dmj/org-remove-redundant-tags ()
227     "Remove redundant tags of headlines in current buffer.
229   A tag is considered redundant if it is local to a headline and
230   inherited by a parent headline."
231     (interactive)
232     (when (eq major-mode 'org-mode)
233       (save-excursion
234         (org-map-entries
235          '(lambda ()
236             (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
237                   local inherited tag)
238               (dolist (tag alltags)
239                 (if (get-text-property 0 'inherited tag)
240                     (push tag inherited) (push tag local)))
241               (dolist (tag local)
242                 (if (member tag inherited) (org-toggle-tag tag 'off)))))
243          t nil))))
244 #+END_SRC
246 ** Remove empty property drawers
248 David Maus proposed this:
250 #+begin_src emacs-lisp
251 (defun dmj:org:remove-empty-propert-drawers ()
252   "*Remove all empty property drawers in current file."
253   (interactive)
254   (unless (eq major-mode 'org-mode)
255     (error "You need to turn on Org mode for this function."))
256   (save-excursion
257     (goto-char (point-min))
258     (while (re-search-forward ":PROPERTIES:" nil t)
259       (save-excursion
260         (org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
261 #+end_src
263 ** Different org-cycle-level behavior
264   -- Ryan Thompson
266 In recent org versions, when your point (cursor) is at the end of an
267 empty header line (like after you first created the header), the TAB
268 key (=org-cycle=) has a special behavior: it cycles the headline through
269 all possible levels. However, I did not like the way it determined
270 "all possible levels," so I rewrote the whole function, along with a
271 couple of supporting functions.
273 The original function's definition of "all possible levels" was "every
274 level from 1 to one more than the initial level of the current
275 headline before you started cycling." My new definition is "every
276 level from 1 to one more than the previous headline's level." So, if
277 you have a headline at level 4 and you use ALT+RET to make a new
278 headline below it, it will cycle between levels 1 and 5, inclusive.
280 The main advantage of my custom =org-cycle-level= function is that it
281 is stateless: the next level in the cycle is determined entirely by
282 the contents of the buffer, and not what command you executed last.
283 This makes it more predictable, I hope.
285 #+BEGIN_SRC emacs-lisp
286 (require 'cl)
288 (defun org-point-at-end-of-empty-headline ()
289   "If point is at the end of an empty headline, return t, else nil."
290   (and (looking-at "[ \t]*$")
291        (save-excursion
292          (beginning-of-line 1)
293          (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))
295 (defun org-level-increment ()
296   "Return the number of stars that will be added or removed at a
297 time to headlines when structure editing, based on the value of
298 `org-odd-levels-only'."
299   (if org-odd-levels-only 2 1))
301 (defvar org-previous-line-level-cached nil)
303 (defun org-recalculate-previous-line-level ()
304   "Same as `org-get-previous-line-level', but does not use cached
305 value. It does *set* the cached value, though."
306   (set 'org-previous-line-level-cached
307        (let ((current-level (org-current-level))
308              (prev-level (when (> (line-number-at-pos) 1)
309                            (save-excursion
310                              (previous-line)
311                              (org-current-level)))))
312          (cond ((null current-level) nil) ; Before first headline
313                ((null prev-level) 0)      ; At first headline
314                (prev-level)))))
316 (defun org-get-previous-line-level ()
317   "Return the outline depth of the last headline before the
318 current line. Returns 0 for the first headline in the buffer, and
319 nil if before the first headline."
320   ;; This calculation is quite expensive, with all the regex searching
321   ;; and stuff. Since org-cycle-level won't change lines, we can reuse
322   ;; the last value of this command.
323   (or (and (eq last-command 'org-cycle-level)
324            org-previous-line-level-cached)
325       (org-recalculate-previous-line-level)))
327 (defun org-cycle-level ()
328   (interactive)
329   (let ((org-adapt-indentation nil))
330     (when (org-point-at-end-of-empty-headline)
331       (setq this-command 'org-cycle-level) ;Only needed for caching
332       (let ((cur-level (org-current-level))
333             (prev-level (org-get-previous-line-level)))
334         (cond
335          ;; If first headline in file, promote to top-level.
336          ((= prev-level 0)
337           (loop repeat (/ (- cur-level 1) (org-level-increment))
338                 do (org-do-promote)))
339          ;; If same level as prev, demote one.
340          ((= prev-level cur-level)
341           (org-do-demote))
342          ;; If parent is top-level, promote to top level if not already.
343          ((= prev-level 1)
344           (loop repeat (/ (- cur-level 1) (org-level-increment))
345                 do (org-do-promote)))
346          ;; If top-level, return to prev-level.
347          ((= cur-level 1)
348           (loop repeat (/ (- prev-level 1) (org-level-increment))
349                 do (org-do-demote)))
350          ;; If less than prev-level, promote one.
351          ((< cur-level prev-level)
352           (org-do-promote))
353          ;; If deeper than prev-level, promote until higher than
354          ;; prev-level.
355          ((> cur-level prev-level)
356           (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
357                 do (org-do-promote))))
358         t))))
359 #+END_SRC
361 ** Add an effort estimate on the fly when clocking in
363 You can use =org-clock-in-prepare-hook= to add an effort estimate.
364 This way you can easily have a "tea-timer" for your tasks when they
365 don't already have an effort estimate.
367 #+begin_src emacs-lisp
368 (add-hook 'org-clock-in-prepare-hook
369           'my-org-mode-ask-effort)
371 (defun my-org-mode-ask-effort ()
372   "Ask for an effort estimate when clocking in."
373   (unless (org-entry-get (point) "Effort")
374     (let ((effort
375            (completing-read
376             "Effort: "
377             (org-entry-get-multivalued-property (point) "Effort"))))
378       (unless (equal effort "")
379         (org-set-property "Effort" effort)))))
380 #+end_src
382 Or you can use a default effort for such a timer:
384 #+begin_src emacs-lisp
385 (add-hook 'org-clock-in-prepare-hook
386           'my-org-mode-add-default-effort)
388 (defvar org-clock-default-effort "1:00")
390 (defun my-org-mode-add-default-effort ()
391   "Add a default effort estimation."
392   (unless (org-entry-get (point) "Effort")
393     (org-set-property "Effort" org-clock-default-effort)))
394 #+end_src
396 ** Customize the size of the frame for remember
398 #FIXME: gmane link?
399 On emacs-orgmode, Ryan C. Thompson suggested this:
401 #+begin_quote
402 I am using org-remember set to open a new frame when used,
403 and the default frame size is much too large. To fix this, I have
404 designed some advice and a custom variable to implement custom
405 parameters for the remember frame:
406 #+end_quote
408 #+begin_src emacs-lisp
409   (defcustom remember-frame-alist nil
410     "Additional frame parameters for dedicated remember frame."
411     :type 'alist
412     :group 'remember)
413   
414   (defadvice remember (around remember-frame-parameters activate)
415     "Set some frame parameters for the remember frame."
416     (let ((default-frame-alist (append remember-frame-alist
417                                        default-frame-alist)))
418       ad-do-it))
419 #+end_src
421 Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
422 reasonable size for the frame.
423 ** Org table
424 *** Dates computation
426 **** Question ([[http://article.gmane.org/gmane.emacs.orgmode/15692][Xin Shi]])
428 I have a table in org which stores the date, I'm wondering if there is
429 any function to calculate the duration? For example:
431 | Start Date |   End Date | Duration |
432 |------------+------------+----------|
433 | 2004.08.07 | 2005.07.08 |          |
435 I tried to use B&-C&, but failed ...
437 **** Answer ([[http://article.gmane.org/gmane.emacs.orgmode/15694][Nick Dokos]])
439 Try the following:
441 | Start Date |   End Date | Duration |
442 |------------+------------+----------|
443 | 2004.08.07 | 2005.07.08 |      335 |
444 :#+TBLFM: $3=(date(<$2>)-date(<$1>))
446 See this thread:
448     http://thread.gmane.org/gmane.emacs.orgmode/7741
450 as well as this post (which is really a followup on the
451 above):
453     http://article.gmane.org/gmane.emacs.orgmode/7753
455 The problem that this last article pointed out was solved
458     http://article.gmane.org/gmane.emacs.orgmode/8001
460 and Chris Randle's original musings are at
462     http://article.gmane.org/gmane.emacs.orgmode/6536/
464 *** Field coordinates in formulas (=@#= and =$#=)
466 -- Michael Brand
468 Following are some use cases that can be implemented with the
469 _field coordinates in formulas_ described in the corresponding
470 chapter in the [[http://orgmode.org/manual/References.html#References][Org manual]], available since =org-version= 6.35.
472 **** Copy a column from a remote table into a column
474 current column =$3= = remote column =$2=:
475 : #+TBLFM: $3 = remote(FOO, @@#$2)
477 **** Copy a row from a remote table transposed into a column
479 current column =$1= = transposed remote row =@1=:
480 : #+TBLFM: $1 = remote(FOO, @$#$@#)
482 **** Transpose a table
484 -- Michael Brand
486 This is more like a demonstration of using _field coordinates in formulas_
487 to [[http://en.wikipedia.org/wiki/Transpose][transpose]] a table or to do it without using org-babel.  The efficient
488 and simple solution for this with the help of org-babel and Emacs Lisp has
489 been provided by Thomas S. Dye on the [[http://thread.gmane.org/gmane.emacs.orgmode/23809/focus=23815][mailing list]].
491 To transpose this 4x7 table
493 : #+TBLNAME: FOO
494 : | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
495 : |------+------+------+------+------+------+------|
496 : | min  |  401 |  501 |  601 |  701 |  801 |  901 |
497 : | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
498 : | max  |  403 |  503 |  603 |  703 |  803 |  903 |
500 start with a 7x4 table without any horizontal line (to have filled
501 also the column header) and yet empty:
503 : |   |   |   |   |
504 : |   |   |   |   |
505 : |   |   |   |   |
506 : |   |   |   |   |
507 : |   |   |   |   |
508 : |   |   |   |   |
509 : |   |   |   |   |
511 Then add the =TBLFM= below with the same formula repeated for each column.
512 After recalculation this will end up with the transposed copy:
514 : | year | min | avg | max |
515 : | 2004 | 401 | 402 | 403 |
516 : | 2005 | 501 | 502 | 503 |
517 : | 2006 | 601 | 602 | 603 |
518 : | 2007 | 701 | 702 | 703 |
519 : | 2008 | 801 | 802 | 803 |
520 : | 2009 | 901 | 902 | 903 |
521 : #+TBLFM: $1 = remote(FOO, @$#$@#) :: $2 = remote(FOO, @$#$@#) :: $3 = remote(FOO, @$#$@#) :: $4 = remote(FOO, @$#$@#)
523 The formulas simply exchange row and column numbers by taking
524 - the absolute remote row number =@$#= from the current column number =$#=
525 - the absolute remote column number =$@#= from the current row number =@#=
527 Possible field formulas from the remote table will have to be transferred
528 manually.  Since there are no row formulas yet there is no need to transfer
529 column formulas to row formulas or vice versa.
531 **** Dynamic variation of ranges
533 -- Michael Brand
535 In this example all columns next to =quote= are calculated from the column
536 =quote= and show the average change of the time series =quote[year]=
537 during the period of the preceding =1=, =2=, =3= or =4= years:
539 : | year | quote |   1 a |   2 a |   3 a |   4 a |
540 : |------+-------+-------+-------+-------+-------|
541 : | 2005 |    10 |       |       |       |       |
542 : | 2006 |    12 | 0.200 |       |       |       |
543 : | 2007 |    14 | 0.167 | 0.183 |       |       |
544 : | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
545 : | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
546 : #+TBLFM: $3=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$4=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$5=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3::$6=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")); f3
548 The formula is the same for each column =$3= through =$6=.  This can easily
549 be seen with the great formula editor invoked by C-c ' on the
550 table. The important part of the formula without the field blanking is:
552 : ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1
554 which is the Emacs Calc implementation of the equation
556 /AvgChange(i, a) = (quote[i] / quote[i - a]) ^ 1 / n - 1/
558 where /i/ is the current time and /a/ is the length of the preceding period.
559 ** Archive in a date tree
561 Posted to Org-mode mailing list by Osamu Okano
562 [2010-04-21 Wed]
564 #+begin_src emacs-lisp
565   ;; (setq org-archive-location "%s_archive::date-tree")
566   (defadvice org-archive-subtree
567     (around org-archive-subtree-to-data-tree activate)
568     "org-archive-subtree to date-tree"
569     (if
570         (string= "date-tree"
571                  (org-extract-archive-heading
572                   (org-get-local-archive-location)))
573         (let* ((dct (decode-time (org-current-time)))
574                (y (nth 5 dct))
575                (m (nth 4 dct))
576                (d (nth 3 dct))
577                (this-buffer (current-buffer))
578                (location (org-get-local-archive-location))
579                (afile (org-extract-archive-file location))
580                (org-archive-location
581                 (format "%s::*** %04d-%02d-%02d %s" afile y m d
582                         (format-time-string "%A" (encode-time 0 0 0 d m y)))))
583           (message "afile=%s" afile)
584           (unless afile
585             (error "Invalid `org-archive-location'"))
586           (save-excursion
587             (switch-to-buffer (find-file-noselect afile))
588             (org-datetree-find-year-create y)
589             (org-datetree-find-month-create y m)
590             (org-datetree-find-day-create y m d)
591             (widen)
592             (switch-to-buffer this-buffer))
593           ad-do-it)
594       ad-do-it))
595 #+end_src
597 ** Make it easier to set org-agenda-files from multiple directories
598   - Matt Lundin
600 #+begin_src emacs-lisp
601   (defun my-org-list-files (dirs ext)
602     "Function to create list of org files in multiple subdirectories.
603   This can be called to generate a list of files for
604   org-agenda-files or org-refile-targets.
605   
606   DIRS is a list of directories.
607   
608   EXT is a list of the extensions of files to be included."
609     (let ((dirs (if (listp dirs)
610                     dirs
611                   (list dirs)))
612           (ext (if (listp ext)
613                    ext
614                  (list ext)))
615           files)
616       (mapc 
617        (lambda (x)
618          (mapc 
619           (lambda (y)
620             (setq files 
621                   (append files 
622                           (file-expand-wildcards 
623                            (concat (file-name-as-directory x) "*" y)))))
624           ext))
625        dirs)
626       (mapc
627        (lambda (x)
628          (when (or (string-match "/.#" x)
629                    (string-match "#$" x))
630            (setq files (delete x files))))
631        files)
632       files))
633   
634   (defvar my-org-agenda-directories '("~/org/")
635     "List of directories containing org files.")
636   (defvar my-org-agenda-extensions '(".org")
637     "List of extensions of agenda files")
638   
639   (setq my-org-agenda-directories '("~/org/" "~/work/"))
640   (setq my-org-agenda-extensions '(".org" ".ref"))
641   
642   (defun my-org-set-agenda-files ()
643     (interactive)
644     (setq org-agenda-files (my-org-list-files 
645                             my-org-agenda-directories
646                             my-org-agenda-extensions)))
647   
648   (my-org-set-agenda-files)
649 #+end_src
651 The code above will set your "default" agenda files to all files
652 ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
653 You can change these values by setting the variables
654 my-org-agenda-extensions and my-org-agenda-directories. The function
655 my-org-agenda-files-by-filetag uses these two variables to determine
656 which files to search for filetags (i.e., the larger set from which
657 the subset will be drawn).
659 You can also easily use my-org-list-files to "mix and match"
660 directories and extensions to generate different lists of agenda
661 files.
663 ** Restrict org-agenda-files by filetag
664   :PROPERTIES:
665   :CUSTOM_ID: set-agenda-files-by-filetag
666   :END:
667   - Matt Lundin
669 It is often helpful to limit yourself to a subset of your agenda
670 files. For instance, at work, you might want to see only files related
671 to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
672 information on filtering tasks using [[file:org-faq.org::#limit-agenda-with-tag-filtering][filetags]] and [[file:org-faq.org::#limit-agenda-with-category-match][custom agenda
673 commands]]. These solutions, however, require reapplying a filter each
674 time you call the agenda or writing several new custom agenda commands
675 for each context. Another solution is to use directories for different
676 types of tasks and to change your agenda files with a function that
677 sets org-agenda-files to the appropriate directory. But this relies on
678 hard and static boundaries between files.
680 The following functions allow for a more dynamic approach to selecting
681 a subset of files based on filetags:
683 #+begin_src emacs-lisp
684   (defun my-org-agenda-restrict-files-by-filetag (&optional tag)
685     "Restrict org agenda files only to those containing filetag."
686     (interactive)
687     (let* ((tagslist (my-org-get-all-filetags))
688            (ftag (or tag 
689                      (completing-read "Tag: " 
690                                       (mapcar 'car tagslist)))))
691       (org-agenda-remove-restriction-lock 'noupdate)
692       (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
693       (setq org-agenda-overriding-restriction 'files)))
694   
695   (defun my-org-get-all-filetags ()
696     "Get list of filetags from all default org-files."
697     (let ((files org-agenda-files)
698           tagslist x)
699       (save-window-excursion
700         (while (setq x (pop files))
701           (set-buffer (find-file-noselect x))
702           (mapc
703            (lambda (y)
704              (let ((tagfiles (assoc y tagslist)))
705                (if tagfiles
706                    (setcdr tagfiles (cons x (cdr tagfiles)))
707                  (add-to-list 'tagslist (list y x)))))
708            (my-org-get-filetags)))
709         tagslist)))
710   
711   (defun my-org-get-filetags ()
712     "Get list of filetags for current buffer"
713     (let ((ftags org-file-tags)
714           x)
715       (mapcar 
716        (lambda (x)
717          (org-substring-no-properties x))
718        ftags)))
719 #+end_src
721 Calling my-org-agenda-restrict-files-by-filetag results in a prompt
722 with all filetags in your "normal" agenda files. When you select a
723 tag, org-agenda-files will be restricted to only those files
724 containing the filetag. To release the restriction, type C-c C-x >
725 (org-agenda-remove-restriction-lock).
727 ** Split horizontally for agenda
729 If you would like to split the frame into two side-by-side windows when
730 displaying the agenda, try this hack from Jan Rehders, which uses the
731 `toggle-window-split' from
733 http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit
735 #+BEGIN_SRC emacs-lisp
736 ;; Patch org-mode to use vertical splitting
737 (defadvice org-prepare-agenda (after org-fix-split)
738   (toggle-window-split))
739 (ad-activate 'org-prepare-agenda)
740 #+END_SRC
742 ** Automatically add an appointment when clocking in a task
744 #+BEGIN_SRC emacs-lisp
745 ;; Make sure you have a sensible value for `appt-message-warning-time'
746 (defvar bzg-org-clock-in-appt-delay 100
747   "Number of minutes for setting an appointment by clocking-in")
748 #+END_SRC
750 This function let's you add an appointment for the current entry.
751 This can be useful when you need a reminder.
753 #+BEGIN_SRC emacs-lisp
754 (defun bzg-org-clock-in-add-appt (&optional n)
755   "Add an appointment for the Org entry at point in N minutes."
756   (interactive)
757   (save-excursion
758     (org-back-to-heading t)
759     (looking-at org-complex-heading-regexp)
760     (let* ((msg (match-string-no-properties 4))
761            (ct-time (decode-time))
762            (appt-min (+ (cadr ct-time)
763                         (or n bzg-org-clock-in-appt-delay)))
764            (appt-time ; define the time for the appointment
765             (progn (setf (cadr ct-time) appt-min) ct-time)))
766       (appt-add (format-time-string
767                  "%H:%M" (apply 'encode-time appt-time)) msg)
768       (if (interactive-p) (message "New appointment for %s" msg)))))
769 #+END_SRC
771 You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
772 add an appointment:
774 #+BEGIN_SRC emacs-lisp
775 (defadvice org-clock-in (after org-clock-in-add-appt activate)
776   "Add an appointment when clocking a task in."
777   (bzg-org-clock-in-add-appt))
778 #+END_SRC
780 You may also want to delete the associated appointment when clocking
781 out.  This function does this:
783 #+BEGIN_SRC emacs-lisp
784 (defun bzg-org-clock-out-delete-appt nil
785   "When clocking out, delete any associated appointment."
786   (interactive)
787   (save-excursion
788     (org-back-to-heading t)
789     (looking-at org-complex-heading-regexp)
790     (let* ((msg (match-string-no-properties 4)))
791       (setq appt-time-msg-list
792             (delete nil
793                     (mapcar
794                      (lambda (appt)
795                        (if (not (string-match (regexp-quote msg)
796                                               (cadr appt))) appt))
797                      appt-time-msg-list)))
798       (appt-check))))
799 #+END_SRC
801 And here is the advice for =org-clock-out= (=C-c C-x C-o=)
803 #+BEGIN_SRC emacs-lisp
804 (defadvice org-clock-out (before org-clock-out-delete-appt activate)
805   "Delete an appointment when clocking a task out."
806   (bzg-org-clock-out-delete-appt))
807 #+END_SRC
809 *IMPORTANT*: You can add appointment by clocking in in both an
810 =org-mode= and an =org-agenda-mode= buffer.  But clocking out from
811 agenda buffer with the advice above will bring an error.
812 ** Highlight the agenda line under cursor
814 This is useful to make sure what task you are operating on.
816 #+BEGIN_SRC emacs-lisp
817 (add-hook 'org-agenda-mode-hook '(lambda () (hl-line-mode 1)))
818 #+END_SRC emacs-lisp
820 Under XEmacs:
822 #+BEGIN_SRC emacs-lisp
823 ;; hl-line seems to be only for emacs
824 (require 'highline)
825 (add-hook 'org-agenda-mode-hook '(lambda () (highline-mode 1)))
827 ;; highline-mode does not work straightaway in tty mode.
828 ;; I use a black background
829 (custom-set-faces
830   '(highline-face ((((type tty) (class color))
831                     (:background "white" :foreground "black")))))
832 #+END_SRC emacs-lisp
834 ** Remove time grid lines that are in an appointment
836 The agenda shows lines for the time grid.  Some people think that
837 these lines are a distraction when there are appointments at those
838 times.  You can get rid of the lines which coincide exactly with the
839 beginning of an appointment.  Michael Ekstrand has written a piece of
840 advice that also removes lines that are somewhere inside an
841 appointment:
843 #+begin_src emacs-lisp
844 (defun org-time-to-minutes (time)
845   "Convert an HHMM time to minutes"
846   (+ (* (/ time 100) 60) (% time 100)))
848 (defun org-time-from-minutes (minutes)
849   "Convert a number of minutes to an HHMM time"
850   (+ (* (/ minutes 60) 100) (% minutes 60)))
852 (defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
853                                                   (list ndays todayp))
854   (if (member 'remove-match (car org-agenda-time-grid))
855       (flet ((extract-window
856               (line)
857               (let ((start (get-text-property 1 'time-of-day line))
858                     (dur (get-text-property 1 'duration line)))
859                 (cond
860                  ((and start dur)
861                   (cons start
862                         (org-time-from-minutes
863                          (+ dur (org-time-to-minutes start)))))
864                  (start start)
865                  (t nil)))))
866         (let* ((windows (delq nil (mapcar 'extract-window list)))
867                (org-agenda-time-grid
868                 (list (car org-agenda-time-grid)
869                       (cadr org-agenda-time-grid)
870                       (remove-if
871                        (lambda (time)
872                          (find-if (lambda (w)
873                                     (if (numberp w)
874                                         (equal w time)
875                                       (and (>= time (car w))
876                                            (< time (cdr w)))))
877                                   windows))
878                        (caddr org-agenda-time-grid)))))
879           ad-do-it))
880     ad-do-it))
881 (ad-activate 'org-agenda-add-time-grid-maybe)
882 #+end_src
884 ** Group task list by a property
886 This advice allows you to group a task list in Org-Mode.  To use it,
887 set the variable =org-agenda-group-by-property= to the name of a
888 property in the option list for a TODO or TAGS search.  The resulting
889 agenda view will group tasks by that property prior to searching.
891 #+begin_src emacs-lisp
892 (defvar org-agenda-group-by-property nil
893   "Set this in org-mode agenda views to group tasks by property")
895 (defun org-group-bucket-items (prop items)
896   (let ((buckets ()))
897     (dolist (item items)
898       (let* ((marker (get-text-property 0 'org-marker item))
899              (pvalue (org-entry-get marker prop t))
900              (cell (assoc pvalue buckets)))
901         (if cell
902             (setcdr cell (cons item (cdr cell)))
903           (setq buckets (cons (cons pvalue (list item))
904                               buckets)))))
905     (setq buckets (mapcar (lambda (bucket)
906                             (cons (car bucket)
907                                   (reverse (cdr bucket))))
908                           buckets))
909     (sort buckets (lambda (i1 i2)
910                     (string< (car i1) (car i2))))))
912 (defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
913                                                (list &optional nosort))
914   "Prepare bucketed agenda entry lists"
915   (if org-agenda-group-by-property
916       ;; bucketed, handle appropriately
917       (let ((text ""))
918         (dolist (bucket (org-group-bucket-items
919                          org-agenda-group-by-property
920                          list))
921           (let ((header (concat "Property "
922                                 org-agenda-group-by-property
923                                 " is "
924                                 (or (car bucket) "<nil>") ":\n")))
925             (add-text-properties 0 (1- (length header))
926                                  (list 'face 'org-agenda-structure)
927                                  header)
928             (setq text
929                   (concat text header
930                           ;; recursively process
931                           (let ((org-agenda-group-by-property nil))
932                             (org-finalize-agenda-entries
933                              (cdr bucket) nosort))
934                           "\n\n"))))
935         (setq ad-return-value text))
936     ad-do-it))
937 (ad-activate 'org-finalize-agenda-entries)
938 #+end_src
939 ** Dynamically adjust tag position
940 Here is a bit of code that allows you to have the tags always
941 right-adjusted in the buffer.
943 This is useful when you have bigger window than default window-size
944 and you dislike the aesthetics of having the tag in the middle of the
945 line.
947 This hack solves the problem of adjusting it whenever you change the
948 window size.
949 Before saving it will revert the file to having the tag position be
950 left-adjusted so that if you track your files with version control,
951 you won't run into artificial diffs just because the window-size
952 changed.
954 *IMPORTANT*: This is probably slow on very big files.
956 #+begin_src emacs-lisp
957   (setq ba/org-adjust-tags-column t)
958   
959   (defun ba/org-adjust-tags-column-reset-tags ()
960     "In org-mode buffers it will reset tag position according to
961   `org-tags-column'."
962     (when (and
963            (not (string= (buffer-name) "*Remember*"))
964            (eql major-mode 'org-mode))
965       (let ((b-m-p (buffer-modified-p)))
966         (condition-case nil
967             (save-excursion
968               (goto-char (point-min))
969               (command-execute 'outline-next-visible-heading)
970               ;; disable (message) that org-set-tags generates
971               (flet ((message (&rest ignored) nil))
972                 (org-set-tags 1 t))
973               (set-buffer-modified-p b-m-p))
974           (error nil)))))
975   
976   (defun ba/org-adjust-tags-column-now ()
977     "Right-adjust `org-tags-column' value, then reset tag position."
978     (set (make-local-variable 'org-tags-column)
979          (- (- (window-width) (length org-ellipsis))))
980     (ba/org-adjust-tags-column-reset-tags))
981   
982   (defun ba/org-adjust-tags-column-maybe ()
983     "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
984     (when ba/org-adjust-tags-column
985       (ba/org-adjust-tags-column-now)))
986   
987   (defun ba/org-adjust-tags-column-before-save ()
988     "Tags need to be left-adjusted when saving."
989     (when ba/org-adjust-tags-column
990        (setq org-tags-column 1)
991        (ba/org-adjust-tags-column-reset-tags)))
992   
993   (defun ba/org-adjust-tags-column-after-save ()
994     "Revert left-adjusted tag position done by before-save hook."
995     (ba/org-adjust-tags-column-maybe)
996     (set-buffer-modified-p nil))
997   
998   ; automatically align tags on right-hand side
999   (add-hook 'window-configuration-change-hook
1000             'ba/org-adjust-tags-column-maybe)
1001   (add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
1002   (add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
1003   (add-hook 'org-agenda-mode-hook '(lambda ()
1004                                     (setq org-agenda-tags-column (- (window-width)))))
1005   
1006   ; between invoking org-refile and displaying the prompt (which
1007   ; triggers window-configuration-change-hook) tags might adjust, 
1008   ; which invalidates the org-refile cache
1009   (defadvice org-refile (around org-refile-disable-adjust-tags)
1010     "Disable dynamically adjusting tags"
1011     (let ((ba/org-adjust-tags-column nil))
1012       ad-do-it))
1013   (ad-activate 'org-refile)
1014 #+end_src
1015 * Hacking Org and Emacs: Modify how org interacts with other Emacs packages.
1016 ** org-remember-anything
1018 [[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:
1020 #+BEGIN_SRC emacs-lisp
1021 (defvar org-remember-anything
1022   '((name . "Org Remember")
1023     (candidates . (lambda () (mapcar 'car org-remember-templates)))
1024     (action . (lambda (name)
1025                 (let* ((orig-template org-remember-templates)
1026                        (org-remember-templates
1027                         (list (assoc name orig-template))))
1028                   (call-interactively 'org-remember))))))
1029 #+END_SRC
1031 You can add it to your 'anything-sources' variable and open remember directly
1032 from anything. I imagine this would be more interesting for people with many
1033 remember templatesm, so that you are out of keys to assign those to. You should
1034 get something like this:
1036 [[file:images/thumbs/org-remember-anything.png]]
1038 ** Org-mode and saveplace.el
1040 Fix a problem with saveplace.el putting you back in a folded position:
1042 #+begin_src emacs-lisp
1043 (add-hook 'org-mode-hook
1044           (lambda ()
1045             (when (outline-invisible-p)
1046               (save-excursion
1047                 (outline-previous-visible-heading 1)
1048                 (org-show-subtree)))))
1049 #+end_src
1051 ** Using ido-completing-read to find attachments
1052   -- Matt Lundin
1054 Org-attach is great for quickly linking files to a project. But if you
1055 use org-attach extensively you might find yourself wanting to browse
1056 all the files you've attached to org headlines. This is not easy to do
1057 manually, since the directories containing the files are not human
1058 readable (i.e., they are based on automatically generated ids). Here's
1059 some code to browse those files using ido (obviously, you need to be
1060 using ido):
1062 #+begin_src emacs-lisp
1063   (load-library "find-lisp")
1064   
1065   ;; Adapted from http://www.emacswiki.org/emacs/RecentFiles
1066   
1067   (defun my-ido-find-org-attach ()
1068     "Find files in org-attachment directory"
1069     (interactive)
1070     (let* ((enable-recursive-minibuffers t)
1071            (files (find-lisp-find-files org-attach-directory "."))
1072            (file-assoc-list
1073             (mapcar (lambda (x)
1074                       (cons (file-name-nondirectory x)
1075                             x))
1076                     files))
1077            (filename-list
1078             (remove-duplicates (mapcar #'car file-assoc-list)
1079                                :test #'string=))
1080            (filename (ido-completing-read "Org attachments: " filename-list nil t))
1081            (longname (cdr (assoc filename file-assoc-list))))
1082       (ido-set-current-directory
1083        (if (file-directory-p longname)
1084            longname
1085          (file-name-directory longname)))
1086       (setq ido-exit 'refresh
1087             ido-text-init ido-text
1088             ido-rotate-temp t)
1089       (exit-minibuffer)))
1090   
1091   (add-hook 'ido-setup-hook 'ido-my-keys)
1092   
1093   (defun ido-my-keys ()
1094     "Add my keybindings for ido."
1095     (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
1096 #+end_src
1098 To browse your org attachments using ido fuzzy matching and/or the
1099 completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
1100 press =C-;=.
1102 ** Use idle timer for automatic agenda views
1104 From John Wiegley's mailing list post (March 18, 2010):
1106 #+begin_quote
1107 I have the following snippet in my .emacs file, which I find very
1108 useful. Basically what it does is that if I don't touch my Emacs for 5
1109 minutes, it displays the current agenda. This keeps my tasks "always
1110 in mind" whenever I come back to Emacs after doing something else,
1111 whereas before I had a tendency to forget that it was there.
1112 #+end_quote  
1114   - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]
1116 #+begin_src emacs-lisp
1117 (defun jump-to-org-agenda ()
1118   (interactive)
1119   (let ((buf (get-buffer "*Org Agenda*"))
1120         wind)
1121     (if buf
1122         (if (setq wind (get-buffer-window buf))
1123             (select-window wind)
1124           (if (called-interactively-p)
1125               (progn
1126                 (select-window (display-buffer buf t t))
1127                 (org-fit-window-to-buffer)
1128                 ;; (org-agenda-redo)
1129                 )
1130             (with-selected-window (display-buffer buf)
1131               (org-fit-window-to-buffer)
1132               ;; (org-agenda-redo)
1133               )))
1134       (call-interactively 'org-agenda-list)))
1135   ;;(let ((buf (get-buffer "*Calendar*")))
1136   ;;  (unless (get-buffer-window buf)
1137   ;;    (org-agenda-goto-calendar)))
1138   )
1139   
1140 (run-with-idle-timer 300 t 'jump-to-org-agenda)
1141 #+end_src
1143 #+results:
1144 : [nil 0 300 0 t jump-to-org-agenda nil idle]
1146 ** Link to Gnus messages by Message-Id
1148 In a [[http://thread.gmane.org/gmane.emacs.orgmode/8860][recent thread]] on the Org-Mode mailing list, there was some
1149 discussion about linking to Gnus messages without encoding the folder
1150 name in the link.  The following code hooks in to the store-link
1151 function in Gnus to capture links by Message-Id when in nnml folders,
1152 and then provides a link type "mid" which can open this link.  The
1153 =mde-org-gnus-open-message-link= function uses the
1154 =mde-mid-resolve-methods= variable to determine what Gnus backends to
1155 scan.  It will go through them, in order, asking each to locate the
1156 message and opening it from the first one that reports success.
1158 It has only been tested with a single nnml backend, so there may be
1159 bugs lurking here and there.
1161 The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
1162 article]].
1164 #+begin_src emacs-lisp
1165 ;; Support for saving Gnus messages by Message-ID
1166 (defun mde-org-gnus-save-by-mid ()
1167   (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
1168     (when (eq major-mode 'gnus-article-mode)
1169       (gnus-article-show-summary))
1170     (let* ((group gnus-newsgroup-name)
1171            (method (gnus-find-method-for-group group)))
1172       (when (eq 'nnml (car method))
1173         (let* ((article (gnus-summary-article-number))
1174                (header (gnus-summary-article-header article))
1175                (from (mail-header-from header))
1176                (message-id
1177                 (save-match-data
1178                   (let ((mid (mail-header-id header)))
1179                     (if (string-match "<\\(.*\\)>" mid)
1180                         (match-string 1 mid)
1181                       (error "Malformed message ID header %s" mid)))))
1182                (date (mail-header-date header))
1183                (subject (gnus-summary-subject-string)))
1184           (org-store-link-props :type "mid" :from from :subject subject
1185                                 :message-id message-id :group group
1186                                 :link (org-make-link "mid:" message-id))
1187           (apply 'org-store-link-props
1188                  :description (org-email-link-description)
1189                  org-store-link-plist)
1190           t)))))
1192 (defvar mde-mid-resolve-methods '()
1193   "List of methods to try when resolving message ID's.  For Gnus,
1194 it is a cons of 'gnus and the select (type and name).")
1195 (setq mde-mid-resolve-methods
1196       '((gnus nnml "")))
1198 (defvar mde-org-gnus-open-level 1
1199   "Level at which Gnus is started when opening a link")
1200 (defun mde-org-gnus-open-message-link (msgid)
1201   "Open a message link with Gnus"
1202   (require 'gnus)
1203   (require 'org-table)
1204   (catch 'method-found
1205     (message "[MID linker] Resolving %s" msgid)
1206     (dolist (method mde-mid-resolve-methods)
1207       (cond
1208        ((and (eq (car method) 'gnus)
1209              (eq (cadr method) 'nnml))
1210         (funcall (cdr (assq 'gnus org-link-frame-setup))
1211                  mde-org-gnus-open-level)
1212         (when gnus-other-frame-object
1213           (select-frame gnus-other-frame-object))
1214         (let* ((msg-info (nnml-find-group-number
1215                           (concat "<" msgid ">")
1216                           (cdr method)))
1217                (group (and msg-info (car msg-info)))
1218                (message (and msg-info (cdr msg-info)))
1219                (qname (and group
1220                            (if (gnus-methods-equal-p
1221                                 (cdr method)
1222                                 gnus-select-method)
1223                                group
1224                              (gnus-group-full-name group (cdr method))))))
1225           (when msg-info
1226             (gnus-summary-read-group qname nil t)
1227             (gnus-summary-goto-article message nil t))
1228           (throw 'method-found t)))
1229        (t (error "Unknown link type"))))))
1231 (eval-after-load 'org-gnus
1232   '(progn
1233      (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
1234      (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
1235 #+end_src
1237 ** Send html messages and attachments with Wanderlust
1238   -- David Maus
1240 /Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
1241 similar functionality for both Wanderlust and Gnus.  The hack below is
1242 still somewhat different: It allows you to toggle sending of html
1243 messages within Wanderlust transparently.  I.e. html markup of the
1244 message body is created right before sending starts.
1246 *** Send HTML message
1248 Putting the code below in your .emacs adds following four functions:
1250    - dmj/wl-send-html-message
1252      Function that does the job: Convert everything between "--text
1253      follows this line--" and first mime entity (read: attachment) or
1254      end of buffer into html markup using `org-export-region-as-html'
1255      and replaces original body with a multipart MIME entity with the
1256      plain text version of body and the html markup version.  Thus a
1257      recipient that prefers html messages can see the html markup,
1258      recipients that prefer or depend on plain text can see the plain
1259      text.
1261      Cannot be called interactively: It is hooked into SEMI's
1262      `mime-edit-translate-hook' if message should be HTML message.
1264    - dmj/wl-send-html-message-draft-init
1266      Cannot be called interactively: It is hooked into WL's
1267      `wl-mail-setup-hook' and provides a buffer local variable to
1268      toggle.
1270    - dmj/wl-send-html-message-draft-maybe
1272      Cannot be called interactively: It is hooked into WL's
1273      `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
1274      `mime-edit-translate-hook' depending on whether HTML message is
1275      toggled on or off
1277    - dmj/wl-send-html-message-toggle
1279      Toggles sending of HTML message.  If toggled on, the letters
1280      "HTML" appear in the mode line.
1282      Call it interactively!  Or bind it to a key in `wl-draft-mode'.
1284 If you have to send HTML messages regularly you can set a global
1285 variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
1286 toggle on sending HTML message by default.
1288 The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
1289 Google's web front end.  As you can see you have the whole markup of
1290 Org at your service: *bold*, /italics/, tables, lists...
1292 So even if you feel uncomfortable with sending HTML messages at least
1293 you send HTML that looks quite good.
1295 #+begin_src emacs-lisp
1296   (defun dmj/wl-send-html-message ()
1297     "Send message as html message.
1298   Convert body of message to html using
1299     `org-export-region-as-html'."
1300     (require 'org)
1301     (save-excursion
1302       (let (beg end html text)
1303         (goto-char (point-min))
1304         (re-search-forward "^--text follows this line--$")
1305         ;; move to beginning of next line
1306         (beginning-of-line 2)
1307         (setq beg (point))
1308         (if (not (re-search-forward "^--\\[\\[" nil t))
1309             (setq end (point-max))
1310           ;; line up
1311           (end-of-line 0)
1312           (setq end (point)))
1313         ;; grab body
1314         (setq text (buffer-substring-no-properties beg end))
1315         ;; convert to html
1316         (with-temp-buffer
1317           (org-mode)
1318           (insert text)
1319           ;; handle signature
1320           (when (re-search-backward "^-- \n" nil t)
1321             ;; preserve link breaks in signature
1322             (insert "\n#+BEGIN_VERSE\n")
1323             (goto-char (point-max))
1324             (insert "\n#+END_VERSE\n")
1325             ;; grab html
1326             (setq html (org-export-region-as-html
1327                         (point-min) (point-max) t 'string))))
1328         (delete-region beg end)
1329         (insert
1330          (concat
1331           "--" "<<alternative>>-{\n"
1332           "--" "[[text/plain]]\n" text
1333           "--" "[[text/html]]\n"  html
1334           "--" "}-<<alternative>>\n")))))
1335   
1336   (defun dmj/wl-send-html-message-toggle ()
1337     "Toggle sending of html message."
1338     (interactive)
1339     (setq dmj/wl-send-html-message-toggled-p
1340           (if dmj/wl-send-html-message-toggled-p
1341               nil "HTML"))
1342     (message "Sending html message toggled %s"
1343              (if dmj/wl-send-html-message-toggled-p
1344                  "on" "off")))
1345   
1346   (defun dmj/wl-send-html-message-draft-init ()
1347     "Create buffer local settings for maybe sending html message."
1348     (unless (boundp 'dmj/wl-send-html-message-toggled-p)
1349       (setq dmj/wl-send-html-message-toggled-p nil))
1350     (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
1351     (add-to-list 'global-mode-string
1352                  '(:eval (if (eq major-mode 'wl-draft-mode)
1353                              dmj/wl-send-html-message-toggled-p))))
1354   
1355   (defun dmj/wl-send-html-message-maybe ()
1356     "Maybe send this message as html message.
1357   
1358   If buffer local variable `dmj/wl-send-html-message-toggled-p' is
1359   non-nil, add `dmj/wl-send-html-message' to
1360   `mime-edit-translate-hook'."
1361     (if dmj/wl-send-html-message-toggled-p
1362         (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
1363       (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))
1364   
1365   (add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
1366   (add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
1367   (add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
1368 #+end_src
1370 *** Attach HTML of region or subtree
1372 Instead of sending a complete HTML message you might only send parts
1373 of an Org file as HTML for the poor souls who are plagued with
1374 non-proportional fonts in their mail program that messes up pretty
1375 ASCII tables.
1377 This short function does the trick: It exports region or subtree to
1378 HTML, prefixes it with a MIME entity delimiter and pushes to killring
1379 and clipboard.  If a region is active, it uses the region, the
1380 complete subtree otherwise.
1382 #+begin_src emacs-lisp
1383 (defun dmj/org-export-region-as-html-attachment (beg end arg)
1384   "Export region between BEG and END as html attachment.
1385 If BEG and END are not set, use current subtree.  Region or
1386 subtree is exported to html without header and footer, prefixed
1387 with a mime entity string and pushed to clipboard and killring.
1388 When called with prefix, mime entity is not marked as
1389 attachment."
1390   (interactive "r\nP")
1391   (save-excursion
1392     (let* ((beg (if (region-active-p) (region-beginning)
1393                   (progn
1394                     (org-back-to-heading)
1395                     (point))))
1396            (end (if (region-active-p) (region-end)
1397                   (progn
1398                     (org-end-of-subtree)
1399                     (point))))
1400            (html (concat "--[[text/html"
1401                          (if arg "" "\nContent-Disposition: attachment")
1402                          "]]\n"
1403                          (org-export-region-as-html beg end t 'string))))
1404       (when (fboundp 'x-set-selection)
1405         (ignore-errors (x-set-selection 'PRIMARY html))
1406         (ignore-errors (x-set-selection 'CLIPBOARD html)))
1407       (message "html export done, pushed to kill ring and clipboard"))))
1408 #+end_src
1410 *** Adopting for Gnus
1412 The whole magic lies in the special strings that mark a HTML
1413 attachment.  So you might just have to find out what these special
1414 strings are in message-mode and modify the functions accordingly.
1415 * Hacking Org and external Programs.
1416 ** Use Org-mode with Screen [Andrew Hyatt]
1418 "The general idea is that you start a task in which all the work will
1419 take place in a shell.  This usually is not a leaf-task for me, but
1420 usually the parent of a leaf task.  From a task in your org-file, M-x
1421 ash-org-screen will prompt for the name of a session.  Give it a name,
1422 and it will insert a link.  Open the link at any time to go the screen
1423 session containing your work!"
1425 http://article.gmane.org/gmane.emacs.orgmode/5276
1427 #+BEGIN_SRC emacs-lisp
1428 (require 'term)
1430 (defun ash-org-goto-screen (name)
1431   "Open the screen with the specified name in the window"
1432   (interactive "MScreen name: ")
1433   (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
1434     (if (member screen-buffer-name
1435                 (mapcar 'buffer-name (buffer-list)))
1436         (switch-to-buffer screen-buffer-name)
1437       (switch-to-buffer (ash-org-screen-helper name "-dr")))))
1439 (defun ash-org-screen-buffer-name (name)
1440   "Returns the buffer name corresponding to the screen name given."
1441   (concat "*screen " name "*"))
1443 (defun ash-org-screen-helper (name arg)
1444   ;; Pick the name of the new buffer.
1445   (let ((term-ansi-buffer-name
1446          (generate-new-buffer-name
1447           (ash-org-screen-buffer-name name))))
1448     (setq term-ansi-buffer-name
1449           (term-ansi-make-term
1450            term-ansi-buffer-name "/usr/bin/screen" nil arg name))
1451     (set-buffer term-ansi-buffer-name)
1452     (term-mode)
1453     (term-char-mode)
1454     (term-set-escape-char ?\C-x)
1455     term-ansi-buffer-name))
1457 (defun ash-org-screen (name)
1458   "Start a screen session with name"
1459   (interactive "MScreen name: ")
1460   (save-excursion
1461     (ash-org-screen-helper name "-S"))
1462   (insert-string (concat "[[screen:" name "]]")))
1464 ;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
1465 ;; \"%s\")") to org-link-abbrev-alist.
1466 #+END_SRC
1468 ** Org Agenda + Appt + Zenity
1470 Russell Adams posted this setup [[http://article.gmane.org/gmane.emacs.orgmode/5806][on the list]].  It make sure your agenda
1471 appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
1472 popup window.
1474 #+BEGIN_SRC emacs-lisp
1475 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1476 ; For org appointment reminders
1478 ;; Get appointments for today
1479 (defun my-org-agenda-to-appt ()
1480   (interactive)
1481   (setq appt-time-msg-list nil)
1482   (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
1483         (org-agenda-to-appt)))
1485 ;; Run once, activate and schedule refresh
1486 (my-org-agenda-to-appt)
1487 (appt-activate t)
1488 (run-at-time "24:01" nil 'my-org-agenda-to-appt)
1490 ; 5 minute warnings
1491 (setq appt-message-warning-time 15)
1492 (setq appt-display-interval 5)
1494 ; Update appt each time agenda opened.
1495 (add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)
1497 ; Setup zenify, we tell appt to use window, and replace default function
1498 (setq appt-display-format 'window)
1499 (setq appt-disp-window-function (function my-appt-disp-window))
1501 (defun my-appt-disp-window (min-to-app new-time msg)
1502   (save-window-excursion (shell-command (concat
1503     "/usr/bin/zenity --info --title='Appointment' --text='"
1504     msg "' &") nil nil)))
1505 #+END_SRC
1507 ** Org-Mode + gnome-osd
1509 Richard Riley uses gnome-osd in interaction with Org-Mode to display
1510 appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].
1512 ** remind2org
1514   From Detlef Steuer
1516 http://article.gmane.org/gmane.emacs.orgmode/5073
1518 #+BEGIN_QUOTE
1519 Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
1520 command line calendaring program. Its features superseed the possibilities
1521 of orgmode in the area of date specifying, so that I want to use it
1522 combined with orgmode.
1524 Using the script below I'm able use remind and incorporate its output in my
1525 agenda views.  The default of using 13 months look ahead is easily
1526 changed. It just happens I sometimes like to look a year into the
1527 future. :-)
1528 #+END_QUOTE
1530 ** Useful webjumps for conkeror
1532 If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
1533 your =~/.conkerorrc= file:
1535 #+begin_example
1536 define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
1537 define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
1538 #+end_example
1540 It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
1541 Org-mode mailing list.
1543 ** Use MathJax for HTML export without requiring JavaScript
1544 As of 2010-08-14, MathJax is the default method used to export math to HTML.
1546 If you like the results but do not want JavaScript in the exported pages,
1547 check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
1548 HTML file from the exported version. It can also embed all referenced fonts
1549 within the HTML file itself, so there are no dependencies to external files.
1551 The download archive contains an elisp file which integrates it into the Org
1552 export process (configurable per file with a "#+StaticMathJax:" line).
1554 Read README.org and the comments in org-static-mathjax.el for usage instructions.
1555 ** Search Org files using lgrep
1557 Matt Lundi suggests this:
1559 #+begin_src emacs-lisp
1560   (defun my-org-grep (search &optional context)
1561     "Search for word in org files. 
1563 Prefix argument determines number of lines."
1564     (interactive "sSearch for: \nP")
1565     (let ((grep-find-ignored-files '("#*" ".#*"))
1566           (grep-template (concat "grep <X> -i -nH " 
1567                                  (when context
1568                                    (concat "-C" (number-to-string context)))
1569                                  " -e <R> <F>")))
1570       (lgrep search "*org*" "/home/matt/org/")))
1572   (global-set-key (kbd "<f8>") 'my-org-grep)
1573 #+end_src