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