Release 6.35b
[org-mode/org-tableheadings.git] / lisp / org-mobile.el
blobcd7a446a80ae8ce906f6f9626ceed436aca6c88b
1 ;;; org-mobile.el --- Code for asymmetric sync with a mobile device
2 ;; Copyright (C) 2009 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.35b
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 (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."))))
362 (defun org-mobile-create-index-file ()
363 "Write the index file in the WebDAV directory."
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)
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)
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))
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"))
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)))
426 (push (cons org-mobile-index-file (md5 (buffer-string)))
427 org-mobile-checksum-files))))
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)
432 file buf entry link-name target-path target-dir check)
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)
439 (make-directory target-dir 'parents))
440 (if org-mobile-use-encryption
441 (org-mobile-encrypt-and-move file target-path)
442 (copy-file file target-path 'ok-if-exists))
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))))
449 (setq file (expand-file-name org-mobile-capture-file
450 org-mobile-directory))
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)))
459 (defun org-mobile-write-checksums ()
460 "Create checksums for all files in `org-mobile-directory'.
461 The table of checksums is written to the file mobile-checksums."
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))))))
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)))
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))
499 (cond
500 ((stringp (cdr e))
501 ;; this is a description entry - skip it
503 ((eq (nth 2 e) 'search)
504 ;; Search view is interactive, skip
506 ((memq (nth 2 e) '(todo-tree tags-tree occur-tree))
507 ;; These are trees, not really agenda commands
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
514 ((memq (nth 2 e) '(agenda alltodo todo tags tags-todo))
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
520 (concat "<after>KEYS=" key " TITLE: "
521 (if (and (stringp desc) (> (length desc) 0))
522 desc (symbol-name type))
523 " " match "</after>"))
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
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
538 (concat "<after>KEYS=" gkey "#" (number-to-string
539 (setq cnt (1+ cnt)))
540 " TITLE: " gdesc " " match "</after>"))
541 settings))
542 (push (list type match settings) new)))))
543 (and new (list "X" "SUMO" (reverse new)
544 '((org-agenda-compact-blocks nil))))))
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)))
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))
617 (file1 (if org-mobile-use-encryption
618 org-mobile-encryption-tempfile
619 file))
620 (sumo (org-mobile-sumo-agenda-command))
621 (org-agenda-custom-commands
622 (list (append sumo (list (list file1)))))
623 (org-mobile-creating-agendas t))
624 (unless (file-writable-p file1)
625 (error "Cannot write to file %s" file1))
626 (when sumo
627 (org-store-agenda-views))
628 (when org-mobile-use-encryption
629 (org-mobile-encrypt-file file1 file)
630 (delete-file file1))))
632 (defun org-mobile-encrypt-and-move (infile outfile)
633 "Encrypt INFILE locally to INFILE_enc, then move it to OUTFILE.
634 We do this in two steps so that remote paths will work, even if the
635 encryption 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))))
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)))))
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)))))
658 (defun org-mobile-move-capture ()
659 "Move the contents of the capture file to the inbox file.
660 Return a marker to the location where the new content has been added.
661 If nothing new has been added, return nil."
662 (interactive)
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)
677 (with-current-buffer capture-buffer
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)
690 (save-buffer)
691 (org-mobile-update-checksum-for-capture-file (buffer-string))))
692 (kill-buffer capture-buffer)
693 (when org-mobile-use-encryption
694 (org-mobile-encrypt-and-move org-mobile-encryption-tempfile
695 capture-file))
696 (if not-empty insertion-point)))
698 (defun org-mobile-update-checksum-for-capture-file (buffer-string)
699 "Find the checksum line and modify it to match BUFFER-STRING."
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))))
713 (defun org-mobile-apply (&optional beg end)
714 "Apply all change requests in the current buffer.
715 If 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)))
721 ;; Remove all Note IDs
722 (goto-char beg)
723 (while (re-search-forward "^\\*\\* Note ID: [-0-9A-F]+[ \t]*\n" end t)
724 (replace-match ""))
726 ;; Find all the referenced entries, without making any changes yet
727 (let ((marker (make-marker))
728 (bos-marker (make-marker))
729 (end (move-marker (make-marker) end))
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)
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)))
744 (goto-char beg)
745 (while (re-search-forward
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))
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")))))
764 ;; OK, now go back and start applying
765 (goto-char beg)
766 (while (re-search-forward "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)" end t)
767 (catch 'next
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
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))))))
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)
846 (move-marker marker nil)
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)))
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")))))
869 (defun org-mobile-smart-read ()
870 "Parse the entry at point for shortcuts and expand them.
871 These shortcuts are meant for fast and easy typing on the limited
872 keyboards of a mobile device. Below we show a list of the shortcuts
873 currently implemented.
875 The entry is expected to contain an inactive time stamp indicating when
876 the entry was created. When setting dates and
877 times (for example for deadlines), the time strings are interpreted
878 relative to that creation date.
879 Abbreviations are expected to take up entire lines, just because it is so
880 easy to type RET on a mobile device. Abbreviations start with one or two
881 letters, followed immediately by a dot and then additional information.
882 Generally the entire shortcut line is removed after action have been taken.
883 Time stamps will be constructed using `org-read-date'. So for example a
884 line \"dd. 2tue\" will set a deadline on the second Tuesday after the
885 creation date.
887 Here are the shortcuts currently implemented:
889 dd. string set deadline
890 ss. string set scheduling
891 tt. string set time tamp, here.
892 ti. string set inactive time
894 tg. tag1 tag2 tag3 set all these tags, change case where necessary
895 td. kwd set this todo keyword, change case where necessary
897 FIXME: Hmmm, not sure if we can make his work against the
898 auto-correction feature. Needs a bit more thinking. So this function
899 is currently a noop.")
902 (defun org-find-olp (path)
903 "Return a marker pointing to the entry at outline path OLP.
904 If anything goes wrong, the return value will instead an error message,
905 as 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))))))))
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))
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))))))
951 (defun org-mobile-edit (what old new)
952 "Edit item WHAT in the current entry by replacing OLD with NEW.
953 WHAT can be \"heading\", \"todo\", \"tags\", \"priority\", or \"body\".
954 The edit only takes place if the current value is equal (except for
955 white space) the OLD. If this is so, OLD will be replace by NEW
956 and the command will return t. If something goes wrong, a string will
957 be returned that indicates what went wrong."
958 (let (current old1 new1)
959 (if (stringp what) (setq what (intern what)))
961 (cond
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))))
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 "")))))
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)))))
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")))))
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))))
1034 (t (error "Body was changed in MobileOrg and on the computer")))))))
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))))
1042 (defun org-mobile-bodies-same-p (a b)
1043 "Compare if A and B are visually equal strings.
1044 We first remove leading and trailing white space from the entire strings.
1045 Then we split the strings into lines and remove leading/trailing whitespace
1046 from each line. Then we compare.
1047 A 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))))
1056 (provide 'org-mobile)
1058 ;; arch-tag: ace0e26c-58f2-4309-8a61-05ec1535f658
1060 ;;; org-mobile.el ends here