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