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