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