Change `org-get-tags' specifications
[org-mode/org-tableheadings.git] / lisp / org-mobile.el
blob28b1157fe4cba2167ad08060e31c6cb3cd9e6325
1 ;;; org-mobile.el --- Code for Asymmetric Sync With a Mobile Device -*- lexical-binding: t; -*-
2 ;; Copyright (C) 2009-2018 Free Software Foundation, Inc.
3 ;;
4 ;; Author: Carsten Dominik <carsten at orgmode dot org>
5 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://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 <https://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 ((org-agenda-buffer-name "*SUMO*")
312 (org-agenda-tag-filter org-agenda-tag-filter)
313 (org-agenda-redo-command org-agenda-redo-command))
314 ;; Offer to save agenda-related buffers before pushing, preventing
315 ;; "Non-existent agenda file" prompt for lock files (see #19448).
316 (let ((agenda-buffers (org-buffer-list 'agenda)))
317 (save-some-buffers nil
318 (lambda () (memq (current-buffer) agenda-buffers))))
319 (save-excursion
320 (save-restriction
321 (save-window-excursion
322 (run-hooks 'org-mobile-pre-push-hook)
323 (org-mobile-check-setup)
324 (org-mobile-prepare-file-lists)
325 (message "Creating agendas...")
326 (let ((inhibit-redisplay t)
327 (org-agenda-files (mapcar 'car org-mobile-files-alist)))
328 (org-mobile-create-sumo-agenda))
329 (message "Creating agendas...done")
330 (org-save-all-org-buffers) ; to save any IDs created by this process
331 (message "Copying files...")
332 (org-mobile-copy-agenda-files)
333 (message "Writing index file...")
334 (org-mobile-create-index-file)
335 (message "Writing checksums...")
336 (org-mobile-write-checksums)
337 (run-hooks 'org-mobile-post-push-hook)))))
338 (org-agenda-maybe-redo)
339 (message "Files for mobile viewer staged"))
341 (defvar org-mobile-before-process-capture-hook nil
342 "Hook that is run after content was moved to `org-mobile-inbox-for-pull'.
343 The inbox file is visited by the current buffer, and the buffer is
344 narrowed to the newly captured data.")
346 ;;;###autoload
347 (defun org-mobile-pull ()
348 "Pull the contents of `org-mobile-capture-file' and integrate them.
349 Apply all flagged actions, flag entries to be flagged and then call an
350 agenda view showing the flagged items."
351 (interactive)
352 (org-mobile-check-setup)
353 (run-hooks 'org-mobile-pre-pull-hook)
354 (let ((insertion-marker (org-mobile-move-capture)))
355 (if (not (markerp insertion-marker))
356 (message "No new items")
357 (org-with-point-at insertion-marker
358 (save-restriction
359 (narrow-to-region (point) (point-max))
360 (run-hooks 'org-mobile-before-process-capture-hook)))
361 (org-with-point-at insertion-marker
362 (org-mobile-apply (point) (point-max)))
363 (move-marker insertion-marker nil)
364 (run-hooks 'org-mobile-post-pull-hook)
365 (when org-mobile-last-flagged-files
366 ;; Make an agenda view of flagged entries, but only in the files
367 ;; where stuff has been added.
368 (put 'org-agenda-files 'org-restrict org-mobile-last-flagged-files)
369 (let ((org-agenda-keep-restricted-file-list t))
370 (org-agenda nil "?"))))))
372 (defun org-mobile-check-setup ()
373 "Check if org-mobile-directory has been set up."
374 (org-mobile-cleanup-encryption-tempfile)
375 (unless (and org-directory
376 (stringp org-directory)
377 (string-match "\\S-" org-directory)
378 (file-exists-p org-directory)
379 (file-directory-p org-directory))
380 (error
381 "Please set `org-directory' to the directory where your org files live"))
382 (unless (and org-mobile-directory
383 (stringp org-mobile-directory)
384 (string-match "\\S-" org-mobile-directory)
385 (file-exists-p org-mobile-directory)
386 (file-directory-p org-mobile-directory))
387 (error
388 "Variable `org-mobile-directory' must point to an existing directory"))
389 (unless (and org-mobile-inbox-for-pull
390 (stringp org-mobile-inbox-for-pull)
391 (string-match "\\S-" org-mobile-inbox-for-pull)
392 (file-exists-p
393 (file-name-directory org-mobile-inbox-for-pull)))
394 (error
395 "Variable `org-mobile-inbox-for-pull' must point to a file in an existing directory"))
396 (unless (and org-mobile-checksum-binary
397 (string-match "\\S-" org-mobile-checksum-binary))
398 (error "No executable found to compute checksums"))
399 (when org-mobile-use-encryption
400 (unless (string-match "\\S-" (org-mobile-encryption-password))
401 (error
402 "To use encryption, you must set `org-mobile-encryption-password'"))
403 (unless (file-writable-p org-mobile-encryption-tempfile)
404 (error "Cannot write to encryption tempfile %s"
405 org-mobile-encryption-tempfile))
406 (unless (executable-find "openssl")
407 (error "OpenSSL is needed to encrypt files"))))
409 (defun org-mobile-create-index-file ()
410 "Write the index file in the WebDAV directory."
411 (let ((files-alist (sort (copy-sequence org-mobile-files-alist)
412 (lambda (a b) (string< (cdr a) (cdr b)))))
413 (def-todo (default-value 'org-todo-keywords))
414 (def-tags org-tag-alist)
415 (target-file (expand-file-name org-mobile-index-file
416 org-mobile-directory))
417 todo-kwds done-kwds tags)
418 (when (stringp (car def-todo))
419 (setq def-todo (list (cons 'sequence def-todo))))
420 (org-agenda-prepare-buffers (mapcar 'car files-alist))
421 (setq done-kwds (org-uniquify org-done-keywords-for-agenda))
422 (setq todo-kwds (org-delete-all
423 done-kwds
424 (org-uniquify org-todo-keywords-for-agenda)))
425 (setq tags (mapcar 'car (org-global-tags-completion-table
426 (mapcar 'car files-alist))))
427 (with-temp-file (if org-mobile-use-encryption org-mobile-encryption-tempfile
428 target-file)
429 (insert "#+READONLY\n")
430 (dolist (entry def-todo)
431 (let ((kwds (mapcar (lambda (x)
432 (if (string-match "(" x)
433 (substring x 0 (match-beginning 0))
435 (cdr entry))))
436 (insert "#+TODO: " (mapconcat #'identity kwds " ") "\n")
437 (let* ((dwds (or (member "|" kwds) (last kwds)))
438 (twds (org-delete-all dwds kwds)))
439 (setq todo-kwds (org-delete-all twds todo-kwds))
440 (setq done-kwds (org-delete-all dwds done-kwds)))))
441 (when (or todo-kwds done-kwds)
442 (insert "#+TODO: " (mapconcat 'identity todo-kwds " ") " | "
443 (mapconcat 'identity done-kwds " ") "\n"))
444 (setq def-tags (split-string (org-tag-alist-to-string def-tags t)))
445 (setq tags (org-delete-all def-tags tags))
446 (setq tags (sort tags (lambda (a b) (string< (downcase a) (downcase b)))))
447 (setq tags (append def-tags tags nil))
448 (insert "#+TAGS: " (mapconcat 'identity tags " ") "\n")
449 (insert "#+ALLPRIORITIES: " org-mobile-allpriorities "\n")
450 (when (file-exists-p (expand-file-name
451 org-mobile-directory "agendas.org"))
452 (insert "* [[file:agendas.org][Agenda Views]]\n"))
453 (pcase-dolist (`(,_ . ,link-name) files-alist)
454 (insert (format "* [[file:%s][%s]]\n" link-name link-name)))
455 (push (cons org-mobile-index-file (md5 (buffer-string)))
456 org-mobile-checksum-files))
457 (when org-mobile-use-encryption
458 (org-mobile-encrypt-and-move org-mobile-encryption-tempfile
459 target-file)
460 (org-mobile-cleanup-encryption-tempfile))))
462 (defun org-mobile-copy-agenda-files ()
463 "Copy all agenda files to the stage or WebDAV directory."
464 (let ((files-alist org-mobile-files-alist)
465 file buf entry link-name target-path target-dir check)
466 (while (setq entry (pop files-alist))
467 (setq file (car entry) link-name (cdr entry))
468 (when (file-exists-p file)
469 (setq target-path (expand-file-name link-name org-mobile-directory)
470 target-dir (file-name-directory target-path))
471 (unless (file-directory-p target-dir)
472 (make-directory target-dir 'parents))
473 (if org-mobile-use-encryption
474 (org-mobile-encrypt-and-move file target-path)
475 (copy-file file target-path 'ok-if-already-exists))
476 (setq check (shell-command-to-string
477 (concat (shell-quote-argument org-mobile-checksum-binary)
479 (shell-quote-argument (expand-file-name file)))))
480 (when (string-match "[a-fA-F0-9]\\{30,40\\}" check)
481 (push (cons link-name (match-string 0 check))
482 org-mobile-checksum-files))))
484 (setq file (expand-file-name org-mobile-capture-file
485 org-mobile-directory))
486 (save-excursion
487 (setq buf (find-file file))
488 (when (and (= (point-min) (point-max)))
489 (insert "\n")
490 (save-buffer)
491 (when org-mobile-use-encryption
492 (write-file org-mobile-encryption-tempfile)
493 (org-mobile-encrypt-and-move org-mobile-encryption-tempfile file)))
494 (push (cons org-mobile-capture-file (md5 (buffer-string)))
495 org-mobile-checksum-files))
496 (org-mobile-cleanup-encryption-tempfile)
497 (kill-buffer buf)))
499 (defun org-mobile-write-checksums ()
500 "Create checksums for all files in `org-mobile-directory'.
501 The table of checksums is written to the file mobile-checksums."
502 (let ((sumfile (expand-file-name "checksums.dat" org-mobile-directory))
503 (files org-mobile-checksum-files)
504 entry file sum)
505 (with-temp-file sumfile
506 (set-buffer-file-coding-system 'undecided-unix nil)
507 (while (setq entry (pop files))
508 (setq file (car entry) sum (cdr entry))
509 (insert (format "%s %s\n" sum file))))))
511 (defun org-mobile-sumo-agenda-command ()
512 "Return an agenda custom command that comprises all custom commands."
513 (let ((custom-list
514 ;; normalize different versions
515 (delq nil
516 (mapcar
517 (lambda (x)
518 (cond ((stringp (cdr x)) nil)
519 ((stringp (nth 1 x)) x)
520 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
521 (t (cons (car x) (cons "" (cdr x))))))
522 org-agenda-custom-commands)))
523 (default-list '(("a" "Agenda" agenda) ("t" "All TODO" alltodo)))
524 thelist atitle new e key desc type match settings cmds gkey gdesc gsettings cnt)
525 (cond
526 ((eq org-mobile-agendas 'custom)
527 (setq thelist custom-list))
528 ((eq org-mobile-agendas 'default)
529 (setq thelist default-list))
530 ((eq org-mobile-agendas 'all)
531 (setq thelist custom-list)
532 (unless (assoc "t" thelist) (push '("t" "ALL TODO" alltodo) thelist))
533 (unless (assoc "a" thelist) (push '("a" "Agenda" agenda) thelist)))
534 ((listp org-mobile-agendas)
535 (setq thelist (append custom-list default-list))
536 (setq thelist (delq nil (mapcar (lambda (k) (assoc k thelist))
537 org-mobile-agendas)))))
538 (while (setq e (pop thelist))
539 (cond
540 ((stringp (cdr e))
541 ;; this is a description entry - skip it
543 ((eq (nth 2 e) 'search)
544 ;; Search view is interactive, skip
546 ((memq (nth 2 e) '(todo-tree tags-tree occur-tree))
547 ;; These are trees, not really agenda commands
549 ((and (memq (nth 2 e) '(todo tags tags-todo))
550 (or (null (nth 3 e))
551 (not (string-match "\\S-" (nth 3 e)))))
552 ;; These would be interactive because the match string is empty
554 ((memq (nth 2 e) '(agenda alltodo todo tags tags-todo))
555 ;; a normal command
556 (setq key (car e) desc (nth 1 e) type (nth 2 e) match (nth 3 e)
557 settings (nth 4 e))
558 (setq settings
559 (cons (list 'org-agenda-title-append
560 (concat "<after>KEYS=" key " TITLE: "
561 (if (and (stringp desc) (> (length desc) 0))
562 desc (symbol-name type))
563 "</after>"))
564 settings))
565 (push (list type match settings) new))
566 ((or (functionp (nth 2 e)) (symbolp (nth 2 e)))
567 ;; A user-defined function, which can do anything, so simply
568 ;; ignore it.
571 ;; a block agenda
572 (setq gkey (car e) gdesc (nth 1 e) gsettings (nth 3 e) cmds (nth 2 e))
573 (setq cnt 0)
574 (while (setq e (pop cmds))
575 (setq type (car e) match (nth 1 e) settings (nth 2 e))
576 (setq atitle (if (string= "" gdesc) match gdesc))
577 (setq settings (append gsettings settings))
578 (setq settings
579 (cons (list 'org-agenda-title-append
580 (concat "<after>KEYS=" gkey "#" (number-to-string
581 (setq cnt (1+ cnt)))
582 " TITLE: " atitle "</after>"))
583 settings))
584 (push (list type match settings) new)))))
585 (and new (list "X" "SUMO" (reverse new)
586 '((org-agenda-compact-blocks nil))))))
588 (defvar org-mobile-creating-agendas nil)
589 (defun org-mobile-write-agenda-for-mobile (file)
590 (let ((all (buffer-string)) in-date id pl prefix line app short m sexp)
591 (with-temp-file file
592 (org-mode)
593 (insert "#+READONLY\n")
594 (insert all)
595 (goto-char (point-min))
596 (while (not (eobp))
597 (cond
598 ((looking-at "[ \t]*$")) ; keep empty lines
599 ((looking-at "=+$")
600 ;; remove underlining
601 (delete-region (point) (point-at-eol)))
602 ((get-text-property (point) 'org-agenda-structural-header)
603 (setq in-date nil)
604 (setq app (get-text-property (point) 'org-agenda-title-append))
605 (setq short (get-text-property (point) 'short-heading))
606 (when (and short (looking-at ".+"))
607 (replace-match short nil t)
608 (beginning-of-line 1))
609 (when app
610 (end-of-line 1)
611 (insert app)
612 (beginning-of-line 1))
613 (insert "* "))
614 ((get-text-property (point) 'org-agenda-date-header)
615 (setq in-date t)
616 (insert "** "))
617 ((setq m (or (get-text-property (point) 'org-hd-marker)
618 (get-text-property (point) 'org-marker)))
619 (setq sexp (member (get-text-property (point) 'type)
620 '("diary" "sexp")))
621 (if (setq pl (text-property-any (point) (point-at-eol) 'org-heading t))
622 (progn
623 (setq prefix (org-trim (buffer-substring
624 (point) pl))
625 line (org-trim (buffer-substring
627 (point-at-eol))))
628 (delete-region (point-at-bol) (point-at-eol))
629 (insert line "<before>" prefix "</before>")
630 (beginning-of-line 1))
631 (and (looking-at "[ \t]+") (replace-match "")))
632 (insert (if in-date "*** " "** "))
633 (end-of-line 1)
634 (insert "\n")
635 (unless sexp
636 (insert (org-agenda-get-some-entry-text
637 m 10 " " 'planning)
638 "\n")
639 (when (setq id
640 (if (bound-and-true-p
641 org-mobile-force-id-on-agenda-items)
642 (org-id-get m 'create)
643 (or (org-entry-get m "ID")
644 (org-mobile-get-outline-path-link m))))
645 (insert " :PROPERTIES:\n :ORIGINAL_ID: " id
646 "\n :END:\n")))))
647 (beginning-of-line 2))
648 (push (cons "agendas.org" (md5 (buffer-string)))
649 org-mobile-checksum-files))
650 (message "Agenda written to Org file %s" file)))
652 (defun org-mobile-get-outline-path-link (pom)
653 (org-with-point-at pom
654 (concat "olp:"
655 (org-mobile-escape-olp (file-name-nondirectory buffer-file-name))
657 (mapconcat 'org-mobile-escape-olp
658 (org-get-outline-path)
659 "/")
661 (org-mobile-escape-olp (nth 4 (org-heading-components))))))
663 (defun org-mobile-escape-olp (s)
664 (let ((table '(?: ?/)))
665 (org-link-escape s table)))
667 (defun org-mobile-create-sumo-agenda ()
668 "Create a file that contains all custom agenda views."
669 (interactive)
670 (let* ((file (expand-file-name "agendas.org"
671 org-mobile-directory))
672 (file1 (if org-mobile-use-encryption
673 org-mobile-encryption-tempfile
674 file))
675 (sumo (org-mobile-sumo-agenda-command))
676 (org-agenda-custom-commands
677 (list (append sumo (list (list file1)))))
678 (org-mobile-creating-agendas t))
679 (unless (file-writable-p file1)
680 (error "Cannot write to file %s" file1))
681 (when sumo
682 (org-store-agenda-views))
683 (when org-mobile-use-encryption
684 (org-mobile-encrypt-and-move file1 file)
685 (delete-file file1)
686 (org-mobile-cleanup-encryption-tempfile))))
688 (defun org-mobile-encrypt-and-move (infile outfile)
689 "Encrypt INFILE locally to INFILE_enc, then move it to OUTFILE.
690 We do this in two steps so that remote paths will work, even if the
691 encryption program does not understand them."
692 (let ((encfile (concat infile "_enc")))
693 (org-mobile-encrypt-file infile encfile)
694 (when outfile
695 (copy-file encfile outfile 'ok-if-already-exists)
696 (delete-file encfile))))
698 (defun org-mobile-encrypt-file (infile outfile)
699 "Encrypt INFILE to OUTFILE, using `org-mobile-encryption-password'."
700 (shell-command
701 (format "openssl enc -md md5 -aes-256-cbc -salt -pass %s -in %s -out %s"
702 (shell-quote-argument (concat "pass:"
703 (org-mobile-encryption-password)))
704 (shell-quote-argument (expand-file-name infile))
705 (shell-quote-argument (expand-file-name outfile)))))
707 (defun org-mobile-decrypt-file (infile outfile)
708 "Decrypt INFILE to OUTFILE, using `org-mobile-encryption-password'."
709 (shell-command
710 (format "openssl enc -md md5 -d -aes-256-cbc -salt -pass %s -in %s -out %s"
711 (shell-quote-argument (concat "pass:"
712 (org-mobile-encryption-password)))
713 (shell-quote-argument (expand-file-name infile))
714 (shell-quote-argument (expand-file-name outfile)))))
716 (defun org-mobile-cleanup-encryption-tempfile ()
717 "Remove the encryption tempfile if it exists."
718 (and (stringp org-mobile-encryption-tempfile)
719 (file-exists-p org-mobile-encryption-tempfile)
720 (delete-file org-mobile-encryption-tempfile)))
722 (defun org-mobile-move-capture ()
723 "Move the contents of the capture file to the inbox file.
724 Return a marker to the location where the new content has been added.
725 If nothing new has been added, return nil."
726 (interactive)
727 (let* ((encfile nil)
728 (capture-file (expand-file-name org-mobile-capture-file
729 org-mobile-directory))
730 (inbox-buffer (find-file-noselect org-mobile-inbox-for-pull))
731 (capture-buffer
732 (if (not org-mobile-use-encryption)
733 (find-file-noselect capture-file)
734 (org-mobile-cleanup-encryption-tempfile)
735 (setq encfile (concat org-mobile-encryption-tempfile "_enc"))
736 (copy-file capture-file encfile)
737 (org-mobile-decrypt-file encfile org-mobile-encryption-tempfile)
738 (find-file-noselect org-mobile-encryption-tempfile)))
739 (insertion-point (make-marker))
740 not-empty content)
741 (with-current-buffer capture-buffer
742 (setq content (buffer-string))
743 (setq not-empty (string-match "\\S-" content))
744 (when not-empty
745 (set-buffer inbox-buffer)
746 (widen)
747 (goto-char (point-max))
748 (or (bolp) (newline))
749 (move-marker insertion-point
750 (prog1 (point) (insert content)))
751 (save-buffer)
752 (set-buffer capture-buffer)
753 (erase-buffer)
754 (save-buffer)
755 (org-mobile-update-checksum-for-capture-file (buffer-string))))
756 (kill-buffer capture-buffer)
757 (when org-mobile-use-encryption
758 (org-mobile-encrypt-and-move org-mobile-encryption-tempfile
759 capture-file)
760 (org-mobile-cleanup-encryption-tempfile))
761 (if not-empty insertion-point)))
763 (defun org-mobile-update-checksum-for-capture-file (buffer-string)
764 "Find the checksum line and modify it to match BUFFER-STRING."
765 (let* ((file (expand-file-name "checksums.dat" org-mobile-directory))
766 (buffer (find-file-noselect file)))
767 (when buffer
768 (with-current-buffer buffer
769 (when (re-search-forward (concat "\\([0-9a-fA-F]\\{30,\\}\\).*?"
770 (regexp-quote org-mobile-capture-file)
771 "[ \t]*$") nil t)
772 (goto-char (match-beginning 1))
773 (delete-region (match-beginning 1) (match-end 1))
774 (insert (md5 buffer-string))
775 (save-buffer)))
776 (kill-buffer buffer))))
778 (defun org-mobile-apply (&optional beg end)
779 "Apply all change requests in the current buffer.
780 If BEG and END are given, only do this in that region."
781 (interactive)
782 (require 'org-archive)
783 (setq org-mobile-last-flagged-files nil)
784 (setq beg (or beg (point-min)) end (or end (point-max)))
786 ;; Remove all Note IDs
787 (goto-char beg)
788 (while (re-search-forward "^\\*\\* Note ID: [-0-9A-F]+[ \t]*\n" end t)
789 (replace-match ""))
791 ;; Find all the referenced entries, without making any changes yet
792 (let ((marker (make-marker))
793 (bos-marker (make-marker))
794 (end (move-marker (make-marker) end))
795 (cnt-new 0)
796 (cnt-edit 0)
797 (cnt-flag 0)
798 (cnt-error 0)
799 buf-list
800 org-mobile-error)
802 ;; Count the new captures
803 (goto-char beg)
804 (while (re-search-forward "^\\* \\(.*\\)" end t)
805 (and (>= (- (match-end 1) (match-beginning 1)) 2)
806 (not (equal (downcase (substring (match-string 1) 0 2)) "f("))
807 (cl-incf cnt-new)))
809 ;; Find and apply the edits
810 (goto-char beg)
811 (while (re-search-forward
812 "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)[ \t]+\\[\\[\\(\\(id\\|olp\\):\\([^]\n]+\\)\\)" end t)
813 (catch 'next
814 (let* ((action (match-string 1))
815 (data (and (match-end 3) (match-string 3)))
816 (id-pos (condition-case msg
817 (org-mobile-locate-entry (match-string 4))
818 (error (nth 1 msg))))
819 (bos (line-beginning-position))
820 (eos (save-excursion (org-end-of-subtree t t)))
821 (cmd (if (equal action "")
822 (let ((note (buffer-substring-no-properties
823 (line-beginning-position 2) eos)))
824 (lambda (_data _old _new)
825 (cl-incf cnt-flag)
826 (org-toggle-tag "FLAGGED" 'on)
827 (org-entry-put
828 nil "THEFLAGGINGNOTE"
829 (replace-regexp-in-string "\n" "\\\\n" note))))
830 (cl-incf cnt-edit)
831 (cdr (assoc action org-mobile-action-alist))))
832 ;; Do not take notes interactively.
833 (org-inhibit-logging 'note)
834 old new)
836 (goto-char bos)
837 (when (and (markerp id-pos)
838 (not (member (marker-buffer id-pos) buf-list)))
839 (org-mobile-timestamp-buffer (marker-buffer id-pos))
840 (push (marker-buffer id-pos) buf-list))
841 (unless (markerp id-pos)
842 (goto-char (+ 2 (point-at-bol)))
843 (if (stringp id-pos)
844 (insert id-pos " ")
845 (insert "BAD REFERENCE "))
846 (cl-incf cnt-error)
847 (throw 'next t))
848 (unless cmd
849 (insert "BAD FLAG ")
850 (cl-incf cnt-error)
851 (throw 'next t))
852 (move-marker bos-marker (point))
853 (if (re-search-forward "^** Old value[ \t]*$" eos t)
854 (setq old (buffer-substring
855 (1+ (match-end 0))
856 (progn (outline-next-heading) (point)))))
857 (if (re-search-forward "^** New value[ \t]*$" eos t)
858 (setq new (buffer-substring
859 (1+ (match-end 0))
860 (progn (outline-next-heading)
861 (if (eobp) (org-back-over-empty-lines))
862 (point)))))
863 (setq old (org-string-nw-p old))
864 (setq new (org-string-nw-p new))
865 (unless (equal data "body")
866 (setq new (and new (org-trim new)))
867 (setq old (and old (org-trim old))))
868 (goto-char (+ 2 bos-marker))
869 ;; Remember this place so that we can return
870 (move-marker marker (point))
871 (setq org-mobile-error nil)
872 (condition-case msg
873 (org-with-point-at id-pos
874 (funcall cmd data old new)
875 (unless (member data '("delete" "archive" "archive-sibling"
876 "addheading"))
877 (when (member "FLAGGED" (org-get-tags nil t))
878 (add-to-list 'org-mobile-last-flagged-files
879 (buffer-file-name)))))
880 (error (setq org-mobile-error msg)))
881 (when org-mobile-error
882 (pop-to-buffer-same-window (marker-buffer marker))
883 (goto-char marker)
884 (cl-incf cnt-error)
885 (insert (if (stringp (nth 1 org-mobile-error))
886 (nth 1 org-mobile-error)
887 "EXECUTION FAILED")
888 " ")
889 (throw 'next t))
890 ;; If we get here, the action has been applied successfully
891 ;; So remove the entry
892 (goto-char bos-marker)
893 (delete-region (point) (org-end-of-subtree t t)))))
894 (save-buffer)
895 (move-marker marker nil)
896 (move-marker end nil)
897 (message "%d new, %d edits, %d flags, %d errors"
898 cnt-new cnt-edit cnt-flag cnt-error)
899 (sit-for 1)))
901 (defun org-mobile-timestamp-buffer (buf)
902 "Time stamp buffer BUF, just to make sure its checksum will change."
903 (with-current-buffer buf
904 (save-excursion
905 (save-restriction
906 (widen)
907 (goto-char (point-min))
908 (if (re-search-forward
909 "^\\([ \t]*\\)#\\+LAST_MOBILE_CHANGE:.*\n?" nil t)
910 (progn
911 (goto-char (match-end 1))
912 (delete-region (point) (match-end 0)))
913 (if (looking-at ".*?-\\*-.*-\\*-")
914 (forward-line 1)))
915 (insert "#+LAST_MOBILE_CHANGE: "
916 (format-time-string "%Y-%m-%d %T") "\n")))))
918 (defun org-mobile-smart-read ()
919 "Parse the entry at point for shortcuts and expand them.
920 These shortcuts are meant for fast and easy typing on the limited
921 keyboards of a mobile device. Below we show a list of the shortcuts
922 currently implemented.
924 The entry is expected to contain an inactive time stamp indicating when
925 the entry was created. When setting dates and
926 times (for example for deadlines), the time strings are interpreted
927 relative to that creation date.
928 Abbreviations are expected to take up entire lines, just because it is so
929 easy to type RET on a mobile device. Abbreviations start with one or two
930 letters, followed immediately by a dot and then additional information.
931 Generally the entire shortcut line is removed after action have been taken.
932 Time stamps will be constructed using `org-read-date'. So for example a
933 line \"dd. 2tue\" will set a deadline on the second Tuesday after the
934 creation date.
936 Here are the shortcuts currently implemented:
938 dd. string set deadline
939 ss. string set scheduling
940 tt. string set time tamp, here.
941 ti. string set inactive time
943 tg. tag1 tag2 tag3 set all these tags, change case where necessary
944 td. kwd set this todo keyword, change case where necessary
946 FIXME: Hmmm, not sure if we can make his work against the
947 auto-correction feature. Needs a bit more thinking. So this function
948 is currently a noop.")
950 (defun org-mobile-locate-entry (link)
951 (if (string-match "\\`id:\\(.*\\)$" link)
952 (org-id-find (match-string 1 link) 'marker)
953 (if (not (string-match "\\`olp:\\(.*?\\):\\(.*\\)$" link))
954 ; not found with path, but maybe it is to be inserted
955 ; in top level of the file?
956 (if (not (string-match "\\`olp:\\(.*?\\)$" link))
958 (let ((file (match-string 1 link)))
959 (setq file (org-link-unescape file))
960 (setq file (expand-file-name file org-directory))
961 (save-excursion
962 (find-file file)
963 (goto-char (point-max))
964 (newline)
965 (goto-char (point-max))
966 (point-marker))))
967 (let ((file (match-string 1 link))
968 (path (match-string 2 link)))
969 (setq file (org-link-unescape file))
970 (setq file (expand-file-name file org-directory))
971 (setq path (mapcar 'org-link-unescape
972 (org-split-string path "/")))
973 (org-find-olp (cons file path))))))
975 (defun org-mobile-edit (what old new)
976 "Edit item WHAT in the current entry by replacing OLD with NEW.
977 WHAT can be \"heading\", \"todo\", \"tags\", \"priority\", or \"body\".
978 The edit only takes place if the current value is equal (except for
979 white space) the OLD. If this is so, OLD will be replace by NEW
980 and the command will return t. If something goes wrong, a string will
981 be returned that indicates what went wrong."
982 (let (current old1 new1 level)
983 (if (stringp what) (setq what (intern what)))
985 (cond
987 ((memq what '(todo todostate))
988 (setq current (org-get-todo-state))
989 (cond
990 ((equal new "DONEARCHIVE")
991 (org-todo 'done)
992 (org-archive-subtree-default))
993 ((equal new current) t) ; nothing needs to be done
994 ((or (equal current old)
995 (eq org-mobile-force-mobile-change t)
996 (memq 'todo org-mobile-force-mobile-change))
997 (org-todo (or new 'none)) t)
998 (t (error "State before change was expected as \"%s\", but is \"%s\""
999 old current))))
1001 ((eq what 'tags)
1002 (setq current (org-get-tags nil t)
1003 new1 (and new (org-split-string new ":+"))
1004 old1 (and old (org-split-string old ":+")))
1005 (cond
1006 ((org-mobile-tags-same-p current new1) t) ; no change needed
1007 ((or (org-mobile-tags-same-p current old1)
1008 (eq org-mobile-force-mobile-change t)
1009 (memq 'tags org-mobile-force-mobile-change))
1010 (org-set-tags-to new1) t)
1011 (t (error "Tags before change were expected as \"%s\", but are \"%s\""
1012 (or old "") (or current "")))))
1014 ((eq what 'priority)
1015 (let ((case-fold-search nil))
1016 (when (looking-at org-complex-heading-regexp)
1017 (let ((current (and (match-end 3) (substring (match-string 3) 2 3))))
1018 (cond
1019 ((equal current new) t) ;no action required
1020 ((or (equal current old)
1021 (eq org-mobile-force-mobile-change t)
1022 (memq 'tags org-mobile-force-mobile-change))
1023 (org-priority (and new (string-to-char new))))
1024 (t (error "Priority was expected to be %s, but is %s"
1025 old current)))))))
1027 ((eq what 'heading)
1028 (let ((case-fold-search nil))
1029 (when (looking-at org-complex-heading-regexp)
1030 (let ((current (match-string 4)))
1031 (cond
1032 ((equal current new) t) ;no action required
1033 ((or (equal current old)
1034 (eq org-mobile-force-mobile-change t)
1035 (memq 'heading org-mobile-force-mobile-change))
1036 (goto-char (match-beginning 4))
1037 (insert new)
1038 (delete-region (point) (+ (point) (length current)))
1039 (org-set-tags nil 'align))
1040 (t (error "Heading changed in MobileOrg and on the computer")))))))
1042 ((eq what 'addheading)
1043 (if (org-at-heading-p) ; if false we are in top-level of file
1044 (progn
1045 ;; Workaround a `org-insert-heading-respect-content' bug
1046 ;; which prevents correct insertion when point is invisible
1047 (org-show-subtree)
1048 (end-of-line 1)
1049 (org-insert-heading-respect-content t)
1050 (org-demote))
1051 (beginning-of-line)
1052 (insert "* "))
1053 (insert new))
1055 ((eq what 'refile)
1056 (org-copy-subtree)
1057 (org-with-point-at (org-mobile-locate-entry new)
1058 (if (org-at-heading-p) ; if false we are in top-level of file
1059 (progn
1060 (setq level (org-get-valid-level (funcall outline-level) 1))
1061 (org-end-of-subtree t t)
1062 (org-paste-subtree level))
1063 (org-paste-subtree 1)))
1064 (org-cut-subtree))
1066 ((eq what 'delete)
1067 (org-cut-subtree))
1069 ((eq what 'archive)
1070 (org-archive-subtree))
1072 ((eq what 'archive-sibling)
1073 (org-archive-to-archive-sibling))
1075 ((eq what 'body)
1076 (setq current (buffer-substring (min (1+ (point-at-eol)) (point-max))
1077 (save-excursion (outline-next-heading)
1078 (point))))
1079 (if (not (string-match "\\S-" current)) (setq current nil))
1080 (cond
1081 ((org-mobile-bodies-same-p current new) t) ; no action necessary
1082 ((or (org-mobile-bodies-same-p current old)
1083 (eq org-mobile-force-mobile-change t)
1084 (memq 'body org-mobile-force-mobile-change))
1085 (save-excursion
1086 (end-of-line 1)
1087 (insert "\n" new)
1088 (or (bolp) (insert "\n"))
1089 (delete-region (point) (progn (org-back-to-heading t)
1090 (outline-next-heading)
1091 (point))))
1093 (t (error "Body was changed in MobileOrg and on the computer")))))))
1095 (defun org-mobile-tags-same-p (list1 list2)
1096 "Are the two tag lists the same?"
1097 (not (or (org-delete-all list1 list2)
1098 (org-delete-all list2 list1))))
1100 (defun org-mobile-bodies-same-p (a b)
1101 "Compare if A and B are visually equal strings.
1102 We first remove leading and trailing white space from the entire strings.
1103 Then we split the strings into lines and remove leading/trailing whitespace
1104 from each line. Then we compare.
1105 A and B must be strings or nil."
1106 (cond
1107 ((and (not a) (not b)) t)
1108 ((or (not a) (not b)) nil)
1109 (t (setq a (org-trim a) b (org-trim b))
1110 (setq a (mapconcat 'identity (org-split-string a "[ \t]*\n[ \t]*") "\n"))
1111 (setq b (mapconcat 'identity (org-split-string b "[ \t]*\n[ \t]*") "\n"))
1112 (equal a b))))
1114 (provide 'org-mobile)
1116 ;; Local variables:
1117 ;; generated-autoload-file: "org-loaddefs.el"
1118 ;; End:
1120 ;;; org-mobile.el ends here