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