Merge branch 'maint'
[org-mode.git] / contrib / lisp / org-index.el
blob8f7b7f3f2da55b18e2e3872fa6c26b42d69e3833
1 ;;; org-index.el --- A personal adaptive index for org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
5 ;; Author: Marc Ihm <org-index@2484.de>
6 ;; Version: 5.7.2
7 ;; Keywords: outlines index
9 ;; This file is not part of GNU Emacs.
11 ;;; License:
13 ;; This program is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Purpose:
30 ;; Fast search for selected org nodes and things outside of org.
32 ;; org-index creates and updates an index table with keywords; each line
33 ;; either points to a heading in org, references something outside or
34 ;; carries a snippet of text to yank. When searching the index, the set
35 ;; of matching lines is updated with every keystroke; results are sorted
36 ;; by usage count and date, so that frequently used entries appear first
37 ;; in the list of results.
39 ;; References are decorated numbers (e.g. 'R237' or '--455--'); they are
40 ;; well suited to be used outside of org, e.g. in folder names, ticket
41 ;; systems or on printed documents.
43 ;; On first invocation org-index will assist you in creating the index
44 ;; table.
46 ;; To start using your index, invoke subcommands 'add', 'ref' and 'yank'
47 ;; to create entries and 'occur' to find them.
50 ;; Setup:
52 ;; - Place this file in a directory of your load-path,
53 ;; e.g. org-mode/contrib/lisp.
54 ;; - Add these lines to your .emacs:
56 ;; (require 'org-index)
58 ;; - Restart your Emacs to make this effective.
59 ;; - Invoke `org-index'; on first run it will assist in creating your
60 ;; index table.
62 ;; - Optionally invoke `M-x org-customize', group 'Org Index', to tune
63 ;; some settings, e.g. the global prefix key 'C-c i'.
66 ;; Further information:
68 ;; - Watch the screencast at http://2484.de/org-index.html.
69 ;; - See the documentation of `org-index', which can also be read by
70 ;; invoking `org-index' and choosing the command help or '?'.
73 ;; Updates:
75 ;; The latest published version of this file can always be found at:
76 ;; http://orgmode.org/w/?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
77 ;; Development version under:
78 ;; https://github.com/marcIhm/org-index
82 ;;; Change Log:
84 ;;
85 ;; - See the command 'news' for recent changes, or
86 ;; - https://github.com/marcIhm/org-index/ChangeLog.org for older news
87 ;; - https://github.com/marcIhm/org-index/commits/master for a complete list of changes
91 ;;; Code:
93 (require 'org-table)
94 (require 'org-id)
95 (require 'org-inlinetask)
96 (require 'cl-lib)
97 (require 'widget)
99 ;; Version of this package
100 (defvar org-index-version "5.7.2" "Version of `org-index', format is major.minor.bugfix, where \"major\" are incompatible changes and \"minor\" are new features.")
102 ;; customizable options
103 (defgroup org-index nil
104 "Options concerning the optional index for org."
105 :tag "Org Index"
106 :group 'org)
108 (defcustom org-index-id nil
109 "Id of the Org-mode node, which contains the index table."
110 :group 'org-index)
112 (defcustom org-index-sort-by 'mixed
113 "Strategy for sorting index table (and whence entries in occur).
114 Valid values are:
116 last-access Sort index by date and time of last access; show
117 more recent entries first.
118 count Sort by usage count; more often used entries first.
119 mixed First, show all index entries, which have been
120 used today; sort them by last access. Then show
121 older entries sorted by usage count."
122 :group 'org-index
123 :set (lambda (s v)
124 (set-default s v)
125 (if (and org-index-id
126 org-index--buffer
127 (functionp 'org-index--sort-silent))
128 (org-index--sort-silent)))
129 :initialize 'custom-initialize-default
130 :type '(choice
131 (const last-accessed)
132 (const count)
133 (const mixed)))
135 (defcustom org-index-dispatch-key "\x03i"
136 "Key to invoke ‘org-index-dispatch’, which is the central entry function for ‘org-index’."
137 :group 'org-index
138 :initialize 'custom-initialize-set
139 :set (lambda (var val)
140 (set-default var val)
141 (global-set-key org-index-dispatch-key 'org-index-dispatch))
142 :type 'key-sequence)
144 (defcustom org-index-idle-delay 68
145 "Delay in seconds after which buffer will sorted or fontified when Emacs is idle."
146 :group 'org-index
147 :type 'integer)
149 (defcustom org-index-prepare-when-idle nil
150 "Fontify and sort index-table when idle to make first call faster.
151 You only need this if your index has grown so large, that first
152 invocation of `org-index' needs a noticable amount of time."
153 :group 'org-index
154 :initialize 'custom-initialize-set
155 :set (lambda (var val)
156 (set-default var val)
157 (when val
158 (setq org-index--align-interactive 200)
159 (run-with-idle-timer org-index-idle-delay nil 'org-index--idle-prepare)))
160 :type 'boolean)
162 (defcustom org-index-yank-after-add 'ref
163 "Specifies which column should be yanked after adding a new index row.
164 Valid values are some columns of index table."
165 :group 'org-index
166 :type '(choice
167 (const ref)
168 (const category)
169 (const keywords)))
171 (defcustom org-index-copy-heading-to-keywords t
172 "When adding a new node to index: Copy heading to keywords-column ?"
173 :group 'org-index
174 :type '(choice (const :tag "Yes" t)
175 (const :tag "No" nil)))
177 (defcustom org-index-strip-ref-and-date-from-heading t
178 "When adding a node to index: strip leading ref or timestamps ?
180 This can be useful, if you have the habit of adding refs and
181 dates to the start of your headings; then, if you change your
182 heading and want to update your index, you do not need to remove
183 those pieces."
184 :group 'org-index
185 :type '(choice (const :tag "Yes" t)
186 (const :tag "No" nil)))
188 (defcustom org-index-edit-on-add '(category keywords)
189 "List of columns to edit when adding a new row."
190 :group 'org-index
191 :type '(repeat (choice
192 (const category)
193 (const keywords))))
195 (defcustom org-index-edit-on-yank '(keywords yank)
196 "List of columns to edit when adding new text to yank."
197 :group 'org-index
198 :type '(repeat (choice
199 (const yank)
200 (const category)
201 (const keywords))))
203 (defcustom org-index-edit-on-ref '(category keywords)
204 "List of columns to edit when adding new ref."
205 :group 'org-index
206 :type '(repeat (choice
207 (const category)
208 (const keywords))))
210 (defcustom org-index-clock-into-focus nil
211 "Clock into focused node ?"
212 :group 'org-index
213 :type 'boolean)
215 (defcustom org-index-goto-bottom-after-focus nil
216 "After visiting a focused nodes; position cursor at bottom of node (as opposed to heading) ?"
217 :group 'org-index
218 :type 'boolean)
220 ;; Variables to hold the configuration of the index table
221 (defvar org-index--head nil "Header before number (e.g. 'R').")
222 (defvar org-index--tail nil "Tail after number (e.g. '}' or ')'.")
223 (defvar org-index--numcols nil "Number of columns in index table.")
224 (defvar org-index--ref-regex nil "Regular expression to match a reference.")
225 (defvar org-index--ref-format nil "Format, that can print a reference.")
226 (defvar org-index--columns nil "Columns of index-table.")
227 (defvar org-index--buffer nil "Buffer of index table.")
228 (defvar org-index--point nil "Position at start of headline of index table.")
229 (defvar org-index--below-hline nil "Position of first cell in first line below hline.")
230 (defvar org-index--saved-positions nil "Saved positions within current buffer and index buffer; filled by ‘org-index--save-positions’.")
231 (defvar org-index--headings nil "Headlines of index-table as a string.")
232 (defvar org-index--headings-visible nil "Visible part of headlines of index-table as a string.")
233 (defvar org-index--ids-focused-nodes nil "Ids of focused node (if any).")
234 (defvar org-index--ids-focused-nodes-saved nil "Backup for ‘org-index--ids-focused-nodes’.")
235 (defvar org-index--id-last-goto-focus nil "Id of last node, that has been focused to.")
237 ;; Variables to hold context and state
238 (defvar org-index--last-fingerprint nil "Fingerprint of last line created.")
239 (defvar org-index--category-before nil "Category of node before.")
240 (defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
241 (defvar org-index--below-cursor nil "Word below cursor.")
242 (defvar org-index--within-index-node nil "True, if we are within node of the index table.")
243 (defvar org-index--within-occur nil "True, if we are within the occur-buffer.")
244 (defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
245 (defvar org-index--occur-help-text nil "Text for help in occur buffer.")
246 (defvar org-index--occur-help-overlay nil "Overlay for help in occur buffer.")
247 (defvar org-index--occur-stack nil "Stack with overlays for hiding lines.")
248 (defvar org-index--occur-tail-overlay nil "Overlay to cover invisible lines.")
249 (defvar org-index--occur-lines-collected 0 "Number of lines collected in occur buffer; helpful for tests.")
250 (defvar org-index--last-sort-assumed nil "Last column, the index has been sorted after (best guess).")
251 (defvar org-index--sort-timer nil "Timer to sort index in correct order.")
252 (defvar org-index--inhibit-sort-idle nil "If set, index will not be sorted in idle background.")
253 (defvar org-index--aligned 0 "For this Emacs session: remember number of table lines aligned.")
254 (defvar org-index--align-interactive most-positive-fixnum "Number of rows to align in ‘org-index--parse-table’.")
255 (defvar org-index--edit-widgets nil "List of widgets used to edit.")
256 (defvar org-index--context-index nil "Position and line used for index in edit buffer.")
257 (defvar org-index--context-occur nil "Position and line used for occur in edit buffer.")
258 (defvar org-index--context-node nil "Buffer and position for node in edit buffer.")
259 (defvar org-index--short-help-buffer-name "*org-index commands*" "Name of buffer to display short help.")
260 (defvar org-index--news-buffer-name "*org-index news*" "Name of buffer to display news.")
261 (defvar org-index--display-short-help nil "True, if short help should be displayed.")
262 (defvar org-index--short-help-displayed nil "True, if short help message has been displayed.")
263 (defvar org-index--prefix-arg nil "True, if prefix argument has been received during input.")
264 (defvar org-index--minibuffer-saved-key nil "Temporarily save entry of minibuffer keymap.")
265 (defvar org-index--after-focus-timer nil "Timer to clock in or update focused node after a delay.")
266 (defvar org-index--after-focus-context nil "Context for after focus action.")
267 (defvar org-index--this-command nil "Subcommand, that is currently excecuted.")
268 (defvar org-index--last-command nil "Subcommand, that hast been excecuted last.")
270 ;; static information for this program package
271 (defconst org-index--commands '(occur add kill head ping index ref yank column edit help short-help news focus example sort find-ref highlight maintain) "List of commands available.")
272 (defconst org-index--valid-headings '(ref id created last-accessed count keywords category level yank tags) "All valid headings.")
273 (defconst org-index--occur-buffer-name "*org-index-occur*" "Name of occur buffer.")
274 (defconst org-index--edit-buffer-name "*org-index-edit*" "Name of edit buffer.")
275 (defvar org-index--short-help-text nil "Cache for result of `org-index--get-short-help-text.")
276 (defvar org-index--shortcut-chars nil "Cache for result of `org-index--get-shortcut-chars.")
277 (defvar org-index--after-focus-delay 10 "Number of seconds to wait before invoking after-focus action.")
280 (defmacro org-index--on (column value &rest body)
281 "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
282 The value returned is the value of the last form in BODY or nil,
283 if VALUE cannot be found."
284 (declare (indent 2) (debug t))
285 (let ((pointvar (make-symbol "point"))
286 (foundvar (make-symbol "found"))
287 (retvar (make-symbol "ret")))
288 `(save-current-buffer
289 (let ((,pointvar (point))
290 ,foundvar
291 ,retvar)
293 (set-buffer org-index--buffer)
295 (setq ,foundvar (org-index--go ,column ,value))
296 (when ,foundvar
297 (setq ,retvar (progn ,@body)))
299 (goto-char ,pointvar)
301 ,retvar))))
304 (defun org-index (&optional command search-ref arg)
305 "Fast search-index for selected org nodes and things outside.
307 This function creates and updates an index table with keywords;
308 each line either points to a heading in org, references something
309 outside or carries a snippet of text to yank. The index table is
310 searched for keywords by means of an incremental occur; results
311 are sorted by usage count and date, so that frequently used
312 entries appear first.
314 References are decorated numbers (e.g. 'R237' or '--455--'); they are
315 well suited to be used outside of org, e.g. in folder names, ticket
316 systems or on printed documents.
318 On first invocation this function will help to create a dedicated node
319 for its index table.
321 To start building up your index, use subcommands 'add', 'ref' and
322 'yank' to create entries and use 'occur' to find them.
324 This is version 5.7.2 of org-index.el.
327 The function `org-index' is the only interactive function of this
328 package and its main entry point; it will present you with a list
329 of subcommands to choose from:
331 \(Note the one-letter shortcuts, e.g. [o]; used like `\\[org-index-dispatch] o'.)
333 occur: [o] Incrementally show matching lines from index.
334 Result is updated after every keystroke. You may enter a
335 list of words seperated by space or comma (`,'), to select
336 lines that contain all of the given words. With a numeric
337 prefix argument, show lines, which have been accessed at
338 most this many days ago.
340 add: [a] Add the current node to index.
341 So that (e.g.) it can be found through the subcommand
342 'occur'. Update index, if node is already present.
344 kill: [k] Kill (delete) the current node from index.
345 Can be invoked from index, from occur or from a headline.
347 head: [h] Search for heading, by ref or from index line.
348 If invoked from within index table, go to associated
349 node (if any), otherwise ask for ref to search.
351 index: [i] Enter index table and maybe go to a specific reference.
352 Use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
354 ping: [p] Echo line from index table for current node.
355 If current node is not in index, than search among its
356 parents.
358 ref: [r] Create a new index line with a reference.
359 This line will not be associated with a node.
361 yank: [y] Store a new string, that can be yanked from occur.
362 The index line will not be associated with a node.
364 column: [c] From within index table: read char and jump to column.
365 Shortcut for column movement; stays within one index line.
367 edit: [e] Present current line in edit buffer.
368 Can be invoked from index, from occur or from a headline.
370 focus: [f] Return to first focused node; repeat to see them all.
371 The focused nodes are kept in a short list; they need not be
372 part of the index though. This command visits one focus node
373 after the other, as long as you invoke it in quick succession
374 and without moving to other nodes; otherwise it returns to
375 the focus node, where you left off. Finally, with a prefix
376 argument, this command offers more options, e.g. to set focus
377 in the first place.
379 help: Show complete help text of `org-index'.
380 I.e. this text.
382 short-help: [?] Show this one-line description of each subcommand.
383 I.e. from the complete help, show only the first line for each
384 subcommand.
386 news: [n] Show news for the current point release.
388 example: Create an example index, that will not be saved.
389 May serve as an example.
391 sort: Sort lines in index, in region or buffer.
392 Region or buffer can be sorted by contained reference; Index
393 by count, reference or last access.
395 find-ref: Search for given reference in all org-buffers.
396 A wrapper to employ Emacs standard `multi-occur' function;
397 asks for reference.
399 highlight: Highlight or unhighlight all references.
400 Operates on active region or whole buffer. Call with prefix
401 argument (`C-u') to remove highlights.
403 maintain: Index maintainance.
404 Offers some choices to check, update or fix your index.
406 If you invoke `org-index' for the first time, an assistant will be
407 invoked, that helps you to create your own index.
409 Invoke `org-customize' to tweak the behaviour of `org-index'.
411 This includes the global key `org-index-dispatch-key' to invoke
412 the most important subcommands with one additional key.
414 A numeric prefix argument is used as a reference number for
415 commands, that need one (e.g. 'head') or to modify their
416 behaviour (e.g. 'occur').
418 Also, a single prefix argument may be specified just before the
419 final character (e.g. like `C-c i C-u f') or by just typing an
420 upper case letter (e.g. `C-c i F').
422 Use from elisp: Optional argument COMMAND is a symbol naming the
423 command to execute. SEARCH-REF specifies a reference to search
424 for, if needed. ARG allows passing in a prefix argument as in
425 interactive calls."
427 (interactive "i\ni\nP")
429 (let (search-id ; id to search for
430 search-fingerprint ; fingerprint to search for
431 sort-what ; sort what ?
432 kill-new-text ; text that will be appended to kill ring
433 message-text) ; text that will be issued as an explanation
436 (catch 'new-index
439 ;; Initialize and parse
442 ;; creates index table, if necessary
443 (org-index--verify-id)
445 ;; Get configuration of index table
446 (org-index--parse-table org-index--align-interactive t)
448 ;; store context information
449 (org-index--retrieve-context)
453 ;; Arrange for proper sorting of index
456 ;; lets assume, that it has been sorted this way (we try hard to make sure)
457 (unless org-index--last-sort-assumed (setq org-index--last-sort-assumed org-index-sort-by))
458 ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
459 (unless org-index--sort-timer
460 (setq org-index--sort-timer
461 (run-with-idle-timer org-index-idle-delay t 'org-index--sort-silent)))
465 ;; Find out, what we are supposed to do
468 ;; Check or read command
469 (if (and command (not (eq command 'short-help)))
470 (unless (memq command org-index--commands)
471 (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
472 command (mapconcat 'symbol-name org-index--commands ",")))
474 ;; read command; if requested display help in read-loop
475 (setq org-index--display-short-help (eq command 'short-help))
476 (setq command (org-index--read-command))
477 (if org-index--prefix-arg (setq arg (or arg '(4))))
478 (setq org-index--display-short-help nil))
480 (setq org-index--last-command org-index--this-command)
481 (setq org-index--this-command command)
485 ;; Get search string, if required; process possible sources one after
486 ;; another (lisp argument, prefix argument, user input).
489 ;; Try prefix, if no lisp argument given
490 (if (and (not search-ref)
491 (numberp arg))
492 (setq search-ref (format "%s%d%s" org-index--head arg org-index--tail)))
494 ;; These actions really need a search string and may even prompt for it
495 (when (memq command '(index head find-ref))
497 ;; search from surrounding text ?
498 (unless search-ref
499 (if org-index--within-index-node
501 (if (org-at-table-p)
502 (setq search-ref (org-index--get-or-set-field 'ref)))
504 (if (and org-index--below-cursor
505 (string-match (concat "\\(" org-index--ref-regex "\\)")
506 org-index--below-cursor))
507 (setq search-ref (match-string 1 org-index--below-cursor)))))
509 ;; If we still do not have a search string, ask user explicitly
510 (unless search-ref
511 (if (eq command 'index)
512 (let ((r (org-index--read-search-for-index)))
513 (setq search-ref (cl-first r))
514 (setq search-id (cl-second r))
515 (setq search-fingerprint (cl-third r)))
516 (unless (and (eq command 'head)
517 org-index--within-index-node
518 (org-at-table-p))
519 (setq search-ref (read-from-minibuffer "Search reference number: ")))))
521 ;; Clean up search string
522 (when search-ref
523 (setq search-ref (org-trim search-ref))
524 (if (string-match "^[0-9]+$" search-ref)
525 (setq search-ref (concat org-index--head search-ref org-index--tail)))
526 (if (string= search-ref "") (setq search-ref nil)))
528 (if (and (not search-ref)
529 (not (eq command 'index))
530 (not (and (eq command 'head)
531 org-index--within-index-node
532 (org-at-table-p))))
533 (error "Command %s needs a reference number" command)))
537 ;; Command sort needs to know in advance, what to sort for
540 (when (eq command 'sort)
541 (setq sort-what (intern (org-completing-read "You may sort:\n - index : your index table by various columns\n - region : the active region by contained reference\n - buffer : the whole current buffer\nPlease choose what to sort: " (list "index" "region" "buffer") nil t))))
545 ;; Enter table
548 ;; Arrange for beeing able to return
549 (when (and (memq command '(occur head index example sort maintain focus))
550 (not (string= (buffer-name) org-index--occur-buffer-name)))
551 (org-mark-ring-push))
553 ;; These commands will leave user in index table after they are finished
554 (when (or (memq command '(index maintain))
555 (and (eq command 'sort)
556 (eq sort-what 'index)))
558 (pop-to-buffer-same-window org-index--buffer)
559 (goto-char org-index--point)
560 (org-index--unfold-buffer))
564 ;; Actually do, what is requested
567 (cond
569 ((eq command 'help)
571 ;; bring up help-buffer for this function
572 (describe-function 'org-index))
575 ((eq command 'short-help)
577 (org-index--display-short-help))
580 ((eq command 'news)
581 (with-current-buffer-window
582 org-index--news-buffer-name nil nil
583 (insert (format "News for Version %s of org-index:\n"
584 (progn
585 (string-match "\\([0-9]+\\.[0-9]+\\)\\." org-index-version)
586 (match-string 1 org-index-version))))
587 (insert "
588 - New option org-index-goto-bottom-after-focus for position after jumping to a focused node
589 - New focus-command 'r' to revert last change to list of focused nodes
591 (insert "\nSee https://github.com/marcIhm/org-index/ChangeLog.org for older news.\n")
592 (org-mode))
593 (shrink-window-if-larger-than-buffer (get-buffer-window org-index--news-buffer-name)))
596 ((eq command 'find-ref)
598 ;; Construct list of all org-buffers
599 (let (org-buffers)
600 (dolist (buff (buffer-list))
601 (set-buffer buff)
602 (if (string= major-mode "org-mode")
603 (setq org-buffers (cons buff org-buffers))))
605 ;; Do multi-occur
606 (multi-occur org-buffers (org-index--make-guarded-search search-ref))
608 ;; Present results
609 (if (get-buffer "*Occur*")
610 (progn
611 (setq message-text (format "Found '%s'" search-ref))
612 (other-window 1)
613 (toggle-truncate-lines 1))
614 (setq message-text (format "Did not find '%s'" search-ref)))))
617 ((eq command 'add)
619 (let ((r (org-index--do-add-or-update (if (equal arg '(4)) t nil)
620 (if (numberp arg) arg nil))))
621 (setq message-text (car r))
622 (setq kill-new-text (cdr r))))
625 ((eq command 'kill)
626 (setq message-text (org-index--do-kill)))
629 ((eq command 'head)
631 (if (and org-index--within-index-node
632 (org-at-table-p))
633 (setq search-id (org-index--get-or-set-field 'id)))
635 (if (and (not search-id) search-ref)
636 (setq search-id (org-index--id-from-ref search-ref)))
638 (setq message-text
639 (if search-id
640 (org-index--find-id search-id)
641 "Current line has no id")))
644 ((eq command 'index)
646 (goto-char org-index--below-hline)
648 (setq message-text
650 (if search-ref
651 (if (org-index--go 'ref search-ref)
652 (progn
653 (org-index--update-current-line)
654 (org-table-goto-column (org-index--column-num 'ref))
655 (format "Found index line '%s'" search-ref))
656 (format "Did not find index line with reference '%s'" search-ref))
658 (if search-id
659 (if (org-index--go 'id search-id)
660 (progn
661 (org-index--update-current-line)
662 (org-table-goto-column (org-index--column-num 'ref))
663 (format "Found index line '%s'" (org-index--get-or-set-field 'ref)))
664 (format "Did not find index line with id '%s'" search-id))
666 (if search-fingerprint
667 (if (org-index--go 'fingerprint org-index--last-fingerprint)
668 (progn
669 (org-index--update-current-line)
670 (beginning-of-line)
671 (format "Found latest index line"))
672 (format "Did not find index line"))
674 ;; simply go into table
675 "At index table"))))
677 (recenter))
680 ((eq command 'ping)
682 (let ((moved-up 0) id info reached-top done)
684 (unless (string= major-mode "org-mode") (error "No node at point"))
685 ;; take id from current node or reference
686 (setq id (if search-ref
687 (org-index--id-from-ref search-ref)
688 (org-id-get)))
690 ;; move up until we find a node in index
691 (save-excursion
692 (org-with-limited-levels (org-back-to-heading))
693 (while (not done)
694 (if id
695 (setq info (org-index--on 'id id
696 (mapcar (lambda (x) (org-index--get-or-set-field x))
697 (list 'keywords 'count 'created 'last-accessed 'category 'ref)))))
699 (setq reached-top (= (org-outline-level) 1))
701 (if (or info reached-top)
702 (setq done t)
703 (outline-up-heading 1 t)
704 (cl-incf moved-up))
706 (setq id (org-id-get))))
708 (if info
709 (progn
710 (setq message-text
711 (apply 'format
712 (append (list "'%s'%s has been accessed %s times between %s and %s; category is '%s', reference is '%s'"
713 (pop info)
714 (if (> moved-up 0) (format " (parent node, %d level up)" moved-up) ""))
715 info)))
716 (setq kill-new-text (car (last info))))
717 (setq message-text "Neither this node nor any of its parents is part of index"))))
720 ((eq command 'occur)
722 (set-buffer org-index--buffer)
723 (org-index--do-occur (if (numberp arg) arg nil)))
726 ((eq command 'ref)
728 (let (args newref)
730 (setq args (org-index--collect-values-from-user org-index-edit-on-ref))
731 (setq newref (org-index--get-save-maxref))
732 (setq args (plist-put args 'ref newref))
733 (apply 'org-index--do-new-line args)
735 (setq kill-new-text newref)
737 (setq message-text (format "Added new row with ref '%s'" newref))))
740 ((eq command 'yank)
742 (let (args)
744 (setq args (org-index--collect-values-from-user org-index-edit-on-yank))
745 (if (plist-get args 'yank)
746 (plist-put args 'yank (replace-regexp-in-string "|" "\\vert" (plist-get args 'yank) nil 'literal)))
747 (setq args (plist-put args 'category "yank"))
748 (apply 'org-index--do-new-line args)
750 (setq message-text "Added new row with text to yank")))
753 ((eq command 'column)
755 (if (and org-index--within-index-node
756 (org-at-table-p))
757 (let (char col num)
758 (setq char (read-char "Please specify, which column to go to (r=ref, k=keywords, c=category, y=yank): "))
759 (unless (memq char (list ?r ?k ?c ?y))
760 (error (format "Invalid char '%c', cannot goto this column" char)))
761 (setq col (cdr (assoc char '((?r . ref) (?k . keywords) (?c . category) (?y . yank)))))
762 (setq num (org-index--column-num col))
763 (if num
764 (progn
765 (org-table-goto-column num)
766 (setq message-text (format "At column %s" (symbol-name col))))
768 (error (format "Column '%s' is not present" col))))
769 (error "Need to be in index table to go to a specific column")))
772 ((eq command 'edit)
774 (setq message-text (org-index--do-edit)))
777 ((eq command 'sort)
779 (let ((sorts (list "count" "last-accessed" "mixed" "id" "ref"))
780 sort groups-and-counts)
782 (cond
783 ((eq sort-what 'index)
784 (setq sort
785 (intern
786 (completing-read
787 "Please choose column to sort index table: "
788 (cl-copy-list sorts)
789 nil t nil nil (symbol-name org-index-sort-by))))
791 (org-index--do-sort-index sort)
792 (org-table-goto-column (org-index--column-num (if (eq sort 'mixed) 'last-access sort)))
793 ;; When saving index, it should again be sorted correctly
794 (with-current-buffer org-index--buffer
795 (add-hook 'before-save-hook 'org-index--sort-silent t))
797 (setq message-text
798 (format
799 (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
800 (if groups-and-counts
801 "; %d groups with equal %s and a total of %d lines have been found"
802 ""))
803 (symbol-name sort)
804 org-index-sort-by
805 org-index-idle-delay
806 (cl-second groups-and-counts)
807 (symbol-name sort)
808 (cl-third groups-and-counts))))
810 ((memq sort-what '(region buffer))
811 (org-index--do-sort-lines sort-what)
812 (setq message-text (format "Sorted %s by contained references" sort-what))))))
815 ((eq command 'highlight)
817 (let ((where "buffer"))
818 (save-excursion
819 (save-restriction
820 (when (and transient-mark-mode
821 mark-active)
822 (narrow-to-region (region-beginning) (region-end))
823 (setq where "region"))
825 (if arg
826 (progn
827 (unhighlight-regexp org-index--ref-regex)
828 (setq message-text (format "Removed highlights for references in %s" where)))
829 (highlight-regexp org-index--ref-regex 'isearch)
830 (setq message-text (format "Highlighted references in %s" where)))))))
833 ((eq command 'focus)
834 (setq message-text (if arg
835 (org-index--more-focus-commands)
836 (org-index--goto-focus))))
839 ((eq command 'maintain)
840 (setq message-text (org-index--do-maintain)))
843 ((eq command 'example)
845 (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
846 (org-index--create-index t)))
849 ((not command) (setq message-text "No command given"))
852 (t (error "Unknown subcommand '%s'" command)))
855 ;; tell, what we have done and what can be yanked
856 (if kill-new-text (setq kill-new-text
857 (substring-no-properties kill-new-text)))
858 (if (string= kill-new-text "") (setq kill-new-text nil))
859 (let ((m (concat
860 message-text
861 (if (and message-text kill-new-text)
862 " and r"
863 (if kill-new-text "R" ""))
864 (if kill-new-text (format "eady to yank '%s'." kill-new-text) (if message-text "." "")))))
865 (unless (string= m "")
866 (message m)
867 (setq org-index--message-text m)))
868 (if kill-new-text (kill-new kill-new-text)))))
871 (defun org-index-dispatch (&optional arg)
872 "Read additional chars and call subcommands of `org-index'.
873 Can be bound in global keyboard map as central entry point.
874 Optional argument ARG is passed on."
875 (interactive "P")
876 (let (char command (c-u-text (if arg " C-u " "")))
877 (while (not char)
878 (if (sit-for 1)
879 (message (concat "org-index (? for detailed prompt) -" c-u-text)))
880 (setq char (key-description (read-key-sequence nil)))
881 (if (string= char "C-g") (keyboard-quit))
882 (if (string= char "SPC") (setq char "?"))
883 (when (string= char (upcase char))
884 (setq char (downcase char))
885 (setq arg (or arg '(4))))
886 (when (string= char "C-u")
887 (setq arg (or arg '(4)))
888 (setq c-u-text " C-u ")
889 (setq char nil)))
890 (setq command (cdr (assoc char (org-index--get-shortcut-chars))))
891 (unless command
892 (message "No subcommand for '%s'; switching to detailed prompt" char)
893 (sit-for 1)
894 (setq command 'short-help))
895 (org-index command nil arg)))
898 (defun org-index-new-line (&rest keys-values)
899 "Create a new line within the index table, returning its reference.
901 The function takes a varying number of argument pairs; each pair
902 is a symbol for an existing column heading followed by its value.
903 The return value is the new reference.
905 Example:
907 (message \"Created reference %s\"
908 (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
910 Optional argument KEYS-VALUES specifies content of new line."
912 (let ((ref (plist-get keys-values 'ref)))
913 (org-index--verify-id)
914 (org-index--parse-table)
915 (if (not (memq ref '(t nil)))
916 (error "Column 'ref' accepts only 't' or 'nil'"))
917 (when ref
918 (setq ref (org-index--get-save-maxref))
919 (setq keys-values (plist-put keys-values 'ref ref)))
921 (apply 'org-index--do-new-line keys-values)
922 ref))
925 (defun org-index--read-command ()
926 "Read subcommand for ‘org-index’ from minibuffer."
927 (let (minibuffer-scroll-window
928 command)
929 (setq org-index--short-help-displayed nil)
930 (setq org-index--prefix-arg nil)
931 (add-hook 'minibuffer-setup-hook 'org-index--minibuffer-setup-function)
932 (add-hook 'minibuffer-exit-hook 'org-index--minibuffer-exit-function)
933 (unwind-protect
934 (setq command
935 (completing-read
936 (concat
937 "Please choose"
938 (if org-index--display-short-help "" " (? for short help)")
939 ": ")
940 (append (mapcar 'symbol-name org-index--commands)
941 (mapcar 'upcase-initials (mapcar 'symbol-name org-index--commands)))
942 nil t))
943 (remove-hook 'minibuffer-setup-hook 'org-index--minibuffer-setup-function)
944 (remove-hook 'minibuffer-exit-hook 'org-index--minibuffer-exit-function)
945 (unless (string= command (downcase command))
946 (if command (setq command (downcase command)))
947 (setq org-index--prefix-arg '(4)))
948 (setq command (intern command))
949 (when org-index--short-help-displayed
950 (quit-windows-on org-index--short-help-buffer-name)))
951 command))
954 (defun org-index--minibuffer-setup-function ()
955 "Prepare minibuffer for `org-index--read-command'."
956 (setq org-index--minibuffer-saved-key (local-key-binding (kbd "?")))
957 (local-set-key (kbd "?") 'org-index--display-short-help)
958 (local-set-key (kbd "C-u") (lambda () (interactive)
959 (setq org-index--prefix-arg t)
960 (message "C-u")))
961 (if org-index--display-short-help (org-index--display-short-help)))
964 (defun org-index--minibuffer-exit-function ()
965 "Restore minibuffer after `org-index--read-command'."
966 (local-set-key (kbd "?") org-index--minibuffer-saved-key)
967 (local-set-key (kbd "C-u") 'universal-argument)
968 (setq org-index--minibuffer-saved-key nil))
971 (defun org-index--display-short-help ()
972 "Helper function to show help in minibuffer."
973 (interactive)
975 (with-temp-buffer-window
976 org-index--short-help-buffer-name nil nil
977 (setq org-index--short-help-displayed t)
978 (princ "Short help; shortcuts in []; capital letter acts like C-u.\n")
979 (princ (org-index--get-short-help-text)))
980 (with-current-buffer org-index--short-help-buffer-name
981 (let ((inhibit-read-only t))
982 (shrink-window-if-larger-than-buffer (get-buffer-window))
983 (goto-char (point-min))
984 (end-of-line)
985 (goto-char (point-min)))))
988 (defun org-index--get-short-help-text ()
989 "Extract text for short help message from long help."
990 (or org-index--short-help-text
991 (with-temp-buffer
992 (insert (documentation 'org-index))
993 (goto-char (point-min))
994 (search-forward (concat " " (symbol-name (cl-first org-index--commands)) ": "))
995 (forward-line 0)
996 (kill-region (point-min) (point))
997 (search-forward (concat " " (symbol-name (car (last org-index--commands))) ": "))
998 (forward-line 1)
999 (kill-region (point) (point-max))
1000 (keep-lines "^ [-a-z]+:" (point-min) (point-max))
1001 (align-regexp (point-min) (point-max) "\\(\\s-*\\):")
1002 (goto-char (point-min))
1003 (while (re-search-forward "\\. *$" nil t)
1004 (replace-match "" nil nil))
1005 (goto-char (point-min))
1006 (re-search-forward "short-help")
1007 (end-of-line)
1008 (insert " (this text)")
1009 (goto-char (point-min))
1010 (unless (= (line-number-at-pos (point-max)) (1+ (length org-index--commands)))
1011 (error "Internal error, unable to properly extract one-line descriptions of subcommands"))
1012 (setq org-index--short-help-text (buffer-string)))))
1015 (defun org-index--get-shortcut-chars ()
1016 "Collect shortcut chars from short help message."
1017 (or org-index--shortcut-chars
1018 (with-temp-buffer
1019 (insert (org-index--get-short-help-text))
1020 (goto-char (point-min))
1021 (while (< (point) (point-max))
1022 (when (looking-at "^ \\([-a-z]+\\)[ \t]+: +\\[\\([a-z?]\\)\\] ")
1023 (setq org-index--shortcut-chars
1024 (cons (cons (match-string 2) (intern (match-string 1)))
1025 org-index--shortcut-chars)))
1026 (forward-line 1))
1027 (unless (> (length org-index--shortcut-chars) 0)
1028 (error "Internal error, did not find shortcut chars"))
1029 org-index--shortcut-chars)))
1032 (defun org-index--goto-focus ()
1033 "Goto focus node, one after the other."
1034 (if org-index--ids-focused-nodes
1035 (let (target-id following-id last-id again explain marker
1036 (repeat-clause "") (bottom-clause "") (heading-is-clause ""))
1037 (setq again (and (eq this-command last-command)
1038 (eq org-index--this-command org-index--last-command)))
1039 (setq last-id (or org-index--id-last-goto-focus
1040 (car (last org-index--ids-focused-nodes))))
1041 (setq following-id (car (or (cdr-safe (member last-id
1042 (append org-index--ids-focused-nodes
1043 org-index--ids-focused-nodes)))
1044 org-index--ids-focused-nodes)))
1046 (setq target-id (if again following-id last-id))
1048 (set-transient-map (let ((map (make-sparse-keymap)))
1049 (define-key map (vector ?f)
1050 (lambda () (interactive)
1051 (setq this-command last-command)
1052 (setq org-index--this-command org-index--last-command)
1053 (message (concat (org-index--goto-focus) " (again)."))))
1054 (define-key map (vector ?h)
1055 (lambda () (interactive)
1056 (org-with-limited-levels (org-back-to-heading))
1057 (recenter 1)
1058 (message "On heading.")))
1059 (define-key map (vector ?b)
1060 (lambda () (interactive)
1061 (org-index--end-of-focused-node)
1062 (recenter -1)
1063 (message "At bottom.")))
1064 (define-key map (vector ?d)
1065 (lambda () (interactive)
1066 (setq this-command last-command)
1067 (org-index--delete-from-focus)
1068 (org-index--persist-focused-nodes)
1069 (message (concat "Current node has been removed from list of focused nodes, " (org-index--goto-focus) "."))))
1070 map) t)
1071 (setq repeat-clause "; type 'f' to repeat or 'd' to delete this node from list, 'h' goes to heading, 'b' to bottom of node")
1073 (if (member target-id (org-index--ids-up-to-top))
1074 (setq explain "Staying below current")
1075 (unless (setq marker (org-id-find target-id 'marker))
1076 (setq org-index--id-last-goto-focus nil)
1077 (error "Could not find focus-node with id %s" target-id))
1079 (pop-to-buffer-same-window (marker-buffer marker))
1080 (goto-char (marker-position marker))
1081 (move-marker marker nil)
1082 (when org-index-goto-bottom-after-focus
1083 (setq bottom-clause "bottom of ")
1084 (setq heading-is-clause (format ", heading is '%s'" (propertize (org-get-heading t t t t) 'face 'org-todo)))
1085 (org-index--end-of-focused-node))
1086 (org-index--unfold-buffer)
1087 (if org-index-goto-bottom-after-focus (recenter -1)))
1089 (if again
1090 (setq explain (format "Jumped to %snext" bottom-clause))
1091 (setq explain (format "Jumped back to %scurrent" bottom-clause)))
1093 (when org-index-clock-into-focus
1094 (if org-index--after-focus-timer (cancel-timer org-index--after-focus-timer))
1095 (setq org-index--after-focus-context target-id)
1096 (setq org-index--after-focus-timer
1097 (run-at-time org-index--after-focus-delay nil
1098 (lambda ()
1099 (when org-index--after-focus-context
1100 (save-window-excursion
1101 (save-excursion
1102 (org-id-goto org-index--after-focus-context)
1103 (org-clock-in)
1104 (org-index--update-line org-index--after-focus-context t)
1105 (setq org-index--after-focus-context nil)
1106 (cancel-timer org-index--after-focus-timer))))))))
1107 (setq org-index--id-last-goto-focus target-id)
1108 (concat
1109 (if (cdr org-index--ids-focused-nodes)
1110 (format "%s focus node (out of %d)%s"
1111 explain
1112 (length org-index--ids-focused-nodes)
1113 heading-is-clause)
1114 (format "Jumped to %ssingle focus-node%s" bottom-clause heading-is-clause))
1115 repeat-clause))
1116 "No nodes in focus, use set-focus"))
1119 (defun org-index--end-of-focused-node ()
1120 "Goto end of focused nodes, ignoring inline-tasks but stopping at first child."
1121 (let (level next (pos (point)))
1122 (when (ignore-errors (org-with-limited-levels (org-back-to-heading)))
1123 (setq level (outline-level))
1124 (forward-char 1)
1125 (if (and (org-with-limited-levels (re-search-forward org-outline-regexp-bol nil t))
1126 (> (outline-level) level))
1127 (progn ; landed on child node
1128 (goto-char (match-beginning 0))
1129 (forward-line -1))
1130 (goto-char pos) ; landed on next sibling or end of buffer
1131 (org-with-limited-levels
1132 (org-end-of-subtree nil t)
1133 (when (org-at-heading-p)
1134 (forward-line -1))))
1135 (beginning-of-line))))
1138 (defun org-index--more-focus-commands ()
1139 "More commands for handling focused nodes."
1140 (let (id text more-text char prompt ids-up-to-top)
1142 (setq prompt (format "Please specify action on the list of %s focused nodes: set, append, delete, restore (s,a,d,r or ? for short help) - "
1143 (length org-index--ids-focused-nodes)))
1144 (while (not (memq char (list ?s ?a ?d ?r)))
1145 (setq char (read-char prompt))
1146 (setq prompt "Actions on list of focused nodes: s)et single focus on this node, a)ppend this node to list, d)elete this node from list, r)estore previous list of focused nodes. Please choose - "))
1147 (setq text
1148 (cond
1150 ((eq char ?s)
1151 (setq id (org-id-get-create))
1152 (setq org-index--ids-focused-nodes-saved org-index--ids-focused-nodes)
1153 (setq org-index--ids-focused-nodes (list id))
1154 (setq org-index--id-last-goto-focus id)
1155 (org-index--update-line id t)
1156 (if org-index-clock-into-focus (org-clock-in))
1157 "Focus has been set on current node (1 node in focus)")
1159 ((eq char ?a)
1160 (setq id (org-id-get-create))
1161 (unless (member id org-index--ids-focused-nodes)
1162 ;; remove any children, that are already in list of focused nodes
1163 (setq org-index--ids-focused-nodes-saved org-index--ids-focused-nodes)
1164 (setq org-index--ids-focused-nodes
1165 (delete nil (mapcar (lambda (x)
1166 (if (member id (org-with-point-at (org-id-find x t)
1167 (org-index--ids-up-to-top)))
1168 (progn
1169 (setq more-text ", removing its children")
1170 nil)
1172 org-index--ids-focused-nodes)))
1173 (setq org-index--ids-focused-nodes-saved org-index--ids-focused-nodes)
1174 ;; remove parent, if already in list of focused nodes
1175 (setq ids-up-to-top (org-index--ids-up-to-top))
1176 (when (seq-intersection ids-up-to-top org-index--ids-focused-nodes)
1177 (setq org-index--ids-focused-nodes (seq-difference org-index--ids-focused-nodes ids-up-to-top))
1178 (setq more-text (concat more-text ", replacing its parent")))
1179 (setq org-index--ids-focused-nodes (cons id org-index--ids-focused-nodes)))
1180 (setq org-index--id-last-goto-focus id)
1181 (org-index--update-line id t)
1182 (if org-index-clock-into-focus (org-clock-in))
1183 "Current node has been appended to list of focused nodes%s (%d node%s in focus)")
1185 ((eq char ?d)
1186 (org-index--delete-from-focus))
1188 ((eq char ?r)
1189 (if org-index--ids-focused-nodes-saved
1190 (let (txt)
1191 (setq txt (format "Discarded current list of focused %d focused node%s and restored previous list; now %%s%%d node%%s in focus" (length org-index--ids-focused-nodes-saved) (if (cdr org-index--ids-focused-nodes-saved) "s" "")))
1192 (setq org-index--ids-focused-nodes org-index--ids-focused-nodes-saved)
1193 txt)
1194 "No saved list of focused nodes to restore, nothing to do"))))
1196 (org-index--persist-focused-nodes)
1198 (format text (or more-text "") (length org-index--ids-focused-nodes) (if (cdr org-index--ids-focused-nodes) "s" ""))))
1201 (defun org-index--persist-focused-nodes ()
1202 "Write list of focused nodes to property."
1203 (with-current-buffer org-index--buffer
1204 (org-entry-put org-index--point "ids-focused-nodes" (string-join org-index--ids-focused-nodes " "))))
1207 (defun org-index--delete-from-focus ()
1208 "Delete current node from list of focused nodes"
1209 (let (id)
1210 (setq id (org-id-get))
1211 (if (and id (member id org-index--ids-focused-nodes))
1212 (progn
1213 (setq org-index--id-last-goto-focus
1214 (or (car-safe (cdr-safe (member id (reverse (append org-index--ids-focused-nodes
1215 org-index--ids-focused-nodes)))))
1216 org-index--id-last-goto-focus))
1217 (setq org-index--ids-focused-nodes-saved org-index--ids-focused-nodes)
1218 (setq org-index--ids-focused-nodes (delete id org-index--ids-focused-nodes))
1219 (setq org-index--id-last-goto-focus nil)
1220 "Current node has been removed from list of focused nodes%s (%d node%s in focus)")
1221 "Current node has not been in list of focused nodes%s (%d node%s in focus)")))
1224 (defun org-index--ids-up-to-top ()
1225 "Get list of all ids from current node up to top level."
1226 (when (string= major-mode "org-mode")
1227 (let (ancestors id level start-level)
1228 (save-excursion
1229 (ignore-errors
1230 (org-with-limited-levels (org-back-to-heading))
1231 (setq id (org-id-get))
1232 (if id (setq ancestors (cons id ancestors)))
1233 (setq start-level (org-outline-level))
1234 (if (<= start-level 1)
1236 (while (> start-level 1)
1237 (setq level start-level)
1238 (while (>= level start-level)
1239 (outline-previous-heading)
1240 (setq level (org-outline-level)))
1241 (setq start-level level)
1242 (setq id (org-id-get))
1243 (if id (setq ancestors (cons id ancestors))))
1244 ancestors))))))
1247 (defun org-index--do-edit ()
1248 "Perform command edit."
1249 (let ((maxlen 0) cols-vals buffer-keymap field-keymap keywords-pos val)
1251 (setq org-index--context-node nil)
1252 (setq org-index--context-occur nil)
1254 ;; change to index, if whithin occur
1255 (if org-index--within-occur
1256 (let ((pos (get-text-property (point) 'org-index-lbp)))
1257 (org-index--occur-test-stale pos)
1258 (setq org-index--context-occur (cons (point) (org-index--line-in-canonical-form)))
1259 (set-buffer org-index--buffer)
1260 (goto-char pos))
1262 ;; change to index, if still not within
1263 (if (not org-index--within-index-node)
1264 (let ((id (org-id-get)))
1265 (setq org-index--context-node (cons (current-buffer) (point)))
1266 (set-buffer org-index--buffer)
1267 (unless (and id (org-index--go 'id id))
1268 (setq org-index--context-node nil)
1269 (error "This node is not in index")))))
1271 ;; retrieve current content of index line
1272 (dolist (col (mapcar 'car (reverse org-index--columns)))
1273 (if (> (length (symbol-name col)) maxlen)
1274 (setq maxlen (length (symbol-name col))))
1275 (setq val (org-index--get-or-set-field col))
1276 (if (and val (eq col 'yank)) (setq val (replace-regexp-in-string (regexp-quote "\\vert") "|" val nil 'literal)))
1277 (setq cols-vals (cons (cons col val)
1278 cols-vals)))
1280 ;; we need two different keymaps
1281 (setq buffer-keymap (make-sparse-keymap))
1282 (set-keymap-parent buffer-keymap widget-keymap)
1283 (define-key buffer-keymap (kbd "C-c C-c") 'org-index--edit-accept)
1284 (define-key buffer-keymap (kbd "C-c C-k") 'org-index--edit-abort)
1286 (setq field-keymap (make-sparse-keymap))
1287 (set-keymap-parent field-keymap widget-field-keymap)
1288 (define-key field-keymap (kbd "C-c C-c") 'org-index--edit-accept)
1289 (define-key field-keymap (kbd "C-c C-k") 'org-index--edit-abort)
1291 ;; prepare buffer
1292 (setq org-index--context-index (cons (point) (org-index--line-in-canonical-form)))
1293 (if (get-buffer org-index--edit-buffer-name) (kill-buffer org-index--edit-buffer-name))
1294 (switch-to-buffer (get-buffer-create org-index--edit-buffer-name))
1296 ;; create and fill widgets
1297 (setq org-index--edit-widgets nil)
1298 (widget-insert "Edit this line from index; type C-c C-c when done, C-c C-k to abort.\n\n")
1299 (dolist (col-val cols-vals)
1300 (if (eq (car col-val) 'keywords) (setq keywords-pos (point)))
1301 (setq org-index--edit-widgets (cons
1302 (cons (car col-val)
1303 (widget-create 'editable-field
1304 :format (format (format "%%%ds: %%%%v" maxlen) (symbol-name (car col-val)))
1305 :keymap field-keymap
1306 (or (cdr col-val) "")))
1307 org-index--edit-widgets)))
1309 (widget-setup)
1310 (goto-char keywords-pos)
1311 (beginning-of-line)
1312 (forward-char (+ maxlen 2))
1313 (use-local-map buffer-keymap)
1314 (setq org-index--inhibit-sort-idle t)
1315 "Editing a single line from index"))
1318 (defun org-index--edit-accept ()
1319 "Function to accept editing in Edit buffer."
1320 (interactive)
1322 (let ((obuf (get-buffer org-index--occur-buffer-name))
1323 val line)
1325 ;; Time might have passed
1326 (org-index--refresh-parse-table)
1328 (with-current-buffer org-index--buffer
1330 ;; check, if buffer has become stale
1331 (save-excursion
1332 (goto-char (car org-index--context-index))
1333 (unless (string= (cdr org-index--context-index)
1334 (org-index--line-in-canonical-form))
1335 (switch-to-buffer org-index--edit-buffer-name)
1336 (error "Index table has changed: Cannot find line, that this buffer is editing")))
1338 (pop-to-buffer-same-window org-index--buffer)
1339 (goto-char (car org-index--context-index))
1341 ;; write back line to index
1342 (dolist (col-widget org-index--edit-widgets)
1343 (setq val (widget-value (cdr col-widget)))
1344 (if (eq (car col-widget) 'yank) (setq val (replace-regexp-in-string "|" (regexp-quote "\\vert") val)))
1345 (org-index--get-or-set-field (car col-widget) val))
1347 (setq line (org-index--align-and-fontify-current-line))
1348 (beginning-of-line))
1350 ;; write line to occur if appropriate
1351 (if org-index--context-occur
1352 (if obuf
1353 (if (string= (cdr org-index--context-index)
1354 (cdr org-index--context-occur))
1355 (progn
1356 (pop-to-buffer-same-window obuf)
1357 (goto-char (car org-index--context-occur))
1358 (beginning-of-line)
1359 (let ((inhibit-read-only t))
1360 (delete-region (line-beginning-position) (line-end-position))
1361 (insert line)
1362 (put-text-property (line-beginning-position) (line-end-position)
1363 'org-index-lbp (car org-index--context-index))))
1364 (error "Occur buffer and index buffer do not match any longer"))
1365 (message "Occur buffer has gone, cannot switch back."))
1366 (setq org-index--context-occur nil))
1368 ;; return to node, if invoked from there
1369 (when org-index--context-node
1370 (pop-to-buffer-same-window (car org-index--context-node))
1371 (goto-char (cdr org-index--context-node)))
1373 ;; clean up
1374 (kill-buffer org-index--edit-buffer-name)
1375 (setq org-index--inhibit-sort-idle nil)
1376 (setq org-index--context-index nil)
1377 (setq org-index--edit-widgets nil)
1378 (beginning-of-line)
1379 (message "Index line has been edited.")))
1382 (defun org-index--edit-abort ()
1383 "Function to abort editing in Edit buffer."
1384 (interactive)
1385 (kill-buffer org-index--edit-buffer-name)
1386 (setq org-index--context-index nil)
1387 (setq org-index--edit-widgets nil)
1388 (beginning-of-line)
1389 (message "Edit aborted."))
1392 (defun org-index--do-new-line (&rest keys-values)
1393 "Do the work for `org-index-new-line'.
1394 Optional argument KEYS-VALUES specifies content of new line."
1396 (org-index--retrieve-context)
1397 (with-current-buffer org-index--buffer
1398 (goto-char org-index--point)
1400 ;; check arguments early; they might come from userland
1401 (let ((kvs keys-values)
1402 k v)
1403 (while kvs
1404 (setq k (car kvs))
1405 (setq v (cadr kvs))
1406 (if (or (not (symbolp k))
1407 (and (symbolp v) (not (eq v t)) (not (eq v nil))))
1408 (error "Arguments must be alternation of key and value"))
1409 (unless (org-index--column-num k)
1410 (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
1411 (setq kvs (cddr kvs))))
1413 (let (yank)
1414 ;; create new line
1415 (org-index--create-new-line)
1417 ;; fill columns
1418 (let ((kvs keys-values)
1419 k v)
1420 (while kvs
1421 (setq k (car kvs))
1422 (setq v (cadr kvs))
1423 (org-table-goto-column (org-index--column-num k))
1424 (insert (org-trim (or v "")))
1425 (setq kvs (cddr kvs))))
1427 ;; align and fontify line
1428 (org-index--promote-current-line)
1429 (org-index--align-and-fontify-current-line)
1431 ;; remember fingerprint to be able to return
1432 (setq org-index--last-fingerprint (org-index--get-or-set-field 'fingerprint))
1434 ;; get column to yank
1435 (setq yank (org-index--get-or-set-field org-index-yank-after-add))
1437 yank)))
1440 (defun org-index-get-line (column value)
1441 "Retrieve an existing line within the index table by ref or id.
1442 Return its contents as a property list.
1444 The function `plist-get' may be used to retrieve specific elements
1445 from the result.
1447 Example:
1449 (plist-get (org-index-get-line 'ref \"R12\") 'count)
1451 retrieves the value of the count-column for reference number 12.
1453 Argument COLUMN is a symbol, either ref or id,
1454 argument VALUE specifies the value to search for."
1455 ;; check arguments
1456 (unless (memq column '(ref id keywords 'yank))
1457 (error "Argument column can only be 'ref', 'id', 'keywords' or 'yank'"))
1459 (unless value
1460 (error "Need a value to search for"))
1462 (org-index--verify-id)
1463 (org-index--parse-table)
1465 (org-index--get-line column value))
1468 (defun org-index--get-line (column value)
1469 "Find a line by ID, return its contents.
1470 Argument COLUMN and VALUE specify line to get."
1471 (let (content)
1472 (org-index--on
1473 column value
1474 (mapc (lambda (x)
1475 (if (and (numberp (cdr x))
1476 (> (cdr x) 0))
1477 (setq content (cons (car x) (cons (or (org-index--get-or-set-field (car x)) "") content)))))
1478 (reverse org-index--columns)))
1479 content))
1482 (defun org-index--ref-from-id (id)
1483 "Get reference from line ID."
1484 (org-index--on 'id id (org-index--get-or-set-field 'ref)))
1487 (defun org-index--id-from-ref (ref)
1488 "Get id from line REF."
1489 (org-index--on 'ref ref (org-index--get-or-set-field 'id)))
1492 (defun org-index--get-fingerprint ()
1493 "Get fingerprint of current line."
1494 (replace-regexp-in-string
1495 "\\s " ""
1496 (mapconcat (lambda (x) (org-index--get-or-set-field x)) '(id ref yank keywords created) "")))
1499 (defun org-index--read-search-for-index ()
1500 "Special input routine for command index."
1502 ;; Accept single char commands or switch to reading a sequence of digits
1503 (let (char prompt search-ref search-id search-fingerprint)
1505 ;; start with short prompt but give more help on next iteration
1506 (setq prompt "Please specify, where to go in index (0-9,.,space,backspace,return or ? for short help) - ")
1508 ;; read one character
1509 (while (not (memq char (append (number-sequence ?0 ?9) (list ?\d ?\b ?\r ?\j ?\s ?.))))
1510 (setq char (read-char prompt))
1511 (setq prompt "Go to specific position in index table. Digits specify a reference number, <space> goes to top of index, <backspace> or <delete> to last line created and <return> or `.' to index line of current node. Please choose - "))
1513 (if (memq char (number-sequence ?0 ?9))
1514 ;; read rest of digits
1515 (setq search-ref (read-from-minibuffer "Search reference number: " (char-to-string char))))
1516 ;; decode single chars
1517 (if (memq char '(?\r ?\n ?.)) (setq search-id (org-id-get)))
1518 (if (memq char '(?\d ?\b)) (setq search-fingerprint org-index--last-fingerprint))
1520 (list search-ref search-id search-fingerprint)))
1523 (defun org-index--verify-id ()
1524 "Check, that we have a valid id."
1526 ;; Check id
1527 (unless org-index-id
1528 (let ((answer (org-completing-read "Cannot find an index (org-index-id is not set). You may:\n - read-help : to learn more about org-index\n - create-index : invoke an assistant to create an initial index\nPlease choose: " (list "read-help" "create-index") nil t nil nil "read-help")))
1529 (if (string= answer "create-index")
1530 (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
1531 (describe-function 'org-index)
1532 (throw 'new-index nil))))
1534 ;; Find node
1535 (let (marker)
1536 (setq marker (org-id-find org-index-id 'marker))
1537 (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
1538 ; Try again with new node
1539 (setq marker (org-id-find org-index-id 'marker))
1540 (unless marker (error "Could not create node"))
1541 (setq org-index--buffer (marker-buffer marker)
1542 org-index--point (marker-position marker))
1543 (move-marker marker nil)))
1546 (defun org-index--retrieve-context ()
1547 "Collect context information before starting with command."
1549 ;; Get the content of the active region or the word under cursor
1550 (setq org-index--active-region
1551 (if (and transient-mark-mode mark-active)
1552 (buffer-substring (region-beginning) (region-end))
1553 nil))
1554 (setq org-index--below-cursor (thing-at-point 'symbol))
1556 ;; get category of current node
1557 (setq org-index--category-before
1558 (save-excursion ; workaround: org-get-category does not give category when at end of buffer
1559 (beginning-of-line)
1560 (org-get-category (point) t)))
1562 ;; Find out, if we are within index table or occur buffer
1563 (setq org-index--within-index-node (string= (org-id-get) org-index-id))
1564 (setq org-index--within-occur (string= (buffer-name) org-index--occur-buffer-name)))
1567 (defun org-index--parse-table (&optional num-lines-to-format check-sort-mixed)
1568 "Parse content of index table.
1569 Optional argument NUM-LINES-TO-FORMAT limits formatting effort and duration.
1570 Optional argument CHECK-SORT-MIXED triggers resorting if mixed and stale."
1572 (let (initial-point
1573 end-of-headings
1574 start-of-headings
1575 max-ref-field)
1577 (unless num-lines-to-format (setq num-lines-to-format 0))
1579 (with-current-buffer org-index--buffer
1581 (setq initial-point (point))
1583 (org-index--go-below-hline)
1584 (org-reveal)
1586 ;; if table is sorted mixed and it was sorted correctly yesterday, it could still be wrong today; so check
1587 (when (and check-sort-mixed (eq org-index-sort-by 'mixed))
1588 (goto-char org-index--below-hline)
1589 (let (count-first-line count-second-line)
1590 (setq count-first-line (string-to-number (concat (org-index--get-or-set-field 'count) " 0")))
1591 (forward-line)
1592 (setq count-second-line (string-to-number (concat (org-index--get-or-set-field 'count) " 0")))
1593 (forward-line -1)
1594 (if (and (string< (org-index--get-or-set-field 'last-accessed)
1595 (org-index--get-mixed-time))
1596 (< count-first-line count-second-line))
1597 (org-index--do-sort-index org-index-sort-by)))
1598 (org-index--go-below-hline))
1600 ;; align and fontify table once for this emacs session
1601 (when (> num-lines-to-format org-index--aligned)
1602 (org-index--go-below-hline)
1603 (message "Aligning and fontifying %s lines of index table (once per emacs session)..."
1604 (if (= num-lines-to-format most-positive-fixnum) "all" (format "%d" num-lines-to-format)))
1605 (save-restriction
1606 (let (from to)
1607 (forward-line -3)
1608 (setq from (point))
1609 (setq to (org-table-end))
1610 (when (< num-lines-to-format most-positive-fixnum)
1611 (forward-line (+ 3 num-lines-to-format))
1612 (narrow-to-region from (point))
1613 (setq to (min (point) to)))
1614 (goto-char org-index--below-hline)
1615 (org-table-align)
1616 (setq to (min (point-max) to))
1617 (font-lock-fontify-region from to)))
1618 (setq org-index--aligned num-lines-to-format)
1619 (org-index--go-below-hline)
1620 (message "Done."))
1622 (beginning-of-line)
1624 ;; get headings to display during occur
1625 (setq end-of-headings (point))
1626 (goto-char (org-table-begin))
1627 (setq start-of-headings (point))
1628 (setq org-index--headings-visible (substring-no-properties (org-index--copy-visible start-of-headings end-of-headings)))
1629 (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
1631 ;; count columns
1632 (org-table-goto-column 100)
1633 (setq org-index--numcols (- (org-table-current-column) 1))
1635 ;; go to top of table
1636 (goto-char (org-table-begin))
1638 ;; parse line of headings
1639 (org-index--parse-headings)
1641 ;; read property or go through table to find maximum number
1642 (goto-char org-index--below-hline)
1643 (setq max-ref-field (or (org-entry-get org-index--point "max-ref")
1644 (org-index--migrate-maxref-to-property)))
1646 (unless org-index--head (org-index--get-decoration-from-ref-field max-ref-field))
1648 ;; Get ids of focused node (if any)
1649 (setq org-index--ids-focused-nodes (split-string (or (org-entry-get nil "ids-focused-nodes") "")))
1650 (org-entry-delete (point) "id-focused-node") ; migrate (kind of) from previous versions
1652 ;; save position below hline
1653 (org-index--go-below-hline)
1654 ;; go back to initial position
1655 (goto-char initial-point))))
1658 (defun org-index--get-decoration-from-ref-field (ref-field)
1659 "Extract decoration from a REF-FIELD."
1660 (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
1661 (org-index--report-index-error
1662 "Reference in index table ('%s') does not contain a number" ref-field))
1664 ;; These are the decorations used within the first ref of index
1665 (setq org-index--head (match-string 1 ref-field))
1666 (setq org-index--tail (match-string 3 ref-field))
1667 (setq org-index--ref-regex (concat (regexp-quote org-index--head)
1668 "\\([0-9]+\\)"
1669 (regexp-quote org-index--tail)))
1670 (setq org-index--ref-format (concat org-index--head "%d" org-index--tail)))
1673 (defun org-index--extract-refnum (ref-field)
1674 "Extract the number from a complete reference REF-FIELD like 'R102'."
1675 (unless (string-match org-index--ref-regex ref-field)
1676 (org-index--report-index-error
1677 "Reference '%s' is not formatted properly (does not match '%s')" ref-field org-index--ref-regex))
1678 (string-to-number (match-string 1 ref-field)))
1681 (defun org-index--migrate-maxref-to-property ()
1682 "One-time migration: No property; need to go through whole table once to find max."
1683 (org-index--go-below-hline)
1684 (let ((max-ref-num 0)
1685 ref-field ref-num)
1686 (message "One-time migration to set index-property maxref...")
1687 (while (org-at-table-p)
1688 (setq ref-field (org-index--get-or-set-field 'ref))
1689 (when ref-field
1690 (unless org-index--head (org-index--get-decoration-from-ref-field ref-field))
1691 (setq ref-num (org-index--extract-refnum ref-field))
1692 (if (> ref-num max-ref-num) (setq max-ref-num ref-num)))
1693 (forward-line))
1694 (unless (> max-ref-num 0)
1695 (org-index--report-index-error "No reference found in property max-ref and none in index"))
1696 (setq ref-field (format org-index--ref-format max-ref-num))
1697 (org-index--go-below-hline)
1698 (org-entry-put org-index--point "max-ref" ref-field)
1699 (message "Done.")
1700 ref-field))
1703 (defun org-index--get-save-maxref (&optional no-inc)
1704 "Get next reference, increment number and store it in index.
1705 Optional argument NO-INC skips automatic increment on maxref."
1706 (let (ref-field)
1707 (with-current-buffer org-index--buffer
1708 (setq ref-field (org-entry-get org-index--point "max-ref"))
1709 (unless no-inc
1710 (setq ref-field (format org-index--ref-format (1+ (org-index--extract-refnum ref-field))))
1711 (org-entry-put org-index--point "max-ref" ref-field)))
1712 ref-field))
1715 (defun org-index--refresh-parse-table ()
1716 "Fast refresh of selected results of parsing index table."
1718 (setq org-index--point (marker-position (org-id-find org-index-id 'marker)))
1719 (with-current-buffer org-index--buffer
1720 (save-excursion
1721 (org-index--go-below-hline))))
1724 (defun org-index--do-maintain ()
1725 "Choose among and perform some tasks to maintain index."
1726 (let ((check-what) (max-mini-window-height 1.0) message-text)
1727 (setq check-what (intern (org-completing-read "These checks and fixes are available:\n - statistics : compute statistics about index table\n - check : check ids by visiting their nodes\n - duplicates : check index for duplicate rows (ref or id)\n - clean : remove obsolete property org-index-id\n - update : update content of index lines, with an id \nPlease choose: " (list "statistics" "check" "duplicates" "clean" "update") nil t nil nil "statistics")))
1728 (message nil)
1730 (cond
1731 ((eq check-what 'check)
1732 (setq message-text (or (org-index--check-ids)
1733 "No problems found")))
1735 ((eq check-what 'statistics)
1736 (setq message-text (org-index--do-statistics)))
1738 ((eq check-what 'duplicates)
1739 (setq message-text (org-index--find-duplicates)))
1741 ((eq check-what 'clean)
1742 (let ((lines 0))
1743 (org-map-entries
1744 (lambda ()
1745 (when (org-entry-get (point) "org-index-ref")
1746 (cl-incf lines)
1747 (org-entry-delete (point) "org-index-ref")))
1748 nil 'agenda)
1749 (setq message-text (format "Removed property 'org-index-ref' from %d lines" lines))))
1751 ((eq check-what 'update)
1752 (if (y-or-n-p "Updating your index will overwrite certain columns with content from the associated heading and category. If unsure, you may try this for a single, already existing line of your index by invoking `add'. Are you SURE to proceed for ALL INDEX LINES ? ")
1753 (setq message-text (org-index--update-all-lines))
1754 (setq message-text "Canceled."))))
1755 message-text))
1758 (defun org-index--get-mixed-time ()
1759 "Get timestamp for sorting order mixed."
1760 (format-time-string
1761 (org-time-stamp-format t t)
1762 (apply 'encode-time (append '(0 0 0) (nthcdr 3 (decode-time))))))
1765 (defun org-index--do-sort-index (sort)
1766 "Sort index table according to SORT."
1768 (let ((is-modified (buffer-modified-p))
1770 bottom
1771 mixed-time)
1773 (unless buffer-read-only
1775 (message "Sorting index table for %s..." (symbol-name sort))
1776 (undo-boundary)
1778 (let ((message-log-max nil)) ; we have just issued a message, dont need those of sort-subr
1780 ;; if needed for mixed sort
1781 (if (eq sort 'mixed)
1782 (setq mixed-time (org-index--get-mixed-time)))
1784 ;; get boundaries of table
1785 (org-index--go-below-hline)
1786 (forward-line 0)
1787 (setq top (point))
1788 (goto-char (org-table-end))
1790 ;; kill all empty rows at bottom
1791 (while (progn
1792 (forward-line -1)
1793 (org-table-goto-column 1)
1794 (and
1795 (not (org-index--get-or-set-field 'ref))
1796 (not (org-index--get-or-set-field 'id))
1797 (not (org-index--get-or-set-field 'yank))))
1798 (org-table-kill-row))
1799 (forward-line 1)
1800 (setq bottom (point))
1802 ;; sort lines
1803 (save-restriction
1804 (narrow-to-region top bottom)
1805 (goto-char top)
1806 (sort-subr t
1807 'forward-line
1808 'end-of-line
1809 (lambda ()
1810 (org-index--get-sort-key sort t mixed-time))
1812 'string<)
1813 (goto-char (point-min))
1815 ;; restore modification state
1816 (set-buffer-modified-p is-modified)))
1818 (setq org-index--last-sort-assumed sort))))
1821 (defun org-index--do-sort-lines (what)
1822 "Sort lines in WHAT according to contained reference."
1823 (save-restriction
1824 (cond
1825 ((eq what 'region)
1826 (if (region-active-p)
1827 (narrow-to-region (region-beginning) (region-end))
1828 (error "No active region, cannot sort")))
1829 ((eq what 'buffer)
1830 (unless (y-or-n-p "Sort whole current buffer ? ")
1831 (error "Canceled"))
1832 (narrow-to-region (point-min) (point-max))))
1834 (goto-char (point-min))
1835 (sort-subr nil 'forward-line 'end-of-line
1836 (lambda ()
1837 (if (looking-at (concat ".*"
1838 (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
1839 (string-to-number (match-string 1))
1840 0)))))
1843 (defun org-index--go-below-hline ()
1844 "Move below hline in index-table."
1846 (let ((errstring (format "index table within node %s" org-index-id)))
1848 (goto-char org-index--point)
1850 ;; go to heading of node
1851 (while (not (org-at-heading-p)) (forward-line -1))
1852 (forward-line 1)
1854 ;; go to first table, but make sure we do not get into another node
1855 (while (and (not (org-at-table-p))
1856 (not (org-at-heading-p))
1857 (not (eobp)))
1858 (forward-line))
1860 ;; check, if there really is a table
1861 (unless (org-at-table-p)
1862 (org-index--create-missing-index "Cannot find %s." errstring))
1864 ;; go just after hline
1865 (while (and (not (org-at-table-hline-p))
1866 (org-at-table-p))
1867 (forward-line))
1868 (forward-line)
1870 ;; and check
1871 (unless (org-at-table-p)
1872 (org-index--report-index-error "Cannot find a hline within %s" errstring))
1874 (org-table-goto-column 1)
1875 (setq org-index--below-hline (point))))
1878 (defun org-index--parse-headings ()
1879 "Parse headings of index table."
1881 (let (field ;; field content
1882 field-symbol) ;; and as a symbol
1884 (setq org-index--columns nil)
1886 ;; For each column
1887 (dotimes (col org-index--numcols)
1889 (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
1891 (if (string= field "")
1892 (error "Heading of column cannot be empty"))
1893 (if (and (not (string= (substring field 0 1) "."))
1894 (not (member (intern field) org-index--valid-headings)))
1895 (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field))
1897 (setq field-symbol (intern field))
1899 ;; check if heading has already appeared
1900 (if (assoc field-symbol org-index--columns)
1901 (org-index--report-index-error
1902 "'%s' appears two times as column heading" (downcase field))
1903 ;; add it to list at front, reverse later
1904 (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
1906 (setq org-index--columns (reverse org-index--columns))
1908 ;; check if all necessary headings have appeared
1909 (mapc (lambda (head)
1910 (unless (cdr (assoc head org-index--columns))
1911 (org-index--report-index-error "No column has heading '%s'" head)))
1912 org-index--valid-headings))
1915 (defun org-index--create-missing-index (&rest reasons)
1916 "Create a new empty index table with detailed explanation. Argument REASONS explains why."
1918 (org-index--ask-before-create-index "Cannot find index table: "
1919 "new permanent" "."
1920 reasons)
1921 (org-index--create-index))
1924 (defun org-index--report-index-error (&rest reasons)
1925 "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
1927 (when org-index--buffer
1928 (pop-to-buffer-same-window org-index--buffer)
1929 (goto-char org-index--below-hline)
1930 (org-reveal t))
1931 (org-index--ask-before-create-index "The existing index contains this error: "
1932 "temporary" ", to compare with."
1933 reasons)
1934 (org-index--create-index t t))
1937 (defun org-index--ask-before-create-index (explanation type for-what reasons)
1938 ; checkdoc-params: (explanation type for-what reasons)
1939 "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
1940 (let (reason prompt)
1942 (setq reason (apply 'format reasons))
1944 (setq prompt (concat explanation reason "\n"
1945 "However, this assistant can help you to create a "
1946 type " index with detailed comments" for-what "\n\n"
1947 "Do you want to proceed ?"))
1949 (unless (let ((max-mini-window-height 1.0))
1950 (y-or-n-p prompt))
1951 (error (concat explanation reason)))))
1954 (defun org-index--create-index (&optional temporary compare)
1955 "Create a new empty index table with detailed explanation.
1956 specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
1957 (let (buffer
1958 title
1959 firstref
1962 (if temporary
1963 (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
1964 (buffer-name "*org-index-example-index*"))
1965 (setq buffer (get-buffer-create buffer-name))
1966 (with-current-buffer buffer
1967 ;; but it needs a file for its index to be found
1968 (unless (string= (buffer-file-name) file-name)
1969 (set-visited-file-name file-name))
1970 (rename-buffer buffer-name) ; name is change by line above
1972 (erase-buffer)
1973 (org-mode)))
1975 (setq buffer (get-buffer (org-completing-read "Please choose the buffer, where the new node for the index table should be created; the new node will be inserted at its end.\n\nBuffer: " (mapcar 'buffer-name (org-buffer-list))))))
1977 (setq title (read-from-minibuffer "Please enter the title of the index node (leave empty for default 'index'): "))
1978 (if (string= title "") (setq title "index"))
1980 (while (progn
1981 (setq firstref (read-from-minibuffer "Please enter your first reference-number. This is an integer number preceeded by some and optionally followed by some non-numeric chars; e.g. 'R1', '-1-' or '#1#' (and your initial number does not need to be '1'). The format of your reference-numbers only needs to make sense for yourself, so that you can spot it easily in your texts or write it on a piece of paper; it should however not already appear frequently within your existing notes, to avoid too many false hits when searching.\n\nPlease choose (leave empty for default 'R1'): "))
1982 (if (string= firstref "") (setq firstref "R1"))
1983 (let (desc)
1984 (when (string-match "[[:blank:]]" firstref)
1985 (setq desc "Contains whitespace"))
1986 (when (string-match "[[:cntrl:]]" firstref)
1987 (setq desc "Contains control characters"))
1988 (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
1989 ;; firstref not okay, report details
1990 (setq desc
1991 (cond ((string= firstref "") "is empty")
1992 ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
1993 ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
1994 ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
1997 (if desc
1998 (progn
1999 (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
2001 nil))))
2003 (with-current-buffer buffer
2004 (goto-char (point-max))
2005 (insert (format "* %s %s\n" firstref title))
2006 (org-entry-put org-index--point "max-ref" firstref)
2007 (if temporary
2008 (insert "
2009 Below you find your temporary index table, which WILL NOT LAST LONGER
2010 THAN YOUR CURRENT EMACS SESSION; please use it only for evaluation.
2012 (insert "
2013 Below you find your initial index table, which will grow over time.
2015 (insert " You may start using it by adding some lines. Just
2016 move to another heading within org, invoke `org-index' and
2017 choose the command 'add'. After adding a few nodes, try the
2018 command 'occur' to search among them.
2020 To gain further insight you may invoke the subcommand 'help', or
2021 (same content) read the help of `org-index'.
2023 Within the index table below, the sequence of columns does not
2024 matter. You may reorder them in any way you like. You may also
2025 add your own columns, which should start with a dot
2026 (e.g. '.my-column').
2028 Invoke `org-customize' to tweak the behaviour of org-index
2029 (see the group org-index).
2031 This node needs not be a top level node; its name is completely
2032 at your choice; it is found through its ID only.
2034 (unless temporary
2035 (insert "
2036 Remark: These lines of explanation can be removed at any time.
2039 (setq id (org-id-get-create))
2040 (insert (format "
2042 | ref | category | keywords | tags | count | level | last-accessed | created | id | yank |
2043 | | | | | | | | | <4> | <4> |
2044 |-----+----------+----------+------+-------+-------+---------------+---------+-----+------|
2045 | %s | | %s | | | | | %s | %s | |
2048 firstref
2049 title
2050 (with-temp-buffer (org-insert-time-stamp nil nil t))
2051 id))
2053 ;; make sure, that node can be found
2054 (org-id-add-location id (buffer-file-name))
2055 (setq buffer-save-without-query t)
2056 (basic-save-buffer)
2058 (while (not (org-at-table-p)) (forward-line -1))
2059 (unless buffer-read-only (org-table-align))
2060 (while (not (org-at-heading-p)) (forward-line -1))
2062 ;; read back some info about new index
2063 (let ((org-index-id id))
2064 (org-index--verify-id))
2066 ;; remember at least for this session
2067 (setq org-index-id id)
2069 ;; present results to user
2070 (if temporary
2071 (progn
2072 ;; Present existing and temporary index together
2073 (when compare
2074 (pop-to-buffer-same-window org-index--buffer)
2075 (goto-char org-index--point)
2076 (org-index--unfold-buffer)
2077 (delete-other-windows)
2078 (select-window (split-window-vertically)))
2079 ;; show new index
2080 (pop-to-buffer-same-window buffer)
2081 (org-id-goto id)
2082 (org-index--unfold-buffer)
2083 (if compare
2084 (progn
2085 (message "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
2086 (throw 'new-index nil))
2087 (message "This is your new temporary index, use command add to populate, occur to search.")))
2088 (progn
2089 ;; Only show the new index
2090 (pop-to-buffer-same-window buffer)
2091 (delete-other-windows)
2092 (org-id-goto id)
2093 (org-index--unfold-buffer)
2094 (if (y-or-n-p "This is your new index table. It is already set for this Emacs session, so you may try it out. Do you want to save its id to make it available for future Emacs sessions too ? ")
2095 (progn
2096 (customize-save-variable 'org-index-id id)
2097 (message "Saved org-index-id '%s' to %s." id (or custom-file
2098 user-init-file))
2099 (throw 'new-index nil))
2100 (let (sq)
2101 (setq sq (format "(setq org-index-id \"%s\")" id))
2102 (kill-new sq)
2103 (message "Did not make the id of this new index permanent; you may want to put\n\n %s\n\ninto your own initialization; it is copied already, just yank it." sq)
2104 (throw 'new-index nil))))))))
2107 (defun org-index--unfold-buffer ()
2108 "Helper function to unfold buffer."
2109 (org-show-context 'ancestors)
2110 (org-show-subtree)
2111 (recenter 1))
2114 (defun org-index--update-line (&optional id-or-pos no-error)
2115 "Update columns count and last-accessed in line ID-OR-POS.
2116 Optional argument NO-ERROR suppresses error."
2118 (let (initial)
2120 (with-current-buffer org-index--buffer
2121 (unless buffer-read-only
2123 (setq initial (point))
2125 (if (if (integerp id-or-pos)
2126 (goto-char id-or-pos)
2127 (org-index--go 'id id-or-pos))
2128 (org-index--update-current-line)
2129 (unless no-error (error "Did not find reference or id '%s'" (list id-or-pos))))
2131 (goto-char initial)))))
2134 (defun org-index--update-current-line ()
2135 "Update current lines columns count and last-accessed."
2136 (let (newcount (count-field (org-index--get-or-set-field 'count)))
2138 ;; update count field only if number or empty
2139 (when (or (not count-field)
2140 (string-match "^[0-9]+$" count-field))
2141 (setq newcount (+ 1 (string-to-number (or count-field "0"))))
2142 (org-index--get-or-set-field 'count
2143 (number-to-string newcount)))
2145 ;; update timestamp
2146 (org-table-goto-column (org-index--column-num 'last-accessed))
2147 (org-table-blank-field)
2148 (org-insert-time-stamp nil t t)
2150 ;; move line according to new content
2151 (org-index--promote-current-line)
2152 (org-index--align-and-fontify-current-line)))
2155 (defun org-index--align-and-fontify-current-line (&optional num)
2156 "Make current line (or NUM lines) blend well among others."
2157 (let (lines lines-fontified)
2158 ;; get current content
2159 (unless num (setq num 1))
2160 (setq lines (delete-and-extract-region (line-beginning-position) (line-end-position num)))
2161 ;; create minimum table with fixed-width columns to align and fontify new line
2162 (insert
2163 (setq
2164 lines-fontified
2165 (with-temp-buffer
2166 (org-set-font-lock-defaults)
2167 (insert org-index--headings-visible)
2168 ;; fill columns, so that aligning cannot shrink them
2169 (goto-char (point-min))
2170 (search-forward "|")
2171 (while (search-forward " " (line-end-position) t)
2172 (replace-match "." nil t))
2173 (goto-char (point-min))
2174 (while (search-forward ".|." (line-end-position) t)
2175 (replace-match " | " nil t))
2176 (goto-char (point-min))
2177 (while (search-forward "|." (line-end-position) t)
2178 (replace-match "| " nil t))
2179 (goto-char (point-max))
2180 (insert lines)
2181 (forward-line 0)
2182 (let ((start (point)))
2183 (while (re-search-forward "^\s +|-" nil t)
2184 (replace-match "| -"))
2185 (goto-char start))
2186 (org-mode)
2187 (org-table-align)
2188 (font-lock-fontify-region (point-min) (point-max))
2189 (goto-char (point-max))
2190 (if (eq -1 (skip-chars-backward "\n"))
2191 (delete-char 1))
2192 (forward-line (- 1 num))
2193 (buffer-substring (line-beginning-position) (line-end-position num)))))
2194 lines-fontified))
2197 (defun org-index--promote-current-line ()
2198 "Move current line up in table according to changed sort fields."
2199 (let (begin end key
2200 (to-skip 0))
2202 (forward-line 0) ; stay at beginning of line
2204 (setq key (org-index--get-sort-key))
2205 (setq begin (point))
2206 (setq end (line-beginning-position 2))
2208 (forward-line -1)
2209 (while (and (org-at-table-p)
2210 (not (org-at-table-hline-p))
2211 (string< (org-index--get-sort-key) key))
2213 (cl-incf to-skip)
2214 (forward-line -1))
2215 (forward-line 1)
2217 ;; insert line at new position
2218 (when (> to-skip 0)
2219 (insert (delete-and-extract-region begin end))
2220 (forward-line -1))))
2223 (defun org-index--get-sort-key (&optional sort with-ref mixed-time)
2224 "Get value for sorting from column SORT, optional WITH-REF; if mixes use MIXED-TIME."
2225 (let (ref
2226 ref-field
2227 key)
2229 (unless sort (setq sort org-index--last-sort-assumed)) ; use default value
2231 (when (or with-ref
2232 (eq sort 'ref))
2233 ;; get reference with leading zeroes, so it can be
2234 ;; sorted as text
2235 (setq ref-field (org-index--get-or-set-field 'ref))
2236 (if ref-field
2237 (progn
2238 (string-match org-index--ref-regex ref-field)
2239 (setq ref (format
2240 "%06d"
2241 (string-to-number
2242 (match-string 1 ref-field)))))
2243 (setq ref "000000")))
2245 (setq key
2246 (cond
2247 ((eq sort 'count)
2248 (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))
2249 ((eq sort 'mixed)
2250 (let ((last-accessed (org-index--get-or-set-field 'last-accessed)))
2251 (unless mixed-time (setq mixed-time (org-index--get-mixed-time)))
2252 (concat
2253 (if (string< mixed-time last-accessed) last-accessed mixed-time)
2254 (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))))
2255 ((eq sort 'ref)
2256 ref)
2257 ((memq sort '(id last-accessed created))
2258 (org-index--get-or-set-field sort))
2259 (t (error "This is a bug: unmatched case '%s'" sort))))
2261 (if with-ref (setq key (concat key ref)))
2263 key))
2266 (defun org-index--get-or-set-field (key &optional value)
2267 "Retrieve field KEY from index table or set it to VALUE."
2268 (let (field)
2269 (save-excursion
2270 (if (eq key 'fingerprint)
2271 (progn
2272 (if value (error "Internal error, pseudo-column fingerprint cannot be set"))
2273 (setq field (org-index--get-fingerprint)))
2274 (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value))))
2275 (if (string= field "") (setq field nil))
2277 (org-no-properties field))))
2280 (defun org-index--column-num (key)
2281 "Return number of column KEY."
2282 (if (numberp key)
2284 (cdr (assoc key org-index--columns))))
2287 (defun org-index--make-guarded-search (ref &optional dont-quote)
2288 "Make robust search string from REF; DONT-QUOTE it, if requested."
2289 (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
2292 (defun org-index--find-duplicates ()
2293 "Find duplicate references or ids in index table."
2294 (let (ref-duplicates id-duplicates)
2296 (setq ref-duplicates (org-index--find-duplicates-helper 'ref))
2297 (setq id-duplicates (org-index--find-duplicates-helper 'id))
2298 (goto-char org-index--below-hline)
2299 (if (or ref-duplicates id-duplicates)
2300 (progn
2301 ;; show results
2302 (pop-to-buffer-same-window
2303 (get-buffer-create "*org-index-duplicates*"))
2304 (when ref-duplicates
2305 (insert "These references appear more than once:\n")
2306 (mapc (lambda (x) (insert " " x "\n")) ref-duplicates)
2307 (insert "\n\n"))
2308 (when id-duplicates
2309 (insert "These ids appear more than once:\n")
2310 (mapc (lambda (x) (insert " " x "\n")) id-duplicates))
2312 "Some references or ids are duplicates")
2313 "No duplicate references or ids found")))
2316 (defun org-index--find-duplicates-helper (column)
2317 "Helper for `org-index--find-duplicates': Go through table and count given COLUMN."
2318 (let (counts duplicates field found)
2320 ;; go through table
2321 (goto-char org-index--below-hline)
2322 (while (org-at-table-p)
2324 ;; get column
2325 (setq field (org-index--get-or-set-field column))
2327 ;; and increment
2328 (setq found (assoc field counts))
2329 (if found
2330 (cl-incf (cdr found))
2331 (setq counts (cons (cons field 1) counts)))
2333 (forward-line))
2335 (mapc (lambda (x) (if (and (> (cdr x) 1)
2336 (car x))
2337 (setq duplicates (cons (car x) duplicates)))) counts)
2339 duplicates))
2342 (defun org-index--do-statistics ()
2343 "Compute statistics about index table."
2344 (let ((total-lines 0) (total-refs 0)
2345 ref ref-field min max message)
2347 ;; go through table
2348 (goto-char org-index--below-hline)
2349 (while (org-at-table-p)
2351 ;; get ref
2352 (setq ref-field (org-index--get-or-set-field 'ref))
2354 (when ref-field
2355 (string-match org-index--ref-regex ref-field)
2356 (setq ref (string-to-number (match-string 1 ref-field)))
2358 ;; record min and max
2359 (if (or (not min) (< ref min)) (setq min ref))
2360 (if (or (not max) (> ref max)) (setq max ref))
2362 (setq total-refs (1+ total-refs)))
2364 ;; count
2365 (setq total-lines (1+ total-lines))
2367 (forward-line))
2369 (setq message (format "%d Lines in index table. First reference is %s, last %s; %d of them are used (%d percent)"
2370 total-lines
2371 (format org-index--ref-format min)
2372 (format org-index--ref-format max)
2373 total-refs
2374 (truncate (* 100 (/ (float total-refs) (1+ (- max min)))))))
2376 (goto-char org-index--below-hline)
2377 message))
2380 (defun org-index--do-add-or-update (&optional create-ref tag-with-ref)
2381 "For current node or current line in index, add or update in index table.
2382 CREATE-REF and TAG-WITH-REF if given."
2384 (let* (id id-from-index ref args yank ret)
2386 (org-index--save-positions)
2387 (unless (or org-index--within-index-node
2388 org-index--within-occur)
2389 (org-with-limited-levels (org-back-to-heading)))
2391 ;; try to do the same things from within index and from outside
2392 (if org-index--within-index-node
2394 (progn
2395 (unless (org-at-table-p)
2396 (error "Within index node but not on table"))
2398 (setq id (org-index--get-or-set-field 'id))
2399 (setq ref (org-index--get-or-set-field 'ref))
2400 (setq args (org-index--collect-values-for-add-update-remote id))
2401 (org-index--write-fields args)
2402 (setq yank (org-index--get-or-set-field org-index-yank-after-add))
2404 (setq ret
2405 (if ref
2406 (cons (format "Updated index line %s" ref) yank)
2407 (cons "Updated index line" nil))))
2409 (setq id (org-id-get-create))
2410 (org-index--refresh-parse-table)
2411 (setq id-from-index (org-index--on 'id id id))
2412 (setq ref (org-index--on 'id id (org-index--get-or-set-field 'ref)))
2414 (if tag-with-ref
2415 (org-toggle-tag (format "%s%d%s" org-index--head tag-with-ref org-index--tail) 'on))
2416 (setq args (org-index--collect-values-for-add-update id))
2418 (when (and create-ref
2419 (not ref))
2420 (setq ref (org-index--get-save-maxref))
2421 (setq args (plist-put args 'ref ref)))
2424 (if id-from-index
2425 ;; already have an id in index, find it and update fields
2426 (progn
2428 (org-index--on
2429 'id id
2430 (org-index--write-fields args)
2431 (setq yank (org-index--get-or-set-field org-index-yank-after-add)))
2433 (setq ret
2434 (if ref
2435 (cons (format "Updated index line %s" ref) yank)
2436 (cons "Updated index line" nil))))
2438 ;; no id here, create new line in index
2439 (if ref (setq args (plist-put args 'ref ref)))
2440 (setq yank (apply 'org-index--do-new-line args))
2442 (setq ret
2443 (if ref
2444 (cons
2445 (format "Added new index line %s" ref)
2446 (concat yank " "))
2447 (cons
2448 "Added new index line"
2449 nil)))))
2451 (org-index--restore-positions)
2453 ret))
2456 (defun org-index--check-ids ()
2457 "Check, that ids really point to a node."
2459 (let ((lines 0)
2460 id ids marker)
2462 (goto-char org-index--below-hline)
2464 (catch 'problem
2465 (while (org-at-table-p)
2467 (when (setq id (org-index--get-or-set-field 'id))
2469 ;; check for double ids
2470 (when (member id ids)
2471 (org-table-goto-column (org-index--column-num 'id))
2472 (throw 'problem "This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
2473 (cl-incf lines)
2474 (setq ids (cons id ids))
2476 ;; check, if id is valid
2477 (setq marker (org-id-find id t))
2478 (unless marker
2479 (org-table-goto-column (org-index--column-num 'id))
2480 (throw 'problem "This id cannot be found")))
2482 (forward-line))
2484 (goto-char org-index--below-hline)
2485 nil)))
2488 (defun org-index--update-all-lines ()
2489 "Update all lines of index at once."
2491 (let ((lines 0)
2492 id kvs)
2494 ;; check for double ids
2496 (org-index--check-ids)
2498 (progn
2499 (goto-char org-index--below-hline)
2500 (while (org-at-table-p)
2502 ;; update single line
2503 (when (setq id (org-index--get-or-set-field 'id))
2504 (setq kvs (org-index--collect-values-for-add-update-remote id))
2505 (org-index--write-fields kvs)
2506 (cl-incf lines))
2507 (forward-line))
2509 (goto-char org-index--below-hline)
2510 (org-table-align)
2511 (format "Updated %d lines" lines)))))
2514 (defun org-index--collect-values-for-add-update (id &optional silent category)
2515 "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
2517 (let ((args (list 'id id))
2518 content)
2520 (dolist (col (mapcar 'car org-index--columns))
2522 (setq content "")
2524 (cond
2525 ((eq col 'keywords)
2526 (if org-index-copy-heading-to-keywords
2527 (setq content (nth 4 (org-heading-components))))
2529 ;; Shift ref and timestamp ?
2530 (if org-index-strip-ref-and-date-from-heading
2531 (dotimes (_i 2)
2532 (if (or (string-match (concat "^\\s-*" org-index--ref-regex) content)
2533 (string-match (concat "^\\s-*" org-ts-regexp-both) content))
2534 (setq content (substring content (match-end 0)))))))
2536 ((eq col 'category)
2537 (setq content (or category org-index--category-before)))
2539 ((eq col 'level)
2540 (setq content (number-to-string (org-outline-level))))
2542 ((eq col 'tags)
2543 (setq content (org-get-tags-string))))
2545 (unless (string= content "")
2546 (setq args (plist-put args col content))))
2548 (if (not silent)
2549 (let ((args-edited (org-index--collect-values-from-user org-index-edit-on-add args)))
2550 (setq args (append args-edited args))))
2552 args))
2555 (defun org-index--collect-values-for-add-update-remote (id)
2556 "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
2558 (let (marker point args)
2560 (setq marker (org-id-find id t))
2561 ;; enter buffer and collect information
2562 (with-current-buffer (marker-buffer marker)
2563 (setq point (point))
2564 (goto-char marker)
2565 (setq args (org-index--collect-values-for-add-update id t (org-get-category (point) t)))
2566 (goto-char point))
2568 args))
2571 (defun org-index--collect-values-from-user (cols &optional defaults)
2572 "Collect values for adding a new line.
2573 Argument COLS gives list of columns to edit.
2574 Optional argument DEFAULTS gives default values."
2576 (let (content args)
2578 (dolist (col cols)
2580 (setq content "")
2582 (setq content (read-from-minibuffer
2583 (format "Enter text for column '%s': " (symbol-name col))
2584 (plist-get col defaults)))
2586 (unless (string= content "")
2587 (setq args (plist-put args col content))))
2588 args))
2591 (defun org-index--write-fields (kvs)
2592 "Update current line with values from KVS (keys-values)."
2593 (while kvs
2594 (org-index--get-or-set-field (car kvs) (org-trim (cadr kvs)))
2595 (setq kvs (cddr kvs))))
2598 (defun org-index--do-kill ()
2599 "Perform command kill from within occur, index or node."
2601 (let (id ref chars-deleted-index text-deleted-from pos-in-index)
2603 (org-index--save-positions)
2604 (unless (or org-index--within-index-node
2605 org-index--within-occur)
2606 (org-with-limited-levels (org-back-to-heading)))
2608 ;; Collect information: What should be deleted ?
2609 (if (or org-index--within-occur
2610 org-index--within-index-node)
2612 (progn
2613 (if org-index--within-index-node
2614 ;; In index
2615 (setq pos-in-index (point))
2616 ;; In occur
2617 (setq pos-in-index (get-text-property (point) 'org-index-lbp))
2618 (org-index--occur-test-stale pos-in-index)
2619 (set-buffer org-index--buffer)
2620 (goto-char pos-in-index))
2621 ;; In Index (maybe moved there)
2622 (setq id (org-index--get-or-set-field 'id))
2623 (setq ref (org-index--get-or-set-field 'ref)))
2625 ;; At a headline
2626 (setq id (org-entry-get (point) "ID"))
2627 (setq ref (org-index--ref-from-id id))
2628 (setq pos-in-index (org-index--on 'id id (point)))
2629 (unless pos-in-index (error "This node is not in index")))
2631 ;; Remark: Current buffer is not certain here, but we have all the information to delete
2633 ;; Delete from node
2634 (when id
2635 (let ((m (org-id-find id 'marker)))
2636 (set-buffer (marker-buffer m))
2637 (goto-char m)
2638 (move-marker m nil)
2639 (unless (string= (org-id-get) id)
2640 (error "Could not find node with id %s" id)))
2642 (org-index--delete-any-ref-from-tags)
2643 (if ref (org-index--delete-ref-from-heading ref))
2644 (setq text-deleted-from (cons "node" text-deleted-from)))
2646 ;; Delete from index
2647 (set-buffer org-index--buffer)
2648 (unless pos-in-index "Internal error, pos-in-index should be defined here")
2649 (goto-char pos-in-index)
2650 (setq chars-deleted-index (length (delete-and-extract-region (line-beginning-position) (line-beginning-position 2))))
2651 (setq text-deleted-from (cons "index" text-deleted-from))
2653 ;; Delete from occur only if we started there, accept that it will be stale otherwise
2654 (if org-index--within-occur
2655 (let ((inhibit-read-only t))
2656 (set-buffer org-index--occur-buffer-name)
2657 (delete-region (line-beginning-position) (line-beginning-position 2))
2658 ;; correct positions
2659 (while (org-at-table-p)
2660 (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp
2661 (- (get-text-property (point) 'org-index-lbp) chars-deleted-index))
2662 (forward-line))
2663 (setq text-deleted-from (cons "occur" text-deleted-from))))
2665 (org-index--restore-positions)
2666 (concat "Deleted from: " (mapconcat 'identity (sort text-deleted-from 'string<) ","))))
2669 (defun org-index--save-positions ()
2670 "Save current buffer and positions in index- and current buffer; not in occur-buffer."
2672 (let (cur-buf cur-mrk idx-pnt idx-mrk)
2673 (setq cur-buf (current-buffer))
2674 (setq cur-mrk (point-marker))
2675 (set-buffer org-index--buffer)
2676 (if (string= (org-id-get) org-index-id)
2677 (setq idx-pnt (point))
2678 (setq idx-mrk (point-marker)))
2679 (set-buffer cur-buf)
2680 (setq org-index--saved-positions (list cur-buf cur-mrk idx-pnt idx-mrk))))
2683 (defun org-index--restore-positions ()
2684 "Restore positions as saved by `org-index--save-positions'."
2686 (cl-multiple-value-bind
2687 (cur-buf cur-mrk idx-pnt idx-mrk buf)
2688 org-index--saved-positions
2689 (setq buf (current-buffer))
2690 (set-buffer cur-buf)
2691 (goto-char cur-mrk)
2692 (set-buffer org-index--buffer)
2693 (goto-char (or idx-pnt idx-mrk))
2694 (set-buffer buf))
2695 (setq org-index--saved-positions nil))
2698 (defun org-index--delete-ref-from-heading (ref)
2699 "Delete given REF from current heading."
2700 (save-excursion
2701 (end-of-line)
2702 (let ((end (point)))
2703 (beginning-of-line)
2704 (when (search-forward ref end t)
2705 (delete-char (- (length ref)))
2706 (just-one-space)))))
2709 (defun org-index--delete-any-ref-from-tags ()
2710 "Delete any reference from list of tags."
2711 (let (new-tags)
2712 (mapc (lambda (tag)
2713 (unless (or (string-match org-index--ref-regex tag)
2714 (string= tag ""))
2715 (setq new-tags (cons tag new-tags))))
2716 (org-get-tags))
2717 (org-set-tags-to new-tags)))
2720 (defun org-index--go (column value)
2721 "Position cursor on index line where COLUMN equals VALUE.
2722 Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
2723 (let (found)
2725 (unless (eq (current-buffer) org-index--buffer)
2726 (error "This is a bug: Not in index buffer"))
2728 (unless value
2729 (error "Cannot search for nil"))
2731 (if (string= value "")
2732 (error "Cannot search for empty string"))
2734 (if (<= (length value) 2)
2735 (warn "Searching for short string '%s' will be slow" value))
2737 (goto-char org-index--below-hline)
2738 (forward-line 0)
2739 (save-restriction
2740 (narrow-to-region (point) (org-table-end))
2741 (while (and (not found)
2742 (search-forward value nil t))
2743 (setq found (string= value (org-index--get-or-set-field column)))))
2745 ;; return value
2746 (if found
2748 (goto-char org-index--below-hline)
2749 nil)))
2752 (defun org-index--find-id (id &optional other)
2753 "Perform command head: Find node with ID and present it.
2754 If OTHER in separate window."
2756 (let (message marker)
2758 (setq marker (org-id-find id t))
2760 (if marker
2761 (progn
2762 (org-index--update-line id)
2763 (if other
2764 (progn
2765 (pop-to-buffer (marker-buffer marker)))
2766 (pop-to-buffer-same-window (marker-buffer marker)))
2768 (goto-char marker)
2769 (org-reveal t)
2770 (org-show-entry)
2771 (recenter)
2772 (unless (string= (org-id-get) id)
2773 (setq message (format "Could not go to node with id %s (narrowed ?)" id)))
2774 (setq message "Found headline"))
2775 (setq message (format "Did not find node with %s" id)))
2776 message))
2779 (defun org-index--do-occur (&optional days)
2780 "Perform command occur; optional narrow to DAYS back."
2781 (let ((word "") ; last word to search for growing and shrinking on keystrokes
2782 (prompt "Search for: ")
2783 (these-commands " NOTE: If you invoke the subcommands edit (`e') or kill (`C-c i k') from within this buffer, the index is updated accordingly")
2784 (lines-wanted (window-body-height))
2785 words ; list words that should match
2786 occur-buffer
2787 begin ; position of first line
2788 help-text ; cons with help text short and long
2789 search-text ; description of text to search for
2790 done ; true, if loop is done
2791 in-c-backspace ; true, while processing C-backspace
2792 help-overlay ; Overlay with help text
2793 initial-frame ; Frame when starting occur
2794 key ; input from user in various forms
2795 key-sequence
2796 key-sequence-raw
2797 days-clause) ; clause to display for days back search
2800 ;; make and show buffer
2801 (if (get-buffer org-index--occur-buffer-name)
2802 (kill-buffer org-index--occur-buffer-name))
2803 (setq occur-buffer (make-indirect-buffer org-index--buffer org-index--occur-buffer-name))
2804 (pop-to-buffer-same-window occur-buffer)
2805 (setq initial-frame (selected-frame))
2807 ;; avoid modifying direct buffer
2808 (setq buffer-read-only t)
2809 (toggle-truncate-lines 1)
2811 ;; reset stack and overlays
2812 (setq org-index--occur-stack nil)
2813 (setq org-index--occur-tail-overlay nil)
2815 ;; narrow to table rows and one line before
2816 (goto-char org-index--below-hline)
2817 (forward-line 0)
2818 (setq begin (point))
2819 (forward-line -1)
2820 (narrow-to-region (point) (org-table-end))
2821 (forward-line)
2823 ;; initialize help text
2824 (setq days-clause (if days (format " (%d days back)" days) ""))
2825 (setq help-text (cons
2826 (concat
2827 (propertize (format "Incremental occur%s" days-clause) 'face 'org-todo)
2828 (propertize "; ? toggles help and headlines.\n" 'face 'org-agenda-dimmed-todo-face))
2829 (concat
2830 (propertize
2831 (org-index--wrap
2832 (concat
2833 "Normal keys add to search word; <space> or <comma> start additional word; <backspace> erases last char, <C-backspace> last word; <return> jumps to heading, <tab> jumps to heading in other window, <S-return> jumps to matching line in index; all other keys end search." these-commands "\n"))
2834 'face 'org-agenda-dimmed-todo-face)
2835 org-index--headings)))
2837 ;; insert overlays for help text and to cover unsearched lines
2838 (setq help-overlay (make-overlay (point-min) begin))
2839 (overlay-put help-overlay 'display (car help-text))
2840 (setq org-index--occur-tail-overlay (make-overlay (point-max) (point-max)))
2841 (overlay-put org-index--occur-tail-overlay 'invisible t)
2843 ;; do not enter loop if number of days is requested
2844 (when days
2845 (goto-char begin)
2846 (org-index--hide-with-overlays (cons word words) lines-wanted days)
2847 (move-overlay org-index--occur-tail-overlay (org-index--occur-end-of-visible) (point-max))
2849 (goto-char begin)
2850 (setq done t))
2852 ;; main loop
2853 (while (not done)
2855 (if in-c-backspace
2856 (setq key "<backspace>")
2857 (setq search-text (mapconcat 'identity (reverse (cons word words)) ","))
2859 ;; read key, if selected frame has not changed
2860 (if (eq initial-frame (selected-frame))
2861 (progn
2862 (setq key-sequence
2863 (let ((echo-keystrokes 0)
2864 (full-prompt (format "%s%s%s"
2865 prompt
2866 search-text
2867 (if (string= search-text "") "" " "))))
2868 (read-key-sequence full-prompt nil nil t t)))
2869 (setq key (key-description key-sequence))
2870 (setq key-sequence-raw (this-single-command-raw-keys)))
2871 (setq done t)
2872 (setq key-sequence nil)
2873 (setq key nil)
2874 (setq key-sequence-raw nil)))
2877 (cond
2880 ((string= key "<C-backspace>")
2881 (setq in-c-backspace t))
2884 ((member key (list "<backspace>" "DEL")) ; erase last char
2886 (if (= (length word) 0)
2888 ;; nothing more to delete from current word; try next
2889 (progn
2890 (setq word (car words))
2891 (setq words (cdr words))
2892 (setq in-c-backspace nil))
2894 ;; some chars are left; shorten word
2895 (setq word (substring word 0 -1))
2896 (when (= (length word) 0) ; when nothing left, use next word from list
2897 (setq word (car words))
2898 (setq words (cdr words))
2899 (setq in-c-backspace nil))
2901 ;; free top list of overlays and remove list
2902 (org-index--unhide)
2903 (move-overlay org-index--occur-tail-overlay
2904 (org-index--occur-end-of-visible)
2905 (point-max))
2907 ;; make sure, point is still visible
2908 (goto-char begin)))
2911 ((member key (list "SPC" ",")) ; space or comma: enter an additional search word
2913 ;; push current word and clear, no need to change display
2914 (unless (string= word "")
2915 (setq words (cons word words))
2916 (setq word "")))
2919 ((string= key "?") ; question mark: toggle display of headlines and help
2920 (setq help-text (cons (cdr help-text) (car help-text)))
2921 (overlay-put help-overlay 'display (car help-text)))
2923 ((and (= (length key) 1)
2924 (aref printable-chars (elt key 0))) ; any printable char: add to current search word
2926 ;; add to word
2927 (setq word (concat word key))
2929 ;; make overlays to hide lines, that do not match longer word any more
2930 (goto-char begin)
2931 (org-index--hide-with-overlays (cons word words) lines-wanted days)
2932 (move-overlay org-index--occur-tail-overlay
2933 (org-index--occur-end-of-visible)
2934 (point-max))
2936 (goto-char begin)
2938 ;; make sure, point is on a visible line
2939 (line-move -1 t)
2940 (line-move 1 t))
2942 ;; anything else terminates input loop
2943 (t (setq done t))))
2945 ;; put back input event, that caused the loop to end
2946 (unless (string= key "C-g")
2947 (setq unread-command-events (listify-key-sequence key-sequence-raw))
2948 (message key))
2950 ;; For performance reasons do not show matching lines for rest of table. So no code here.
2952 ;; make permanent copy
2953 ;; copy visible lines
2954 (let ((lines-collected 0)
2955 keymap line all-lines all-lines-lbp header-lines lbp)
2957 (setq cursor-type t)
2958 (goto-char begin)
2959 (let ((inhibit-read-only t))
2960 (put-text-property begin (org-table-end) 'face nil))
2962 ;; collect all visible lines
2963 (while (and (not (eobp))
2964 (< lines-collected lines-wanted))
2965 ;; skip over invisible lines
2966 (while (and (invisible-p (point))
2967 (not (eobp)))
2968 (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
2969 (setq lbp (line-beginning-position))
2970 (setq line (buffer-substring-no-properties lbp (line-end-position)))
2971 (unless (string= line "")
2972 (cl-incf lines-collected)
2973 (setq all-lines (cons (concat line
2974 "\n")
2975 all-lines))
2976 (setq all-lines-lbp (cons lbp all-lines-lbp)))
2977 (forward-line 1))
2979 (kill-buffer org-index--occur-buffer-name) ; cannot keep this buffer; might become stale soon
2981 ;; create new buffer
2982 (setq occur-buffer (get-buffer-create org-index--occur-buffer-name))
2983 (pop-to-buffer-same-window occur-buffer)
2984 (insert org-index--headings)
2985 (setq header-lines (line-number-at-pos))
2987 ;; insert into new buffer
2988 (save-excursion
2989 (apply 'insert (reverse all-lines))
2990 (if (= lines-collected lines-wanted)
2991 (insert "\n(more lines omitted)\n")))
2992 (setq org-index--occur-lines-collected lines-collected)
2994 (org-mode)
2995 (setq truncate-lines t)
2996 (if all-lines (org-index--align-and-fontify-current-line (length all-lines)))
2997 (when (fboundp 'font-lock-ensure)
2998 (font-lock-ensure)
2999 (font-lock-flush))
3000 (when all-lines-lbp
3001 (while (not (org-at-table-p))
3002 (forward-line -1))
3003 (while all-lines-lbp
3004 (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp (car all-lines-lbp))
3005 (setq all-lines-lbp (cdr all-lines-lbp))
3006 (forward-line -1)))
3008 ;; prepare help text
3009 (goto-char (point-min))
3010 (forward-line (1- header-lines))
3011 (setq org-index--occur-help-overlay (make-overlay (point-min) (point)))
3012 (setq org-index--occur-help-text
3013 (cons
3014 (org-index--wrap
3015 (propertize (format "Search is done%s; ? toggles help and headlines.\n" days-clause) 'face 'org-agenda-dimmed-todo-face))
3016 (concat
3017 (org-index--wrap
3018 (propertize
3019 (format
3020 (concat (format "Search is done%s." days-clause)
3021 (if (< lines-collected lines-wanted)
3022 " Showing all %d matches for "
3023 " Showing one window of matches for ")
3024 "\"" search-text
3025 "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> jumps to matching line in index, <space> increments count.\n" these-commands "\n")
3026 (length all-lines))
3027 'face 'org-agenda-dimmed-todo-face))
3028 org-index--headings)))
3030 (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))
3032 ;; highlight words
3033 (mapc (lambda (w) (unless (or (not w) (string= w ""))
3034 (highlight-regexp
3035 (if (string= w (downcase w))
3036 (apply 'concat (mapcar (lambda (c) (if (string-match "[[:alpha:]]" (char-to-string c))
3037 (format "[%c%c]" (downcase c) (upcase c))
3038 (char-to-string c)))
3039 (regexp-quote w)))
3040 (regexp-quote w)) 'isearch)))
3041 (cons word words))
3043 (setq buffer-read-only t)
3045 ;; install keyboard-shortcuts
3046 (setq keymap (make-sparse-keymap))
3047 (set-keymap-parent keymap org-mode-map)
3049 (mapc (lambda (x) (define-key keymap (kbd x)
3050 (lambda () (interactive)
3051 (message "%s" (org-index--occur-action)))))
3052 (list "<return>" "RET"))
3054 (define-key keymap (kbd "<tab>")
3055 (lambda () (interactive)
3056 (message (org-index--occur-action t))))
3058 (define-key keymap (kbd "e")
3059 (lambda () (interactive)
3060 (message (org-index 'edit))))
3062 (define-key keymap (kbd "SPC")
3063 (lambda () (interactive)
3064 (org-index--refresh-parse-table)
3065 ;; increment in index
3066 (let ((ref (org-index--get-or-set-field 'ref))
3067 count)
3068 (org-index--on
3069 'ref ref
3070 (setq count (+ 1 (string-to-number (org-index--get-or-set-field 'count))))
3071 (org-index--get-or-set-field 'count (number-to-string count))
3072 (org-index--promote-current-line)
3073 (org-index--align-and-fontify-current-line))
3074 ;; increment in this buffer
3075 (let ((inhibit-read-only t))
3076 (org-index--get-or-set-field 'count (number-to-string count)))
3077 (message "Incremented count to %d" count))))
3079 (define-key keymap (kbd "<S-return>")
3080 (lambda () (interactive)
3081 (let ((pos (get-text-property (point) 'org-index-lbp)))
3082 (org-index--refresh-parse-table)
3083 (org-index--occur-test-stale pos)
3084 (pop-to-buffer org-index--buffer)
3085 (goto-char pos)
3086 (org-reveal t)
3087 (org-index--update-current-line)
3088 (beginning-of-line))))
3090 (define-key keymap (kbd "?")
3091 (lambda () (interactive)
3092 (org-index--refresh-parse-table)
3093 (setq-local org-index--occur-help-text (cons (cdr org-index--occur-help-text) (car org-index--occur-help-text)))
3094 (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))))
3096 (use-local-map keymap))))
3099 (defun org-index--occur-end-of-visible ()
3100 "End of visible stretch during occur."
3101 (if org-index--occur-stack
3102 (cdr (assoc :end-of-visible (car org-index--occur-stack)))
3103 (point-max)))
3106 (defun org-index--occur-test-stale (pos)
3107 "Test, if current line in occur buffer has become stale at POS."
3108 (let (here there)
3109 (org-index--refresh-parse-table)
3110 (setq here (org-index--line-in-canonical-form))
3111 (with-current-buffer org-index--buffer
3112 (goto-char pos)
3113 (setq there (org-index--line-in-canonical-form)))
3114 (unless (string= here there)
3115 (error "Occur buffer has become stale; please repeat search"))))
3118 (defun org-index--line-in-canonical-form ()
3119 "Return current line in its canonical form."
3120 (org-trim (substring-no-properties (replace-regexp-in-string "\s +" " " (buffer-substring (line-beginning-position) (line-beginning-position 2))))))
3123 (defun org-index--wrap (text)
3124 "Wrap TEXT at fill column."
3125 (with-temp-buffer
3126 (insert text)
3127 (fill-region (point-min) (point-max) nil t)
3128 (buffer-string)))
3131 (defun org-index--occur-action (&optional other)
3132 "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window; or copy yank column."
3133 (if (org-at-table-p)
3134 (let ((id (org-index--get-or-set-field 'id))
3135 (ref (org-index--get-or-set-field 'ref))
3136 (yank (org-index--get-or-set-field 'yank)))
3137 (if id
3138 (org-index--find-id id other)
3139 (if ref
3140 (progn
3141 (org-mark-ring-goto)
3142 (format "Found reference %s (no node is associated)" ref))
3143 (if yank
3144 (progn
3145 (org-index--update-line (get-text-property (point) 'org-index-lbp))
3146 (setq yank (replace-regexp-in-string (regexp-quote "\\vert") "|" yank nil 'literal))
3147 (kill-new yank)
3148 (org-mark-ring-goto)
3149 (if (and (>= (length yank) 4) (string= (substring yank 0 4) "http"))
3150 (progn
3151 (browse-url yank)
3152 (format "Opened '%s' in browser (and copied it too)" yank))
3153 (format "Copied '%s' (no node is associated)" yank)))
3154 (error "Internal error, this line contains neither id, nor reference, nor text to yank")))))
3155 (message "Not at table")))
3158 (defun org-index--hide-with-overlays (words lines-wanted days)
3159 "Hide lines that are currently visible and do not match WORDS;
3160 leave LINES-WANTED lines visible.
3161 Argument DAYS hides older lines."
3162 (let ((lines-found 0)
3163 (end-of-visible (point))
3164 overlay overlays start matched places all-places)
3166 ;; main loop
3167 (while (and (not (eobp))
3168 (< lines-found lines-wanted))
3170 ;; skip invisible lines
3171 (while (and (not (eobp))
3172 (and
3173 (invisible-p (point))
3174 (< (point) (overlay-start org-index--occur-tail-overlay))))
3175 (goto-char (overlay-end (car (overlays-at (point))))))
3177 ;; find stretch of lines, that are currently visible but should be invisible now
3178 (setq matched nil)
3179 (setq places nil)
3180 (setq start (point))
3181 (while (and (not (eobp))
3182 (not (and
3183 (invisible-p (point))
3184 (< (point) (overlay-start org-index--occur-tail-overlay))))
3185 ;; either regard words or days, but not both
3186 (if days
3187 (let ((last-accessed (org-index--get-or-set-field 'last-accessed)))
3188 (if last-accessed
3189 (not (and
3190 (<= (- (time-to-days (current-time))
3191 (time-to-days (org-read-date nil t last-accessed nil)))
3192 days)
3193 (setq matched t))) ; for its side effect
3195 (not (and (setq places (org-index--test-words words))
3196 (setq matched t))))) ; for its side effect
3197 (forward-line 1))
3199 (setq all-places (append places all-places))
3201 ;; create overlay to hide this stretch
3202 (when (< start (point)) ; avoid creating an empty overlay
3203 (setq overlay (make-overlay start (point)))
3204 (overlay-put overlay 'invisible t)
3205 (setq overlays (cons overlay overlays)))
3207 ;; skip and count line, that matched
3208 (when matched
3209 (let ((inhibit-read-only t) (lbp (line-beginning-position)))
3210 (put-text-property lbp (line-end-position) 'face nil)
3211 (while places
3212 (put-text-property (caar places) (+ (caar places) (cdar places)) 'face 'isearch)
3213 (setq places (cdr places))))
3214 (forward-line 1)
3215 (setq end-of-visible (point))
3216 (cl-incf lines-found)))
3218 ;; put new list on top of stack
3219 (setq org-index--occur-stack
3220 (cons (list (cons :overlays overlays)
3221 (cons :end-of-visible end-of-visible)
3222 (cons :lines lines-found)
3223 (cons :places all-places))
3224 org-index--occur-stack))
3226 lines-found))
3229 (defun org-index--unhide ()
3230 "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
3231 (let (places)
3232 (when org-index--occur-stack
3233 ;; delete overlays and make visible again
3234 (mapc (lambda (y)
3235 (delete-overlay y))
3236 (cdr (assoc :overlays (car org-index--occur-stack))))
3237 ;; remove latest highlights
3238 (setq places (cdr (assoc :places (car org-index--occur-stack))))
3239 (while places
3240 (let ((inhibit-read-only t))
3241 (put-text-property (caar places) (+ (caar places) (cdar places)) 'face nil))
3242 (setq places (cdr places)))
3243 ;; remove top of stack
3244 (setq org-index--occur-stack (cdr org-index--occur-stack))
3245 ;; redo older highlights
3246 (setq places (cdr (assoc :places (car org-index--occur-stack))))
3247 (while places
3248 (let ((inhibit-read-only t))
3249 (put-text-property (caar places) (+ (caar places) (cdar places)) 'face 'isearch))
3250 (setq places (cdr places))))))
3253 (defun org-index--test-words (words)
3254 "Test current line for match against WORDS."
3255 (let ((lbp (line-beginning-position))
3256 line dc-line places index)
3257 (setq line (buffer-substring lbp (line-beginning-position 2)))
3258 (setq dc-line (downcase line))
3259 (catch 'not-found
3260 (dolist (word words)
3261 (if (setq index (cl-search word (if (string= word (downcase word)) dc-line line)))
3262 (setq places (cons (cons (+ lbp index) (length word)) places))
3263 (throw 'not-found nil)))
3264 places)))
3267 (defun org-index--create-new-line ()
3268 "Do the common work for `org-index-new-line' and `org-index'."
3270 ;; insert ref or id as last or first line, depending on sort-column
3271 (goto-char org-index--below-hline)
3272 (if (eq org-index-sort-by 'count)
3273 (progn
3274 (goto-char (org-table-end))
3275 (forward-line -1)
3276 (org-table-insert-row t))
3277 (org-table-insert-row))
3279 ;; insert some of the standard values
3280 (org-table-goto-column (org-index--column-num 'created))
3281 (org-insert-time-stamp nil nil t)
3282 (org-table-goto-column (org-index--column-num 'count))
3283 (insert "1"))
3286 (defun org-index--sort-silent ()
3287 "Sort index for default column to remove any effects of temporary sorting."
3288 (unless org-index--inhibit-sort-idle
3289 (save-excursion
3290 (org-index--verify-id)
3291 (org-index--parse-table)
3292 (with-current-buffer org-index--buffer
3293 (save-excursion
3294 (goto-char org-index--below-hline)
3295 (org-index--do-sort-index org-index-sort-by)
3296 (remove-hook 'before-save-hook 'org-index--sort-silent))))))
3299 (defun org-index--idle-prepare ()
3300 "For parsing table when idle."
3301 (org-index--verify-id)
3302 (org-index--parse-table most-positive-fixnum t))
3305 (defun org-index--copy-visible (beg end)
3306 "Copy the visible parts of the region between BEG and END without adding it to `kill-ring'; copy of `org-copy-visible'."
3307 (let (snippets s)
3308 (save-excursion
3309 (save-restriction
3310 (narrow-to-region beg end)
3311 (setq s (goto-char (point-min)))
3312 (while (not (= (point) (point-max)))
3313 (goto-char (org-find-invisible))
3314 (push (buffer-substring s (point)) snippets)
3315 (setq s (goto-char (org-find-visible))))))
3316 (apply 'concat (nreverse snippets))))
3319 (provide 'org-index)
3321 ;; Local Variables:
3322 ;; fill-column: 75
3323 ;; comment-column: 50
3324 ;; End:
3326 ;;; org-index.el ends here