2010-04-10 Carsten Dominik <carsten.dominik@gmail.com>
[bpt/emacs.git] / lisp / org / org-mobile.el
CommitLineData
8d642074 1;;; org-mobile.el --- Code for asymmetric sync with a mobile device
114f9c96 2;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
8d642074
CD
3;;
4;; Author: Carsten Dominik <carsten at orgmode dot org>
5;; Keywords: outlines, hypermedia, calendar, wp
6;; Homepage: http://orgmode.org
ed21c5c8 7;; Version: 6.35i
8d642074
CD
8;;
9;; This file is part of GNU Emacs.
10;;
11;; GNU Emacs is free software: you can redistribute it and/or modify
12;; it under the terms of the GNU General Public License as published by
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
15;;
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19;; GNU General Public License for more details.
20;;
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23;;
24;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25;;
26;;; Commentary:
27;;
28;; This file contains the code to interact with Richard Moreland's iPhone
29;; application MobileOrg. This code is documented in Appendix B of the
30;; Org-mode manual. The code is not specific for the iPhone, however.
8bfe682a 31;; Any external viewer/flagging/editing application that uses the same
8d642074
CD
32;; conventions could be used.
33
34(require 'org)
35(require 'org-agenda)
8bfe682a 36(eval-when-compile (require 'cl))
8d642074
CD
37
38(defgroup org-mobile nil
8bfe682a 39 "Options concerning support for a viewer/editor on a mobile device."
8d642074
CD
40 :tag "Org Mobile"
41 :group 'org)
42
43(defcustom org-mobile-files '(org-agenda-files)
44 "Files to be staged for MobileOrg.
8bfe682a 45This is basically a list of files and directories. Files will be staged
8d642074
CD
46directly. Directories will be search for files with the extension `.org'.
47In addition to this, the list may also contain the following symbols:
48
49org-agenda-files
ed21c5c8 50 This means include the complete, unrestricted list of files given in
8d642074
CD
51 the variable `org-agenda-files'.
52org-agenda-text-search-extra-files
53 Include the files given in the variable
54 `org-agenda-text-search-extra-files'"
55 :group 'org-mobile
56 :type '(list :greedy t
57 (option (const :tag "org-agenda-files" org-agenda-files))
58 (option (const :tag "org-agenda-text-search-extra-files"
59 org-agenda-text-search-extra-files))
60 (repeat :inline t :tag "Additional files"
61 (file))))
62
63(defcustom org-mobile-directory ""
64 "The WebDAV directory where the interaction with the mobile takes place."
65 :group 'org-mobile
66 :type 'directory)
67
ed21c5c8
CD
68(defcustom org-mobile-use-encryption nil
69 "Non-nil means keep only encrypted files on the webdav server.
70Encryption uses AES-256, with a password given in
71`org-mobile-encryption-password'.
72When nil, plain files are kept on the server.
73Turning on encryption requires to set the same password in the MobileOrg
74application."
75 :group 'org-mobile
76 :type 'boolean)
77
78(defcustom org-mobile-encryption-tempfile "~/orgtmpcrypt"
79 "File that is being used as a temporary file for encryption.
80This must be local file on your local machine (not on the webdav server).
81You might want to put this file into a directory where only you have access."
82 :group 'org-mobile
83 :type 'directory)
84
85(defcustom org-mobile-encryption-password ""
86 "Password for encrypting files uploaded to the server.
87This is a single password which is used for AES-256 encryption. The same
88password must also be set in the MobileOrg application. All Org files,
89including mobileorg.org will be encrypted using this password.
90Note that, whe Org runs the encryption commands, the password could
91be visible on your system with the `ps' command. So this method is only
92intended to keep the files secure on the server, not on your own machine."
93 :group 'org-mobile
94 :type '(string :tag "Password"))
95
8d642074
CD
96(defcustom org-mobile-inbox-for-pull "~/org/from-mobile.org"
97 "The file where captured notes and flags will be appended to.
98During the execution of `org-mobile-pull', the file
99`org-mobile-capture-file' will be emptied it's contents have
8bfe682a
CD
100been appended to the file given here. This file should be in
101`org-directory', and not in the staging area or on the web server."
8d642074
CD
102 :group 'org-mobile
103 :type 'file)
104
105(defconst org-mobile-capture-file "mobileorg.org"
106 "The capture file where the mobile stores captured notes and flags.
107This should not be changed, because MobileOrg assumes this name.")
108
109(defcustom org-mobile-index-file "index.org"
110 "The index file with inks to all Org files that should be loaded by MobileOrg.
111Relative to `org-mobile-directory'. The Address field in the MobileOrg setup
112should point to this file."
113 :group 'org-mobile
114 :type 'file)
115
ed21c5c8
CD
116(defcustom org-mobile-agendas 'all
117 "The agendas that should be pushed to MobileOrg.
118Allowed values:
119
120default the weekly agenda and the global TODO list
121custom all custom agendas defined by the user
122all the custom agendas and the default ones
123list a list of selection key(s) as string."
124 :group 'org-mobile
125 :type '(choice
126 (const :tag "Default Agendas" default)
127 (const :tag "Custom Agendas" custom)
128 (const :tag "Default and Custom Agendas" all)
129 (repeat :tag "Selected"
130 (string :tag "Selection Keys"))))
131
8d642074
CD
132(defcustom org-mobile-force-id-on-agenda-items t
133 "Non-nil means make all agenda items carry and ID."
134 :group 'org-mobile
135 :type 'boolean)
136
8bfe682a 137(defcustom org-mobile-force-mobile-change nil
ed21c5c8 138 "Non-nil means force the change made on the mobile device.
8bfe682a
CD
139So even if there have been changes to the computer version of the entry,
140force the new value set on the mobile.
141When nil, mark the entry from the mobile with an error message.
142Instead of nil or t, this variable can also be a list of symbols, indicating
143the editing types for which the mobile version should always dominate."
144 :group 'org-mobile
145 :type '(choice
146 (const :tag "Always" t)
147 (const :tag "Never" nil)
148 (set :greedy t :tag "Specify"
149 (const todo)
150 (const tags)
151 (const priority)
152 (const heading)
153 (const body))))
154
8d642074 155(defcustom org-mobile-action-alist
8bfe682a 156 '(("edit" . (org-mobile-edit data old new)))
8d642074
CD
157 "Alist with flags and actions for mobile sync.
158When flagging an entry, MobileOrg will create entries that look like
159
160 * F(action:data) [[id:entry-id][entry title]]
161
162This alist defines that the ACTION in the parentheses of F() should mean,
163i.e. what action should be taken. The :data part in the parenthesis is
164optional. If present, the string after the colon will be passed to the
165action form as the `data' variable.
166The car of each elements of the alist is an actions string. The cdr is
167an Emacs Lisp form that will be evaluated with the cursor on the headline
8bfe682a
CD
168of that entry.
169
170For now, it is not recommended to change this variable."
8d642074
CD
171 :group 'org-mobile
172 :type '(repeat
173 (cons (string :tag "Action flag")
174 (sexp :tag "Action form"))))
175
8bfe682a
CD
176(defcustom org-mobile-checksum-binary (or (executable-find "shasum")
177 (executable-find "sha1sum")
178 (executable-find "md5sum")
179 (executable-find "md5"))
180 "Executable used for computing checksums of agenda files."
181 :group 'org-mobile
182 :type 'string)
183
8d642074
CD
184(defvar org-mobile-pre-push-hook nil
185 "Hook run before running `org-mobile-push'.
186This could be used to clean up `org-mobile-directory', for example to
187remove files that used to be included in the agenda but no longer are.
188The presence of such files would not really be a problem, but after time
189they may accumulate.")
190
191(defvar org-mobile-post-push-hook nil
192 "Hook run after running `org-mobile-push'.
193If Emacs does not have direct write access to the WebDAV directory used
194by the mobile device, this hook should be used to copy all files from the
195local staging directory `org-mobile-directory' to the WebDAV directory,
196for example using `rsync' or `scp'.")
197
198(defvar org-mobile-pre-pull-hook nil
199 "Hook run before executing `org-mobile-pull'.
200If Emacs does not have direct write access to the WebDAV directory used
201by the mobile device, this hook should be used to copy the capture file
202`mobileorg.org' from the WebDAV location to the local staging
203directory `org-mobile-directory'.")
204
205(defvar org-mobile-post-pull-hook nil
206 "Hook run after running `org-mobile-pull'.
207If Emacs does not have direct write access to the WebDAV directory used
208by the mobile device, this hook should be used to copy the emptied
209capture file `mobileorg.org' back to the WebDAV directory, for example
210using `rsync' or `scp'.")
211
212(defvar org-mobile-last-flagged-files nil
8bfe682a 213 "List of files containing entries flagged in the latest pull.")
8d642074
CD
214
215(defvar org-mobile-files-alist nil)
216(defvar org-mobile-checksum-files nil)
217
218(defun org-mobile-prepare-file-lists ()
219 (setq org-mobile-files-alist (org-mobile-files-alist))
8bfe682a 220 (setq org-mobile-checksum-files nil))
8d642074
CD
221
222(defun org-mobile-files-alist ()
223 "Expand the list in `org-mobile-files' to a list of existing files."
8bfe682a
CD
224 (let* ((include-archives
225 (and (member 'org-agenda-text-search-extra-files org-mobile-files)
226 (member 'agenda-archives org-agenda-text-search-extra-files)
227 t))
228 (files
229 (apply 'append
230 (mapcar
231 (lambda (f)
232 (cond
233 ((eq f 'org-agenda-files)
234 (org-agenda-files t include-archives))
235 ((eq f 'org-agenda-text-search-extra-files)
236 (delq 'agenda-archives
237 (copy-sequence
238 org-agenda-text-search-extra-files)))
239 ((and (stringp f) (file-directory-p f))
240 (directory-files f 'full "\\.org\\'"))
241 ((and (stringp f) (file-exists-p f))
242 (list f))
243 (t nil)))
244 org-mobile-files)))
8d642074
CD
245 (orgdir-uname (file-name-as-directory (file-truename org-directory)))
246 (orgdir-re (concat "\\`" (regexp-quote orgdir-uname)))
247 uname seen rtn file link-name)
248 ;; Make the files unique, and determine the name under which they will
249 ;; be listed.
250 (while (setq file (pop files))
8bfe682a
CD
251 (if (not (file-name-absolute-p file))
252 (setq file (expand-file-name file org-directory)))
8d642074
CD
253 (setq uname (file-truename file))
254 (unless (member uname seen)
255 (push uname seen)
256 (if (string-match orgdir-re uname)
257 (setq link-name (substring uname (match-end 0)))
258 (setq link-name (file-name-nondirectory uname)))
259 (push (cons file link-name) rtn)))
260 (nreverse rtn)))
261
262;;;###autoload
263(defun org-mobile-push ()
264 "Push the current state of Org affairs to the WebDAV directory.
265This will create the index file, copy all agenda files there, and also
266create all custom agenda views, for upload to the mobile phone."
267 (interactive)
8bfe682a
CD
268 (let ((a-buffer (get-buffer org-agenda-buffer-name)))
269 (let ((org-agenda-buffer-name "*SUMO*")
270 (org-agenda-filter org-agenda-filter)
271 (org-agenda-redo-command org-agenda-redo-command))
272 (save-excursion
273 (save-window-excursion
274 (org-mobile-check-setup)
275 (org-mobile-prepare-file-lists)
276 (run-hooks 'org-mobile-pre-push-hook)
277 (message "Creating agendas...")
278 (let ((inhibit-redisplay t)) (org-mobile-create-sumo-agenda))
279 (message "Creating agendas...done")
280 (org-save-all-org-buffers) ; to save any IDs created by this process
281 (message "Copying files...")
282 (org-mobile-copy-agenda-files)
283 (message "Writing index file...")
284 (org-mobile-create-index-file)
285 (message "Writing checksums...")
286 (org-mobile-write-checksums)
287 (run-hooks 'org-mobile-post-push-hook))))
288 (redraw-display)
289 (when (and a-buffer (buffer-live-p a-buffer))
290 (if (not (get-buffer-window a-buffer))
291 (kill-buffer a-buffer)
292 (let ((cw (selected-window)))
293 (select-window (get-buffer-window a-buffer))
8bfe682a
CD
294 (org-agenda-redo)
295 (select-window cw)))))
8d642074 296 (message "Files for mobile viewer staged"))
ed21c5c8 297
8bfe682a
CD
298(defvar org-mobile-before-process-capture-hook nil
299 "Hook that is run after content was moved to `org-mobile-inbox-for-pull'.
ed21c5c8
CD
300The inbox file is visited by the current buffer, and the buffer is
301narrowed to the newly captured data.")
8d642074
CD
302
303;;;###autoload
304(defun org-mobile-pull ()
305 "Pull the contents of `org-mobile-capture-file' and integrate them.
306Apply all flagged actions, flag entries to be flagged and then call an
307agenda view showing the flagged items."
308 (interactive)
309 (org-mobile-check-setup)
310 (run-hooks 'org-mobile-pre-pull-hook)
311 (let ((insertion-marker (org-mobile-move-capture)))
312 (if (not (markerp insertion-marker))
313 (message "No new items")
314 (org-with-point-at insertion-marker
8bfe682a
CD
315 (save-restriction
316 (narrow-to-region (point) (point-max))
317 (run-hooks 'org-mobile-before-process-capture-hook)))
318 (org-with-point-at insertion-marker
319 (org-mobile-apply (point) (point-max)))
8d642074
CD
320 (move-marker insertion-marker nil)
321 (run-hooks 'org-mobile-post-pull-hook)
322 (when org-mobile-last-flagged-files
323 ;; Make an agenda view of flagged entries, but only in the files
324 ;; where stuff has been added.
325 (put 'org-agenda-files 'org-restrict org-mobile-last-flagged-files)
8bfe682a 326 (let ((org-agenda-keep-restricted-file-list t))
8d642074
CD
327 (org-agenda nil "?"))))))
328
329(defun org-mobile-check-setup ()
330 "Check if org-mobile-directory has been set up."
8bfe682a
CD
331 (unless (and org-directory
332 (stringp org-directory)
333 (string-match "\\S-" org-directory)
334 (file-exists-p org-directory)
335 (file-directory-p org-directory))
336 (error
337 "Please set `org-directory' to the directory where your org files live"))
338 (unless (and org-mobile-directory
339 (stringp org-mobile-directory)
340 (string-match "\\S-" org-mobile-directory)
341 (file-exists-p org-mobile-directory)
342 (file-directory-p org-mobile-directory))
8d642074
CD
343 (error
344 "Variable `org-mobile-directory' must point to an existing directory"))
8bfe682a
CD
345 (unless (and org-mobile-inbox-for-pull
346 (stringp org-mobile-inbox-for-pull)
347 (string-match "\\S-" org-mobile-inbox-for-pull)
348 (file-exists-p
349 (file-name-directory org-mobile-inbox-for-pull)))
8d642074 350 (error
ed21c5c8
CD
351 "Variable `org-mobile-inbox-for-pull' must point to a file in an existing directory"))
352 (when org-mobile-use-encryption
353 (unless (string-match "\\S-" org-mobile-encryption-password)
354 (error
355 "To use encryption, you must set `org-mobile-encryption-password'"))
356 (unless (file-writable-p org-mobile-encryption-tempfile)
357 (error "Cannot write to entryption tempfile %s"
358 org-mobile-encryption-tempfile))
359 (unless (executable-find "openssl")
360 (error "openssl is needed to encrypt files."))))
8d642074
CD
361
362(defun org-mobile-create-index-file ()
363 "Write the index file in the WebDAV directory."
8bfe682a
CD
364 (let ((files-alist (sort (copy-sequence org-mobile-files-alist)
365 (lambda (a b) (string< (cdr a) (cdr b)))))
366 (def-todo (default-value 'org-todo-keywords))
367 (def-tags (default-value 'org-tag-alist))
368 file link-name todo-kwds done-kwds tags drawers entry kwds dwds twds)
ed21c5c8 369
8d642074
CD
370 (org-prepare-agenda-buffers (mapcar 'car files-alist))
371 (setq done-kwds (org-uniquify org-done-keywords-for-agenda))
372 (setq todo-kwds (org-delete-all
373 done-kwds
374 (org-uniquify org-todo-keywords-for-agenda)))
375 (setq drawers (org-uniquify org-drawers-for-agenda))
376 (setq tags (org-uniquify
377 (delq nil
378 (mapcar
379 (lambda (e)
380 (cond ((stringp e) e)
381 ((listp e)
382 (if (stringp (car e)) (car e) nil))
383 (t nil)))
384 org-tag-alist-for-agenda))))
385 (with-temp-file
386 (expand-file-name org-mobile-index-file org-mobile-directory)
8bfe682a
CD
387 (while (setq entry (pop def-todo))
388 (insert "#+READONLY\n")
389 (setq kwds (mapcar (lambda (x) (if (string-match "(" x)
390 (substring x 0 (match-beginning 0))
391 x))
392 (cdr entry)))
393 (insert "#+TODO: " (mapconcat 'identity kwds " ") "\n")
394 (setq dwds (member "|" kwds)
395 twds (org-delete-all dwds kwds)
396 todo-kwds (org-delete-all twds todo-kwds)
397 done-kwds (org-delete-all dwds done-kwds)))
398 (when (or todo-kwds done-kwds)
399 (insert "#+TODO: " (mapconcat 'identity todo-kwds " ") " | "
400 (mapconcat 'identity done-kwds " ") "\n"))
401 (setq def-tags (mapcar
402 (lambda (x)
403 (cond ((null x) nil)
404 ((stringp x) x)
405 ((eq (car x) :startgroup) "{")
406 ((eq (car x) :endgroup) "}")
407 ((eq (car x) :newline) nil)
408 ((listp x) (car x))
409 (t nil)))
410 def-tags))
411 (setq def-tags (delq nil def-tags))
412 (setq tags (org-delete-all def-tags tags))
413 (setq tags (sort tags (lambda (a b) (string< (downcase a) (downcase b)))))
414 (setq tags (append def-tags tags nil))
415 (insert "#+TAGS: " (mapconcat 'identity tags " ") "\n")
416 (insert "#+DRAWERS: " (mapconcat 'identity drawers " ") "\n")
417 (insert "#+ALLPRIORITIES: A B C" "\n")
418 (when (file-exists-p (expand-file-name
419 org-mobile-directory "agendas.org"))
420 (insert "* [[file:agendas.org][Agenda Views]]\n"))
8d642074
CD
421 (while (setq entry (pop files-alist))
422 (setq file (car entry)
423 link-name (cdr entry))
424 (insert (format "* [[file:%s][%s]]\n"
425 link-name link-name)))
8bfe682a
CD
426 (push (cons org-mobile-index-file (md5 (buffer-string)))
427 org-mobile-checksum-files))))
8d642074
CD
428
429(defun org-mobile-copy-agenda-files ()
430 "Copy all agenda files to the stage or WebDAV directory."
431 (let ((files-alist org-mobile-files-alist)
8bfe682a 432 file buf entry link-name target-path target-dir check)
8d642074
CD
433 (while (setq entry (pop files-alist))
434 (setq file (car entry) link-name (cdr entry))
435 (when (file-exists-p file)
436 (setq target-path (expand-file-name link-name org-mobile-directory)
437 target-dir (file-name-directory target-path))
438 (unless (file-directory-p target-dir)
8bfe682a 439 (make-directory target-dir 'parents))
ed21c5c8
CD
440 (if org-mobile-use-encryption
441 (org-mobile-encrypt-and-move file target-path)
442 (copy-file file target-path 'ok-if-exists))
8bfe682a
CD
443 (setq check (shell-command-to-string
444 (concat org-mobile-checksum-binary " "
445 (shell-quote-argument (expand-file-name file)))))
446 (when (string-match "[a-fA-F0-9]\\{30,40\\}" check)
447 (push (cons link-name (match-string 0 check))
448 org-mobile-checksum-files))))
8d642074
CD
449 (setq file (expand-file-name org-mobile-capture-file
450 org-mobile-directory))
8bfe682a
CD
451 (save-excursion
452 (setq buf (find-file file))
453 (and (= (point-min) (point-max)) (insert "\n"))
454 (save-buffer)
455 (push (cons org-mobile-capture-file (md5 (buffer-string)))
456 org-mobile-checksum-files))
457 (kill-buffer buf)))
8d642074
CD
458
459(defun org-mobile-write-checksums ()
460 "Create checksums for all files in `org-mobile-directory'.
461The table of checksums is written to the file mobile-checksums."
8bfe682a
CD
462 (let ((sumfile (expand-file-name "checksums.dat" org-mobile-directory))
463 (files org-mobile-checksum-files)
464 entry file sum)
465 (with-temp-file sumfile
466 (set-buffer-file-coding-system 'undecided-unix nil)
467 (while (setq entry (pop files))
468 (setq file (car entry) sum (cdr entry))
469 (insert (format "%s %s\n" sum file))))))
8d642074
CD
470
471(defun org-mobile-sumo-agenda-command ()
472 "Return an agenda custom command that comprises all custom commands."
473 (let ((custom-list
474 ;; normalize different versions
475 (delq nil
476 (mapcar
477 (lambda (x)
478 (cond ((stringp (cdr x)) nil)
479 ((stringp (nth 1 x)) x)
480 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
481 (t (cons (car x) (cons "" (cdr x))))))
482 org-agenda-custom-commands)))
ed21c5c8
CD
483 (default-list '(("a" "Agenda" agenda) ("t" "All TODO" alltodo)))
484 thelist new e key desc type match settings cmds gkey gdesc gsettings cnt)
485 (cond
486 ((eq org-mobile-agendas 'custom)
487 (setq thelist custom-list))
488 ((eq org-mobile-agendas 'default)
489 (setq thelist default-list))
490 ((eq org-mobile-agendas 'all)
491 (setq thelist custom-list)
492 (unless (assoc "t" thelist) (push '("t" "ALL TODO" alltodo) thelist))
493 (unless (assoc "a" thelist) (push '("a" "Agenda" agenda) thelist)))
494 ((listp org-mobile-agendas)
495 (setq thelist (append custom-list default-list))
496 (setq thelist (delq nil (mapcar (lambda (k) (assoc k thelist))
497 org-mobile-agendas)))))
498 (while (setq e (pop thelist))
8d642074
CD
499 (cond
500 ((stringp (cdr e))
501 ;; this is a description entry - skip it
502 )
503 ((eq (nth 2 e) 'search)
504 ;; Search view is interactive, skip
505 )
506 ((memq (nth 2 e) '(todo-tree tags-tree occur-tree))
507 ;; These are trees, not really agenda commands
508 )
ed21c5c8
CD
509 ((and (memq (nth 2 e) '(todo tags tags-todo))
510 (or (null (nth 3 e))
511 (not (string-match "\\S-" (nth 3 e)))))
512 ;; These would be interactive because the match string is empty
513 )
514 ((memq (nth 2 e) '(agenda alltodo todo tags tags-todo))
8d642074
CD
515 ;; a normal command
516 (setq key (car e) desc (nth 1 e) type (nth 2 e) match (nth 3 e)
517 settings (nth 4 e))
518 (setq settings
519 (cons (list 'org-agenda-title-append
8bfe682a 520 (concat "<after>KEYS=" key " TITLE: "
8d642074
CD
521 (if (and (stringp desc) (> (length desc) 0))
522 desc (symbol-name type))
8bfe682a 523 " " match "</after>"))
8d642074
CD
524 settings))
525 (push (list type match settings) new))
526 ((symbolp (nth 2 e))
527 ;; A user-defined function, not sure how to handle that yet
528 )
529 (t
530 ;; a block agenda
531 (setq gkey (car e) gdesc (nth 1 e) gsettings (nth 3 e) cmds (nth 2 e))
532 (setq cnt 0)
533 (while (setq e (pop cmds))
534 (setq type (car e) match (nth 1 e) settings (nth 2 e))
535 (setq settings (append gsettings settings))
536 (setq settings
537 (cons (list 'org-agenda-title-append
8bfe682a 538 (concat "<after>KEYS=" gkey "#" (number-to-string
8d642074 539 (setq cnt (1+ cnt)))
8bfe682a 540 " TITLE: " gdesc " " match "</after>"))
8d642074
CD
541 settings))
542 (push (list type match settings) new)))))
8bfe682a
CD
543 (and new (list "X" "SUMO" (reverse new)
544 '((org-agenda-compact-blocks nil))))))
545
546(defvar org-mobile-creating-agendas nil)
547(defun org-mobile-write-agenda-for-mobile (file)
548 (let ((all (buffer-string)) in-date id pl prefix line app short m sexp)
549 (with-temp-file file
550 (org-mode)
551 (insert "#+READONLY\n")
552 (insert all)
553 (goto-char (point-min))
554 (while (not (eobp))
555 (cond
556 ((looking-at "[ \t]*$")) ; keep empty lines
557 ((looking-at "=+$")
558 ;; remove underlining
559 (delete-region (point) (point-at-eol)))
560 ((get-text-property (point) 'org-agenda-structural-header)
561 (setq in-date nil)
562 (setq app (get-text-property (point)
563 'org-agenda-title-append))
564 (setq short (get-text-property (point)
565 'short-heading))
566 (when (and short (looking-at ".+"))
567 (replace-match short)
568 (beginning-of-line 1))
569 (when app
570 (end-of-line 1)
571 (insert app)
572 (beginning-of-line 1))
573 (insert "* "))
574 ((get-text-property (point) 'org-agenda-date-header)
575 (setq in-date t)
576 (insert "** "))
577 ((setq m (or (get-text-property (point) 'org-hd-marker)
578 (get-text-property (point) 'org-marker)))
579 (setq sexp (member (get-text-property (point) 'type)
580 '("diary" "sexp")))
581 (if (setq pl (get-text-property (point) 'prefix-length))
582 (progn
583 (setq prefix (org-trim (buffer-substring
584 (point) (+ (point) pl)))
585 line (org-trim (buffer-substring
586 (+ (point) pl)
587 (point-at-eol))))
588 (delete-region (point-at-bol) (point-at-eol))
589 (insert line "<before>" prefix "</before>")
590 (beginning-of-line 1))
591 (and (looking-at "[ \t]+") (replace-match "")))
592 (insert (if in-date "*** " "** "))
593 (end-of-line 1)
594 (insert "\n")
595 (unless sexp
596 (insert (org-agenda-get-some-entry-text
597 m 10 " " 'planning)
598 "\n")
599 (when (setq id
600 (if (org-bound-and-true-p
601 org-mobile-force-id-on-agenda-items)
602 (org-id-get m 'create)
603 (org-entry-get m "ID")))
604 (insert " :PROPERTIES:\n :ORIGINAL_ID: " id
605 "\n :END:\n")))))
606 (beginning-of-line 2))
607 (push (cons (file-name-nondirectory file) (md5 (buffer-string)))
608 org-mobile-checksum-files))
609 (message "Agenda written to Org file %s" file)))
8d642074
CD
610
611;;;###autoload
612(defun org-mobile-create-sumo-agenda ()
613 "Create a file that contains all custom agenda views."
614 (interactive)
615 (let* ((file (expand-file-name "agendas.org"
616 org-mobile-directory))
ed21c5c8
CD
617 (file1 (if org-mobile-use-encryption
618 org-mobile-encryption-tempfile
619 file))
8bfe682a 620 (sumo (org-mobile-sumo-agenda-command))
8d642074 621 (org-agenda-custom-commands
ed21c5c8 622 (list (append sumo (list (list file1)))))
8bfe682a 623 (org-mobile-creating-agendas t))
ed21c5c8
CD
624 (unless (file-writable-p file1)
625 (error "Cannot write to file %s" file1))
8bfe682a 626 (when sumo
ed21c5c8
CD
627 (org-store-agenda-views))
628 (when org-mobile-use-encryption
629 (org-mobile-encrypt-file file1 file)
630 (delete-file file1))))
631
632(defun org-mobile-encrypt-and-move (infile outfile)
633 "Encrypt INFILE locally to INFILE_enc, then move it to OUTFILE.
634We do this in two steps so that remote paths will work, even if the
635encryption program does not understand them."
636 (let ((encfile (concat infile "_enc")))
637 (org-mobile-encrypt-file infile encfile)
638 (when outfile
639 (copy-file encfile outfile 'ok-if-exists)
640 (delete-file encfile))))
641
642(defun org-mobile-encrypt-file (infile outfile)
643 "Encrypt INFILE to OUTFILE, using `org-mobile-encryption-password'."
644 (shell-command
645 (format "openssl enc -aes-256-cbc -salt -pass %s -in %s -out %s"
646 (shell-quote-argument (concat "pass:" org-mobile-encryption-password))
647 (shell-quote-argument (expand-file-name infile))
648 (shell-quote-argument (expand-file-name outfile)))))
649
650(defun org-mobile-decrypt-file (infile outfile)
651 "Decrypt INFILE to OUTFILE, using `org-mobile-encryption-password'."
652 (shell-command
653 (format "openssl enc -d -aes-256-cbc -salt -pass %s -in %s -out %s"
654 (shell-quote-argument (concat "pass:" org-mobile-encryption-password))
655 (shell-quote-argument (expand-file-name infile))
656 (shell-quote-argument (expand-file-name outfile)))))
8d642074
CD
657
658(defun org-mobile-move-capture ()
659 "Move the contents of the capture file to the inbox file.
660Return a marker to the location where the new content has been added.
8bfe682a 661If nothing new has been added, return nil."
8d642074 662 (interactive)
ed21c5c8
CD
663 (let* ((encfile nil)
664 (capture-file (expand-file-name org-mobile-capture-file
665 org-mobile-directory))
666 (inbox-buffer (find-file-noselect org-mobile-inbox-for-pull))
667 (capture-buffer
668 (if (not org-mobile-use-encryption)
669 (find-file-noselect capture-file)
670 (delete-file org-mobile-encryption-tempfile)
671 (setq encfile (concat org-mobile-encryption-tempfile "_enc"))
672 (copy-file capture-file encfile)
673 (org-mobile-decrypt-file encfile org-mobile-encryption-tempfile)
674 (find-file-noselect org-mobile-encryption-tempfile)))
675 (insertion-point (make-marker))
676 not-empty content)
81ad75af 677 (with-current-buffer capture-buffer
8d642074
CD
678 (setq content (buffer-string))
679 (setq not-empty (string-match "\\S-" content))
680 (when not-empty
681 (set-buffer inbox-buffer)
682 (widen)
683 (goto-char (point-max))
684 (or (bolp) (newline))
685 (move-marker insertion-point
686 (prog1 (point) (insert content)))
687 (save-buffer)
688 (set-buffer capture-buffer)
689 (erase-buffer)
8bfe682a
CD
690 (save-buffer)
691 (org-mobile-update-checksum-for-capture-file (buffer-string))))
8d642074 692 (kill-buffer capture-buffer)
ed21c5c8
CD
693 (when org-mobile-use-encryption
694 (org-mobile-encrypt-and-move org-mobile-encryption-tempfile
695 capture-file))
8d642074
CD
696 (if not-empty insertion-point)))
697
8bfe682a 698(defun org-mobile-update-checksum-for-capture-file (buffer-string)
ed21c5c8 699 "Find the checksum line and modify it to match BUFFER-STRING."
8bfe682a
CD
700 (let* ((file (expand-file-name "checksums.dat" org-mobile-directory))
701 (buffer (find-file-noselect file)))
702 (when buffer
703 (with-current-buffer buffer
704 (when (re-search-forward (concat "\\([0-9a-fA-F]\\{30,\\}\\).*?"
705 (regexp-quote org-mobile-capture-file)
706 "[ \t]*$") nil t)
707 (goto-char (match-beginning 1))
708 (delete-region (match-beginning 1) (match-end 1))
709 (insert (md5 buffer-string))
710 (save-buffer)))
711 (kill-buffer buffer))))
712
713(defun org-mobile-apply (&optional beg end)
714 "Apply all change requests in the current buffer.
8d642074
CD
715If BEG and END are given, only do this in that region."
716 (interactive)
717 (require 'org-archive)
718 (setq org-mobile-last-flagged-files nil)
719 (setq beg (or beg (point-min)) end (or end (point-max)))
8bfe682a
CD
720
721 ;; Remove all Note IDs
8d642074 722 (goto-char beg)
8bfe682a
CD
723 (while (re-search-forward "^\\*\\* Note ID: [-0-9A-F]+[ \t]*\n" end t)
724 (replace-match ""))
725
726 ;; Find all the referenced entries, without making any changes yet
8d642074 727 (let ((marker (make-marker))
8bfe682a 728 (bos-marker (make-marker))
8d642074 729 (end (move-marker (make-marker) end))
8bfe682a
CD
730 (cnt-new 0)
731 (cnt-edit 0)
732 (cnt-flag 0)
733 (cnt-error 0)
734 buf-list
735 id-pos org-mobile-error)
736
737 ;; Count the new captures
738 (goto-char beg)
739 (while (re-search-forward "^\\* \\(.*\\)" end t)
740 (and (>= (- (match-end 1) (match-beginning 1)) 2)
741 (not (equal (downcase (substring (match-string 1) 0 2)) "f("))
742 (incf cnt-new)))
743
744 (goto-char beg)
8d642074 745 (while (re-search-forward
8bfe682a
CD
746 "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)[ \t]+\\[\\[\\(\\(id\\|olp\\):\\([^]\n]+\\)\\)" end t)
747 (setq id-pos (condition-case msg
748 (org-mobile-locate-entry (match-string 4))
749 (error (nth 1 msg))))
750 (when (and (markerp id-pos)
751 (not (member (marker-buffer id-pos) buf-list)))
752 (org-mobile-timestamp-buffer (marker-buffer id-pos))
753 (push (marker-buffer id-pos) buf-list))
754
755 (if (or (not id-pos) (stringp id-pos))
756 (progn
757 (goto-char (+ 2 (point-at-bol)))
758 (insert id-pos " ")
759 (incf cnt-error))
760 (add-text-properties (point-at-bol) (point-at-eol)
761 (list 'org-mobile-marker
762 (or id-pos "Linked entry not found")))))
763
764 ;; OK, now go back and start applying
765 (goto-char beg)
766 (while (re-search-forward "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)" end t)
8d642074 767 (catch 'next
8bfe682a
CD
768 (setq id-pos (get-text-property (point-at-bol) 'org-mobile-marker))
769 (if (not (markerp id-pos))
770 (progn
771 (incf cnt-error)
772 (insert "UNKNOWN PROBLEM"))
773 (let* ((action (match-string 1))
774 (data (and (match-end 3) (match-string 3)))
775 (bos (point-at-bol))
776 (eos (save-excursion (org-end-of-subtree t t)))
777 (cmd (if (equal action "")
778 '(progn
779 (incf cnt-flag)
780 (org-toggle-tag "FLAGGED" 'on)
781 (and note
782 (org-entry-put nil "THEFLAGGINGNOTE" note)))
783 (incf cnt-edit)
784 (cdr (assoc action org-mobile-action-alist))))
785 (note (and (equal action "")
786 (buffer-substring (1+ (point-at-eol)) eos)))
787 (org-inhibit-logging 'note) ;; Do not take notes interactively
788 old new)
789 (goto-char bos)
790 (move-marker bos-marker (point))
791 (if (re-search-forward "^** Old value[ \t]*$" eos t)
792 (setq old (buffer-substring
793 (1+ (match-end 0))
794 (progn (outline-next-heading) (point)))))
795 (if (re-search-forward "^** New value[ \t]*$" eos t)
796 (setq new (buffer-substring
797 (1+ (match-end 0))
798 (progn (outline-next-heading)
799 (if (eobp) (org-back-over-empty-lines))
800 (point)))))
801 (setq old (and old (if (string-match "\\S-" old) old nil)))
802 (setq new (and new (if (string-match "\\S-" new) new nil)))
803 (if (and note (> (length note) 0))
804 ;; Make Note into a single line, to fit into a property
805 (setq note (mapconcat 'identity
806 (org-split-string (org-trim note) "\n")
807 "\\n")))
808 (unless (equal data "body")
809 (setq new (and new (org-trim new))
810 old (and old (org-trim old))))
811 (goto-char (+ 2 bos-marker))
812 (unless (markerp id-pos)
813 (insert "BAD REFERENCE ")
814 (incf cnt-error)
815 (throw 'next t))
816 (unless cmd
817 (insert "BAD FLAG ")
818 (incf cnt-error)
819 (throw 'next t))
820 ;; Remember this place so that we can return
821 (move-marker marker (point))
822 (setq org-mobile-error nil)
823 (save-excursion
824 (condition-case msg
825 (org-with-point-at id-pos
826 (progn
8d642074
CD
827 (eval cmd)
828 (if (member "FLAGGED" (org-get-tags))
829 (add-to-list 'org-mobile-last-flagged-files
830 (buffer-file-name (current-buffer))))))
8bfe682a
CD
831 (error (setq org-mobile-error msg))))
832 (when org-mobile-error
833 (switch-to-buffer (marker-buffer marker))
834 (goto-char marker)
835 (incf cnt-error)
836 (insert (if (stringp (nth 1 org-mobile-error))
837 (nth 1 org-mobile-error)
838 "EXECUTION FAILED")
839 " ")
840 (throw 'next t))
841 ;; If we get here, the action has been applied successfully
842 ;; So remove the entry
843 (goto-char bos-marker)
844 (delete-region (point) (org-end-of-subtree t t))))))
845 (save-buffer)
8d642074 846 (move-marker marker nil)
8bfe682a
CD
847 (move-marker end nil)
848 (message "%d new, %d edits, %d flags, %d errors" cnt-new
849 cnt-edit cnt-flag cnt-error)
850 (sit-for 1)))
851
852(defun org-mobile-timestamp-buffer (buf)
853 "Time stamp buffer BUF, just to make sure its checksum will change."
854 (with-current-buffer buf
855 (save-excursion
856 (save-restriction
857 (widen)
858 (goto-char (point-min))
859 (if (re-search-forward
860 "^\\([ \t]*\\)#\\+LAST_MOBILE_CHANGE:.*\n?" nil t)
861 (progn
862 (goto-char (match-end 1))
863 (delete-region (point) (match-end 0)))
864 (if (looking-at ".*?-\\*-.*-\\*-")
865 (forward-line 1)))
866 (insert "#+LAST_MOBILE_CHANGE: "
867 (format-time-string "%Y-%m-%d %T") "\n")))))
8d642074
CD
868
869(defun org-mobile-smart-read ()
870 "Parse the entry at point for shortcuts and expand them.
871These shortcuts are meant for fast and easy typing on the limited
872keyboards of a mobile device. Below we show a list of the shortcuts
873currently implemented.
874
875The entry is expected to contain an inactive time stamp indicating when
876the entry was created. When setting dates and
877times (for example for deadlines), the time strings are interpreted
878relative to that creation date.
8bfe682a 879Abbreviations are expected to take up entire lines, just because it is so
8d642074
CD
880easy to type RET on a mobile device. Abbreviations start with one or two
881letters, followed immediately by a dot and then additional information.
882Generally the entire shortcut line is removed after action have been taken.
883Time stamps will be constructed using `org-read-date'. So for example a
884line \"dd. 2tue\" will set a deadline on the second Tuesday after the
885creation date.
886
887Here are the shortcuts currently implemented:
888
889dd. string set deadline
890ss. string set scheduling
891tt. string set time tamp, here.
892ti. string set inactive time
893
894tg. tag1 tag2 tag3 set all these tags, change case where necessary
895td. kwd set this todo keyword, change case where necessary
896
897FIXME: Hmmm, not sure if we can make his work against the
898auto-correction feature. Needs a bit more thinking. So this function
899is currently a noop.")
900
8bfe682a
CD
901
902(defun org-find-olp (path)
903 "Return a marker pointing to the entry at outline path OLP.
904If anything goes wrong, the return value will instead an error message,
905as a string."
906 (let* ((file (pop path))
907 (buffer (find-file-noselect file))
908 (level 1)
909 (lmin 1)
910 (lmax 1)
911 limit re end found pos heading cnt)
912 (unless buffer (error "File not found :%s" file))
913 (with-current-buffer buffer
914 (save-excursion
915 (save-restriction
916 (widen)
917 (setq limit (point-max))
918 (goto-char (point-min))
919 (while (setq heading (pop path))
920 (setq re (format org-complex-heading-regexp-format
921 (regexp-quote heading)))
922 (setq cnt 0 pos (point))
923 (while (re-search-forward re end t)
924 (setq level (- (match-end 1) (match-beginning 1)))
925 (if (and (>= level lmin) (<= level lmax))
926 (setq found (match-beginning 0) cnt (1+ cnt))))
927 (when (= cnt 0) (error "Heading not found on level %d: %s"
928 lmax heading))
929 (when (> cnt 1) (error "Heading not unique on level %d: %s"
930 lmax heading))
931 (goto-char found)
932 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
933 (setq end (save-excursion (org-end-of-subtree t t))))
934 (when (org-on-heading-p)
935 (move-marker (make-marker) (point))))))))
936
937(defun org-mobile-locate-entry (link)
938 (if (string-match "\\`id:\\(.*\\)$" link)
939 (org-id-find (match-string 1 link) 'marker)
940 (if (not (string-match "\\`olp:\\(.*?\\):\\(.*\\)$" link))
941 nil
942 (let ((file (match-string 1 link))
943 (path (match-string 2 link))
944 (table '((?: . "%3a") (?\[ . "%5b") (?\] . "%5d") (?/ . "%2f"))))
945 (setq file (org-link-unescape file table))
946 (setq file (expand-file-name file org-directory))
947 (setq path (mapcar (lambda (x) (org-link-unescape x table))
948 (org-split-string path "/")))
949 (org-find-olp (cons file path))))))
950
951(defun org-mobile-edit (what old new)
952 "Edit item WHAT in the current entry by replacing OLD with NEW.
953WHAT can be \"heading\", \"todo\", \"tags\", \"priority\", or \"body\".
954The edit only takes place if the current value is equal (except for
955white space) the OLD. If this is so, OLD will be replace by NEW
956and the command will return t. If something goes wrong, a string will
957be returned that indicates what went wrong."
958 (let (current old1 new1)
959 (if (stringp what) (setq what (intern what)))
960
961 (cond
962
963 ((memq what '(todo todostate))
964 (setq current (org-get-todo-state))
965 (cond
966 ((equal new "DONEARCHIVE")
967 (org-todo 'done)
968 (org-archive-subtree-default))
969 ((equal new current) t) ; nothing needs to be done
970 ((or (equal current old)
971 (eq org-mobile-force-mobile-change t)
972 (memq 'todo org-mobile-force-mobile-change))
973 (org-todo (or new 'none)) t)
974 (t (error "State before change was expected as \"%s\", but is \"%s\""
975 old current))))
ed21c5c8 976
8bfe682a
CD
977 ((eq what 'tags)
978 (setq current (org-get-tags)
979 new1 (and new (org-split-string new ":+"))
980 old1 (and old (org-split-string old ":+")))
981 (cond
982 ((org-mobile-tags-same-p current new1) t) ; no change needed
983 ((or (org-mobile-tags-same-p current old1)
984 (eq org-mobile-force-mobile-change t)
985 (memq 'tags org-mobile-force-mobile-change))
986 (org-set-tags-to new1) t)
987 (t (error "Tags before change were expected as \"%s\", but are \"%s\""
988 (or old "") (or current "")))))
ed21c5c8 989
8bfe682a
CD
990 ((eq what 'priority)
991 (when (looking-at org-complex-heading-regexp)
992 (setq current (and (match-end 3) (substring (match-string 3) 2 3)))
993 (cond
994 ((equal current new) t) ; no action required
995 ((or (equal current old)
996 (eq org-mobile-force-mobile-change t)
997 (memq 'tags org-mobile-force-mobile-change))
998 (org-priority (and new (string-to-char new))))
999 (t (error "Priority was expected to be %s, but is %s"
1000 old current)))))
1001
1002 ((eq what 'heading)
1003 (when (looking-at org-complex-heading-regexp)
1004 (setq current (match-string 4))
1005 (cond
1006 ((equal current new) t) ; no action required
1007 ((or (equal current old)
1008 (eq org-mobile-force-mobile-change t)
1009 (memq 'heading org-mobile-force-mobile-change))
1010 (goto-char (match-beginning 4))
1011 (insert new)
1012 (delete-region (point) (+ (point) (length current)))
1013 (org-set-tags nil 'align))
1014 (t (error "Heading changed in MobileOrg and on the computer")))))
ed21c5c8 1015
8bfe682a
CD
1016 ((eq what 'body)
1017 (setq current (buffer-substring (min (1+ (point-at-eol)) (point-max))
1018 (save-excursion (outline-next-heading)
1019 (point))))
1020 (if (not (string-match "\\S-" current)) (setq current nil))
1021 (cond
1022 ((org-mobile-bodies-same-p current new) t) ; no action necessary
1023 ((or (org-mobile-bodies-same-p current old)
1024 (eq org-mobile-force-mobile-change t)
1025 (memq 'body org-mobile-force-mobile-change))
1026 (save-excursion
1027 (end-of-line 1)
1028 (insert "\n" new)
1029 (or (bolp) (insert "\n"))
1030 (delete-region (point) (progn (org-back-to-heading t)
1031 (outline-next-heading)
1032 (point))))
1033 t)
1034 (t (error "Body was changed in MobileOrg and on the computer")))))))
ed21c5c8 1035
8bfe682a
CD
1036
1037(defun org-mobile-tags-same-p (list1 list2)
1038 "Are the two tag lists the same?"
1039 (not (or (org-delete-all list1 list2)
1040 (org-delete-all list2 list1))))
1041
1042(defun org-mobile-bodies-same-p (a b)
1043 "Compare if A and B are visually equal strings.
1044We first remove leading and trailing white space from the entire strings.
1045Then we split the strings into lines and remove leading/trailing whitespace
1046from each line. Then we compare.
1047A and B must be strings or nil."
1048 (cond
1049 ((and (not a) (not b)) t)
1050 ((or (not a) (not b)) nil)
1051 (t (setq a (org-trim a) b (org-trim b))
1052 (setq a (mapconcat 'identity (org-split-string a "[ \t]*\n[ \t]*") "\n"))
1053 (setq b (mapconcat 'identity (org-split-string b "[ \t]*\n[ \t]*") "\n"))
1054 (equal a b))))
1055
8d642074
CD
1056(provide 'org-mobile)
1057
1058;; arch-tag: ace0e26c-58f2-4309-8a61-05ec1535f658
1059
1060;;; org-mobile.el ends here
1061