Make updating the mibileorg.org checksum safe
[org-mode.git] / lisp / org-mobile.el
blob0a856d4e7467a087dffa48fa7a2f9a73c898ff1f
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.31trans
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* ((files
181 (apply 'append (mapcar
182 (lambda (f)
183 (cond
184 ((eq f 'org-agenda-files) (org-agenda-files t))
185 ((eq f 'org-agenda-text-search-extra-files)
186 org-agenda-text-search-extra-files)
187 ((and (stringp f) (file-directory-p f))
188 (directory-files f 'full "\\.org\\'"))
189 ((and (stringp f) (file-exists-p f))
190 (list f))
191 (t nil)))
192 org-mobile-files)))
193 (orgdir-uname (file-name-as-directory (file-truename org-directory)))
194 (orgdir-re (concat "\\`" (regexp-quote orgdir-uname)))
195 uname seen rtn file link-name)
196 ;; Make the files unique, and determine the name under which they will
197 ;; be listed.
198 (while (setq file (pop files))
199 (setq uname (file-truename file))
200 (unless (member uname seen)
201 (push uname seen)
202 (if (string-match orgdir-re uname)
203 (setq link-name (substring uname (match-end 0)))
204 (setq link-name (file-name-nondirectory uname)))
205 (push (cons file link-name) rtn)))
206 (nreverse rtn)))
208 ;;;###autoload
209 (defun org-mobile-push ()
210 "Push the current state of Org affairs to the WebDAV directory.
211 This will create the index file, copy all agenda files there, and also
212 create all custom agenda views, for upload to the mobile phone."
213 (interactive)
214 (org-mobile-check-setup)
215 (org-mobile-prepare-file-lists)
216 (run-hooks 'org-mobile-pre-push-hook)
217 (org-mobile-create-sumo-agenda)
218 (org-save-all-org-buffers) ; to save any IDs created by this process
219 (org-mobile-copy-agenda-files)
220 (org-mobile-create-index-file)
221 (org-mobile-write-checksums)
222 (run-hooks 'org-mobile-post-push-hook)
223 (message "Files for mobile viewer staged"))
225 ;;;###autoload
226 (defun org-mobile-pull ()
227 "Pull the contents of `org-mobile-capture-file' and integrate them.
228 Apply all flagged actions, flag entries to be flagged and then call an
229 agenda view showing the flagged items."
230 (interactive)
231 (org-mobile-check-setup)
232 (run-hooks 'org-mobile-pre-pull-hook)
233 (let ((insertion-marker (org-mobile-move-capture)))
234 (if (not (markerp insertion-marker))
235 (message "No new items")
236 (org-with-point-at insertion-marker
237 (org-mobile-apply (point) (point-max)))
238 (move-marker insertion-marker nil)
239 (run-hooks 'org-mobile-post-pull-hook)
240 (when org-mobile-last-flagged-files
241 ;; Make an agenda view of flagged entries, but only in the files
242 ;; where stuff has been added.
243 (put 'org-agenda-files 'org-restrict org-mobile-last-flagged-files)
244 (let ((org-agenda-keep-restriced-file-list t))
245 (org-agenda nil "?"))))))
247 (defun org-mobile-check-setup ()
248 "Check if org-mobile-directory has been set up."
249 (unless (and org-directory
250 (stringp org-directory)
251 (string-match "\\S-" org-directory)
252 (file-exists-p org-directory)
253 (file-directory-p org-directory))
254 (error
255 "Please set `org-directory' to the directory where your org files live"))
256 (unless (and org-mobile-directory
257 (stringp org-mobile-directory)
258 (string-match "\\S-" org-mobile-directory)
259 (file-exists-p org-mobile-directory)
260 (file-directory-p org-mobile-directory))
261 (error
262 "Variable `org-mobile-directory' must point to an existing directory"))
263 (unless (and org-mobile-inbox-for-pull
264 (stringp org-mobile-inbox-for-pull)
265 (string-match "\\S-" org-mobile-inbox-for-pull)
266 (file-exists-p
267 (file-name-directory org-mobile-inbox-for-pull)))
268 (error
269 "Variable `org-mobile-inbox-for-pull' must point to a file in an existing directory")))
271 (defun org-mobile-create-index-file ()
272 "Write the index file in the WebDAV directory."
273 (let ((files-alist (sort (copy-sequence org-mobile-files-alist)
274 (lambda (a b) (string< (cdr a) (cdr b)))))
275 (def-todo (default-value 'org-todo-keywords))
276 (def-tags (default-value 'org-tag-alist))
277 file link-name todo-kwds done-kwds tags drawers entry kwds dwds twds)
279 (org-prepare-agenda-buffers (mapcar 'car files-alist))
280 (setq done-kwds (org-uniquify org-done-keywords-for-agenda))
281 (setq todo-kwds (org-delete-all
282 done-kwds
283 (org-uniquify org-todo-keywords-for-agenda)))
284 (setq drawers (org-uniquify org-drawers-for-agenda))
285 (setq tags (org-uniquify
286 (delq nil
287 (mapcar
288 (lambda (e)
289 (cond ((stringp e) e)
290 ((listp e)
291 (if (stringp (car e)) (car e) nil))
292 (t nil)))
293 org-tag-alist-for-agenda))))
294 (with-temp-file
295 (expand-file-name org-mobile-index-file org-mobile-directory)
296 (while (setq entry (pop def-todo))
297 (insert "#+READONLY\n")
298 (setq kwds (mapcar (lambda (x) (if (string-match "(" x)
299 (substring x 0 (match-beginning 0))
301 (cdr entry)))
302 (insert "#+TODO: " (mapconcat 'identity kwds " ") "\n")
303 (setq dwds (member "|" kwds)
304 twds (org-delete-all dwds kwds)
305 todo-kwds (org-delete-all twds todo-kwds)
306 done-kwds (org-delete-all dwds done-kwds)))
307 (when (or todo-kwds done-kwds)
308 (insert "#+TODO: " (mapconcat 'identity todo-kwds " ") " | "
309 (mapconcat 'identity done-kwds " ") "\n"))
310 (setq def-tags (mapcar
311 (lambda (x)
312 (cond ((null x) nil)
313 ((stringp x) x)
314 ((eq (car x) :startgroup) "{")
315 ((eq (car x) :endgroup) "}")
316 ((eq (car x) :newline) nil)
317 ((listp x) (car x))
318 (t nil)))
319 def-tags))
320 (setq def-tags (delq nil def-tags))
321 (setq tags (org-delete-all def-tags tags))
322 (setq tags (sort tags (lambda (a b) (string< (downcase a) (downcase b)))))
323 (setq tags (append def-tags tags nil))
324 (insert "#+TAGS: " (mapconcat 'identity tags " ") "\n")
325 (insert "#+DRAWERS: " (mapconcat 'identity drawers " ") "\n")
326 (insert "#+ALLPRIORITIES: A B C" "\n")
327 (when (file-exists-p (expand-file-name
328 org-mobile-directory "agendas.org"))
329 (insert "* [[file:agendas.org][Agenda Views]]\n"))
330 (while (setq entry (pop files-alist))
331 (setq file (car entry)
332 link-name (cdr entry))
333 (insert (format "* [[file:%s][%s]]\n"
334 link-name link-name)))
335 (push (cons org-mobile-index-file (md5 (buffer-string)))
336 org-mobile-checksum-files))))
338 (defun org-mobile-copy-agenda-files ()
339 "Copy all agenda files to the stage or WebDAV directory."
340 (let ((files-alist org-mobile-files-alist)
341 file buf entry link-name target-path target-dir check)
342 (while (setq entry (pop files-alist))
343 (setq file (car entry) link-name (cdr entry))
344 (when (file-exists-p file)
345 (setq target-path (expand-file-name link-name org-mobile-directory)
346 target-dir (file-name-directory target-path))
347 (unless (file-directory-p target-dir)
348 (make-directory target-dir 'parents))
349 (copy-file file target-path 'ok-if-exists)
350 (setq check (shell-command-to-string
351 (concat org-mobile-checksum-binary " "
352 (shell-quote-argument (expand-file-name file)))))
353 (when (string-match "[a-fA-F0-9]\\{30,40\\}" check)
354 (push (cons link-name (match-string 0 check))
355 org-mobile-checksum-files))))
356 (setq file (expand-file-name org-mobile-capture-file
357 org-mobile-directory))
358 (save-excursion
359 (setq buf (find-file file))
360 (and (= (point-min) (point-max)) (insert "\n"))
361 (save-buffer)
362 (push (cons org-mobile-capture-file (md5 (buffer-string)))
363 org-mobile-checksum-files))
364 (kill-buffer buf)))
366 (defun org-mobile-write-checksums ()
367 "Create checksums for all files in `org-mobile-directory'.
368 The table of checksums is written to the file mobile-checksums."
369 (let ((sumfile (expand-file-name "checksums.dat" org-mobile-directory))
370 (files org-mobile-checksum-files)
371 entry file sum)
372 (with-temp-file sumfile
373 (while (setq entry (pop files))
374 (setq file (car entry) sum (cdr entry))
375 (insert (format "%s %s\n" sum file))))))
377 (defun org-mobile-sumo-agenda-command ()
378 "Return an agenda custom command that comprises all custom commands."
379 (let ((custom-list
380 ;; normalize different versions
381 (delq nil
382 (mapcar
383 (lambda (x)
384 (cond ((stringp (cdr x)) nil)
385 ((stringp (nth 1 x)) x)
386 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
387 (t (cons (car x) (cons "" (cdr x))))))
388 org-agenda-custom-commands)))
389 new e key desc type match settings cmds gkey gdesc gsettings cnt)
390 (while (setq e (pop custom-list))
391 (cond
392 ((stringp (cdr e))
393 ;; this is a description entry - skip it
395 ((eq (nth 2 e) 'search)
396 ;; Search view is interactive, skip
398 ((memq (nth 2 e) '(todo-tree tags-tree occur-tree))
399 ;; These are trees, not really agenda commands
401 ((memq (nth 2 e) '(agenda todo tags))
402 ;; a normal command
403 (setq key (car e) desc (nth 1 e) type (nth 2 e) match (nth 3 e)
404 settings (nth 4 e))
405 (setq settings
406 (cons (list 'org-agenda-title-append
407 (concat "<after>KEYS=" key " TITLE: "
408 (if (and (stringp desc) (> (length desc) 0))
409 desc (symbol-name type))
410 " " match "</after>"))
411 settings))
412 (push (list type match settings) new))
413 ((symbolp (nth 2 e))
414 ;; A user-defined function, not sure how to handle that yet
417 ;; a block agenda
418 (setq gkey (car e) gdesc (nth 1 e) gsettings (nth 3 e) cmds (nth 2 e))
419 (setq cnt 0)
420 (while (setq e (pop cmds))
421 (setq type (car e) match (nth 1 e) settings (nth 2 e))
422 (setq settings (append gsettings settings))
423 (setq settings
424 (cons (list 'org-agenda-title-append
425 (concat "<after>KEYS=" gkey "#" (number-to-string
426 (setq cnt (1+ cnt)))
427 " TITLE: " gdesc " " match "</after>"))
428 settings))
429 (push (list type match settings) new)))))
430 (and new (list "X" "SUMO" (reverse new)
431 '((org-agenda-compact-blocks nil))))))
433 (defvar org-mobile-creating-agendas nil)
434 (defun org-mobile-write-agenda-for-mobile (file)
435 (let ((all (buffer-string)) in-date id pl prefix line app short m sexp)
436 (with-temp-file file
437 (org-mode)
438 (insert "#+READONLY\n")
439 (insert all)
440 (goto-char (point-min))
441 (while (not (eobp))
442 (cond
443 ((looking-at "[ \t]*$")) ; keep empty lines
444 ((looking-at "=+$")
445 ;; remove underlining
446 (delete-region (point) (point-at-eol)))
447 ((get-text-property (point) 'org-agenda-structural-header)
448 (setq in-date nil)
449 (setq app (get-text-property (point)
450 'org-agenda-title-append))
451 (setq short (get-text-property (point)
452 'short-heading))
453 (when (and short (looking-at ".+"))
454 (replace-match short)
455 (beginning-of-line 1))
456 (when app
457 (end-of-line 1)
458 (insert app)
459 (beginning-of-line 1))
460 (insert "* "))
461 ((get-text-property (point) 'org-agenda-date-header)
462 (setq in-date t)
463 (insert "** "))
464 ((setq m (or (get-text-property (point) 'org-hd-marker)
465 (get-text-property (point) 'org-marker)))
466 (setq sexp (member (get-text-property (point) 'type)
467 '("diary" "sexp")))
468 (if (setq pl (get-text-property (point) 'prefix-length))
469 (progn
470 (setq prefix (org-trim (buffer-substring
471 (point) (+ (point) pl)))
472 line (org-trim (buffer-substring
473 (+ (point) pl)
474 (point-at-eol))))
475 (delete-region (point-at-bol) (point-at-eol))
476 (insert line "<before>" prefix "</before>")
477 (beginning-of-line 1))
478 (and (looking-at "[ \t]+") (replace-match "")))
479 (insert (if in-date "*** " "** "))
480 (end-of-line 1)
481 (insert "\n")
482 (unless sexp
483 (insert (org-agenda-get-some-entry-text
484 m 10 " " 'planning)
485 "\n")
486 (when (setq id
487 (if (org-bound-and-true-p
488 org-mobile-force-id-on-agenda-items)
489 (org-id-get m 'create)
490 (org-entry-get m "ID")))
491 (insert " :PROPERTIES:\n :ORIGINAL_ID: " id
492 "\n :END:\n")))))
493 (beginning-of-line 2))
494 (push (cons (file-name-nondirectory file) (md5 (buffer-string)))
495 org-mobile-checksum-files))
496 (message "Agenda written to Org file %s" file)))
498 ;;;###autoload
499 (defun org-mobile-create-sumo-agenda ()
500 "Create a file that contains all custom agenda views."
501 (interactive)
502 (let* ((file (expand-file-name "agendas.org"
503 org-mobile-directory))
504 (sumo (org-mobile-sumo-agenda-command))
505 (org-agenda-custom-commands
506 (list (append sumo (list (list file)))))
507 (org-mobile-creating-agendas t))
508 (unless (file-writable-p file)
509 (error "Cannot write to file %s" file))
510 (when sumo
511 (org-store-agenda-views))))
513 (defun org-mobile-move-capture ()
514 "Move the contents of the capture file to the inbox file.
515 Return a marker to the location where the new content has been added.
516 If nothing new has beed added, return nil."
517 (interactive)
518 (let ((inbox-buffer (find-file-noselect org-mobile-inbox-for-pull))
519 (capture-buffer (find-file-noselect
520 (expand-file-name org-mobile-capture-file
521 org-mobile-directory)))
522 (insertion-point (make-marker))
523 not-empty content)
524 (save-excursion
525 (set-buffer capture-buffer)
526 (setq content (buffer-string))
527 (setq not-empty (string-match "\\S-" content))
528 (when not-empty
529 (set-buffer inbox-buffer)
530 (widen)
531 (goto-char (point-max))
532 (or (bolp) (newline))
533 (move-marker insertion-point
534 (prog1 (point) (insert content)))
535 (save-buffer)
536 (set-buffer capture-buffer)
537 (erase-buffer)
538 (save-buffer)
539 (org-mobile-update-checksum-for-capture-file (buffer-string))))
540 (kill-buffer capture-buffer)
541 (if not-empty insertion-point)))
543 (defun org-mobile-update-checksum-for-capture-file (buffer-string)
544 (let* ((file (expand-file-name "checksums.dat" org-mobile-directory))
545 (buffer (find-file-noselect file)))
546 (when buffer
547 (with-current-buffer buffer
548 (when (re-search-forward (concat "\\([0-9a-fA-F]\\{30,\\}\\).*?"
549 (regexp-quote org-mobile-capture-file)
550 "[ \t]*$") nil t)
551 (goto-char (match-beginning 1))
552 (delete-region (match-beginning 1) (match-end 1))
553 (insert (md5 buffer-string))
554 (save-buffer)))
555 (kill-buffer buffer))))
557 (defun org-mobile-apply (&optional beg end)
558 "Apply all change requests in the current buffer.
559 If BEG and END are given, only do this in that region."
560 (interactive)
561 (require 'org-archive)
562 (setq org-mobile-last-flagged-files nil)
563 (setq beg (or beg (point-min)) end (or end (point-max)))
565 ;; Remove all Note IDs
566 (goto-char beg)
567 (while (re-search-forward "^\\*\\* Note ID: [-0-9A-F]+[ \t]*\n" end t)
568 (replace-match ""))
570 ;; Find all the referenced entries, without making any changes yet
571 (let ((marker (make-marker))
572 (bos-marker (make-marker))
573 (end (move-marker (make-marker) end))
574 (cnt-new 0)
575 (cnt-edit 0)
576 (cnt-flag 0)
577 (cnt-error 0)
578 buf-list
579 id-pos org-mobile-error)
581 ;; Count the new captures
582 (goto-char beg)
583 (while (re-search-forward "^\\* \\(.*\\)" end t)
584 (and (>= (- (match-end 1) (match-beginning 1)) 2)
585 (not (equal (downcase (substring (match-string 1) 0 2)) "f("))
586 (incf cnt-new)))
588 (goto-char beg)
589 (while (re-search-forward
590 "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)[ \t]+\\[\\[\\(\\(id\\|olp\\):\\([^]\n]+\\)\\)" end t)
591 (setq id-pos (condition-case msg
592 (org-mobile-locate-entry (match-string 4))
593 (error (nth 1 msg))))
594 (when (and (markerp id-pos)
595 (not (member (marker-buffer id-pos) buf-list)))
596 (org-mobile-timestamp-buffer (marker-buffer id-pos))
597 (push (marker-buffer id-pos) buf-list))
599 (if (or (not id-pos) (stringp id-pos))
600 (progn
601 (goto-char (+ 2 (point-at-bol)))
602 (insert id-pos " ")
603 (incf cnt-error))
604 (add-text-properties (point-at-bol) (point-at-eol)
605 (list 'org-mobile-marker
606 (or id-pos "Linked entry not found")))))
608 ;; OK, now go back and start applying
609 (goto-char beg)
610 (while (re-search-forward "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)" end t)
611 (catch 'next
612 (setq id-pos (get-text-property (point-at-bol) 'org-mobile-marker))
613 (if (not (markerp id-pos))
614 (progn
615 (incf cnt-error)
616 (insert "UNKNOWN PROBLEM"))
617 (let* ((action (match-string 1))
618 (data (and (match-end 3) (match-string 3)))
619 (bos (point-at-bol))
620 (eos (save-excursion (org-end-of-subtree t t)))
621 (cmd (if (equal action "")
622 '(progn
623 (incf cnt-flag)
624 (org-toggle-tag "FLAGGED" 'on)
625 (and note
626 (org-entry-put nil "THEFLAGGINGNOTE" note)))
627 (incf cnt-edit)
628 (cdr (assoc action org-mobile-action-alist))))
629 (note (and (equal action "")
630 (buffer-substring (1+ (point-at-eol)) eos)))
631 (org-inhibit-logging 'note) ;; Do not take notes interactively
632 old new)
633 (goto-char bos)
634 (move-marker bos-marker (point))
635 (if (re-search-forward "^** Old value[ \t]*$" eos t)
636 (setq old (buffer-substring
637 (1+ (match-end 0))
638 (progn (outline-next-heading) (point)))))
639 (if (re-search-forward "^** New value[ \t]*$" eos t)
640 (setq new (buffer-substring
641 (1+ (match-end 0))
642 (progn (outline-next-heading)
643 (if (eobp) (org-back-over-empty-lines))
644 (point)))))
645 (setq old (and old (if (string-match "\\S-" old) old nil)))
646 (setq new (and new (if (string-match "\\S-" new) new nil)))
647 (if (and note (> (length note) 0))
648 ;; Make Note into a single line, to fit into a property
649 (setq note (mapconcat 'identity
650 (org-split-string (org-trim note) "\n")
651 "\\n")))
652 (unless (equal data "body")
653 (setq new (and new (org-trim new))
654 old (and old (org-trim old))))
655 (goto-char (+ 2 bos-marker))
656 (unless (markerp id-pos)
657 (insert "BAD REFERENCE ")
658 (incf cnt-error)
659 (throw 'next t))
660 (unless cmd
661 (insert "BAD FLAG ")
662 (incf cnt-error)
663 (throw 'next t))
664 ;; Remember this place so tha we can return
665 (move-marker marker (point))
666 (setq org-mobile-error nil)
667 (save-excursion
668 (condition-case msg
669 (org-with-point-at id-pos
670 (progn
671 (eval cmd)
672 (if (member "FLAGGED" (org-get-tags))
673 (add-to-list 'org-mobile-last-flagged-files
674 (buffer-file-name (current-buffer))))))
675 (error (setq org-mobile-error msg))))
676 (when org-mobile-error
677 (switch-to-buffer (marker-buffer marker))
678 (goto-char marker)
679 (incf cnt-error)
680 (insert (if (stringp (nth 1 org-mobile-error))
681 (nth 1 org-mobile-error)
682 "EXECUTION FAILED")
683 " ")
684 (throw 'next t))
685 ;; If we get here, the action has been applied successfully
686 ;; So remove the entry
687 (goto-char bos-marker)
688 (delete-region (point) (org-end-of-subtree t t))))))
689 (move-marker marker nil)
690 (move-marker end nil)
691 (message "%d new, %d edits, %d flags, %d errors" cnt-new
692 cnt-edit cnt-flag cnt-error)
693 (sit-for 1)))
695 (defun org-mobile-timestamp-buffer (buf)
696 "Time stamp buffer BUF, just to make sure its checksum will change."
697 (with-current-buffer buf
698 (save-excursion
699 (save-restriction
700 (widen)
701 (goto-char (point-min))
702 (when (re-search-forward
703 "^\\([ \t]*\\)#\\+LAST_MOBILE_CHANGE:.*\n?" nil t)
704 (goto-char (match-end 1))
705 (delete-region (point) (match-end 0)))
706 (insert "#+LAST_MOBILE_CHANGE: "
707 (format-time-string "%Y-%m-%d %T") "\n")))))
709 (defun org-mobile-smart-read ()
710 "Parse the entry at point for shortcuts and expand them.
711 These shortcuts are meant for fast and easy typing on the limited
712 keyboards of a mobile device. Below we show a list of the shortcuts
713 currently implemented.
715 The entry is expected to contain an inactive time stamp indicating when
716 the entry was created. When setting dates and
717 times (for example for deadlines), the time strings are interpreted
718 relative to that creation date.
719 Abbreviations are expected to take up entire lines, jst because it is so
720 easy to type RET on a mobile device. Abbreviations start with one or two
721 letters, followed immediately by a dot and then additional information.
722 Generally the entire shortcut line is removed after action have been taken.
723 Time stamps will be constructed using `org-read-date'. So for example a
724 line \"dd. 2tue\" will set a deadline on the second Tuesday after the
725 creation date.
727 Here are the shortcuts currently implemented:
729 dd. string set deadline
730 ss. string set scheduling
731 tt. string set time tamp, here.
732 ti. string set inactive time
734 tg. tag1 tag2 tag3 set all these tags, change case where necessary
735 td. kwd set this todo keyword, change case where necessary
737 FIXME: Hmmm, not sure if we can make his work against the
738 auto-correction feature. Needs a bit more thinking. So this function
739 is currently a noop.")
742 (defun org-find-olp (path)
743 "Return a marker pointing to the entry at outline path OLP.
744 If anything goes wrong, the return value will instead an error message,
745 as a string."
746 (let* ((file (pop path))
747 (buffer (find-file-noselect file))
748 (level 1)
749 (lmin 1)
750 (lmax 1)
751 limit re end found pos heading cnt)
752 (unless buffer (error "File not found :%s" file))
753 (with-current-buffer buffer
754 (save-excursion
755 (save-restriction
756 (widen)
757 (setq limit (point-max))
758 (goto-char (point-min))
759 (while (setq heading (pop path))
760 (setq re (format org-complex-heading-regexp-format
761 (regexp-quote heading)))
762 (setq cnt 0 pos (point))
763 (while (re-search-forward re end t)
764 (setq level (- (match-end 1) (match-beginning 1)))
765 (if (and (>= level lmin) (<= level lmax))
766 (setq found (match-beginning 0) cnt (1+ cnt))))
767 (when (= cnt 0) (error "Heading not found on level %d: %s"
768 lmax heading))
769 (when (> cnt 1) (error "Heading not unique on level %d: %s"
770 lmax heading))
771 (goto-char found)
772 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
773 (setq end (save-excursion (org-end-of-subtree t t))))
774 (when (org-on-heading-p)
775 (move-marker (make-marker) (point))))))))
777 (defun org-mobile-locate-entry (link)
778 (if (string-match "\\`id:\\(.*\\)$" link)
779 (org-id-find (match-string 1 link) 'marker)
780 (if (not (string-match "\\`olp:\\(.*?\\):\\(.*\\)$" link))
782 (let ((file (match-string 1 link))
783 (path (match-string 2 link))
784 (table '((?: . "%3a") (?\[ . "%5b") (?\] . "%5d") (?/ . "%2f"))))
785 (setq file (org-link-unescape file table))
786 (setq file (expand-file-name file org-directory))
787 (setq path (mapcar (lambda (x) (org-link-unescape x table))
788 (org-split-string path "/")))
789 (org-find-olp (cons file path))))))
791 (defun org-mobile-edit (what old new)
792 "Edit item WHAT in the current entry by replacing OLD wih NEW.
793 WHAT can be \"heading\", \"todo\", \"tags\", \"priority\", or \"body\".
794 The edit only takes place if the current value is equal (except for
795 white space) the OLD. If this is so, OLD will be replace by NEW
796 and the command will return t. If something goes wrong, a string will
797 be returned that indicates what went wrong."
798 (let (current old1 new1)
799 (if (stringp what) (setq what (intern what)))
801 (cond
803 ((memq what '(todo todostate))
804 (setq current (org-get-todo-state))
805 (cond
806 ((equal new "DONEARCHIVE")
807 (org-todo 'done)
808 (org-archive-subtree-default))
809 ((equal new current) t) ; nothing needs to be done
810 ((or (equal current old)
811 (eq org-mobile-force-mobile-change t)
812 (memq 'todo org-mobile-force-mobile-change))
813 (org-todo (or new 'none)) t)
814 (t (error "State before change was expected as \"%s\", but is \"%s\""
815 old current))))
817 ((eq what 'tags)
818 (setq current (org-get-tags)
819 new1 (and new (org-split-string new ":+"))
820 old1 (and old (org-split-string old ":+")))
821 (cond
822 ((org-mobile-tags-same-p current new1) t) ; no change needed
823 ((or (org-mobile-tags-same-p current old1)
824 (eq org-mobile-force-mobile-change t)
825 (memq 'tags org-mobile-force-mobile-change))
826 (org-set-tags-to new1) t)
827 (t (error "Tags before change were expected as \"%s\", but are \"%s\""
828 (or old "") (or current "")))))
830 ((eq what 'priority)
831 (when (looking-at org-complex-heading-regexp)
832 (setq current (and (match-end 3) (substring (match-string 3) 2 3)))
833 (cond
834 ((equal current new) t) ; no action required
835 ((or (equal current old)
836 (eq org-mobile-force-mobile-change t)
837 (memq 'tags org-mobile-force-mobile-change))
838 (org-priority (and new (string-to-char new))))
839 (t (error "Priority was expected to be %s, but is %s"
840 old current)))))
842 ((eq what 'heading)
843 (when (looking-at org-complex-heading-regexp)
844 (setq current (match-string 4))
845 (cond
846 ((equal current new) t) ; no action required
847 ((or (equal current old)
848 (eq org-mobile-force-mobile-change t)
849 (memq 'heading org-mobile-force-mobile-change))
850 (goto-char (match-beginning 4))
851 (insert new)
852 (delete-region (point) (+ (point) (length current)))
853 (org-set-tags nil 'align))
854 (t (error "Heading changed in MobileOrg and on the computer")))))
856 ((eq what 'body)
857 (setq current (buffer-substring (min (1+ (point-at-eol)) (point-max))
858 (save-excursion (outline-next-heading)
859 (point))))
860 (if (not (string-match "\\S-" current)) (setq current nil))
861 (cond
862 ((org-mobile-bodies-same-p current new) t) ; no ation necesary
863 ((or (org-mobile-bodies-same-p current old)
864 (eq org-mobile-force-mobile-change t)
865 (memq 'body org-mobile-force-mobile-change))
866 (save-excursion
867 (end-of-line 1)
868 (insert "\n" new)
869 (or (bolp) (insert "\n"))
870 (delete-region (point) (progn (org-back-to-heading t)
871 (outline-next-heading)
872 (point))))
874 (t (error "Body was changed in MobileOrg and on the computer")))))))
877 (defun org-mobile-tags-same-p (list1 list2)
878 "Are the two tag lists the same?"
879 (not (or (org-delete-all list1 list2)
880 (org-delete-all list2 list1))))
882 (defun org-mobile-bodies-same-p (a b)
883 "Compare if A and B are visually equal strings.
884 We first remove leading and trailing white space from the entire strings.
885 Then we split the strings into lines and remove leading/trailing whitespace
886 from each line. Then we compare.
887 A and B must be strings or nil."
888 (cond
889 ((and (not a) (not b)) t)
890 ((or (not a) (not b)) nil)
891 (t (setq a (org-trim a) b (org-trim b))
892 (setq a (mapconcat 'identity (org-split-string a "[ \t]*\n[ \t]*") "\n"))
893 (setq b (mapconcat 'identity (org-split-string b "[ \t]*\n[ \t]*") "\n"))
894 (equal a b))))
896 (provide 'org-mobile)
898 ;; arch-tag: ace0e26c-58f2-4309-8a61-05ec1535f658
900 ;;; org-mobile.el ends here