org-index.el version 4.1.1
[org-mode.git] / contrib / lisp / org-index.el
blobd7a243a0bf89d92856953dfd0fb563e4f9bf110e
1 ;;; org-index.el --- A personal index for org and beyond
3 ;; Copyright (C) 2011-2015 Free Software Foundation, Inc.
5 ;; Author: Marc Ihm <org-index@2484.de>
6 ;; Version: 4.1.1
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 headings and things outside of org.
32 ;; This package creates and updates an index table of headings or
33 ;; keywords, references and ids, where each line points to a heading
34 ;; within org or references something outside. This table is sorted by
35 ;; usage count, so that frequently used lines appear among the first
36 ;; results.
38 ;; References are essentially small numbers (e.g. 'R237' or '--455--'), as
39 ;; created by this package; they are well suited to be used outside of
40 ;; org, e.g. in folder names, issue trackers or on printed documents.
42 ;; On first invocation org-index will guide you to create a dedicated node
43 ;; for its index table and its configuration flags.
45 ;; For basic usage, subcommands 'add' and 'occur' are most important.
48 ;; Setup:
50 ;; - Add these lines to your .emacs:
52 ;; (require 'org-index)
53 ;; (org-index-default-keybindings) ; optional
55 ;; - Restart your Emacs to make these lines effective.
57 ;; - Invoke `org-index', which will assist in creating your index
58 ;; table. The variable org-index-id will be persisted within your
59 ;; customization file (typically .emacs).
62 ;; Further reading:
64 ;; See the documentation of `org-index', which can also be read
65 ;; by invoking `org-index' and choosing the help-command.
68 ;; Updates:
70 ;; The latest tested version of this file can always be found at:
72 ;; http://orgmode.org/w/org-mode.git?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
74 ;;; Change Log:
76 ;; [2015-03-03 Tu] Version 4.0.1
77 ;; - org-mark-ring is now used more consistently
79 ;; [2015-02-26 Th] Version 4.0.0 and 4.1.0:
80 ;; - Removed command "leave"; rather go back with org-mark-ring-goto
81 ;; - Property "org-index-ref" is no longer used or needed
82 ;; - Renamed column "link" to "id"
83 ;; - Added maintainance options to find duplicate rows, to check ids,
84 ;; update index or remove property org-index-ref from nodes
85 ;; - New command point
86 ;; - Shortened versin history
88 ;; [2014-12-07 Sa] to [2015-01-31 Sa] Version 3.0.0 to 3.2.0:
89 ;; - Complete sorting of index only occurs in idle-timer
90 ;; - New command "maintain" with some subcommands
91 ;; - Rewrote command "occur" with overlays in an indirect buffer
92 ;; - introduced variable org-index-version
93 ;; - Command "add" updates index, if node is already present
94 ;; - New commands "add" and "delete" to easily add and remove
95 ;; the current node to or from your index.
96 ;; - New command "example" to create an example index.
97 ;; - Moved flags to a list within the same node as the index table;
98 ;; this breaks compatibility to prior versions of the package.
99 ;; - Several new flags that are explained within index node.
100 ;; - Removed commands "reuse", "missing", "put", "goto",
101 ;; "update", "link", "fill", "unhighlight"
102 ;; - New function `org-index-default-keybindings'
104 ;; [2012-12-07 Fr] to [2014-04-26 Sa] Version 2.0.0 to 2.4.3:
105 ;; - New functions org-index-new-line and org-index-get-line
106 ;; offer access to org-index from other lisp programs
107 ;; - Regression tests with ert
108 ;; - Renamed from "org-favtable" to "org-index"
109 ;; - Added an assistant to set up the index table
110 ;; - occur is now incremental, searching as you type
111 ;; - Integrated with org-mark-ring-goto
112 ;; - Added full support for ids
113 ;; - Renamed the package from "org-reftable" to "org-favtable"
114 ;; - Additional columns are required (e.g. "link"). Error messages will
115 ;; guide you
116 ;; - Ask user explicitly, which command to invoke
117 ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
119 ;; [2011-12-10 Sa] to [2012-09-22 Sa] Version Version 1.2.0 to 1.5.0:
120 ;; - New command "sort" to sort a buffer or region by reference number
121 ;; - New commands "highlight" and "unhighlight" to mark references
122 ;; - New command "head" to find a headline with a reference number
123 ;; - New commands occur and multi-occur
124 ;; - Started this Change Log
126 ;;; Code:
128 (require 'org-table)
129 (require 'cl)
131 (defcustom org-index-id nil
132 "Id of the Org-mode node, which contains the index table."
133 :group 'org
134 :group 'org-index)
136 ;; Version of this package
137 (defvar org-index-version "4.1.0" "Version of `org-index', format is major.minor.bugfix, where \"major\" is a change in index-table and \"minor\" are new features.")
139 ;; Variables to hold the configuration of the index table
140 (defvar org-index--maxref nil "Maximum number from reference table (e.g. \"153\").")
141 (defvar org-index--head nil "Any header before number (e.g. \"R\").")
142 (defvar org-index--tail nil "Tail after number (e.g. \"}\" or \")\".")
143 (defvar org-index--numcols nil "Number of columns in index table.")
144 (defvar org-index--ref-regex nil "Regular expression to match a reference.")
145 (defvar org-index--ref-format nil "Format, that can print a reference.")
146 (defvar org-index--columns nil "Columns of index-table.")
147 (defvar org-index--special-columns nil "Columns with flags, that may appear only once.")
148 (defvar org-index--flagged-columns nil "Columns with flags, that may appear multiple times.")
149 (defvar org-index--buffer nil "Buffer of index table.")
150 (defvar org-index--point nil "Position at start of headline of index table.")
151 (defvar org-index--below-hline nil "Position of first cell in first line below hline.")
152 (defvar org-index--headings nil "Headlines of index-table as a string.")
153 (defvar org-index-map nil "Keymap for shortcuts for some commands of `org-index'. Can be activated and filled by org-index-default-keybings.")
155 ;; Variables to hold context and state
156 (defvar org-index--last-ref nil "Last reference created or visited.")
157 (defvar org-index--category-before nil "Category of node before.")
158 (defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
159 (defvar org-index--below-cursor nil "Word below cursor.")
160 (defvar org-index--within-node nil "True, if we are within node of the index table.")
161 (defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
162 (defvar org-index--occur-help-text nil "Text for help in occur buffer.")
163 (defvar org-index--occur-help-overlay nil "Overlay for help in occur buffer.")
164 (defvar org-index--occur-stack nil "Stack with overlays for hiding lines.")
165 (defvar org-index--occur-tail-overlay nil "Overlay to cover invisible lines.")
166 (defvar org-index--last-sort nil "Last column, the index has been sorted after.")
167 (defvar org-index--sort-timer nil "Timer to sort index in correct order.")
168 (defvar org-index--aligned nil "Remember for this Emacs session, if table has been aligned at least once.")
170 ;; static information for this program package
171 (defconst org-index--commands '(occur add delete head point enter ref help example sort multi-occur highlight maintain) "List of commands available.")
172 (defconst org-index--required-flags '(sort) "Flags that are required.")
173 (defconst org-index--single-flags '(sort point-on-add yank-after-add get-category-on-add get-heading-on-add shift-ref-and-date-on-add) "Flags, that may only appear once; these can appear as special-columns.")
174 (defconst org-index--multiple-flags '(edit-on-add) "Flags, that might appear multiple times.")
175 (defconst org-index--all-flags (append org-index--single-flags org-index--multiple-flags) "All flags.")
176 (defconst org-index--required-headings '(ref id created last-accessed count) "All required headings.")
177 (defconst org-index--valid-headings (append org-index--required-headings '(keywords category)) "All valid headings.")
178 (defconst org-index--occur-buffer-name "*org-index-occur*" "Name of occur buffer.")
179 (defconst org-index--sort-idle-delay 300 "Delay in seconds after which buffer will sorted.")
180 (defconst org-index--sample-flags
182 - columns-and-flags :: associate columns of index table with flags. Do not remove.
183 - ref
184 - yank-after-add
185 - category
186 - get-category-on-add
187 - edit-on-add
188 - keywords
189 - get-heading-on-add
190 - edit-on-add
191 - point-on-add
192 - count
193 - sort
194 - last-accessed
195 - created
196 - id
197 - all-columns-explained :: All columns of the index table and their meaning.
198 - ref :: The reference number; will be generated automatically.
199 - id :: id of the node, that this line represents
200 - created :: When has this entry been created ?
201 - last-accessed :: When has this entry been accessed last ?
202 - count :: How many times has this entry been picked ?
203 - keywords :: (optional) Suggested column to keep a list of keywords,
204 which may match your input during occur.
205 - category :: (optional) Suggested column to get category of node.
206 - Any name starting with a dot (`.') :: No predefined meaning,
207 depends on its flags.
208 - all-flags-explained :: All flags, that can be associated with columns.
209 - sort :: Sort whole table according to this column.
210 - yank-after-add :: This column will be yanked after picking this line during
211 occur.
212 - edit-on-add :: This field will be presented for editing, when adding
213 a new line to your index.
214 - point-on-add :: Point will land here, when adding a new line, e.g. with
215 command ref.
216 - get-category-on-add :: This column will receive the nodes category
217 during command add.
218 - get-heading-on-add :: This column will receive the nodes heading
219 during add.
220 - shift-ref-and-date-on-add :: Remove leading reference and timestamp on add."
221 "A sample string of flags.")
224 (defmacro org-index--on (column value &rest body)
225 "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
226 The value returned is the value of the last form in BODY or nil,
227 if VALUE cannot be found."
228 (declare (indent 2) (debug t))
229 (let ((pointvar (make-symbol "point")) ; avoid clash with same-named variables in body
230 (foundvar (make-symbol "found"))
231 (retvar (make-symbol "ret")))
232 `(save-current-buffer
233 (set-buffer org-index--buffer)
234 (setq ,pointvar (point))
235 (setq ,foundvar nil)
236 (setq ,retvar nil)
238 (setq ,foundvar (org-index--go ,column ,value))
239 (when ,foundvar
240 (setq ,retvar (progn ,@body)))
242 (goto-char ,pointvar)
244 ,retvar)))
247 (defun org-index (&optional command search-ref arg)
248 "Fast search for selected org headings and things outside of org.
250 This package creates and updates an index table of headings or
251 keywords, references and ids, where each line points to a heading
252 within org or references something outside. This table is sorted by
253 usage count, so that frequently used lines appear among the first
254 results.
256 References are essentially small numbers (e.g. 'R237' or '--455--'), as
257 created by this package; they are well suited to be used outside of
258 org, e.g. in folder names, issue trackers or on printed documents.
260 On first invocation `org-index' will guide you to create a dedicated node
261 for its index table and its configuration flags.
263 For basic usage, subcommands 'add' and 'occur' are most important.
265 This is version 4.1.0 of org-index.el.
266 \\<org-mode-map>
267 The function `org-index' operates on a dedicated table, the index
268 table, which lives within its own Org-mode node. The table and
269 its containing node will be created, when you first invoke
270 `org-index'. The node also contains a commented list, describing
271 the columns of the index table and their associated flags. The
272 node is found through its id, which is stored within the variable
273 `org-index-id'.
276 The function `org-index' is the only interactive function of this
277 package and its main entry point; it will present you with a list
278 of subcommands to choose from:
280 occur: Incremental search, that shows matching lines from the
281 index table. It is updated after every keystroke. You may
282 enter a list of words seperated by space or comma (`,'), to
283 select lines that contain all of the given words.
285 add: Add the current node to your index, so that it can be
286 found through the subcommand \"occur\". Update index,
287 if node has already been present.
289 delete: Delete the current node from your index.
291 head: Ask for a reference number and search for this heading.
293 enter: Enter index table and maybe go to a specific reference;
294 use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
296 point: Echo information from index table for node at point.
298 ref: Create a new reference.
300 help: Show this text.
302 example: Create a temporary index, that will not be saved, but
303 may serve as an example.
305 sort: Sort lines in index, in region or buffer by contained
306 reference, or sort index by count, reference or last access.
308 multi-occur: Apply Emacs standard `multi-occur' operation on all
309 `org-mode' buffers to search for the given reference.
311 highlight: Highlight or unhiglight references in active region or buffer.
312 Call with prefix argument (`C-u') to remove highlights.
314 maintain: Offers some choices to check, update or fix your index.
316 If you invoke `org-index' for the first time, an assistant will be
317 invoked, that helps you to create your own, commented index.
319 Use `org-index-default-keybindings' to establish convenient
320 keyboard shortcuts.
322 See the commented list of flags within your index node for ways to
323 modify the behaviour of org-index.
325 Optional arguments for use from elisp: COMMAND is a symbol naming
326 the command to execute. SEARCH-REF specifies a reference to
327 search for, if needed. ARG allows passing in a prefix argument
328 as in interactive calls."
330 (interactive "P")
332 (let (search-id ; id to search for
333 sort-what ; sort what ?
334 kill-new-text ; text that will be appended to kill ring
335 message-text) ; text that will be issued as an explanation
339 ;; Initialize and parse
342 ;; creates index table, if necessary
343 (org-index--verify-id)
345 ;; Get configuration of index table
346 (org-index--parse-table)
348 ;; store context information
349 (org-index--retrieve-context)
353 ;; Arrange for proper sorting of index
356 ;; lets assume, that it has been sorted this way (we try hard to make sure)
357 (unless org-index--last-sort (setq org-index--last-sort (org-index--special-column 'sort)))
358 ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
359 (unless org-index--sort-timer
360 (setq org-index--sort-timer
361 (run-with-idle-timer org-index--sort-idle-delay t 'org-index--sort-silent)))
365 ;; Find out, what we are supposed to do
368 (when (equal command '(4))
369 (setq arg command)
370 (setq command nil))
372 (if command
373 (unless (memq command org-index--commands)
374 (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
375 command (mapconcat 'symbol-name org-index--commands ",")))
376 (setq command (intern (org-completing-read
377 "Please choose: "
378 (mapcar 'symbol-name org-index--commands)))))
382 ;; Get search string, if required
385 ;; These actions need a search string:
386 (when (memq command '(enter head multi-occur))
388 ;; search from surrounding text ?
389 (unless search-ref
390 (if org-index--within-node
392 (if (org-at-table-p)
393 (setq search-ref (org-index--get-or-set-field 'ref)))
395 (if (and org-index--below-cursor
396 (string-match (concat "\\(" org-index--ref-regex "\\)")
397 org-index--below-cursor))
398 (setq search-ref (match-string 1 org-index--below-cursor)))))
400 ;; If we still do not have a search string, ask user explicitly
401 (unless search-ref
402 (if (eq command 'enter)
403 (let ((r (org-index--read-search-for-enter)))
404 (setq search-ref (car r))
405 (setq search-id (cdr r)))
406 (setq search-ref (read-from-minibuffer "Search reference number: "))))
408 ;; Clean up search string
409 (when search-ref
410 (setq search-ref (org-trim search-ref))
411 (if (string-match "^[0-9]+$" search-ref)
412 (setq search-ref (concat org-index--head search-ref org-index--tail)))
413 (if (string= search-ref "") (setq search-ref nil)))
415 (if (and (not search-ref)
416 (not (eq command 'enter)))
417 (error "Command %s needs a reference number" command)))
421 ;; Command sort needs to know in advance, what to sort for
424 (when (eq command 'sort)
425 (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))))
428 ;; Arrange for beeing able to return
431 (when (memq command '(occur head enter ref example sort maintain))
432 (org-mark-ring-push))
436 ;; Enter table
439 ;; These commands will leave user in index table after they are finished
440 (when (or (memq command '(enter ref maintain))
441 (and (eq command 'sort)
442 (eq sort-what 'index)))
444 ;; Support orgmode-standard of going back (buffer and position)
445 (org-mark-ring-push)
447 (pop-to-buffer-same-window org-index--buffer)
448 (goto-char org-index--point)
449 (org-index--unfold-buffer))
453 ;; Actually do, what is requested
456 (cond
459 ((eq command 'help)
461 ;; bring up help-buffer for this function
462 (describe-function 'org-index))
465 ((eq command 'multi-occur)
467 ;; Construct list of all org-buffers
468 (let (buff org-buffers)
469 (dolist (buff (buffer-list))
470 (set-buffer buff)
471 (if (string= major-mode "org-mode")
472 (setq org-buffers (cons buff org-buffers))))
474 ;; Do multi-occur
475 (multi-occur org-buffers (org-index--make-guarded-search search-ref))
477 ;; Present results
478 (if (get-buffer "*Occur*")
479 (progn
480 (setq message-text (format "multi-occur for '%s'" search-ref))
481 (other-window 1)
482 (toggle-truncate-lines 1))
483 (setq message-text (format "Did not find '%s'" search-ref)))))
486 ((eq command 'add)
488 (let ((r (org-index--do-add-or-update)))
489 (setq message-text (car r))
490 (setq kill-new-text (cdr r))))
493 ((eq command 'delete)
495 (setq message-text (org-index--do-delete)))
498 ((eq command 'head)
500 (if (and org-index--within-node
501 (org-at-table-p))
502 (setq search-id (org-index--get-or-set-field 'id)))
504 (setq message-text
505 (if search-id
506 (org-index--do-head search-ref search-id)
507 (message "Current line has no id."))))
510 ((eq command 'enter)
512 (goto-char org-index--below-hline)
514 (setq message-text
516 (if search-ref
517 (if (org-index--go 'ref search-ref)
518 (progn
519 (org-index--update-current-line)
520 (org-table-goto-column (org-index--column-num 'ref))
521 (format "Found index line '%s'" search-ref))
522 (format "Did not find index line with reference '%s'" search-ref))
524 (if search-id
525 (if (org-index--go 'id search-id)
526 (progn
527 (org-index--update-current-line)
528 (org-table-goto-column (org-index--column-num 'ref))
529 (format "Found index line '%s'" (org-index--get-or-set-field 'ref)))
530 (format "Did not find index line with id '%s'" search-id))
532 ;; simply go into table
533 (setq message-text "At index table"))))
535 (recenter))
538 ((eq command 'point)
540 (let (id info)
541 (setq id (org-id-get))
542 (if id
543 (setq info (org-index--on 'id id
544 (mapcar (lambda (x) (org-index--get-or-set-field x))
545 (list 'created 'count 'last-accessed 'ref)))))
546 (if info
547 (progn
548 (setq message-text (apply 'format (cons "Created %s, %s times accessed, last %s" info)))
549 (setq kill-new-text (car (last info))))
550 (setq message-text "This node is not part of index"))))
553 ((eq command 'occur)
555 (set-buffer org-index--buffer)
556 (org-index--do-occur))
559 ((eq command 'ref)
561 (let (new)
563 ;; add a new row
564 (setq new (org-index--create-new-line))
566 ;; fill special columns with standard values
567 (org-table-goto-column (org-index--column-num 'ref))
568 (insert new)
569 (setq org-index--last-ref new)
571 ;; goto point-field or first empty one or first field
572 (if (org-index--special-column 'point-on-add)
573 (org-table-goto-column (org-index--column-num (org-index--special-column 'point-on-add)))
574 (unless (catch 'empty
575 (dotimes (col org-index--numcols)
576 (org-table-goto-column (+ col 1))
577 (if (string= (org-trim (org-table-get-field)) "")
578 (throw 'empty t))))
579 ;; none found, goto first
580 (org-table-goto-column 1)))
582 (if org-index--active-region (setq kill-new-text org-index--active-region))
583 (setq message-text (format "Adding a new row with ref '%s'" new))))
586 ((eq command 'sort)
588 (let ((columns (list "ref" "count" "created" "last-accessed" "id"))
589 sort groups-and-counts)
591 (cond
592 ((eq sort-what 'index)
593 (setq sort
594 (intern
595 (org-icompleting-read
596 "Please choose column to sort index table: "
597 (append (copy-list columns) (list "group-by"))
598 nil t nil nil (symbol-name (org-index--special-column 'sort)))))
600 (when (eq sort 'group-by)
601 (setq sort
602 (intern
603 (org-icompleting-read
604 "Please choose column to group index table by: "
605 columns
606 nil t nil nil (symbol-name (org-index--special-column 'sort)))))
607 (setq groups-and-counts (org-index--collect-sort-groups sort)))
609 (org-index--do-sort-index sort (first groups-and-counts))
610 (org-table-goto-column (org-index--column-num sort))
611 ;; When saving index, it should again be sorted correctly
612 (with-current-buffer org-index--buffer
613 (add-hook 'before-save-hook 'org-index--sort-silent t))
615 (setq message-text
616 (format
617 (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
618 (if groups-and-counts
619 "; %d groups with equal %s and a total of %d lines have been found"
620 ""))
621 (symbol-name sort)
622 (org-index--special-column 'sort)
623 org-index--sort-idle-delay
624 (second groups-and-counts)
625 (symbol-name sort)
626 (third groups-and-counts))))
628 ((memq sort-what '(region buffer))
629 (org-index--do-sort-lines sort-what)
630 (setq message-text (format "Sorted %s by contained references" sort-what))))))
633 ((eq command 'highlight)
635 (let ((where "buffer"))
636 (save-excursion
637 (save-restriction
638 (when (and transient-mark-mode
639 mark-active)
640 (narrow-to-region (region-beginning) (region-end))
641 (setq where "region"))
643 (if arg
644 (progn
645 (unhighlight-regexp org-index--ref-regex)
646 (setq message-text (format "Removed highlights for references in %s" where)))
647 (highlight-regexp org-index--ref-regex 'isearch)
648 (setq message-text (format "Highlighted references in %s" where)))))))
651 ((eq command 'maintain)
652 (setq message-text (org-index--do-maintain)))
655 ((eq command 'example)
657 (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
658 (org-index--create-index t)))
661 (t (error "Unknown subcommand '%s'" command)))
664 ;; tell, what we have done and what can be yanked
665 (if kill-new-text (setq kill-new-text
666 (substring-no-properties kill-new-text)))
667 (if (string= kill-new-text "") (setq kill-new-text nil))
668 (let ((m (concat
669 message-text
670 (if (and message-text kill-new-text)
671 " and r"
672 (if kill-new-text "R" ""))
673 (if kill-new-text (format "eady to yank '%s'." kill-new-text) (if message-text "." "")))))
674 (unless (string= m "")
675 (message m)
676 (setq org-index--message-text m)))
677 (if kill-new-text (kill-new kill-new-text))))
680 (defun org-index-default-keybindings ()
681 "Set default keybindings for `org-index'.
683 Establish the common prefix key `C-c i' Which is followed by the
684 first letter of selected subcommands:
686 key action or subcommand
687 --- --------------------
689 i or SPC show complete list of commands
690 o occur
691 a add
692 d delete
693 h head
694 e enter
695 p or . point
696 r ref
697 ? help
699 See `org-index' for a description of all subcommands."
700 (interactive)
701 (define-prefix-command 'org-index-map)
702 (global-set-key (kbd "C-c i") 'org-index-map)
703 (define-key org-index-map (kbd "i") (lambda (arg) (interactive "P") (message nil) (org-index nil nil arg)))
704 (define-key org-index-map (kbd "SPC") (lambda (arg) (interactive "P") (message nil) (org-index nil nil arg)))
705 (define-key org-index-map (kbd "o") (lambda (arg) (interactive "P") (message nil) (org-index 'occur nil arg)))
706 (define-key org-index-map (kbd "a") (lambda (arg) (interactive "P") (message nil) (org-index 'add nil arg)))
707 (define-key org-index-map (kbd "d") (lambda (arg) (interactive "P") (message nil) (org-index 'delete nil arg)))
708 (define-key org-index-map (kbd "h") (lambda (arg) (interactive "P") (message nil) (org-index 'head nil arg)))
709 (define-key org-index-map (kbd "e") (lambda (arg) (interactive "P") (message nil) (org-index 'enter nil arg)))
710 (define-key org-index-map (kbd "p") (lambda (arg) (interactive "P") (message nil) (org-index 'point nil arg)))
711 (define-key org-index-map (kbd ".") (lambda (arg) (interactive "P") (message nil) (org-index 'point nil arg)))
712 (define-key org-index-map (kbd "?") (lambda (arg) (interactive "P") (message nil) (org-index 'help nil arg))))
715 (defun org-index-new-line (&rest keys-values)
716 "Create a new line within the index table, returning its reference.
718 The function takes a varying number of argument pairs; each pair
719 is a symbol for an existing column heading followed by its value.
720 The return value is the new reference.
722 Example:
724 (message \"Created reference %s\"
725 (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
727 Optional argument KEYS-VALUES specifies content of new line."
729 (org-index--verify-id)
730 (org-index--parse-table)
732 (car (apply 'org-index--do-new-line keys-values)))
735 (defun org-index--do-new-line (&rest keys-values)
736 "Do the work for `org-index-new-line'.
737 Optional argument KEYS-VALUES specifies content of new line."
739 (save-excursion
740 (org-index--retrieve-context)
741 (with-current-buffer org-index--buffer
742 (goto-char org-index--point)
744 ;; check arguments early; they might come from lisp-user
745 (let ((kvs keys-values)
746 k v)
747 (while kvs
748 (setq k (car kvs))
749 (setq v (cadr kvs))
750 (if (eq k 'ref)
751 (unless (memq v '(t nil))
752 (error "Column 'ref' accepts only \"t\" or \"nil\""))
753 (if (or (not (symbolp k))
754 (and (symbolp v) (not (eq v t)) (not (eq v nil))))
755 (error "Arguments must be alternation of key and value")))
756 (unless (org-index--column-num k)
757 (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
758 (setq kvs (cddr kvs))))
760 (let (ref yank)
761 ;; create new line
762 (setq ref (org-index--create-new-line))
763 (plist-put keys-values 'ref ref)
765 ;; fill columns
766 (let ((kvs keys-values)
767 k v n)
768 (while kvs
769 (setq k (car kvs))
770 (setq v (cadr kvs))
771 (org-table-goto-column (org-index--column-num k))
772 (insert (org-trim v))
773 (setq kvs (cddr kvs))))
775 ;; align table and fontify line
776 (org-table-align)
777 (setq org-index--aligned t)
778 (font-lock-fontify-region (line-beginning-position) (line-end-position))
780 ;; get column to yank
781 (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add)))
783 (cons ref yank)))))
786 (defun org-index-get-line (column value)
787 "Retrieve an existing line within the index table by ref or id.
788 Return its contents as a property list.
790 The function `plist-get' may be used to retrieve specific elements
791 from the result.
793 Example:
795 (plist-get (org-index-get-line 'ref \"R12\") 'count)
797 retrieves the value of the count-column for reference number 12.
799 Argument COLUMN is a symbol, either ref or id,
800 argument VALUE specifies the value to search for."
801 ;; check arguments
802 (unless (memq column '(ref id))
803 (error "Argument column can only be 'ref' or 'id'"))
805 (unless value
806 (error "Need a value to search for"))
808 (org-index--verify-id)
809 (org-index--parse-table)
811 (org-index--get-line column value))
814 (defun org-index--get-line (column value)
815 "Find a line by ID, return its contents.
816 Argument COLUMN and VALUE specify line to get."
817 (let (content)
818 (org-index--on
819 column value
820 (mapc (lambda (x)
821 (if (and (numberp (cdr x))
822 (> (cdr x) 0))
823 (setq content (cons (car x) (cons (or (org-index--get-or-set-field (car x)) "") content)))))
824 (reverse org-index--columns)))
825 content))
828 (defun org-index--delete-line (id)
829 "Delete a line specified by ID."
830 (let (content)
831 (org-index--on
832 'id id
833 (let ((start (line-beginning-position)))
834 (beginning-of-line)
835 (forward-line)
836 (delete-region start (point))
837 t))))
840 (defun org-index--ref-from-id (id)
841 "Get reference from line ID."
842 (org-index--on 'id id (org-index--get-or-set-field 'ref)))
845 (defun org-index--id-from-ref (ref)
846 "Get id from line REF."
847 (org-index--on 'ref ref (org-index--get-or-set-field 'id)))
850 (defun org-index--read-search-for-enter ()
851 "Special input routine for command enter."
852 ;; Accept single char commands or switch to reading a sequence of digits
853 (let (char prompt search-ref search-id)
855 ;; start with short prompt but give more help on next iteration
856 (setq prompt "Please specify, where to go in index (0-9.,space,backspace,return or ? for help): ")
858 ;; read one character
859 (while (not (memq char (append (number-sequence ?0 ?9) (list ?\d ?\b ?\r ?\j ?\s ?.))))
860 (setq char (read-char prompt))
861 (setq prompt "Go to index table and specific position. Digits specify a reference number to got to, <space> goes to top of index, <backspace> or <delete> to last line created and <return> or `.' to index line of current node. Please choose: "))
863 (if (memq char (number-sequence ?0 ?9))
864 ;; read rest of digits
865 (setq search-ref (read-from-minibuffer "Search reference number: " (char-to-string char))))
866 ;; decode single chars
867 (if (memq char '(?\r ?\n ?.)) (setq search-id (org-id-get)))
868 (if (memq char '(?\d ?\b)) (setq search-ref (number-to-string org-index--maxref)))
870 (cons search-ref search-id)))
873 (defun org-index--verify-id ()
874 "Check, that we have a valid id."
876 ;; Check id
877 (unless org-index-id
878 (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")))
879 (if (string= "create-index" answer)
880 (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
881 (describe-function 'org-index))))
883 ;; Find node
884 (let (marker)
885 (setq marker (org-id-find org-index-id 'marker))
886 (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
887 ; Try again with new node
888 (setq marker (org-id-find org-index-id 'marker))
889 (unless marker (error "Could not create node"))
890 (setq org-index--buffer (marker-buffer marker)
891 org-index--point (marker-position marker))
892 (move-marker marker nil)))
895 (defun org-index--retrieve-context ()
896 "Collect context information before starting with command."
898 ;; Get the content of the active region or the word under cursor
899 (setq org-index--active-region
900 (if (and transient-mark-mode mark-active)
901 (buffer-substring (region-beginning) (region-end))
902 nil))
903 (setq org-index--below-cursor (thing-at-point 'symbol))
905 ;; get category of current node
906 (setq org-index--category-before
907 (save-excursion ; workaround: org-get-category does not give category when at end of buffer
908 (beginning-of-line)
909 (org-get-category)))
911 ;; Find out, if we are within index table or not
912 (setq org-index--within-node (string= (org-id-get) org-index-id)))
915 (defun org-index--parse-table ()
916 "Parse content of index table."
918 (let (ref-field
919 id-field
920 initial-point
921 end-of-headings
922 start-of-headings)
924 (with-current-buffer org-index--buffer
926 (setq org-index--maxref 0)
927 (setq initial-point (point))
929 (org-index--go-below-hline)
931 ;; align and fontify table once for this emacs session
932 (unless org-index--aligned
933 (org-table-align) ; needs to happen before fontification to be effective ?
934 (let ((is-modified (buffer-modified-p))
935 (below (point)))
936 (while (org-at-table-p)
937 (forward-line))
938 (font-lock-fontify-region below (point))
939 (org-index--go-below-hline)
940 (setq org-index--aligned t)
941 (set-buffer-modified-p is-modified)))
943 (org-index--go-below-hline)
944 (setq org-index--below-hline (point-marker))
945 (beginning-of-line)
947 ;; get headings to display during occur
948 (setq end-of-headings (point))
949 (while (org-at-table-p) (forward-line -1))
950 (forward-line)
951 (setq start-of-headings (point))
952 (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
954 ;; count columns
955 (org-table-goto-column 100)
956 (setq org-index--numcols (- (org-table-current-column) 1))
958 ;; go to top of table
959 (while (org-at-table-p)
960 (forward-line -1))
961 (forward-line)
963 ;; parse line of headings
964 (org-index--parse-headings)
966 ;; parse list of flags
967 (goto-char org-index--point)
968 (org-index--parse-flags)
970 ;; Retrieve any decorations around the number within the first nonempty ref-field
971 (goto-char org-index--below-hline)
972 (while (and (org-at-table-p)
973 (not (setq ref-field (org-index--get-or-set-field 'ref))))
974 (forward-line))
976 ;; Some Checking
977 (unless ref-field
978 (org-index--report-index-error "Reference column is empty"))
980 (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
981 (org-index--report-index-error
982 "First reference in index table ('%s') does not contain a number" ref-field))
984 ;; These are the decorations used within the first ref of index
985 (setq org-index--head (match-string 1 ref-field))
986 (setq org-index--tail (match-string 3 ref-field))
987 (setq org-index--ref-regex (concat (regexp-quote org-index--head)
988 "\\([0-9]+\\)"
989 (regexp-quote org-index--tail)))
990 (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
992 ;; Go through table to find maximum number and do some checking
993 (let ((ref 0))
995 (while (org-at-table-p)
997 (setq ref-field (org-index--get-or-set-field 'ref))
998 (setq id-field (org-index--get-or-set-field 'id))
1000 (when (and (not ref-field)
1001 (not id-field))
1002 (kill-whole-line)
1003 (message "Removing line from index-table with both ref and id empty"))
1005 (if ref-field
1006 (if (string-match org-index--ref-regex ref-field)
1007 ;; grab number
1008 (setq ref (string-to-number (match-string 1 ref-field)))
1009 (kill-whole-line)
1010 (message "Removing line from index-table whose ref does not contain a number")))
1012 ;; check, if higher ref
1013 (if (> ref org-index--maxref) (setq org-index--maxref ref))
1015 (forward-line 1)))
1017 ;; go back to initial position
1018 (goto-char initial-point))))
1021 (defun org-index--do-maintain ()
1022 "Choose among and perform some tasks to maintain index."
1023 (let ((check-what) (max-mini-window-height 1.0) message-text)
1024 (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 (any column)\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")))
1025 (message nil)
1027 (cond
1028 ((eq check-what 'check)
1029 (setq message-text (or (org-index--check-ids)
1030 "No problems found")))
1032 ((eq check-what 'statistics)
1033 (setq message-text (org-index--do-statistics)))
1035 ((eq check-what 'duplicates)
1036 (setq message-text "Finding duplcates can be done by sorting your index appropriately: Choose 'group-by' and select a column; rows will then be sorted together, if they have the same value within the coosen column."))
1038 ((eq check-what 'clean)
1039 (let ((lines 0))
1040 (org-map-entries
1041 (lambda ()
1042 (when (org-entry-get (point) "org-index-ref")
1043 (incf lines)
1044 (org-entry-delete (point) "org-index-ref")))
1045 nil 'agenda)
1046 (setq message-text (format "Removed property 'org-index-ref' from %d lines" lines))))
1048 ((eq check-what 'update)
1049 (if (and (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 doing `add' from within your index. Are you sure to proceed for ALL index lines ? ")
1050 (or (not (or (org-index--flag-p 'edit-on-add (org-index--special-column 'get-heading-on-add))
1051 (org-index--flag-p 'edit-on-add (org-index--special-column 'get-category-on-add))))
1052 (y-or-n-p "If you did any editing of keyowrds or category while adding lines to your index before, these edits will now get lost. Do you still want to proceed ? ")))
1053 (setq message-text (org-index--update-all-lines))
1054 (setq message-text "Canceled."))))
1055 message-text))
1058 (defun org-index--do-sort-index (sort &optional groups)
1059 "Sort index table according to SORT, optinally with GROUPS."
1061 (let ((is-modified (buffer-modified-p))
1063 bottom
1064 ref-field
1065 count-field)
1067 (unless buffer-read-only
1069 (message "Sorting table for %s..." (symbol-name sort))
1070 (undo-boundary)
1072 (let ((message-log-max nil)) ; we have just issued a message, dont need those of sort-subr
1074 ;; get boundaries of table
1075 (goto-char org-index--below-hline)
1076 (forward-line 0)
1077 (setq top (point))
1078 (while (org-at-table-p) (forward-line))
1080 ;; kill all empty rows at bottom
1081 (while (progn
1082 (forward-line -1)
1083 (org-table-goto-column 1)
1084 (and
1085 (not (org-index--get-or-set-field 'ref))
1086 (not (org-index--get-or-set-field 'id))))
1087 (org-table-kill-row))
1088 (forward-line 1)
1089 (setq bottom (point))
1091 ;; sort lines
1092 (save-restriction
1093 (narrow-to-region top bottom)
1094 (goto-char top)
1095 (sort-subr t
1096 'forward-line
1097 'end-of-line
1098 (lambda ()
1099 (concat
1100 (if groups
1101 (format "%06d-" (cdr (assoc (org-index--get-or-set-field sort) groups)))
1103 (org-index--get-sort-key sort t)))
1105 'string<)
1106 (goto-char (point-min))
1108 ;; restore modification state
1109 (set-buffer-modified-p is-modified)))
1111 (setq org-index--last-sort sort))))
1114 (defun org-index--collect-sort-groups (sort)
1115 "Collect groups to SORT for."
1116 (let ((count-groups 0) (count-lines 0)
1117 groups key key-value)
1119 (org-index--on
1120 nil nil
1121 (while (org-at-table-p)
1122 (setq key (org-index--get-or-set-field sort))
1123 (setq key-value (assoc key groups))
1124 (if key-value
1125 (progn
1126 (incf (cdr key-value)))
1127 (setq groups (cons (cons key 1) groups)))
1128 (forward-line)))
1130 (mapc (lambda (x) (when (> (cdr x) 1)
1131 (incf count-groups)
1132 (incf count-lines (cdr x))))
1133 groups)
1135 (list groups count-groups count-lines)))
1138 (defun org-index--do-sort-lines (what)
1139 "Sort lines in WHAT according to contained reference."
1140 (save-restriction
1141 (cond
1142 ((eq what 'region)
1143 (if (region-active-p)
1144 (narrow-to-region (region-beginning) (region-end))
1145 (error "No active region, cannot sort")))
1146 ((eq what 'buffer)
1147 (unless (y-or-n-p "Sort whole current buffer ? ")
1148 (error "Canceled"))
1149 (narrow-to-region (point-min) (point-max))))
1151 (goto-char (point-min))
1152 (sort-subr nil 'forward-line 'end-of-line
1153 (lambda ()
1154 (if (looking-at (concat ".*"
1155 (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
1156 (string-to-number (match-string 1))
1157 0)))))
1160 (defun org-index--go-below-hline ()
1161 "Move below hline in index-table."
1163 (let ((count 0)
1164 (errstring (format "index table within node %s" org-index-id)))
1166 (goto-char org-index--point)
1168 ;; go to heading of node
1169 (while (not (org-at-heading-p)) (forward-line -1))
1170 (forward-line 1)
1172 ;; go to first table, but make sure we do not get into another node
1173 (while (and (not (org-at-table-p))
1174 (not (org-at-heading-p))
1175 (not (eobp)))
1176 (forward-line))
1178 ;; check, if there really is a table
1179 (unless (org-at-table-p)
1180 (org-index--create-missing-index "Cannot find %s." errstring))
1182 ;; go just after hline
1183 (while (and (not (org-at-table-hline-p))
1184 (org-at-table-p))
1185 (forward-line))
1186 (forward-line)
1188 ;; and check
1189 (unless (org-at-table-p)
1190 (org-index--report-index-error "Cannot find a hline within %s" errstring))
1192 (org-table-goto-column 1)))
1195 (defun org-index--parse-headings ()
1196 "Parse headings of index table."
1198 (let (field ;; field content
1199 field-symbol ;; and as a symbol
1200 found)
1202 (setq org-index--columns nil)
1204 ;; For each column
1205 (dotimes (col org-index--numcols)
1207 (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
1209 (if (string= field "")
1210 (error "Heading of column cannot be empty"))
1211 (if (and (not (string= (substring field 0 1) "."))
1212 (not (member (intern field) org-index--valid-headings)))
1214 (if (string= field "link")
1215 ;; Ask user to migrate his index to new version (since [2015-02-11 Mi])
1216 (progn
1217 ;; pop to index buffer
1218 (pop-to-buffer-same-window org-index--buffer)
1219 (goto-char org-index--below-hline)
1220 (org-reveal t)
1221 ;; go to column
1222 (while (org-at-table-p)
1223 (forward-line -1))
1224 (forward-line)
1225 (org-table-goto-column (+ 1 col))
1226 (error "Column 'link' should be named 'id' with recent versions of org-index,\nplease adjust your table (cursor is already positioned right)"))
1227 (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field)))
1229 (setq field-symbol (intern field))
1231 ;; check if heading has already appeared
1232 (if (assoc field-symbol org-index--columns)
1233 (org-index--report-index-error
1234 "'%s' appears two times as column heading" (downcase field))
1235 ;; add it to list at front, reverse later
1236 (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
1238 (setq org-index--columns (reverse org-index--columns))
1240 ;; check if all necessary headings have appeared
1241 (mapc (lambda (head)
1242 (unless (cdr (assoc head org-index--columns))
1243 (org-index--report-index-error "No column has heading '%s'" head)))
1244 org-index--required-headings))
1247 (defun org-index--parse-flags ()
1248 "Parse list of flags in index table."
1250 (let (parent parent-is-comment child)
1252 ;; reset configuration variables
1253 (setq org-index--special-columns nil)
1254 (setq org-index--flagged-columns nil)
1256 (org-index--goto-list "columns-and-flags" t)
1257 (forward-line 1)
1259 ;; outer loop over columns
1260 (while (and (setq parent (org-index--parse-list-item))
1261 parent
1262 (> (cdr (assoc :indent parent)) 0))
1264 (setq parent-is-comment (member (cdr (assoc :text parent)) '("all-columns-explained" "all-flags-explained")))
1266 ;; check, that we have a valid heading
1267 (unless (or parent-is-comment
1268 (assoc (cdr (assoc :sym parent)) org-index--columns))
1269 (when (string= "link" (cdr (assoc :text parent)))
1270 (pop-to-buffer-same-window org-index--buffer)
1271 (org-reveal t)
1272 (error "Flag 'link' should be named 'id' with recent versions of org-index,\nplease adjust this flag (cursor is already positioned right)"))
1273 (org-index--report-index-error "'%s' appears within flags, but not as a index column. " (cdr (assoc :text parent))))
1275 ;; inner loop over children
1276 (while (and (forward-line 1)
1277 (setq child (org-index--parse-list-item))
1278 child
1279 (> (cdr (assoc :indent child))
1280 (cdr (assoc :indent parent))))
1282 (unless parent-is-comment
1283 ;; check, that we have a valid flag
1284 (unless (memq (cdr (assoc :sym child)) org-index--all-flags)
1285 (org-index--report-index-error "'%s' is not a valid flag" (cdr (assoc :text child))))
1287 ;; process flag with respect to current index-column
1288 (if (memq (cdr (assoc :sym child)) org-index--single-flags)
1289 ;; Check, that none of org-index--single-flags appears twice
1290 (if (assoc (cdr (assoc :sym child)) org-index--special-columns)
1291 (org-index--report-index-error
1292 "More than one column is marked with flag '%s'" (cdr (assoc :text child)))
1293 ;; add it to list
1294 (setq org-index--special-columns (cons (cons (cdr (assoc :sym child)) (cdr (assoc :sym parent)))
1295 org-index--special-columns))))
1297 ;; all flags are stored in org-index--flagged-columns
1298 (let ((l (assoc (cdr (assoc :sym child)) org-index--flagged-columns))) ;; list of flag and columns, that carry this flag
1299 (unless l
1300 ;; no list of columns with this flag is present, create one
1301 (setq org-index--flagged-columns
1302 (cons (cons (cdr (assoc :sym child)) nil)
1303 org-index--flagged-columns))
1304 (setq l (car org-index--flagged-columns)))
1305 ;; prepend this column to list of columns with this flag
1306 (setcdr l (cons (cdr (assoc :sym parent)) (cdr l)))))))
1308 ;; check, that all needed flags have been specified
1309 (mapc (lambda (x)
1310 (unless (assoc x org-index--special-columns)
1311 (org-index--report-index-error "Required flag '%s' does not appear" (substring (symbol-name x) 1))))
1312 org-index--required-flags)))
1315 (defun org-index--goto-list (name &optional required non-top)
1316 "Goto list NAME (maybe NON-TOP Level) in index node, err if REQUIRED list is not present."
1317 (goto-char org-index--point)
1319 ;; go to heading of node
1320 (while (not (org-at-heading-p)) (forward-line -1))
1321 (forward-line 1)
1323 ;; go to named list
1324 (while (and (not (let ((item (org-index--parse-list-item)))
1325 (if item
1326 (and (or non-top (= (cdr (assoc :indent item)) 0)) ;; accept only toplevel ?
1327 (string= (cdr (assoc :text item)) name)) ;; with requested name
1328 nil)))
1329 (not (org-at-table-p))
1330 (not (org-at-heading-p))
1331 (not (eobp)))
1332 (forward-line 1))
1334 (if (org-at-item-p)
1336 (if required
1337 (org-index--report-index-error "Could not find required list '%s'" name)
1338 nil)))
1341 (defun org-index--parse-list-item ()
1342 "Parse a list item into an assoc array (indent, checkbox, text, value)."
1344 ;; matche full list-item, maybe with checkbox and double-colon
1345 (if (looking-at org-list-full-item-re)
1347 ;; retrieve interesting parts of list item from match data
1348 (let (indent checkbox text value next-line)
1350 (setq indent
1351 (- (save-excursion (goto-char (match-beginning 1)) (current-column)) ; first column
1352 (save-match-data (org-current-level)) ; indent-level
1354 (setq checkbox (match-string 3))
1355 (setq text (match-string 4))
1356 (set (if text 'value 'text) (buffer-substring (match-end 0) (line-end-position))) ; regexp did not capture this
1358 ;; peek ahead, if item continues on next line
1359 (forward-line 1)
1360 (if (looking-at org-list-full-item-re)
1361 (forward-line -1) ; already at next item; go back
1362 (setq next-line (buffer-substring (line-beginning-position) (line-end-position))))
1364 ;; clean up strings
1365 (mapc (lambda (x)
1366 (if (stringp (symbol-value x))
1367 (set x (org-trim (substring-no-properties (symbol-value x))))))
1368 '(text value next-line))
1370 (if next-line (setq text (concat text " " next-line))) ; append next line if
1372 (list (cons :indent indent) (cons :text text) (cons :value value) (cons :sym (intern text))))
1373 nil))
1376 (defun org-index--create-missing-index (&rest reasons)
1377 "Create a new empty index table with detailed explanation. Argument REASONS explains why."
1379 (org-index--ask-before-create-index "Cannot find your index table: "
1380 "new permanent" "."
1381 reasons)
1382 (org-index--create-index))
1385 (defun org-index--report-index-error (&rest reasons)
1386 "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
1388 (when org-index--buffer
1389 (pop-to-buffer-same-window org-index--buffer)
1390 (goto-char org-index--below-hline)
1391 (org-reveal t))
1392 (org-index--ask-before-create-index "The existing index contains this error: "
1393 "temporary" ", to compare with."
1394 reasons)
1395 (org-index--create-index t t))
1398 (defun org-index--ask-before-create-index (explanation type for-what reasons)
1399 ; checkdoc-params: (explanation type for-what reasons)
1400 "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
1401 (let (reason prompt)
1403 (setq reason (apply 'format reasons))
1405 (setq prompt (concat explanation reason "\n\n"
1406 "However, this assistant can help you to create a "
1407 type " index with detailed comments" for-what "\n\n"
1408 "Do you want to proceed ?"))
1410 (unless (let ((max-mini-window-height 1.0))
1411 (y-or-n-p prompt))
1412 (error (concat explanation reason)))))
1415 (defun org-index--create-index (&optional temporary compare)
1416 "Create a new empty index table with detailed explanation.
1417 specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
1418 (let (buffer
1419 title
1420 firstref
1423 (if temporary
1424 (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
1425 (buffer-name "*org-index-example-index*"))
1426 (setq buffer (get-buffer-create buffer-name))
1427 (with-current-buffer buffer
1428 ;; but it needs a file for its index to be found
1429 (unless (string= (buffer-file-name) file-name)
1430 (set-visited-file-name file-name))
1431 (rename-buffer buffer-name) ; name is change by line above
1433 (erase-buffer)
1434 (org-mode)))
1436 (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))))))
1438 (setq title (read-from-minibuffer "Please enter the title of the index node: "))
1440 (while (progn
1441 (setq firstref (read-from-minibuffer "Please enter your first reference-number. This is a number preceeded by some non-digit chars and optionally followed by some more non-digit 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 to frequently within your existing notes, to avoid too many false hits when searching.\n\nPlease choose: "))
1442 (let (desc)
1443 (when (string-match "[[:blank:]]" firstref)
1444 (setq desc "Contains whitespace"))
1445 (when (string-match "[[:cntrl:]]" firstref)
1446 (setq desc "Contains control characters"))
1447 (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
1448 ;; firstref not okay, report details
1449 (setq desc
1450 (cond ((string= firstref "") "is empty")
1451 ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
1452 ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
1453 ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
1456 (if desc
1457 (progn
1458 (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
1460 nil))))
1462 (with-current-buffer buffer
1463 (goto-char (point-max))
1464 (insert (format "* %s %s\n" firstref title))
1465 (if temporary
1466 (insert "
1467 Below you find your temporary index table, which WILL NOT LAST LONGER
1468 THAN YOUR CURRENT EMACS SESSION.
1470 (insert "
1471 Below you find your initial index table, which will grow over time.
1473 (insert "
1474 You may start using it by adding some lines. Just move to
1475 another heading, invoke `org-index' and choose the command
1476 'add'. After adding a few nodes, try the command 'occur'
1477 to search among them.
1479 To gain further insight you may invoke the subcommand 'help', or
1480 read the description of `org-index'.
1482 Within the index table below, dhe sequence of columns does not
1483 matter. You may reorder them in any way you please. Columns are
1484 found by their heading. You may also add your own columns,
1485 which should start with a dot (e.g. '.custom').
1487 Following this explanations you will find the item-list
1488 `columns-and-flags', which influences the behaviour of
1489 `org-index'. See the explanations which are part of this list.
1491 This node needs not be a top level node; its name is completely
1492 at your choice; it is found through its ID only.
1494 (unless temporary
1495 (insert "
1496 Remark: These lines of explanation can be removed at any time.
1499 (setq id (org-id-get-create))
1500 (insert (format "
1504 | ref | category | keywords | count | last-accessed | created | id |
1505 | | | | | | | <4> |
1506 |-----+-----------+----------+-------+---------------+---------+------|
1507 | %s | | %s | | | %s | %s |
1510 org-index--sample-flags
1511 firstref
1512 "This node"
1513 (with-temp-buffer (org-insert-time-stamp nil nil t))
1514 id))
1516 ;; make sure, that node can be found
1517 (org-id-add-location id (buffer-file-name))
1518 (setq buffer-save-without-query t)
1519 (basic-save-buffer)
1521 (while (not (org-at-table-p)) (forward-line -1))
1522 (unless buffer-read-only (org-table-align))
1523 (while (not (org-at-heading-p)) (forward-line -1))
1525 ;; read back some info about new index
1526 (let ((org-index-id id))
1527 (org-index--verify-id))
1529 ;; remember at least for this session
1530 (setq org-index-id id)
1532 ;; present results to user
1533 (if temporary
1534 (progn
1535 ;; Present existing and temporary index together
1536 (when compare
1537 (pop-to-buffer-same-window org-index--buffer)
1538 (goto-char org-index--point)
1539 (org-index--unfold-buffer)
1540 (delete-other-windows)
1541 (select-window (split-window-vertically)))
1542 ;; show new index
1543 (pop-to-buffer-same-window buffer)
1544 (org-id-goto id)
1545 (org-index--unfold-buffer)
1546 (if compare
1547 (error "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
1548 (message "This is your new temporary index.")))
1549 (progn
1550 ;; Only show the new index
1551 (pop-to-buffer-same-window buffer)
1552 (delete-other-windows)
1553 (org-id-goto id)
1554 (org-index--unfold-buffer)
1555 (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 ? ")
1556 (progn
1557 (customize-save-variable 'org-index-id id)
1558 (error "Saved org-index-id '%s' to %s" id (or custom-file
1559 user-init-file)))
1560 (let (sq)
1561 (setq sq (format "(setq org-index-id \"%s\")" id))
1562 (kill-new sq)
1563 (error "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))))))))
1566 (defun org-index--unfold-buffer ()
1567 "Helper function to unfold buffer."
1568 (org-show-context)
1569 (org-show-subtree)
1570 (recenter 1)
1571 (save-excursion
1572 (org-back-to-heading)
1573 (forward-line) ;; on property drawer
1574 (org-cycle)
1575 (org-index--goto-list "columns-and-flags")
1576 (org-cycle)))
1579 (defun org-index--update-line (&optional ref-or-id)
1580 "Update columns count and last-accessed in line REF-OR-ID."
1582 (let ((newcount 0)
1583 initial)
1585 (with-current-buffer org-index--buffer
1586 (unless buffer-read-only
1588 ;; search reference or id, if given (or assume, that we are already positioned right)
1589 (when ref-or-id
1590 (setq initial (point))
1591 (goto-char org-index--below-hline)
1592 (while (and (org-at-table-p)
1593 (not (or (string= ref-or-id (org-index--get-or-set-field 'ref))
1594 (string= ref-or-id (org-index--get-or-set-field 'id)))))
1595 (forward-line)))
1597 (if (not (org-at-table-p))
1598 (error "Did not find reference or id '%s'" ref-or-id)
1599 (org-index--update-current-line))
1601 (if initial (goto-char initial))))))
1604 (defun org-index--update-current-line ()
1605 "Update current lines columns count and last-accessed."
1606 (let (newcount (count-field (org-index--get-or-set-field 'count)))
1608 ;; update count field only if number or empty
1609 (when (or (not count-field)
1610 (string-match "^[0-9]+$" count-field))
1611 (setq newcount (+ 1 (string-to-number (or count-field "0"))))
1612 (org-index--get-or-set-field 'count
1613 (number-to-string newcount)))
1615 ;; update timestamp
1616 (org-table-goto-column (org-index--column-num 'last-accessed))
1617 (org-table-blank-field)
1618 (org-insert-time-stamp nil t t)
1620 ;; move line according to new content
1621 (org-index--promote-current-line)))
1624 (defun org-index--promote-current-line ()
1625 "Move current line up in table according to changed sort fields."
1626 (let (begin end key
1627 (to-skip 0))
1629 (forward-line 0) ; stay at beginning of line
1631 (setq key (org-index--get-sort-key))
1632 (setq begin (point))
1633 (setq end (line-beginning-position 2))
1635 (forward-line -1)
1636 (while (and (org-at-table-p)
1637 (not (org-at-table-hline-p))
1638 (string< (org-index--get-sort-key) key))
1640 (incf to-skip)
1641 (forward-line -1))
1642 (forward-line 1)
1644 ;; insert line at new position
1645 (when (> to-skip 0)
1646 (insert (delete-and-extract-region begin end))
1647 (forward-line -1))))
1650 (defun org-index--get-sort-key (&optional sort with-ref)
1651 "Get value for sorting from column SORT, optional WITH-REF."
1652 (let (ref
1653 ref-field
1654 key)
1656 (unless sort (setq sort org-index--last-sort)) ; use default value
1658 (when (or with-ref
1659 (eq sort 'ref))
1660 ;; get reference with leading zeroes, so it can be
1661 ;; sorted as text
1662 (setq ref-field (org-index--get-or-set-field 'ref))
1663 (string-match org-index--ref-regex ref-field)
1664 (setq ref (format
1665 "%06d"
1666 (string-to-number
1667 (or (match-string 1 ref-field)
1668 "0")))))
1670 (setq key
1671 (cond
1672 ((eq sort 'count)
1673 (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))
1674 ((eq sort 'ref)
1675 ref)
1676 ((eq sort 'id)
1677 (org-index--get-or-set-field sort))
1678 ((eq sort 'last-accessed)
1679 (org-index--get-or-set-field sort))
1680 ((eq sort 'created)
1681 (org-index--get-or-set-field sort))
1682 (t (error "This is a bug: unmatched case '%s'" sort))))
1684 (if with-ref (setq key (concat key ref)))
1686 key))
1689 (defun org-index--get-or-set-field (key &optional value)
1690 "Retrieve field KEY from index table or set it to VALUE."
1691 (let (field)
1692 (save-excursion
1693 (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value)))
1694 (if (string= field "") (setq field nil))
1696 (org-no-properties field))))
1699 (defun org-index--column-num (key)
1700 "Return number of column KEY."
1701 (if (numberp key)
1703 (cdr (assoc key org-index--columns))))
1706 (defun org-index--special-column (key)
1707 "Return column (not a number) for special column KEY."
1708 (cdr (assoc key org-index--special-columns)))
1711 (defun org-index--flag-p (flag column)
1712 "Check if COLUMN has FLAG set."
1713 (unless (memq flag org-index--all-flags)
1714 (error (format "Internal error: unknown flag %s" (symbol-name flag))))
1715 (memq column (assoc flag org-index--flagged-columns)))
1718 (defun org-index--make-guarded-search (ref &optional dont-quote)
1719 "Make robust search string from REF; DONT-QUOTE it, if requested."
1720 (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
1723 (defun org-index--do-statistics ()
1724 "Compute statistics about index table."
1725 (let ((total 0)
1726 ref-field ref min max message)
1729 ;; go through table and remove all refs, that we see
1730 (goto-char org-index--below-hline)
1731 (while (org-at-table-p)
1733 ;; get ref-field and number
1734 (setq ref-field (org-index--get-or-set-field 'ref))
1735 (if (and ref-field
1736 (string-match org-index--ref-regex ref-field))
1737 (setq ref (string-to-number (match-string 1 ref-field))))
1739 ;; record min and max
1740 (if (or (not min) (< ref min)) (setq min ref))
1741 (if (or (not max) (> ref max)) (setq max ref))
1743 ;; count
1744 (setq total (1+ total))
1746 (forward-line))
1748 (setq message (format "First reference is %s, last %s; %d values in between, %d of them are used (%d percent)"
1749 (format org-index--ref-format min)
1750 (format org-index--ref-format max)
1751 (1+ (- max min))
1752 total
1753 (truncate (* 100 (/ (float total) (1+ (- max min)))))
1757 (goto-char org-index--below-hline)
1758 message))
1761 (defun org-index--do-add-or-update ()
1762 "For current node or current line in index, add a new line to index table or update existing."
1764 (let* (id ref args yank ref-and-yank)
1766 ;; do the same things from within index and from outside
1767 (if org-index--within-node
1769 (progn
1770 (unless (org-at-table-p)
1771 (error "Within index node but not on table"))
1773 (setq id (org-index--get-or-set-field 'id))
1774 (setq ref (org-index--get-or-set-field 'ref))
1775 (setq args (org-index--collect-values-for-add-update-remote id))
1776 (org-index--write-fields-for-add-update args)
1777 (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add)))
1779 (cons (format "Updated index line %s" ref) yank))
1781 (unless (org-at-heading-p)
1782 (error "Not at headline"))
1784 (setq id (org-id-get-create))
1785 (setq ref (org-index--on 'id id (org-index--get-or-set-field 'ref)))
1786 (setq args (org-index--collect-values-for-add-update id ref))
1788 (if ref
1789 ;; already have a ref, find it in index and update fields
1790 (let ((kvs args)
1791 found-and-message)
1793 (org-index--on
1794 'ref ref
1795 (org-index--write-fields-for-add-update args)
1796 (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add))))
1798 (cons (format "Updated index line %s" ref) yank))
1800 ;; no ref here, create new line in index
1801 (setq ref-and-yank (apply 'org-index--do-new-line args))
1803 (cons (format "Added index line %s" (car ref-and-yank)) (cdr ref-and-yank))))))
1806 (defun org-index--check-ids ()
1807 "Check, that ids really point to a node."
1809 (let ((lines 0)
1810 id ids marker)
1812 (goto-char org-index--below-hline)
1814 (catch 'problem
1815 (while (org-at-table-p)
1817 (when (setq id (org-index--get-or-set-field 'id))
1819 ;; check for double ids
1820 (when (member id ids)
1821 (org-table-goto-column (org-index--column-num 'id))
1822 (throw 'problem "This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
1823 (incf lines)
1824 (setq ids (cons id ids))
1826 ;; check, if id is valid
1827 (setq marker (org-id-find id t))
1828 (unless marker
1829 (org-table-goto-column (org-index--column-num 'id))
1830 (throw 'problem "This id cannot be found")))
1832 (forward-line))
1834 (goto-char org-index--below-hline)
1835 nil)))
1838 (defun org-index--update-all-lines ()
1839 "Update all lines of index at once."
1841 (let ((lines 0)
1842 id ref kvs)
1844 ;; check for double ids
1846 (org-index--check-ids)
1848 (progn
1849 (goto-char org-index--below-hline)
1850 (while (org-at-table-p)
1852 ;; update single line
1853 (when (setq id (org-index--get-or-set-field 'id))
1854 (setq ref (org-index--get-or-set-field 'ref))
1855 (setq kvs (org-index--collect-values-for-add-update-remote id))
1856 (org-index--write-fields-for-add-update kvs)
1857 (incf lines))
1858 (forward-line))
1860 (goto-char org-index--below-hline)
1861 (org-table-align)
1862 (format "Updated %d lines" lines)))))
1865 (defun org-index--collect-values-for-add-update (id &optional silent category)
1866 "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
1868 (let ((args (list 'ref t 'id id))
1869 content)
1871 (dolist (col-num org-index--columns)
1873 (setq content "")
1875 ;; copy heading ?
1876 (if (org-index--flag-p 'get-heading-on-add (car col-num))
1877 (setq content (nth 4 (org-heading-components))))
1879 ;; copy category ?
1880 (if (org-index--flag-p 'get-category-on-add (car col-num))
1881 (setq content (or category org-index--category-before)))
1883 ;; Shift ref and timestamp ?
1884 (if (org-index--flag-p 'shift-ref-and-date-on-add (car col-num))
1885 (dotimes (i 2)
1886 (if (or (string-match (concat "^\\s-*" org-index--ref-regex) content)
1887 (string-match (concat org-ts-regexp-both) content))
1888 (setq content (substring content (match-end 0))))))
1890 (if (and (not silent) ; do not edit, if heading has already been added
1891 (org-index--flag-p 'edit-on-add (car col-num)))
1892 (setq content (read-from-minibuffer
1893 (format "Edit text for column '%s': " (symbol-name (car col-num)))
1894 content)))
1896 (if (not (string= content ""))
1897 (setq args (append (list (car col-num) content) args))))
1898 args))
1901 (defun org-index--collect-values-for-add-update-remote (id)
1902 "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
1904 (let (marker point args)
1906 (setq marker (org-id-find id t))
1907 ;; enter buffer and collect information
1908 (with-current-buffer (marker-buffer marker)
1909 (setq point (point))
1910 (goto-char marker)
1911 (setq args (org-index--collect-values-for-add-update id t (org-get-category)))
1912 (goto-char point))
1914 args))
1917 (defun org-index--write-fields-for-add-update (kvs)
1918 "Update current line with values from KVS (keys-values)."
1919 (while kvs
1920 (unless (eq (car kvs) 'ref)
1921 (org-index--get-or-set-field (car kvs) (org-trim (cadr kvs))))
1922 (setq kvs (cddr kvs))))
1925 (defun org-index--do-delete ()
1926 "Perform command delete."
1928 (unless (org-at-heading-p)
1929 (error "Not at headline"))
1931 (let* ((id (org-entry-get (point) "ID"))
1932 (ref (org-index--ref-from-id id)))
1934 ;; maybe delete from heading
1935 (if ref
1936 (save-excursion
1937 (end-of-line)
1938 (let ((end (point)))
1939 (beginning-of-line)
1940 (when (search-forward ref end t)
1941 (delete-char (- (length ref)))
1942 (just-one-space)))))
1944 ;; delete from index table
1945 (if (org-index--delete-line id)
1946 (format "Deleted index line %s" ref)
1947 (format "Did not find id %s in index" id))))
1950 (defun org-index--go (&optional column value)
1951 "Position cursor on index line where COLUMN equals VALUE.
1952 Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
1953 (let (found text)
1955 (unless (eq (current-buffer) org-index--buffer)
1956 (error "This is a bug: Not in index buffer"))
1958 ;; loop over lines
1959 (goto-char org-index--below-hline)
1960 (if column
1961 (progn
1962 (forward-line -1)
1963 (while (and (not found)
1964 (forward-line)
1965 (org-at-table-p))
1966 (setq found (string= value (org-index--get-or-set-field column)))))
1967 (setq found t))
1969 ;; return value
1970 (if found
1972 (goto-char org-index--below-hline)
1973 nil)))
1976 (defun org-index--do-head (ref id &optional other)
1977 "Perform command head: Find node with REF or ID and present it.
1978 If OTHER in separate window."
1980 (setq org-index--last-ref ref)
1982 (let (message marker)
1984 (setq marker (org-id-find id t))
1986 (if marker
1987 (progn
1988 (org-index--update-line id)
1989 (let (cb)
1990 (if other
1991 (progn
1992 (setq cb (current-buffer))
1993 (pop-to-buffer (marker-buffer marker)))
1994 (pop-to-buffer-same-window (marker-buffer marker)))
1996 (goto-char marker)
1997 (org-reveal t)
1998 (org-show-entry)
1999 (recenter))
2000 (setq message (format "Found headline %s" ref)))
2001 (setq message (format "Did not find headline %s" ref)))))
2004 (defun org-index--do-occur ()
2005 "Perform command occur."
2006 (let ((word "") ; last word to search for growing and shrinking on keystrokes
2007 (prompt "Search for: ")
2008 (lines-wanted (window-body-height))
2009 (lines-found 0) ; number of lines found
2010 words ; list words that should match
2011 occur-buffer
2012 begin ; position of first line
2013 narrow ; start of narrowed buffer
2014 help-text ; cons with help text short and long
2015 key-help ; for keys with special function
2016 search-text ; description of text to search for
2017 done ; true, if loop is done
2018 in-c-backspace ; true, while processing C-backspace
2019 show-headings ; true, if headings should be shown
2020 help-overlay ; Overlay with help text
2021 last-point ; Last position before end of search
2022 key ; input from user
2023 key-sequence) ; as a sequence
2026 ;; make and show buffer
2027 (if (get-buffer org-index--occur-buffer-name)
2028 (kill-buffer org-index--occur-buffer-name))
2029 (setq occur-buffer (make-indirect-buffer org-index--buffer org-index--occur-buffer-name))
2030 (pop-to-buffer-same-window occur-buffer)
2031 ;; avoid modifying direct buffer
2032 (setq buffer-read-only t)
2033 (toggle-truncate-lines 1)
2034 (setq font-lock-keywords-case-fold-search t)
2035 (setq case-fold-search t)
2037 ;; reset stack and overlays
2038 (setq org-index--occur-stack nil)
2039 (setq org-index--occur-tail-overlay nil)
2041 ;; narrow to table rows and one line before
2042 (goto-char (marker-position org-index--below-hline))
2043 (forward-line 0)
2044 (setq begin (point))
2045 (forward-line -1)
2046 (setq narrow (point))
2047 (while (org-at-table-p)
2048 (forward-line))
2049 (narrow-to-region narrow (point))
2050 (goto-char (point-min))
2051 (forward-line)
2053 ;; initialize help text
2054 (setq help-text (cons
2055 "Incremental occur; `?' toggles help and headlines.\n"
2056 (concat
2057 (org-index--wrap
2058 (concat
2059 "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; all other keys end search.\n"))
2060 org-index--headings)))
2062 ;; insert overlays for help text and to cover unsearched lines
2063 (setq help-overlay (make-overlay (point-min) begin))
2064 (overlay-put help-overlay 'display (car help-text))
2065 (overlay-put help-overlay 'face 'org-agenda-dimmed-todo-face)
2066 (setq org-index--occur-tail-overlay (make-overlay (point-max) (point-max)))
2067 (overlay-put org-index--occur-tail-overlay 'invisible t)
2069 (while (not done)
2071 (if in-c-backspace
2072 (setq key "<backspace>")
2073 (setq search-text (mapconcat 'identity (reverse (cons word words)) ","))
2074 ;; read key
2075 (setq key-sequence
2076 (vector (read-key
2077 (format "%s%s%s"
2078 prompt
2079 search-text
2080 (if (string= search-text "") "" " ")))))
2081 (setq key (key-description key-sequence)))
2083 (cond
2086 ((string= key "<C-backspace>")
2087 (setq in-c-backspace t))
2090 ((member key (list "<backspace>" "DEL")) ; erase last char
2092 (if (= (length word) 0)
2094 ;; nothing more to delete from current word; try next
2095 (progn
2096 (setq word (car words))
2097 (setq words (cdr words))
2098 (setq in-c-backspace nil))
2100 ;; unhighlight longer match
2101 (unhighlight-regexp (regexp-quote word))
2103 ;; some chars are left; shorten word
2104 (setq word (substring word 0 -1))
2105 (when (= (length word) 0) ; when nothing left, use next word from list
2106 (setq word (car words))
2107 (setq words (cdr words))
2108 (setq in-c-backspace nil))
2110 ;; free top list of overlays and remove list
2111 (setq lines-found (or (org-index--unhide) lines-wanted))
2112 (move-overlay org-index--occur-tail-overlay
2113 (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
2114 (point-max))
2115 (point-max))
2118 ;; highlight shorter word
2119 (unless (= (length word) 0)
2120 (highlight-regexp (regexp-quote word) 'isearch))
2122 ;; make sure, point is still visible
2123 (goto-char begin)))
2126 ((member key (list "SPC" ",")) ; space or comma: enter an additional search word
2128 ;; push current word and clear, no need to change display
2129 (setq words (cons word words))
2130 (setq word ""))
2133 ((string= key "?") ; question mark: toggle display of headlines and help
2134 (setq help-text (cons (cdr help-text) (car help-text)))
2135 (overlay-put help-overlay 'display (car help-text)))
2137 ((and (= (length key) 1)
2138 (aref printable-chars (elt key 0))) ; any printable char: add to current search word
2140 ;; unhighlight short word
2141 (unless (= (length word) 0)
2142 (unhighlight-regexp (regexp-quote word)))
2144 ;; add to word
2145 (setq word (concat word key))
2147 ;; make overlays to hide lines, that do not match longer word any more
2148 (goto-char begin)
2149 (setq lines-found (org-index--hide-with-overlays (cons word words) lines-wanted))
2150 (move-overlay org-index--occur-tail-overlay
2151 (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
2152 (point-max))
2153 (point-max))
2155 (goto-char begin)
2157 ;; highlight longer word
2158 (highlight-regexp (regexp-quote word) 'isearch)
2160 ;; make sure, point is on a visible line
2161 (line-move -1 t)
2162 (line-move 1 t))
2164 ;; anything else terminates loop
2165 (t (setq done t))))
2167 ;; put back input event, that caused the loop to end
2168 (unless (string= key "C-g")
2169 (setq unread-command-events (listify-key-sequence key-sequence))
2170 (message key))
2172 ;; postprocessing
2173 (setq last-point (point))
2175 ;; For performance reasons do not show matching lines for rest of table. So no code here.
2177 ;; make permanent copy
2178 ;; copy visible lines
2179 (let ((lines-collected 0)
2180 keymap line all-lines end-of-head)
2182 (setq cursor-type t)
2183 (goto-char begin)
2185 ;; collect all visible lines
2186 (while (and (not (eobp))
2187 (< lines-collected lines-wanted))
2188 ;; skip over invisible lines
2189 (while (and (invisible-p (point))
2190 (not (eobp)))
2191 (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
2192 (setq line (buffer-substring (line-beginning-position) (line-end-position)))
2193 (unless (string= line "")
2194 (incf lines-collected)
2195 (setq all-lines (cons (concat line
2196 "\n")
2197 all-lines)))
2198 (forward-line 1))
2200 (kill-buffer org-index--occur-buffer-name) ; cannot keep this buffer; might become stale soon
2202 ;; create new buffer
2203 (setq occur-buffer (get-buffer-create org-index--occur-buffer-name))
2204 (pop-to-buffer-same-window occur-buffer)
2205 (insert org-index--headings)
2206 (setq end-of-head (point))
2208 ;; insert into new buffer
2209 (save-excursion
2210 (apply 'insert (reverse all-lines))
2211 (if (= lines-collected lines-wanted)
2212 (insert "\n(more lines omitted)\n")))
2214 (org-mode)
2215 (setq truncate-lines t)
2216 (if (org-at-table-p) (org-table-align))
2217 (font-lock-fontify-buffer)
2219 ;; prepare help text
2220 (setq org-index--occur-help-overlay (make-overlay (point-min) end-of-head))
2221 (setq org-index--occur-help-text
2222 (cons
2223 (org-index--wrap
2224 (concat "Search is done; `?' toggles help and headlines.\n"))
2225 (concat
2226 (org-index--wrap (format (concat "Search is done. "
2227 (if (< lines-collected lines-wanted)
2228 " Showing all %d matches for "
2229 " Showing one window of matches for ")
2230 "\"" search-text
2231 "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> to matching line in index, <space> increments count.\n" )
2232 (length all-lines)))
2233 org-index--headings)))
2235 (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))
2236 (overlay-put org-index--occur-help-overlay 'face 'org-agenda-dimmed-todo-face)
2238 ;; highlight words
2239 (setq case-fold-search t)
2240 (setq font-lock-keywords-case-fold-search t)
2241 (mapc (lambda (w) (unless (or (not w) (string= w "")) (highlight-regexp (regexp-quote w) 'isearch)))
2242 (cons word words))
2244 (setq buffer-read-only t)
2246 ;; install keyboard-shortcuts
2247 (setq keymap (make-sparse-keymap))
2248 (set-keymap-parent keymap org-mode-map)
2250 (mapc (lambda (x) (define-key keymap (kbd x)
2251 (lambda () (interactive)
2252 (message "%s" (org-index--occur-to-head)))))
2253 (list "<return>" "RET"))
2255 (define-key keymap (kbd "<tab>")
2256 (lambda () (interactive)
2257 (message (org-index--occur-to-head t))))
2259 (define-key keymap (kbd "SPC")
2260 (lambda () (interactive)
2261 ;; increment in index
2262 (let ((ref (org-index--get-or-set-field 'ref))
2263 count)
2264 (org-index--on
2265 'ref ref
2266 (setq count (+ 1 (string-to-number (org-index--get-or-set-field 'count))))
2267 (org-index--get-or-set-field 'count (number-to-string count))
2268 (org-index--promote-current-line))
2269 ;; increment in this buffer
2270 (let ((inhibit-read-only t))
2271 (org-index--get-or-set-field 'count (number-to-string count)))
2272 (message "Incremented count to %d" count))))
2274 (define-key keymap (kbd "<S-return>")
2275 (lambda () (interactive)
2276 (org-index 'enter (org-index--get-or-set-field 'ref))))
2278 (define-key keymap (kbd "?")
2279 (lambda () (interactive)
2280 (setq-local org-index--occur-help-text (cons (cdr org-index--occur-help-text) (car org-index--occur-help-text)))
2281 (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))))
2283 (use-local-map keymap))))
2286 (defun org-index--wrap (text)
2287 "Wrap TEXT at fill column."
2288 (with-temp-buffer
2289 (insert text)
2290 (fill-region (point-min) (point-max) nil t)
2291 (buffer-string)))
2294 (defun org-index--occur-to-head (&optional other)
2295 "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window."
2296 (let ((ref (org-index--get-or-set-field 'ref))
2297 (id (org-index--get-or-set-field 'id)))
2298 (org-mark-ring-push)
2299 (if id
2300 (org-index--do-head ref id other)
2301 (message "Current line has no id."))))
2304 (defun org-index--hide-with-overlays (words lines-wanted)
2305 "Hide text that is currently visible and does not match WORDS by creating overlays; leave LINES-WANTED lines visible."
2306 (let ((lines-found 0)
2307 (end-of-visible (point))
2308 overlay overlays start matched)
2310 ;; main loop
2311 (while (and (not (eobp))
2312 (< lines-found lines-wanted))
2314 ;; skip invisible lines
2315 (while (and (not (eobp))
2316 (and
2317 (invisible-p (point))
2318 (< (point) (overlay-start org-index--occur-tail-overlay))))
2319 (goto-char (overlay-end (car (overlays-at (point))))))
2321 ;; find stretch of lines, that are currently visible but should be invisible now
2322 (setq matched nil)
2323 (setq start (point))
2324 (while (and (not (eobp))
2325 (not
2326 (and
2327 (invisible-p (point))
2328 (< (point) (overlay-start org-index--occur-tail-overlay))))
2329 (not (and (org-index--test-words words)
2330 (setq matched t)))) ; for its side effect
2331 (forward-line 1))
2333 ;; create overlay to hide this stretch
2334 (when (< start (point)) ; avoid creating an empty overlay
2335 (setq overlay (make-overlay start (point)))
2336 (overlay-put overlay 'invisible t)
2337 (setq overlays (cons overlay overlays)))
2339 ;; skip and count line, that matched
2340 (when matched
2341 (forward-line 1)
2342 (setq end-of-visible (point))
2343 (incf lines-found)))
2345 ;; put new list on top of stack
2346 (setq org-index--occur-stack
2347 (cons (list (cons :overlays overlays)
2348 (cons :end-of-visible end-of-visible)
2349 (cons :lines lines-found))
2350 org-index--occur-stack))
2352 lines-found))
2355 (defun org-index--unhide ()
2356 "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
2357 (when org-index--occur-stack
2358 ;; delete overlays and make visible again
2359 (mapc (lambda (y)
2360 (delete-overlay y))
2361 (cdr (assoc :overlays (car org-index--occur-stack))))
2362 ;; remove from stack
2363 (setq org-index--occur-stack (cdr org-index--occur-stack))
2364 ;; return number of lines, that are now visible
2365 (if org-index--occur-stack (cdr (assoc :lines (car org-index--occur-stack))))))
2368 (defun org-index--test-words (words)
2369 "Test current line for match against WORDS."
2370 (let (line)
2371 (setq line (downcase (buffer-substring (line-beginning-position) (line-beginning-position 2))))
2372 (catch 'not-found
2373 (dolist (w words)
2374 (or (search w line)
2375 (throw 'not-found nil)))
2376 t)))
2379 (defun org-index--create-new-line ()
2380 "Do the common work for `org-index-new-line' and `org-index'."
2382 (let (new)
2384 ;; construct new reference
2385 (unless new
2386 (setq new (format "%s%d%s" org-index--head (1+ org-index--maxref) org-index--tail)))
2388 ;; insert ref or id as last or first line, depending on sort-column
2389 (goto-char org-index--below-hline)
2390 (if (eq (org-index--special-column 'sort) 'count)
2391 (progn
2392 (while (org-at-table-p)
2393 (forward-line))
2394 (forward-line -1)
2395 (org-table-insert-row t))
2396 (org-table-insert-row))
2398 ;; insert some of the standard values
2399 (org-table-goto-column (org-index--column-num 'created))
2400 (org-insert-time-stamp nil nil t)
2401 (org-table-goto-column (org-index--column-num 'count))
2402 (insert "1")
2404 new))
2407 (defun org-index--sort-silent ()
2408 "Sort index for default column to remove any effects of temporary sorting."
2409 (save-excursion
2410 (org-index--verify-id)
2411 (org-index--parse-table)
2412 (org-index--on nil nil
2413 (org-index--do-sort-index (org-index--special-column 'sort))
2414 (org-table-align)
2415 (remove-hook 'before-save-hook 'org-index--sort-silent))))
2418 (provide 'org-index)
2420 ;; Local Variables:
2421 ;; fill-column: 75
2422 ;; comment-column: 50
2423 ;; lexical-binding: t
2424 ;; End:
2426 ;;; org-index.el ends here