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