Merge commit 'bernt/typos'
[org-mode/org-tableheadings.git] / lisp / org-mobile.el
blobdb75d6def7fef40933529ab3769b89b06f8a9a2c
1 ;;; org-mobile.el --- Code for asymmetric sync with a mobile device
2 ;; Copyright (C) 2009 Free Software Foundation, Inc.
3 ;;
4 ;; Author: Carsten Dominik <carsten at orgmode dot org>
5 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: http://orgmode.org
7 ;; Version: 6.32trans
8 ;;
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This file contains the code to interact with Richard Moreland's iPhone
29 ;; application MobileOrg. This code is documented in Appendix B of the
30 ;; Org-mode manual. The code is not specific for the iPhone, however.
31 ;; Any external viewer/flagging/editing application that uses the same
32 ;; conventions could be used.
34 (require 'org)
35 (require 'org-agenda)
36 (eval-when-compile (require 'cl))
38 (defgroup org-mobile nil
39 "Options concerning support for a viewer/editor on a mobile device."
40 :tag "Org Mobile"
41 :group 'org)
43 (defcustom org-mobile-files '(org-agenda-files)
44 "Files to be staged for MobileOrg.
45 This is basically a list of filesand directories. Files will be staged
46 directly. Directories will be search for files with the extension `.org'.
47 In addition to this, the list may also contain the following symbols:
49 org-agenda-files
50 This means, include the complete, unrestricted list of files given in
51 the variable `org-agenda-files'.
52 org-agenda-text-search-extra-files
53 Include the files given in the variable
54 `org-agenda-text-search-extra-files'"
55 :group 'org-mobile
56 :type '(list :greedy t
57 (option (const :tag "org-agenda-files" org-agenda-files))
58 (option (const :tag "org-agenda-text-search-extra-files"
59 org-agenda-text-search-extra-files))
60 (repeat :inline t :tag "Additional files"
61 (file))))
63 (defcustom org-mobile-directory ""
64 "The WebDAV directory where the interaction with the mobile takes place."
65 :group 'org-mobile
66 :type 'directory)
68 (defcustom org-mobile-inbox-for-pull "~/org/from-mobile.org"
69 "The file where captured notes and flags will be appended to.
70 During the execution of `org-mobile-pull', the file
71 `org-mobile-capture-file' will be emptied it's contents have
72 been appended to the file given here. This file should be in
73 `org-directory', and not in the staging area or on the web server."
74 :group 'org-mobile
75 :type 'file)
77 (defconst org-mobile-capture-file "mobileorg.org"
78 "The capture file where the mobile stores captured notes and flags.
79 This should not be changed, because MobileOrg assumes this name.")
81 (defcustom org-mobile-index-file "index.org"
82 "The index file with inks to all Org files that should be loaded by MobileOrg.
83 Relative to `org-mobile-directory'. The Address field in the MobileOrg setup
84 should point to this file."
85 :group 'org-mobile
86 :type 'file)
88 (defcustom org-mobile-force-id-on-agenda-items t
89 "Non-nil means make all agenda items carry and ID."
90 :group 'org-mobile
91 :type 'boolean)
93 (defcustom org-mobile-force-mobile-change nil
94 "Non-nil means, force the change made on the mobile device.
95 So even if there have been changes to the computer version of the entry,
96 force the new value set on the mobile.
97 When nil, mark the entry from the mobile with an error message.
98 Instead of nil or t, this variable can also be a list of symbols, indicating
99 the editing types for which the mobile version should always dominate."
100 :group 'org-mobile
101 :type '(choice
102 (const :tag "Always" t)
103 (const :tag "Never" nil)
104 (set :greedy t :tag "Specify"
105 (const todo)
106 (const tags)
107 (const priority)
108 (const heading)
109 (const body))))
111 (defcustom org-mobile-action-alist
112 '(("edit" . (org-mobile-edit data old new)))
113 "Alist with flags and actions for mobile sync.
114 When flagging an entry, MobileOrg will create entries that look like
116 * F(action:data) [[id:entry-id][entry title]]
118 This alist defines that the ACTION in the parentheses of F() should mean,
119 i.e. what action should be taken. The :data part in the parenthesis is
120 optional. If present, the string after the colon will be passed to the
121 action form as the `data' variable.
122 The car of each elements of the alist is an actions string. The cdr is
123 an Emacs Lisp form that will be evaluated with the cursor on the headline
124 of that entry.
126 For now, it is not recommended to change this variable."
127 :group 'org-mobile
128 :type '(repeat
129 (cons (string :tag "Action flag")
130 (sexp :tag "Action form"))))
132 (defcustom org-mobile-checksum-binary (or (executable-find "shasum")
133 (executable-find "sha1sum")
134 (executable-find "md5sum")
135 (executable-find "md5"))
136 "Executable used for computing checksums of agenda files."
137 :group 'org-mobile
138 :type 'string)
140 (defvar org-mobile-pre-push-hook nil
141 "Hook run before running `org-mobile-push'.
142 This could be used to clean up `org-mobile-directory', for example to
143 remove files that used to be included in the agenda but no longer are.
144 The presence of such files would not really be a problem, but after time
145 they may accumulate.")
147 (defvar org-mobile-post-push-hook nil
148 "Hook run after running `org-mobile-push'.
149 If Emacs does not have direct write access to the WebDAV directory used
150 by the mobile device, this hook should be used to copy all files from the
151 local staging directory `org-mobile-directory' to the WebDAV directory,
152 for example using `rsync' or `scp'.")
154 (defvar org-mobile-pre-pull-hook nil
155 "Hook run before executing `org-mobile-pull'.
156 If Emacs does not have direct write access to the WebDAV directory used
157 by the mobile device, this hook should be used to copy the capture file
158 `mobileorg.org' from the WebDAV location to the local staging
159 directory `org-mobile-directory'.")
161 (defvar org-mobile-post-pull-hook nil
162 "Hook run after running `org-mobile-pull'.
163 If Emacs does not have direct write access to the WebDAV directory used
164 by the mobile device, this hook should be used to copy the emptied
165 capture file `mobileorg.org' back to the WebDAV directory, for example
166 using `rsync' or `scp'.")
168 (defvar org-mobile-last-flagged-files nil
169 "List of files containing entreis flagged in the latest pull.")
171 (defvar org-mobile-files-alist nil)
172 (defvar org-mobile-checksum-files nil)
174 (defun org-mobile-prepare-file-lists ()
175 (setq org-mobile-files-alist (org-mobile-files-alist))
176 (setq org-mobile-checksum-files nil))
178 (defun org-mobile-files-alist ()
179 "Expand the list in `org-mobile-files' to a list of existing files."
180 (let* ((include-archives
181 (and (member 'org-agenda-text-search-extra-files org-mobile-files)
182 (member 'agenda-archives org-agenda-text-search-extra-files)
184 (files
185 (apply 'append
186 (mapcar
187 (lambda (f)
188 (cond
189 ((eq f 'org-agenda-files)
190 (org-agenda-files t include-archives))
191 ((eq f 'org-agenda-text-search-extra-files)
192 (delq 'agenda-archives
193 (copy-sequence
194 org-agenda-text-search-extra-files)))
195 ((and (stringp f) (file-directory-p f))
196 (directory-files f 'full "\\.org\\'"))
197 ((and (stringp f) (file-exists-p f))
198 (list f))
199 (t nil)))
200 org-mobile-files)))
201 (orgdir-uname (file-name-as-directory (file-truename org-directory)))
202 (orgdir-re (concat "\\`" (regexp-quote orgdir-uname)))
203 uname seen rtn file link-name)
204 ;; Make the files unique, and determine the name under which they will
205 ;; be listed.
206 (while (setq file (pop files))
207 (if (not (file-name-absolute-p file))
208 (setq file (expand-file-name file org-directory)))
209 (setq uname (file-truename file))
210 (unless (member uname seen)
211 (push uname seen)
212 (if (string-match orgdir-re uname)
213 (setq link-name (substring uname (match-end 0)))
214 (setq link-name (file-name-nondirectory uname)))
215 (push (cons file link-name) rtn)))
216 (nreverse rtn)))
218 ;;;###autoload
219 (defun org-mobile-push ()
220 "Push the current state of Org affairs to the WebDAV directory.
221 This will create the index file, copy all agenda files there, and also
222 create all custom agenda views, for upload to the mobile phone."
223 (interactive)
224 (let ((a-buffer (get-buffer org-agenda-buffer-name)))
225 (let ((org-agenda-buffer-name "*SUMO*")
226 (org-agenda-filter org-agenda-filter)
227 (org-agenda-redo-command org-agenda-redo-command))
228 (save-excursion
229 (save-window-excursion
230 (org-mobile-check-setup)
231 (org-mobile-prepare-file-lists)
232 (run-hooks 'org-mobile-pre-push-hook)
233 (message "Creating agendas...")
234 (let ((inhibit-redisplay t)) (org-mobile-create-sumo-agenda))
235 (message "Creating agendas...done")
236 (org-save-all-org-buffers) ; to save any IDs created by this process
237 (message "Copying files...")
238 (org-mobile-copy-agenda-files)
239 (message "Writing index file...")
240 (org-mobile-create-index-file)
241 (message "Writing checksums...")
242 (org-mobile-write-checksums)
243 (run-hooks 'org-mobile-post-push-hook))))
244 (redraw-display)
245 (when (and a-buffer (buffer-live-p a-buffer))
246 (if (not (get-buffer-window a-buffer))
247 (kill-buffer a-buffer)
248 (let ((cw (selected-window)))
249 (select-window (get-buffer-window a-buffer))
251 (org-agenda-redo)
252 (select-window cw)))))
253 (message "Files for mobile viewer staged"))
255 (defvar org-mobile-before-process-capture-hook nil
256 "Hook that is run after content was moved to `org-mobile-inbox-for-pull'.
257 The inbox file is in the current buffer, and the buffer is arrowed to the
258 new captured data.")
260 ;;;###autoload
261 (defun org-mobile-pull ()
262 "Pull the contents of `org-mobile-capture-file' and integrate them.
263 Apply all flagged actions, flag entries to be flagged and then call an
264 agenda view showing the flagged items."
265 (interactive)
266 (org-mobile-check-setup)
267 (run-hooks 'org-mobile-pre-pull-hook)
268 (let ((insertion-marker (org-mobile-move-capture)))
269 (if (not (markerp insertion-marker))
270 (message "No new items")
271 (org-with-point-at insertion-marker
272 (save-restriction
273 (narrow-to-region (point) (point-max))
274 (run-hooks 'org-mobile-before-process-capture-hook)))
275 (org-with-point-at insertion-marker
276 (org-mobile-apply (point) (point-max)))
277 (move-marker insertion-marker nil)
278 (run-hooks 'org-mobile-post-pull-hook)
279 (when org-mobile-last-flagged-files
280 ;; Make an agenda view of flagged entries, but only in the files
281 ;; where stuff has been added.
282 (put 'org-agenda-files 'org-restrict org-mobile-last-flagged-files)
283 (let ((org-agenda-keep-restriced-file-list t))
284 (org-agenda nil "?"))))))
286 (defun org-mobile-check-setup ()
287 "Check if org-mobile-directory has been set up."
288 (unless (and org-directory
289 (stringp org-directory)
290 (string-match "\\S-" org-directory)
291 (file-exists-p org-directory)
292 (file-directory-p org-directory))
293 (error
294 "Please set `org-directory' to the directory where your org files live"))
295 (unless (and org-mobile-directory
296 (stringp org-mobile-directory)
297 (string-match "\\S-" org-mobile-directory)
298 (file-exists-p org-mobile-directory)
299 (file-directory-p org-mobile-directory))
300 (error
301 "Variable `org-mobile-directory' must point to an existing directory"))
302 (unless (and org-mobile-inbox-for-pull
303 (stringp org-mobile-inbox-for-pull)
304 (string-match "\\S-" org-mobile-inbox-for-pull)
305 (file-exists-p
306 (file-name-directory org-mobile-inbox-for-pull)))
307 (error
308 "Variable `org-mobile-inbox-for-pull' must point to a file in an existing directory")))
310 (defun org-mobile-create-index-file ()
311 "Write the index file in the WebDAV directory."
312 (let ((files-alist (sort (copy-sequence org-mobile-files-alist)
313 (lambda (a b) (string< (cdr a) (cdr b)))))
314 (def-todo (default-value 'org-todo-keywords))
315 (def-tags (default-value 'org-tag-alist))
316 file link-name todo-kwds done-kwds tags drawers entry kwds dwds twds)
318 (org-prepare-agenda-buffers (mapcar 'car files-alist))
319 (setq done-kwds (org-uniquify org-done-keywords-for-agenda))
320 (setq todo-kwds (org-delete-all
321 done-kwds
322 (org-uniquify org-todo-keywords-for-agenda)))
323 (setq drawers (org-uniquify org-drawers-for-agenda))
324 (setq tags (org-uniquify
325 (delq nil
326 (mapcar
327 (lambda (e)
328 (cond ((stringp e) e)
329 ((listp e)
330 (if (stringp (car e)) (car e) nil))
331 (t nil)))
332 org-tag-alist-for-agenda))))
333 (with-temp-file
334 (expand-file-name org-mobile-index-file org-mobile-directory)
335 (while (setq entry (pop def-todo))
336 (insert "#+READONLY\n")
337 (setq kwds (mapcar (lambda (x) (if (string-match "(" x)
338 (substring x 0 (match-beginning 0))
340 (cdr entry)))
341 (insert "#+TODO: " (mapconcat 'identity kwds " ") "\n")
342 (setq dwds (member "|" kwds)
343 twds (org-delete-all dwds kwds)
344 todo-kwds (org-delete-all twds todo-kwds)
345 done-kwds (org-delete-all dwds done-kwds)))
346 (when (or todo-kwds done-kwds)
347 (insert "#+TODO: " (mapconcat 'identity todo-kwds " ") " | "
348 (mapconcat 'identity done-kwds " ") "\n"))
349 (setq def-tags (mapcar
350 (lambda (x)
351 (cond ((null x) nil)
352 ((stringp x) x)
353 ((eq (car x) :startgroup) "{")
354 ((eq (car x) :endgroup) "}")
355 ((eq (car x) :newline) nil)
356 ((listp x) (car x))
357 (t nil)))
358 def-tags))
359 (setq def-tags (delq nil def-tags))
360 (setq tags (org-delete-all def-tags tags))
361 (setq tags (sort tags (lambda (a b) (string< (downcase a) (downcase b)))))
362 (setq tags (append def-tags tags nil))
363 (insert "#+TAGS: " (mapconcat 'identity tags " ") "\n")
364 (insert "#+DRAWERS: " (mapconcat 'identity drawers " ") "\n")
365 (insert "#+ALLPRIORITIES: A B C" "\n")
366 (when (file-exists-p (expand-file-name
367 org-mobile-directory "agendas.org"))
368 (insert "* [[file:agendas.org][Agenda Views]]\n"))
369 (while (setq entry (pop files-alist))
370 (setq file (car entry)
371 link-name (cdr entry))
372 (insert (format "* [[file:%s][%s]]\n"
373 link-name link-name)))
374 (push (cons org-mobile-index-file (md5 (buffer-string)))
375 org-mobile-checksum-files))))
377 (defun org-mobile-copy-agenda-files ()
378 "Copy all agenda files to the stage or WebDAV directory."
379 (let ((files-alist org-mobile-files-alist)
380 file buf entry link-name target-path target-dir check)
381 (while (setq entry (pop files-alist))
382 (setq file (car entry) link-name (cdr entry))
383 (when (file-exists-p file)
384 (setq target-path (expand-file-name link-name org-mobile-directory)
385 target-dir (file-name-directory target-path))
386 (unless (file-directory-p target-dir)
387 (make-directory target-dir 'parents))
388 (copy-file file target-path 'ok-if-exists)
389 (setq check (shell-command-to-string
390 (concat org-mobile-checksum-binary " "
391 (shell-quote-argument (expand-file-name file)))))
392 (when (string-match "[a-fA-F0-9]\\{30,40\\}" check)
393 (push (cons link-name (match-string 0 check))
394 org-mobile-checksum-files))))
395 (setq file (expand-file-name org-mobile-capture-file
396 org-mobile-directory))
397 (save-excursion
398 (setq buf (find-file file))
399 (and (= (point-min) (point-max)) (insert "\n"))
400 (save-buffer)
401 (push (cons org-mobile-capture-file (md5 (buffer-string)))
402 org-mobile-checksum-files))
403 (kill-buffer buf)))
405 (defun org-mobile-write-checksums ()
406 "Create checksums for all files in `org-mobile-directory'.
407 The table of checksums is written to the file mobile-checksums."
408 (let ((sumfile (expand-file-name "checksums.dat" org-mobile-directory))
409 (files org-mobile-checksum-files)
410 entry file sum)
411 (with-temp-file sumfile
412 (while (setq entry (pop files))
413 (setq file (car entry) sum (cdr entry))
414 (insert (format "%s %s\n" sum file))))))
416 (defun org-mobile-sumo-agenda-command ()
417 "Return an agenda custom command that comprises all custom commands."
418 (let ((custom-list
419 ;; normalize different versions
420 (delq nil
421 (mapcar
422 (lambda (x)
423 (cond ((stringp (cdr x)) nil)
424 ((stringp (nth 1 x)) x)
425 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
426 (t (cons (car x) (cons "" (cdr x))))))
427 org-agenda-custom-commands)))
428 new e key desc type match settings cmds gkey gdesc gsettings cnt)
429 (while (setq e (pop custom-list))
430 (cond
431 ((stringp (cdr e))
432 ;; this is a description entry - skip it
434 ((eq (nth 2 e) 'search)
435 ;; Search view is interactive, skip
437 ((memq (nth 2 e) '(todo-tree tags-tree occur-tree))
438 ;; These are trees, not really agenda commands
440 ((memq (nth 2 e) '(agenda todo tags))
441 ;; a normal command
442 (setq key (car e) desc (nth 1 e) type (nth 2 e) match (nth 3 e)
443 settings (nth 4 e))
444 (setq settings
445 (cons (list 'org-agenda-title-append
446 (concat "<after>KEYS=" key " TITLE: "
447 (if (and (stringp desc) (> (length desc) 0))
448 desc (symbol-name type))
449 " " match "</after>"))
450 settings))
451 (push (list type match settings) new))
452 ((symbolp (nth 2 e))
453 ;; A user-defined function, not sure how to handle that yet
456 ;; a block agenda
457 (setq gkey (car e) gdesc (nth 1 e) gsettings (nth 3 e) cmds (nth 2 e))
458 (setq cnt 0)
459 (while (setq e (pop cmds))
460 (setq type (car e) match (nth 1 e) settings (nth 2 e))
461 (setq settings (append gsettings settings))
462 (setq settings
463 (cons (list 'org-agenda-title-append
464 (concat "<after>KEYS=" gkey "#" (number-to-string
465 (setq cnt (1+ cnt)))
466 " TITLE: " gdesc " " match "</after>"))
467 settings))
468 (push (list type match settings) new)))))
469 (and new (list "X" "SUMO" (reverse new)
470 '((org-agenda-compact-blocks nil))))))
472 (defvar org-mobile-creating-agendas nil)
473 (defun org-mobile-write-agenda-for-mobile (file)
474 (let ((all (buffer-string)) in-date id pl prefix line app short m sexp)
475 (with-temp-file file
476 (org-mode)
477 (insert "#+READONLY\n")
478 (insert all)
479 (goto-char (point-min))
480 (while (not (eobp))
481 (cond
482 ((looking-at "[ \t]*$")) ; keep empty lines
483 ((looking-at "=+$")
484 ;; remove underlining
485 (delete-region (point) (point-at-eol)))
486 ((get-text-property (point) 'org-agenda-structural-header)
487 (setq in-date nil)
488 (setq app (get-text-property (point)
489 'org-agenda-title-append))
490 (setq short (get-text-property (point)
491 'short-heading))
492 (when (and short (looking-at ".+"))
493 (replace-match short)
494 (beginning-of-line 1))
495 (when app
496 (end-of-line 1)
497 (insert app)
498 (beginning-of-line 1))
499 (insert "* "))
500 ((get-text-property (point) 'org-agenda-date-header)
501 (setq in-date t)
502 (insert "** "))
503 ((setq m (or (get-text-property (point) 'org-hd-marker)
504 (get-text-property (point) 'org-marker)))
505 (setq sexp (member (get-text-property (point) 'type)
506 '("diary" "sexp")))
507 (if (setq pl (get-text-property (point) 'prefix-length))
508 (progn
509 (setq prefix (org-trim (buffer-substring
510 (point) (+ (point) pl)))
511 line (org-trim (buffer-substring
512 (+ (point) pl)
513 (point-at-eol))))
514 (delete-region (point-at-bol) (point-at-eol))
515 (insert line "<before>" prefix "</before>")
516 (beginning-of-line 1))
517 (and (looking-at "[ \t]+") (replace-match "")))
518 (insert (if in-date "*** " "** "))
519 (end-of-line 1)
520 (insert "\n")
521 (unless sexp
522 (insert (org-agenda-get-some-entry-text
523 m 10 " " 'planning)
524 "\n")
525 (when (setq id
526 (if (org-bound-and-true-p
527 org-mobile-force-id-on-agenda-items)
528 (org-id-get m 'create)
529 (org-entry-get m "ID")))
530 (insert " :PROPERTIES:\n :ORIGINAL_ID: " id
531 "\n :END:\n")))))
532 (beginning-of-line 2))
533 (push (cons (file-name-nondirectory file) (md5 (buffer-string)))
534 org-mobile-checksum-files))
535 (message "Agenda written to Org file %s" file)))
537 ;;;###autoload
538 (defun org-mobile-create-sumo-agenda ()
539 "Create a file that contains all custom agenda views."
540 (interactive)
541 (let* ((file (expand-file-name "agendas.org"
542 org-mobile-directory))
543 (sumo (org-mobile-sumo-agenda-command))
544 (org-agenda-custom-commands
545 (list (append sumo (list (list file)))))
546 (org-mobile-creating-agendas t))
547 (unless (file-writable-p file)
548 (error "Cannot write to file %s" file))
549 (when sumo
550 (org-store-agenda-views))))
552 (defun org-mobile-move-capture ()
553 "Move the contents of the capture file to the inbox file.
554 Return a marker to the location where the new content has been added.
555 If nothing new has been added, return nil."
556 (interactive)
557 (let ((inbox-buffer (find-file-noselect org-mobile-inbox-for-pull))
558 (capture-buffer (find-file-noselect
559 (expand-file-name org-mobile-capture-file
560 org-mobile-directory)))
561 (insertion-point (make-marker))
562 not-empty content)
563 (with-current-buffer capture-buffer
564 (setq content (buffer-string))
565 (setq not-empty (string-match "\\S-" content))
566 (when not-empty
567 (set-buffer inbox-buffer)
568 (widen)
569 (goto-char (point-max))
570 (or (bolp) (newline))
571 (move-marker insertion-point
572 (prog1 (point) (insert content)))
573 (save-buffer)
574 (set-buffer capture-buffer)
575 (erase-buffer)
576 (save-buffer)
577 (org-mobile-update-checksum-for-capture-file (buffer-string))))
578 (kill-buffer capture-buffer)
579 (if not-empty insertion-point)))
581 (defun org-mobile-update-checksum-for-capture-file (buffer-string)
582 (let* ((file (expand-file-name "checksums.dat" org-mobile-directory))
583 (buffer (find-file-noselect file)))
584 (when buffer
585 (with-current-buffer buffer
586 (when (re-search-forward (concat "\\([0-9a-fA-F]\\{30,\\}\\).*?"
587 (regexp-quote org-mobile-capture-file)
588 "[ \t]*$") nil t)
589 (goto-char (match-beginning 1))
590 (delete-region (match-beginning 1) (match-end 1))
591 (insert (md5 buffer-string))
592 (save-buffer)))
593 (kill-buffer buffer))))
595 (defun org-mobile-apply (&optional beg end)
596 "Apply all change requests in the current buffer.
597 If BEG and END are given, only do this in that region."
598 (interactive)
599 (require 'org-archive)
600 (setq org-mobile-last-flagged-files nil)
601 (setq beg (or beg (point-min)) end (or end (point-max)))
603 ;; Remove all Note IDs
604 (goto-char beg)
605 (while (re-search-forward "^\\*\\* Note ID: [-0-9A-F]+[ \t]*\n" end t)
606 (replace-match ""))
608 ;; Find all the referenced entries, without making any changes yet
609 (let ((marker (make-marker))
610 (bos-marker (make-marker))
611 (end (move-marker (make-marker) end))
612 (cnt-new 0)
613 (cnt-edit 0)
614 (cnt-flag 0)
615 (cnt-error 0)
616 buf-list
617 id-pos org-mobile-error)
619 ;; Count the new captures
620 (goto-char beg)
621 (while (re-search-forward "^\\* \\(.*\\)" end t)
622 (and (>= (- (match-end 1) (match-beginning 1)) 2)
623 (not (equal (downcase (substring (match-string 1) 0 2)) "f("))
624 (incf cnt-new)))
626 (goto-char beg)
627 (while (re-search-forward
628 "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)[ \t]+\\[\\[\\(\\(id\\|olp\\):\\([^]\n]+\\)\\)" end t)
629 (setq id-pos (condition-case msg
630 (org-mobile-locate-entry (match-string 4))
631 (error (nth 1 msg))))
632 (when (and (markerp id-pos)
633 (not (member (marker-buffer id-pos) buf-list)))
634 (org-mobile-timestamp-buffer (marker-buffer id-pos))
635 (push (marker-buffer id-pos) buf-list))
637 (if (or (not id-pos) (stringp id-pos))
638 (progn
639 (goto-char (+ 2 (point-at-bol)))
640 (insert id-pos " ")
641 (incf cnt-error))
642 (add-text-properties (point-at-bol) (point-at-eol)
643 (list 'org-mobile-marker
644 (or id-pos "Linked entry not found")))))
646 ;; OK, now go back and start applying
647 (goto-char beg)
648 (while (re-search-forward "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)" end t)
649 (catch 'next
650 (setq id-pos (get-text-property (point-at-bol) 'org-mobile-marker))
651 (if (not (markerp id-pos))
652 (progn
653 (incf cnt-error)
654 (insert "UNKNOWN PROBLEM"))
655 (let* ((action (match-string 1))
656 (data (and (match-end 3) (match-string 3)))
657 (bos (point-at-bol))
658 (eos (save-excursion (org-end-of-subtree t t)))
659 (cmd (if (equal action "")
660 '(progn
661 (incf cnt-flag)
662 (org-toggle-tag "FLAGGED" 'on)
663 (and note
664 (org-entry-put nil "THEFLAGGINGNOTE" note)))
665 (incf cnt-edit)
666 (cdr (assoc action org-mobile-action-alist))))
667 (note (and (equal action "")
668 (buffer-substring (1+ (point-at-eol)) eos)))
669 (org-inhibit-logging 'note) ;; Do not take notes interactively
670 old new)
671 (goto-char bos)
672 (move-marker bos-marker (point))
673 (if (re-search-forward "^** Old value[ \t]*$" eos t)
674 (setq old (buffer-substring
675 (1+ (match-end 0))
676 (progn (outline-next-heading) (point)))))
677 (if (re-search-forward "^** New value[ \t]*$" eos t)
678 (setq new (buffer-substring
679 (1+ (match-end 0))
680 (progn (outline-next-heading)
681 (if (eobp) (org-back-over-empty-lines))
682 (point)))))
683 (setq old (and old (if (string-match "\\S-" old) old nil)))
684 (setq new (and new (if (string-match "\\S-" new) new nil)))
685 (if (and note (> (length note) 0))
686 ;; Make Note into a single line, to fit into a property
687 (setq note (mapconcat 'identity
688 (org-split-string (org-trim note) "\n")
689 "\\n")))
690 (unless (equal data "body")
691 (setq new (and new (org-trim new))
692 old (and old (org-trim old))))
693 (goto-char (+ 2 bos-marker))
694 (unless (markerp id-pos)
695 (insert "BAD REFERENCE ")
696 (incf cnt-error)
697 (throw 'next t))
698 (unless cmd
699 (insert "BAD FLAG ")
700 (incf cnt-error)
701 (throw 'next t))
702 ;; Remember this place so tha we can return
703 (move-marker marker (point))
704 (setq org-mobile-error nil)
705 (save-excursion
706 (condition-case msg
707 (org-with-point-at id-pos
708 (progn
709 (eval cmd)
710 (if (member "FLAGGED" (org-get-tags))
711 (add-to-list 'org-mobile-last-flagged-files
712 (buffer-file-name (current-buffer))))))
713 (error (setq org-mobile-error msg))))
714 (when org-mobile-error
715 (switch-to-buffer (marker-buffer marker))
716 (goto-char marker)
717 (incf cnt-error)
718 (insert (if (stringp (nth 1 org-mobile-error))
719 (nth 1 org-mobile-error)
720 "EXECUTION FAILED")
721 " ")
722 (throw 'next t))
723 ;; If we get here, the action has been applied successfully
724 ;; So remove the entry
725 (goto-char bos-marker)
726 (delete-region (point) (org-end-of-subtree t t))))))
727 (save-buffer)
728 (move-marker marker nil)
729 (move-marker end nil)
730 (message "%d new, %d edits, %d flags, %d errors" cnt-new
731 cnt-edit cnt-flag cnt-error)
732 (sit-for 1)))
734 (defun org-mobile-timestamp-buffer (buf)
735 "Time stamp buffer BUF, just to make sure its checksum will change."
736 (with-current-buffer buf
737 (save-excursion
738 (save-restriction
739 (widen)
740 (goto-char (point-min))
741 (when (re-search-forward
742 "^\\([ \t]*\\)#\\+LAST_MOBILE_CHANGE:.*\n?" nil t)
743 (goto-char (match-end 1))
744 (delete-region (point) (match-end 0)))
745 (insert "#+LAST_MOBILE_CHANGE: "
746 (format-time-string "%Y-%m-%d %T") "\n")))))
748 (defun org-mobile-smart-read ()
749 "Parse the entry at point for shortcuts and expand them.
750 These shortcuts are meant for fast and easy typing on the limited
751 keyboards of a mobile device. Below we show a list of the shortcuts
752 currently implemented.
754 The entry is expected to contain an inactive time stamp indicating when
755 the entry was created. When setting dates and
756 times (for example for deadlines), the time strings are interpreted
757 relative to that creation date.
758 Abbreviations are expected to take up entire lines, jst because it is so
759 easy to type RET on a mobile device. Abbreviations start with one or two
760 letters, followed immediately by a dot and then additional information.
761 Generally the entire shortcut line is removed after action have been taken.
762 Time stamps will be constructed using `org-read-date'. So for example a
763 line \"dd. 2tue\" will set a deadline on the second Tuesday after the
764 creation date.
766 Here are the shortcuts currently implemented:
768 dd. string set deadline
769 ss. string set scheduling
770 tt. string set time tamp, here.
771 ti. string set inactive time
773 tg. tag1 tag2 tag3 set all these tags, change case where necessary
774 td. kwd set this todo keyword, change case where necessary
776 FIXME: Hmmm, not sure if we can make his work against the
777 auto-correction feature. Needs a bit more thinking. So this function
778 is currently a noop.")
781 (defun org-find-olp (path)
782 "Return a marker pointing to the entry at outline path OLP.
783 If anything goes wrong, the return value will instead an error message,
784 as a string."
785 (let* ((file (pop path))
786 (buffer (find-file-noselect file))
787 (level 1)
788 (lmin 1)
789 (lmax 1)
790 limit re end found pos heading cnt)
791 (unless buffer (error "File not found :%s" file))
792 (with-current-buffer buffer
793 (save-excursion
794 (save-restriction
795 (widen)
796 (setq limit (point-max))
797 (goto-char (point-min))
798 (while (setq heading (pop path))
799 (setq re (format org-complex-heading-regexp-format
800 (regexp-quote heading)))
801 (setq cnt 0 pos (point))
802 (while (re-search-forward re end t)
803 (setq level (- (match-end 1) (match-beginning 1)))
804 (if (and (>= level lmin) (<= level lmax))
805 (setq found (match-beginning 0) cnt (1+ cnt))))
806 (when (= cnt 0) (error "Heading not found on level %d: %s"
807 lmax heading))
808 (when (> cnt 1) (error "Heading not unique on level %d: %s"
809 lmax heading))
810 (goto-char found)
811 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
812 (setq end (save-excursion (org-end-of-subtree t t))))
813 (when (org-on-heading-p)
814 (move-marker (make-marker) (point))))))))
816 (defun org-mobile-locate-entry (link)
817 (if (string-match "\\`id:\\(.*\\)$" link)
818 (org-id-find (match-string 1 link) 'marker)
819 (if (not (string-match "\\`olp:\\(.*?\\):\\(.*\\)$" link))
821 (let ((file (match-string 1 link))
822 (path (match-string 2 link))
823 (table '((?: . "%3a") (?\[ . "%5b") (?\] . "%5d") (?/ . "%2f"))))
824 (setq file (org-link-unescape file table))
825 (setq file (expand-file-name file org-directory))
826 (setq path (mapcar (lambda (x) (org-link-unescape x table))
827 (org-split-string path "/")))
828 (org-find-olp (cons file path))))))
830 (defun org-mobile-edit (what old new)
831 "Edit item WHAT in the current entry by replacing OLD wih NEW.
832 WHAT can be \"heading\", \"todo\", \"tags\", \"priority\", or \"body\".
833 The edit only takes place if the current value is equal (except for
834 white space) the OLD. If this is so, OLD will be replace by NEW
835 and the command will return t. If something goes wrong, a string will
836 be returned that indicates what went wrong."
837 (let (current old1 new1)
838 (if (stringp what) (setq what (intern what)))
840 (cond
842 ((memq what '(todo todostate))
843 (setq current (org-get-todo-state))
844 (cond
845 ((equal new "DONEARCHIVE")
846 (org-todo 'done)
847 (org-archive-subtree-default))
848 ((equal new current) t) ; nothing needs to be done
849 ((or (equal current old)
850 (eq org-mobile-force-mobile-change t)
851 (memq 'todo org-mobile-force-mobile-change))
852 (org-todo (or new 'none)) t)
853 (t (error "State before change was expected as \"%s\", but is \"%s\""
854 old current))))
856 ((eq what 'tags)
857 (setq current (org-get-tags)
858 new1 (and new (org-split-string new ":+"))
859 old1 (and old (org-split-string old ":+")))
860 (cond
861 ((org-mobile-tags-same-p current new1) t) ; no change needed
862 ((or (org-mobile-tags-same-p current old1)
863 (eq org-mobile-force-mobile-change t)
864 (memq 'tags org-mobile-force-mobile-change))
865 (org-set-tags-to new1) t)
866 (t (error "Tags before change were expected as \"%s\", but are \"%s\""
867 (or old "") (or current "")))))
869 ((eq what 'priority)
870 (when (looking-at org-complex-heading-regexp)
871 (setq current (and (match-end 3) (substring (match-string 3) 2 3)))
872 (cond
873 ((equal current new) t) ; no action required
874 ((or (equal current old)
875 (eq org-mobile-force-mobile-change t)
876 (memq 'tags org-mobile-force-mobile-change))
877 (org-priority (and new (string-to-char new))))
878 (t (error "Priority was expected to be %s, but is %s"
879 old current)))))
881 ((eq what 'heading)
882 (when (looking-at org-complex-heading-regexp)
883 (setq current (match-string 4))
884 (cond
885 ((equal current new) t) ; no action required
886 ((or (equal current old)
887 (eq org-mobile-force-mobile-change t)
888 (memq 'heading org-mobile-force-mobile-change))
889 (goto-char (match-beginning 4))
890 (insert new)
891 (delete-region (point) (+ (point) (length current)))
892 (org-set-tags nil 'align))
893 (t (error "Heading changed in MobileOrg and on the computer")))))
895 ((eq what 'body)
896 (setq current (buffer-substring (min (1+ (point-at-eol)) (point-max))
897 (save-excursion (outline-next-heading)
898 (point))))
899 (if (not (string-match "\\S-" current)) (setq current nil))
900 (cond
901 ((org-mobile-bodies-same-p current new) t) ; no ation necesary
902 ((or (org-mobile-bodies-same-p current old)
903 (eq org-mobile-force-mobile-change t)
904 (memq 'body org-mobile-force-mobile-change))
905 (save-excursion
906 (end-of-line 1)
907 (insert "\n" new)
908 (or (bolp) (insert "\n"))
909 (delete-region (point) (progn (org-back-to-heading t)
910 (outline-next-heading)
911 (point))))
913 (t (error "Body was changed in MobileOrg and on the computer")))))))
916 (defun org-mobile-tags-same-p (list1 list2)
917 "Are the two tag lists the same?"
918 (not (or (org-delete-all list1 list2)
919 (org-delete-all list2 list1))))
921 (defun org-mobile-bodies-same-p (a b)
922 "Compare if A and B are visually equal strings.
923 We first remove leading and trailing white space from the entire strings.
924 Then we split the strings into lines and remove leading/trailing whitespace
925 from each line. Then we compare.
926 A and B must be strings or nil."
927 (cond
928 ((and (not a) (not b)) t)
929 ((or (not a) (not b)) nil)
930 (t (setq a (org-trim a) b (org-trim b))
931 (setq a (mapconcat 'identity (org-split-string a "[ \t]*\n[ \t]*") "\n"))
932 (setq b (mapconcat 'identity (org-split-string b "[ \t]*\n[ \t]*") "\n"))
933 (equal a b))))
935 (provide 'org-mobile)
937 ;; arch-tag: ace0e26c-58f2-4309-8a61-05ec1535f658
939 ;;; org-mobile.el ends here