Use inactive timestamps when re-scheduling or re-deadlining
[org-mode/org-tableheadings.git] / contrib / lisp / org-index.el
blob26edc85a0509c1bf8cc792587d95ea530730ab80
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.2.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 ;; search 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-18 We] Version 4.2.1
77 ;; - No garbage in kill-ring
78 ;; - No recentering after add
80 ;; [2015-03-08 Su] Version 4.2.0
81 ;; - Reference numbers for subcommands can be passed as a prefix argument
82 ;; - Renamed subcommand 'point' to 'ping'
83 ;; - New variable org-index-default-keybindings-list with a list of
84 ;; default keybindings for org-index-default-keybindings
85 ;; - Added new column level
86 ;; - removed flags get-category-on-add and get-heading-on-add
88 ;; [2015-03-05 Th] Version 4.1.1 and 4.1.2
89 ;; - org-mark-ring is now used more consistently
90 ;; - Bugfix when going to a heading by ref
92 ;; [2015-02-26 Th] Version 4.0.0 and 4.1.0:
93 ;; - Removed command "leave"; rather go back with org-mark-ring-goto
94 ;; - Property "org-index-ref" is no longer used or needed
95 ;; - Renamed column "link" to "id"
96 ;; - Added maintainance options to find duplicate rows, to check ids,
97 ;; update index or remove property org-index-ref from nodes
98 ;; - New command point
99 ;; - Shortened versin history
101 ;; [2014-12-07 Sa] to [2015-01-31 Sa] Version 3.0.0 to 3.2.0:
102 ;; - Complete sorting of index only occurs in idle-timer
103 ;; - New command "maintain" with some subcommands
104 ;; - Rewrote command "occur" with overlays in an indirect buffer
105 ;; - introduced variable org-index-version
106 ;; - Command "add" updates index, if node is already present
107 ;; - New commands "add" and "delete" to easily add and remove
108 ;; the current node to or from your index.
109 ;; - New command "example" to create an example index.
110 ;; - Moved flags to a list within the same node as the index table;
111 ;; this breaks compatibility to prior versions of the package.
112 ;; - Several new flags that are explained within index node.
113 ;; - Removed commands "reuse", "missing", "put", "goto",
114 ;; "update", "link", "fill", "unhighlight"
115 ;; - New function `org-index-default-keybindings'
117 ;; [2012-12-07 Fr] to [2014-04-26 Sa] Version 2.0.0 to 2.4.3:
118 ;; - New functions org-index-new-line and org-index-get-line
119 ;; offer access to org-index from other lisp programs
120 ;; - Regression tests with ert
121 ;; - Renamed from "org-favtable" to "org-index"
122 ;; - Added an assistant to set up the index table
123 ;; - occur is now incremental, searching as you type
124 ;; - Integrated with org-mark-ring-goto
125 ;; - Added full support for ids
126 ;; - Renamed the package from "org-reftable" to "org-favtable"
127 ;; - Additional columns are required (e.g. "link"). Error messages will
128 ;; guide you
129 ;; - Ask user explicitly, which command to invoke
130 ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
132 ;; [2011-12-10 Sa] to [2012-09-22 Sa] Version Version 1.2.0 to 1.5.0:
133 ;; - New command "sort" to sort a buffer or region by reference number
134 ;; - New commands "highlight" and "unhighlight" to mark references
135 ;; - New command "head" to find a headline with a reference number
136 ;; - New commands occur and multi-occur
137 ;; - Started this Change Log
139 ;;; Code:
141 (require 'org-table)
142 (require 'cl)
144 (defcustom org-index-id nil
145 "Id of the Org-mode node, which contains the index table."
146 :group 'org
147 :group 'org-index)
149 ;; Version of this package
150 (defvar org-index-version "4.2.1" "Version of `org-index', format is major.minor.bugfix, where \"major\" is a change in index-table and \"minor\" are new features.")
152 ;; Variables to hold the configuration of the index table
153 (defvar org-index--maxref nil "Maximum number from reference table (e.g. '153').")
154 (defvar org-index--head nil "Any header before number (e.g. 'R').")
155 (defvar org-index--tail nil "Tail after number (e.g. '}' or ')'.")
156 (defvar org-index--numcols nil "Number of columns in index table.")
157 (defvar org-index--ref-regex nil "Regular expression to match a reference.")
158 (defvar org-index--ref-format nil "Format, that can print a reference.")
159 (defvar org-index--columns nil "Columns of index-table.")
160 (defvar org-index--special-columns nil "Columns with flags, that may appear only once.")
161 (defvar org-index--flagged-columns nil "Columns with flags, that may appear multiple times.")
162 (defvar org-index--buffer nil "Buffer of index table.")
163 (defvar org-index--point nil "Position at start of headline of index table.")
164 (defvar org-index--below-hline nil "Position of first cell in first line below hline.")
165 (defvar org-index--headings nil "Headlines of index-table as a string.")
166 (defvar org-index--headings-visible nil "Visible part of headlines of index-table as a string.")
167 (defvar org-index--keymap nil "Keymap for shortcuts for some commands of `org-index'. Filled and activated by `org-index-default-keybings'.")
169 ;; Variables to hold context and state
170 (defvar org-index--last-ref nil "Last reference created or visited.")
171 (defvar org-index--category-before nil "Category of node before.")
172 (defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
173 (defvar org-index--below-cursor nil "Word below cursor.")
174 (defvar org-index--within-node nil "True, if we are within node of the index table.")
175 (defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
176 (defvar org-index--occur-help-text nil "Text for help in occur buffer.")
177 (defvar org-index--occur-help-overlay nil "Overlay for help in occur buffer.")
178 (defvar org-index--occur-stack nil "Stack with overlays for hiding lines.")
179 (defvar org-index--occur-tail-overlay nil "Overlay to cover invisible lines.")
180 (defvar org-index--last-sort nil "Last column, the index has been sorted after.")
181 (defvar org-index--sort-timer nil "Timer to sort index in correct order.")
182 (defvar org-index--aligned nil "Remember for this Emacs session, if table has been aligned at least once.")
184 ;; static information for this program package
185 (defconst org-index--commands '(occur add delete head ping enter ref help example sort multi-occur highlight maintain) "List of commands available.")
186 (defconst org-index--required-flags '(sort) "Flags that are required.")
187 (defconst org-index--single-flags '(sort point-on-add yank-after-add shift-ref-and-date-on-add) "Flags, that may only appear once; these can appear as special-columns.")
188 (defconst org-index--multiple-flags '(edit-on-add) "Flags, that might appear multiple times.")
189 (defconst org-index--all-flags (append org-index--single-flags org-index--multiple-flags) "All flags.")
190 (defconst org-index--required-headings '(ref id created last-accessed count) "All required headings.")
191 (defconst org-index--valid-headings (append org-index--required-headings '(keywords category level)) "All valid headings.")
192 (defconst org-index--occur-buffer-name "*org-index-occur*" "Name of occur buffer.")
193 (defconst org-index--sort-idle-delay 300 "Delay in seconds after which buffer will sorted.")
194 (defvar org-index-default-keybindings-list '(("a" . 'add) ("i " . nil) ("o" . 'occur) ("a" . 'add) ("d" . 'delete) ("h" . 'head) ("e" . 'enter) ("p." . 'ping) ("r" . 'ref) ("?" . 'help)) "One-letter short cuts for selected subcommands of `org-index', put in effect by `org-index-default-keybindings'")
195 (defconst org-index--sample-flags
197 - columns-and-flags :: associate columns of index table with flags. Do not remove.
198 - ref
199 - yank-after-add
200 - category
201 - edit-on-add
202 - keywords
203 - edit-on-add
204 - point-on-add
205 - count
206 - sort
207 - last-accessed
208 - created
209 - id
210 - all-columns-explained :: All columns of the index table and their meaning.
211 - ref :: The reference number; will be generated automatically.
212 - id :: id of the node, that this line represents
213 - created :: When has this entry been created ?
214 - last-accessed :: When has this entry been accessed last ?
215 - count :: How many times has this entry been picked ?
216 - keywords :: Optional column, suggested to keep a list of keywords,
217 which may match your input during occur. While adding a line to your index,
218 this column will be filled with the nodes heading.
219 - category :: (optional) column to store the category of newly added nodes.
220 - level :: Nesting level of node
221 - Any name starting with a dot (`.') :: No predefined meaning,
222 depends on its flags.
223 - all-flags-explained :: All flags, that can be associated with columns.
224 - sort :: Sort whole table according to this column.
225 - yank-after-add :: This column will be yanked after picking this line during
226 occur.
227 - edit-on-add :: This field will be presented for editing, when adding
228 a new line to your index.
229 - point-on-add :: Point will land here, when adding a new line, e.g. with
230 command ref.
231 - shift-ref-and-date-on-add :: Remove leading reference and timestamp on add."
232 "A sample string of flags.")
235 (defmacro org-index--on (column value &rest body)
236 "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
237 The value returned is the value of the last form in BODY or nil,
238 if VALUE cannot be found."
239 (declare (indent 2) (debug t))
240 (let ((pointvar (make-symbol "point")) ; avoid clash with same-named variables in body
241 (foundvar (make-symbol "found"))
242 (retvar (make-symbol "ret")))
243 `(save-current-buffer
244 (set-buffer org-index--buffer)
245 (setq ,pointvar (point))
246 (setq ,foundvar nil)
247 (setq ,retvar nil)
249 (setq ,foundvar (org-index--go ,column ,value))
250 (when ,foundvar
251 (setq ,retvar (progn ,@body)))
253 (goto-char ,pointvar)
255 ,retvar)))
258 (defun org-index (&optional command search-ref arg)
259 "Fast search for selected org headings and things outside of org.
261 This package creates and updates an index table of headings or
262 keywords, references and ids, where each line points to a heading
263 within org or references something outside. This table is sorted by
264 usage count, so that frequently used lines appear among the first
265 search results.
267 References are essentially small numbers (e.g. 'R237' or '--455--'), as
268 created by this package; they are well suited to be used outside of
269 org, e.g. in folder names, issue trackers or on printed documents.
271 On first invocation `org-index' will guide you to create a dedicated node
272 for its index table and its configuration flags.
274 For basic usage, subcommands 'add' and 'occur' are most important.
276 This is version 4.2.1 of org-index.el.
277 \\<org-mode-map>
278 The function `org-index' operates on a dedicated table, the index
279 table, which lives within its own Org-mode node. The table and
280 its containing node will be created, when you first invoke
281 `org-index'. The node also contains a commented list, describing
282 the columns of the index table and their associated flags. The
283 node is found through its id, which is stored within the variable
284 `org-index-id'.
287 The function `org-index' is the only interactive function of this
288 package and its main entry point; it will present you with a list
289 of subcommands to choose from:
291 occur: Incremental search, that shows matching lines from the
292 index table. It is updated after every keystroke. You may
293 enter a list of words seperated by space or comma (`,'), to
294 select lines that contain all of the given words.
296 add: Add the current node to your index, so that it can be
297 found through the subcommand \"occur\". Update index,
298 if node has already been present.
300 delete: Delete the current node from your index.
302 head: Ask for a reference number and search for this heading.
304 enter: Enter index table and maybe go to a specific reference;
305 use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
307 ping: Echo line from index table for current node or first of
308 its ancestor from index.
310 ref: Create a new reference.
312 help: Show this text.
314 example: Create a temporary index, that will not be saved, but
315 may serve as an example.
317 sort: Sort lines in index, in region or buffer by contained
318 reference, or sort index by count, reference or last access.
320 multi-occur: Apply Emacs standard `multi-occur' operation on all
321 `org-mode' buffers to search for the given reference.
323 highlight: Highlight or unhiglight references in active region or buffer.
324 Call with prefix argument (`C-u') to remove highlights.
326 maintain: Offers some choices to check, update or fix your index.
328 If you invoke `org-index' for the first time, an assistant will be
329 invoked, that helps you to create your own, commented index.
331 Use `org-index-default-keybindings' to establish convenient
332 keyboard shortcuts.
334 See the commented list of flags within your index node for ways to
335 modify the behaviour of org-index.
337 A numeric prefix argument is used as a reference number for
338 commands, that need one (e.g. 'head').
340 Optional arguments for use from elisp: COMMAND is a symbol naming
341 the command to execute. SEARCH-REF specifies a reference to
342 search for, if needed. ARG allows passing in a prefix argument
343 as in interactive calls."
345 (interactive "i\ni\nP")
347 (let (search-id ; id to search for
348 sort-what ; sort what ?
349 kill-new-text ; text that will be appended to kill ring
350 message-text) ; text that will be issued as an explanation
354 ;; Initialize and parse
357 ;; creates index table, if necessary
358 (org-index--verify-id)
360 ;; Get configuration of index table
361 (org-index--parse-table)
363 ;; store context information
364 (org-index--retrieve-context)
368 ;; Arrange for proper sorting of index
371 ;; lets assume, that it has been sorted this way (we try hard to make sure)
372 (unless org-index--last-sort (setq org-index--last-sort (org-index--special-column 'sort)))
373 ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
374 (unless org-index--sort-timer
375 (setq org-index--sort-timer
376 (run-with-idle-timer org-index--sort-idle-delay t 'org-index--sort-silent)))
380 ;; Find out, what we are supposed to do
383 ;; check or read command
384 (if command
385 (unless (memq command org-index--commands)
386 (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
387 command (mapconcat 'symbol-name org-index--commands ",")))
388 (setq command (intern (org-completing-read
389 "Please choose: "
390 (mapcar 'symbol-name org-index--commands)))))
394 ;; Get search string, if required; process possible sources one after
395 ;; another (lisp argument, prefix argumen, user input).
398 ;; Try prefix, if no lisp argument given
399 (if (and (not search-ref)
400 (numberp arg))
401 (setq search-ref (format "%s%d%s" org-index--head arg org-index--tail)))
403 ;; These actions really need a search string and may even prompt for it
404 (when (memq command '(enter head multi-occur))
406 ;; search from surrounding text ?
407 (unless search-ref
408 (if org-index--within-node
410 (if (org-at-table-p)
411 (setq search-ref (org-index--get-or-set-field 'ref)))
413 (if (and org-index--below-cursor
414 (string-match (concat "\\(" org-index--ref-regex "\\)")
415 org-index--below-cursor))
416 (setq search-ref (match-string 1 org-index--below-cursor)))))
418 ;; If we still do not have a search string, ask user explicitly
419 (unless search-ref
420 (if (eq command 'enter)
421 (let ((r (org-index--read-search-for-enter)))
422 (setq search-ref (car r))
423 (setq search-id (cdr r)))
424 (setq search-ref (read-from-minibuffer "Search reference number: "))))
426 ;; Clean up search string
427 (when search-ref
428 (setq search-ref (org-trim search-ref))
429 (if (string-match "^[0-9]+$" search-ref)
430 (setq search-ref (concat org-index--head search-ref org-index--tail)))
431 (if (string= search-ref "") (setq search-ref nil)))
433 (if (and (not search-ref)
434 (not (eq command 'enter)))
435 (error "Command %s needs a reference number" command)))
439 ;; Command sort needs to know in advance, what to sort for
442 (when (eq command 'sort)
443 (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))))
447 ;; Enter table
450 ;; Arrange for beeing able to return
451 (when (and (memq command '(occur head enter ref example sort maintain))
452 (not (string= (buffer-name) org-index--occur-buffer-name)))
453 (org-mark-ring-push))
455 ;; These commands will leave user in index table after they are finished
456 (when (or (memq command '(enter ref maintain))
457 (and (eq command 'sort)
458 (eq sort-what 'index)))
460 (pop-to-buffer-same-window org-index--buffer)
461 (goto-char org-index--point)
462 (org-index--unfold-buffer))
466 ;; Actually do, what is requested
469 (cond
472 ((eq command 'help)
474 ;; bring up help-buffer for this function
475 (describe-function 'org-index))
478 ((eq command 'multi-occur)
480 ;; Construct list of all org-buffers
481 (let (buff org-buffers)
482 (dolist (buff (buffer-list))
483 (set-buffer buff)
484 (if (string= major-mode "org-mode")
485 (setq org-buffers (cons buff org-buffers))))
487 ;; Do multi-occur
488 (multi-occur org-buffers (org-index--make-guarded-search search-ref))
490 ;; Present results
491 (if (get-buffer "*Occur*")
492 (progn
493 (setq message-text (format "multi-occur for '%s'" search-ref))
494 (other-window 1)
495 (toggle-truncate-lines 1))
496 (setq message-text (format "Did not find '%s'" search-ref)))))
499 ((eq command 'add)
501 (let ((r (org-index--do-add-or-update)))
502 (setq message-text (car r))
503 (setq kill-new-text (cdr r))))
506 ((eq command 'delete)
508 (setq message-text (org-index--do-delete)))
511 ((eq command 'head)
513 (if (and org-index--within-node
514 (org-at-table-p))
515 (setq search-id (org-index--get-or-set-field 'id)))
517 (setq search-id (or search-id (org-index--id-from-ref search-ref)))
518 (setq message-text
519 (if search-id
520 (org-index--do-head search-ref search-id)
521 (message "Current line has no id."))))
524 ((eq command 'enter)
526 (goto-char org-index--below-hline)
528 (setq message-text
530 (if search-ref
531 (if (org-index--go 'ref search-ref)
532 (progn
533 (org-index--update-current-line)
534 (org-table-goto-column (org-index--column-num 'ref))
535 (format "Found index line '%s'" search-ref))
536 (format "Did not find index line with reference '%s'" search-ref))
538 (if search-id
539 (if (org-index--go 'id search-id)
540 (progn
541 (org-index--update-current-line)
542 (org-table-goto-column (org-index--column-num 'ref))
543 (format "Found index line '%s'" (org-index--get-or-set-field 'ref)))
544 (format "Did not find index line with id '%s'" search-id))
546 ;; simply go into table
547 (setq message-text "At index table"))))
549 (recenter))
552 ((eq command 'ping)
554 (let ((moved-up 0) id info reached-top)
556 (unless (string= major-mode "org-mode") (error "No node at point"))
557 ;; take id from current node or reference
558 (setq id (if search-ref
559 (org-index--id-from-ref search-ref)
560 (org-id-get)))
562 ;; move up until we find a node in index
563 (save-excursion
564 (outline-back-to-heading)
565 (while (not (or info
566 reached-top))
567 (if id
568 (setq info (org-index--on 'id id
569 (mapcar (lambda (x) (org-index--get-or-set-field x))
570 (list 'ref 'count 'created 'last-accessed 'category 'keywords 'ref)))))
572 (setq reached-top (= (org-outline-level) 1))
574 (unless (or info
575 reached-top)
576 (outline-up-heading 1 t)
577 (incf moved-up))
579 (setq id (org-id-get))))
581 (if info
582 (progn
583 (setq message-text
584 (apply 'format
585 (append (list "'%s'%shas been accessed %s times between %s and %s; category is '%s', keywords are '%s'"
586 (pop info)
587 (if (> moved-up 0) (format " (parent node, %d level up) " moved-up) " "))
588 info)))
589 (setq kill-new-text (car (last info))))
590 (setq message-text "Neither this node nor any of its parents is part of index"))))
593 ((eq command 'occur)
595 (set-buffer org-index--buffer)
596 (org-index--do-occur))
599 ((eq command 'ref)
601 (let (new)
603 ;; add a new row
604 (setq new (org-index--create-new-line))
606 ;; fill special columns with standard values
607 (org-table-goto-column (org-index--column-num 'ref))
608 (insert new)
609 (setq org-index--last-ref new)
611 ;; goto point-field or first empty one or first field
612 (if (org-index--special-column 'point-on-add)
613 (org-table-goto-column (org-index--column-num (org-index--special-column 'point-on-add)))
614 (unless (catch 'empty
615 (dotimes (col org-index--numcols)
616 (org-table-goto-column (+ col 1))
617 (if (string= (org-trim (org-table-get-field)) "")
618 (throw 'empty t))))
619 ;; none found, goto first
620 (org-table-goto-column 1)))
622 (if org-index--active-region (setq kill-new-text org-index--active-region))
623 (setq message-text (format "Adding a new row with ref '%s'" new))))
626 ((eq command 'sort)
628 (let ((columns (list "ref" "count" "created" "last-accessed" "id"))
629 sort groups-and-counts)
631 (cond
632 ((eq sort-what 'index)
633 (setq sort
634 (intern
635 (org-icompleting-read
636 "Please choose column to sort index table: "
637 (append (copy-list columns) (list "group-by"))
638 nil t nil nil (symbol-name (org-index--special-column 'sort)))))
640 (when (eq sort 'group-by)
641 (setq sort
642 (intern
643 (org-icompleting-read
644 "Please choose column to group index table by: "
645 columns
646 nil t nil nil (symbol-name (org-index--special-column 'sort)))))
647 (setq groups-and-counts (org-index--collect-sort-groups sort)))
649 (org-index--do-sort-index sort (first groups-and-counts))
650 (org-table-goto-column (org-index--column-num sort))
651 ;; When saving index, it should again be sorted correctly
652 (with-current-buffer org-index--buffer
653 (add-hook 'before-save-hook 'org-index--sort-silent t))
655 (setq message-text
656 (format
657 (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
658 (if groups-and-counts
659 "; %d groups with equal %s and a total of %d lines have been found"
660 ""))
661 (symbol-name sort)
662 (org-index--special-column 'sort)
663 org-index--sort-idle-delay
664 (second groups-and-counts)
665 (symbol-name sort)
666 (third groups-and-counts))))
668 ((memq sort-what '(region buffer))
669 (org-index--do-sort-lines sort-what)
670 (setq message-text (format "Sorted %s by contained references" sort-what))))))
673 ((eq command 'highlight)
675 (let ((where "buffer"))
676 (save-excursion
677 (save-restriction
678 (when (and transient-mark-mode
679 mark-active)
680 (narrow-to-region (region-beginning) (region-end))
681 (setq where "region"))
683 (if arg
684 (progn
685 (unhighlight-regexp org-index--ref-regex)
686 (setq message-text (format "Removed highlights for references in %s" where)))
687 (highlight-regexp org-index--ref-regex 'isearch)
688 (setq message-text (format "Highlighted references in %s" where)))))))
691 ((eq command 'maintain)
692 (setq message-text (org-index--do-maintain)))
695 ((eq command 'example)
697 (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
698 (org-index--create-index t)))
701 (t (error "Unknown subcommand '%s'" command)))
704 ;; tell, what we have done and what can be yanked
705 (if kill-new-text (setq kill-new-text
706 (substring-no-properties kill-new-text)))
707 (if (string= kill-new-text "") (setq kill-new-text nil))
708 (let ((m (concat
709 message-text
710 (if (and message-text kill-new-text)
711 " and r"
712 (if kill-new-text "R" ""))
713 (if kill-new-text (format "eady to yank '%s'." kill-new-text) (if message-text "." "")))))
714 (unless (string= m "")
715 (message m)
716 (setq org-index--message-text m)))
717 (if kill-new-text (kill-new kill-new-text))))
720 (defun org-index-default-keybindings (&optional prefix)
721 "Set default keybindings for `org-index'.
723 Invoke subcommands of org index with a single key
724 sequence. Establish the common prefix key 'C-c i' which should be
725 followed by the first letter of a subcommand.
727 The ist of letters and subcommands is specified in within
728 `org-index-default-keybindings-list'.
730 See `org-index' for a description of all subcommands.
732 Optional argument PREFIX specifies common prefix, defaults to 'C-c i'"
733 (interactive)
735 (define-prefix-command 'org-index--keymap)
736 ;; prefix command
737 (global-set-key (kbd (or prefix "C-c i")) 'org-index--keymap)
738 ;; loop over subcommands
739 (mapcar
740 (lambda (x)
741 ;; loop over letters, that invoke the same subcommand
742 (mapcar (lambda (c)
743 (define-key org-index--keymap (kbd (char-to-string c))
744 `(lambda (arg) (interactive "P")
745 (message nil)
746 (org-index ,(cdr x) nil arg))))
747 (car x)))
748 org-index-default-keybindings-list))
751 (defun org-index-new-line (&rest keys-values)
752 "Create a new line within the index table, returning its reference.
754 The function takes a varying number of argument pairs; each pair
755 is a symbol for an existing column heading followed by its value.
756 The return value is the new reference.
758 Example:
760 (message \"Created reference %s\"
761 (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
763 Optional argument KEYS-VALUES specifies content of new line."
765 (org-index--verify-id)
766 (org-index--parse-table)
768 (car (apply 'org-index--do-new-line keys-values)))
771 (defun org-index--do-new-line (&rest keys-values)
772 "Do the work for `org-index-new-line'.
773 Optional argument KEYS-VALUES specifies content of new line."
775 (save-excursion
776 (org-index--retrieve-context)
777 (with-current-buffer org-index--buffer
778 (goto-char org-index--point)
780 ;; check arguments early; they might come from lisp-user
781 (let ((kvs keys-values)
782 k v)
783 (while kvs
784 (setq k (car kvs))
785 (setq v (cadr kvs))
786 (if (eq k 'ref)
787 (unless (memq v '(t nil))
788 (error "Column 'ref' accepts only \"t\" or \"nil\""))
789 (if (or (not (symbolp k))
790 (and (symbolp v) (not (eq v t)) (not (eq v nil))))
791 (error "Arguments must be alternation of key and value")))
792 (unless (org-index--column-num k)
793 (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
794 (setq kvs (cddr kvs))))
796 (let (ref yank)
797 ;; create new line
798 (setq ref (org-index--create-new-line))
799 (plist-put keys-values 'ref ref)
801 ;; fill columns
802 (let ((kvs keys-values)
803 k v n)
804 (while kvs
805 (setq k (car kvs))
806 (setq v (cadr kvs))
807 (org-table-goto-column (org-index--column-num k))
808 (insert (org-trim v))
809 (setq kvs (cddr kvs))))
811 ;; align and fontify line
812 (org-index--promote-current-line)
813 (org-index--align-and-fontify-current-line)
815 ;; get column to yank
816 (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add)))
818 (cons ref yank)))))
821 (defun org-index-get-line (column value)
822 "Retrieve an existing line within the index table by ref or id.
823 Return its contents as a property list.
825 The function `plist-get' may be used to retrieve specific elements
826 from the result.
828 Example:
830 (plist-get (org-index-get-line 'ref \"R12\") 'count)
832 retrieves the value of the count-column for reference number 12.
834 Argument COLUMN is a symbol, either ref or id,
835 argument VALUE specifies the value to search for."
836 ;; check arguments
837 (unless (memq column '(ref id))
838 (error "Argument column can only be 'ref' or 'id'"))
840 (unless value
841 (error "Need a value to search for"))
843 (org-index--verify-id)
844 (org-index--parse-table)
846 (org-index--get-line column value))
849 (defun org-index--get-line (column value)
850 "Find a line by ID, return its contents.
851 Argument COLUMN and VALUE specify line to get."
852 (let (content)
853 (org-index--on
854 column value
855 (mapc (lambda (x)
856 (if (and (numberp (cdr x))
857 (> (cdr x) 0))
858 (setq content (cons (car x) (cons (or (org-index--get-or-set-field (car x)) "") content)))))
859 (reverse org-index--columns)))
860 content))
863 (defun org-index--delete-line (id)
864 "Delete a line specified by ID."
865 (let (content)
866 (org-index--on
867 'id id
868 (let ((start (line-beginning-position)))
869 (beginning-of-line)
870 (forward-line)
871 (delete-region start (point))
872 t))))
875 (defun org-index--ref-from-id (id)
876 "Get reference from line ID."
877 (org-index--on 'id id (org-index--get-or-set-field 'ref)))
880 (defun org-index--id-from-ref (ref)
881 "Get id from line REF."
882 (org-index--on 'ref ref (org-index--get-or-set-field 'id)))
885 (defun org-index--read-search-for-enter ()
886 "Special input routine for command enter."
887 ;; Accept single char commands or switch to reading a sequence of digits
888 (let (char prompt search-ref search-id)
890 ;; start with short prompt but give more help on next iteration
891 (setq prompt "Please specify, where to go in index (0-9.,space,backspace,return or ? for help): ")
893 ;; read one character
894 (while (not (memq char (append (number-sequence ?0 ?9) (list ?\d ?\b ?\r ?\j ?\s ?.))))
895 (setq char (read-char prompt))
896 (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: "))
898 (if (memq char (number-sequence ?0 ?9))
899 ;; read rest of digits
900 (setq search-ref (read-from-minibuffer "Search reference number: " (char-to-string char))))
901 ;; decode single chars
902 (if (memq char '(?\r ?\n ?.)) (setq search-id (org-id-get)))
903 (if (memq char '(?\d ?\b)) (setq search-ref (number-to-string org-index--maxref)))
905 (cons search-ref search-id)))
908 (defun org-index--verify-id ()
909 "Check, that we have a valid id."
911 ;; Check id
912 (unless org-index-id
913 (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")))
914 (if (string= "create-index" answer)
915 (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
916 (describe-function 'org-index))))
918 ;; Find node
919 (let (marker)
920 (setq marker (org-id-find org-index-id 'marker))
921 (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
922 ; Try again with new node
923 (setq marker (org-id-find org-index-id 'marker))
924 (unless marker (error "Could not create node"))
925 (setq org-index--buffer (marker-buffer marker)
926 org-index--point (marker-position marker))
927 (move-marker marker nil)))
930 (defun org-index--retrieve-context ()
931 "Collect context information before starting with command."
933 ;; Get the content of the active region or the word under cursor
934 (setq org-index--active-region
935 (if (and transient-mark-mode mark-active)
936 (buffer-substring (region-beginning) (region-end))
937 nil))
938 (setq org-index--below-cursor (thing-at-point 'symbol))
940 ;; get category of current node
941 (setq org-index--category-before
942 (save-excursion ; workaround: org-get-category does not give category when at end of buffer
943 (beginning-of-line)
944 (org-get-category (point) t)))
946 ;; Find out, if we are within index table or not
947 (setq org-index--within-node (string= (org-id-get) org-index-id)))
950 (defun org-index--parse-table ()
951 "Parse content of index table."
953 (let (ref-field
954 id-field
955 initial-point
956 end-of-headings
957 start-of-headings)
959 (with-current-buffer org-index--buffer
961 (setq org-index--maxref 0)
962 (setq initial-point (point))
964 (org-index--go-below-hline)
966 ;; align and fontify table once for this emacs session
967 (unless org-index--aligned
968 (org-table-align) ; needs to happen before fontification to be effective ?
969 (let ((is-modified (buffer-modified-p))
970 (below (point)))
971 (while (org-at-table-p)
972 (forward-line))
973 (font-lock-fontify-region below (point))
974 (org-index--go-below-hline)
975 (setq org-index--aligned t)
976 (set-buffer-modified-p is-modified)))
978 (org-index--go-below-hline)
979 (setq org-index--below-hline (point-marker))
980 (beginning-of-line)
982 ;; get headings to display during occur
983 (setq end-of-headings (point))
984 (while (org-at-table-p) (forward-line -1))
985 (forward-line)
986 (setq start-of-headings (point))
987 (setq org-index--headings-visible (substring-no-properties (org-index--copy-visible start-of-headings end-of-headings)))
988 (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
990 ;; count columns
991 (org-table-goto-column 100)
992 (setq org-index--numcols (- (org-table-current-column) 1))
994 ;; go to top of table
995 (while (org-at-table-p)
996 (forward-line -1))
997 (forward-line)
999 ;; parse line of headings
1000 (org-index--parse-headings)
1002 ;; parse list of flags
1003 (goto-char org-index--point)
1004 (org-index--parse-flags)
1006 ;; Retrieve any decorations around the number within the first nonempty ref-field
1007 (goto-char org-index--below-hline)
1008 (while (and (org-at-table-p)
1009 (not (setq ref-field (org-index--get-or-set-field 'ref))))
1010 (forward-line))
1012 ;; Some Checking
1013 (unless ref-field
1014 (org-index--report-index-error "Reference column is empty"))
1016 (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
1017 (org-index--report-index-error
1018 "First reference in index table ('%s') does not contain a number" ref-field))
1020 ;; These are the decorations used within the first ref of index
1021 (setq org-index--head (match-string 1 ref-field))
1022 (setq org-index--tail (match-string 3 ref-field))
1023 (setq org-index--ref-regex (concat (regexp-quote org-index--head)
1024 "\\([0-9]+\\)"
1025 (regexp-quote org-index--tail)))
1026 (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
1028 ;; Go through table to find maximum number and do some checking
1029 (let ((ref 0))
1031 (while (org-at-table-p)
1033 (setq ref-field (org-index--get-or-set-field 'ref))
1034 (setq id-field (org-index--get-or-set-field 'id))
1036 (when (and (not ref-field)
1037 (not id-field))
1038 (kill-whole-line)
1039 (message "Removing line from index-table with both ref and id empty"))
1041 (if ref-field
1042 (if (string-match org-index--ref-regex ref-field)
1043 ;; grab number
1044 (setq ref (string-to-number (match-string 1 ref-field)))
1045 (kill-whole-line)
1046 (message "Removing line from index-table whose ref does not contain a number")))
1048 ;; check, if higher ref
1049 (if (> ref org-index--maxref) (setq org-index--maxref ref))
1051 (forward-line 1)))
1053 ;; go back to initial position
1054 (goto-char initial-point))))
1057 (defun org-index--do-maintain ()
1058 "Choose among and perform some tasks to maintain index."
1059 (let ((check-what) (max-mini-window-height 1.0) message-text)
1060 (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")))
1061 (message nil)
1063 (cond
1064 ((eq check-what 'check)
1065 (setq message-text (or (org-index--check-ids)
1066 "No problems found")))
1068 ((eq check-what 'statistics)
1069 (setq message-text (org-index--do-statistics)))
1071 ((eq check-what 'duplicates)
1072 (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."))
1074 ((eq check-what 'clean)
1075 (let ((lines 0))
1076 (org-map-entries
1077 (lambda ()
1078 (when (org-entry-get (point) "org-index-ref")
1079 (incf lines)
1080 (org-entry-delete (point) "org-index-ref")))
1081 nil 'agenda)
1082 (setq message-text (format "Removed property 'org-index-ref' from %d lines" lines))))
1084 ((eq check-what 'update)
1085 (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 doing `add' from within your index. Are you SURE to proceed for ALL INDEX LINES ? ")
1086 (setq message-text (org-index--update-all-lines))
1087 (setq message-text "Canceled."))))
1088 message-text))
1091 (defun org-index--do-sort-index (sort &optional groups)
1092 "Sort index table according to SORT, optinally with GROUPS."
1094 (let ((is-modified (buffer-modified-p))
1096 bottom
1097 ref-field
1098 count-field)
1100 (unless buffer-read-only
1102 (message "Sorting table for %s..." (symbol-name sort))
1103 (undo-boundary)
1105 (let ((message-log-max nil)) ; we have just issued a message, dont need those of sort-subr
1107 ;; get boundaries of table
1108 (goto-char org-index--below-hline)
1109 (forward-line 0)
1110 (setq top (point))
1111 (while (org-at-table-p) (forward-line))
1113 ;; kill all empty rows at bottom
1114 (while (progn
1115 (forward-line -1)
1116 (org-table-goto-column 1)
1117 (and
1118 (not (org-index--get-or-set-field 'ref))
1119 (not (org-index--get-or-set-field 'id))))
1120 (org-table-kill-row))
1121 (forward-line 1)
1122 (setq bottom (point))
1124 ;; sort lines
1125 (save-restriction
1126 (narrow-to-region top bottom)
1127 (goto-char top)
1128 (sort-subr t
1129 'forward-line
1130 'end-of-line
1131 (lambda ()
1132 (concat
1133 (if groups
1134 (format "%06d-" (cdr (assoc (org-index--get-or-set-field sort) groups)))
1136 (org-index--get-sort-key sort t)))
1138 'string<)
1139 (goto-char (point-min))
1141 ;; restore modification state
1142 (set-buffer-modified-p is-modified)))
1144 (setq org-index--last-sort sort))))
1147 (defun org-index--collect-sort-groups (sort)
1148 "Collect groups to SORT for."
1149 (let ((count-groups 0) (count-lines 0)
1150 groups key key-value)
1152 (org-index--on
1153 nil nil
1154 (while (org-at-table-p)
1155 (setq key (org-index--get-or-set-field sort))
1156 (setq key-value (assoc key groups))
1157 (if key-value
1158 (progn
1159 (incf (cdr key-value)))
1160 (setq groups (cons (cons key 1) groups)))
1161 (forward-line)))
1163 (mapc (lambda (x) (when (> (cdr x) 1)
1164 (incf count-groups)
1165 (incf count-lines (cdr x))))
1166 groups)
1168 (list groups count-groups count-lines)))
1171 (defun org-index--do-sort-lines (what)
1172 "Sort lines in WHAT according to contained reference."
1173 (save-restriction
1174 (cond
1175 ((eq what 'region)
1176 (if (region-active-p)
1177 (narrow-to-region (region-beginning) (region-end))
1178 (error "No active region, cannot sort")))
1179 ((eq what 'buffer)
1180 (unless (y-or-n-p "Sort whole current buffer ? ")
1181 (error "Canceled"))
1182 (narrow-to-region (point-min) (point-max))))
1184 (goto-char (point-min))
1185 (sort-subr nil 'forward-line 'end-of-line
1186 (lambda ()
1187 (if (looking-at (concat ".*"
1188 (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
1189 (string-to-number (match-string 1))
1190 0)))))
1193 (defun org-index--go-below-hline ()
1194 "Move below hline in index-table."
1196 (let ((count 0)
1197 (errstring (format "index table within node %s" org-index-id)))
1199 (goto-char org-index--point)
1201 ;; go to heading of node
1202 (while (not (org-at-heading-p)) (forward-line -1))
1203 (forward-line 1)
1205 ;; go to first table, but make sure we do not get into another node
1206 (while (and (not (org-at-table-p))
1207 (not (org-at-heading-p))
1208 (not (eobp)))
1209 (forward-line))
1211 ;; check, if there really is a table
1212 (unless (org-at-table-p)
1213 (org-index--create-missing-index "Cannot find %s." errstring))
1215 ;; go just after hline
1216 (while (and (not (org-at-table-hline-p))
1217 (org-at-table-p))
1218 (forward-line))
1219 (forward-line)
1221 ;; and check
1222 (unless (org-at-table-p)
1223 (org-index--report-index-error "Cannot find a hline within %s" errstring))
1225 (org-table-goto-column 1)))
1228 (defun org-index--parse-headings ()
1229 "Parse headings of index table."
1231 (let (field ;; field content
1232 field-symbol ;; and as a symbol
1233 found)
1235 (setq org-index--columns nil)
1237 ;; For each column
1238 (dotimes (col org-index--numcols)
1240 (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
1242 (if (string= field "")
1243 (error "Heading of column cannot be empty"))
1244 (if (and (not (string= (substring field 0 1) "."))
1245 (not (member (intern field) org-index--valid-headings)))
1247 (if (string= field "link")
1248 ;; Ask user to migrate his index to new version (since [2015-02-11 Mi])
1249 (progn
1250 ;; pop to index buffer
1251 (pop-to-buffer-same-window org-index--buffer)
1252 (goto-char org-index--below-hline)
1253 (org-reveal t)
1254 ;; go to column
1255 (while (org-at-table-p)
1256 (forward-line -1))
1257 (forward-line)
1258 (org-table-goto-column (+ 1 col))
1259 (error "Column 'link' should be named 'id' with recent versions of org-index,\nplease adjust your table (cursor is already positioned right)"))
1260 (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field)))
1262 (setq field-symbol (intern field))
1264 ;; check if heading has already appeared
1265 (if (assoc field-symbol org-index--columns)
1266 (org-index--report-index-error
1267 "'%s' appears two times as column heading" (downcase field))
1268 ;; add it to list at front, reverse later
1269 (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
1271 (setq org-index--columns (reverse org-index--columns))
1273 ;; check if all necessary headings have appeared
1274 (mapc (lambda (head)
1275 (unless (cdr (assoc head org-index--columns))
1276 (org-index--report-index-error "No column has heading '%s'" head)))
1277 org-index--required-headings))
1280 (defun org-index--parse-flags ()
1281 "Parse list of flags in index table."
1283 (let (parent parent-is-comment child)
1285 ;; reset configuration variables
1286 (setq org-index--special-columns nil)
1287 (setq org-index--flagged-columns nil)
1289 (org-index--goto-list "columns-and-flags" t)
1290 (forward-line 1)
1292 ;; outer loop over columns
1293 (while (and (setq parent (org-index--parse-list-item))
1294 parent
1295 (> (cdr (assoc :indent parent)) 0))
1297 (setq parent-is-comment (member (cdr (assoc :text parent)) '("all-columns-explained" "all-flags-explained")))
1299 ;; check, that we have a valid heading
1300 (unless (or parent-is-comment
1301 (assoc (cdr (assoc :sym parent)) org-index--columns))
1302 (when (string= "link" (cdr (assoc :text parent)))
1303 (pop-to-buffer-same-window org-index--buffer)
1304 (org-reveal t)
1305 (error "Flag 'link' should be named 'id' with recent versions of org-index,\nplease adjust this flag (cursor is already positioned right)"))
1306 (org-index--report-index-error "'%s' appears within flags, but not as a index column. " (cdr (assoc :text parent))))
1308 ;; inner loop over children
1309 (while (and (forward-line 1)
1310 (setq child (org-index--parse-list-item))
1311 child
1312 (> (cdr (assoc :indent child))
1313 (cdr (assoc :indent parent))))
1315 (unless parent-is-comment
1316 ;; check, that we have a valid flag
1317 (unless (memq (cdr (assoc :sym child)) org-index--all-flags)
1318 (org-index--report-index-error "'%s' is not a valid flag" (cdr (assoc :text child))))
1320 ;; process flag with respect to current index-column
1321 (if (memq (cdr (assoc :sym child)) org-index--single-flags)
1322 ;; Check, that none of org-index--single-flags appears twice
1323 (if (assoc (cdr (assoc :sym child)) org-index--special-columns)
1324 (org-index--report-index-error
1325 "More than one column is marked with flag '%s'" (cdr (assoc :text child)))
1326 ;; add it to list
1327 (setq org-index--special-columns (cons (cons (cdr (assoc :sym child)) (cdr (assoc :sym parent)))
1328 org-index--special-columns))))
1330 ;; all flags are stored in org-index--flagged-columns
1331 (let ((l (assoc (cdr (assoc :sym child)) org-index--flagged-columns))) ;; list of flag and columns, that carry this flag
1332 (unless l
1333 ;; no list of columns with this flag is present, create one
1334 (setq org-index--flagged-columns
1335 (cons (cons (cdr (assoc :sym child)) nil)
1336 org-index--flagged-columns))
1337 (setq l (car org-index--flagged-columns)))
1338 ;; prepend this column to list of columns with this flag
1339 (setcdr l (cons (cdr (assoc :sym parent)) (cdr l)))))))
1341 ;; check, that all needed flags have been specified
1342 (mapc (lambda (x)
1343 (unless (assoc x org-index--special-columns)
1344 (org-index--report-index-error "Required flag '%s' does not appear" (substring (symbol-name x) 1))))
1345 org-index--required-flags)))
1348 (defun org-index--goto-list (name &optional required non-top)
1349 "Goto list NAME (maybe NON-TOP Level) in index node, err if REQUIRED list is not present."
1350 (goto-char org-index--point)
1352 ;; go to heading of node
1353 (while (not (org-at-heading-p)) (forward-line -1))
1354 (forward-line 1)
1356 ;; go to named list
1357 (while (and (not (let ((item (org-index--parse-list-item)))
1358 (if item
1359 (and (or non-top (= (cdr (assoc :indent item)) 0)) ;; accept only toplevel ?
1360 (string= (cdr (assoc :text item)) name)) ;; with requested name
1361 nil)))
1362 (not (org-at-table-p))
1363 (not (org-at-heading-p))
1364 (not (eobp)))
1365 (forward-line 1))
1367 (if (org-at-item-p)
1369 (if required
1370 (org-index--report-index-error "Could not find required list '%s'" name)
1371 nil)))
1374 (defun org-index--parse-list-item ()
1375 "Parse a list item into an assoc array (indent, checkbox, text, value)."
1377 ;; matche full list-item, maybe with checkbox and double-colon
1378 (if (looking-at org-list-full-item-re)
1380 ;; retrieve interesting parts of list item from match data
1381 (let (indent checkbox text value next-line)
1383 (setq indent
1384 (- (save-excursion (goto-char (match-beginning 1)) (current-column)) ; first column
1385 (save-match-data (org-current-level)) ; indent-level
1387 (setq checkbox (match-string 3))
1388 (setq text (match-string 4))
1389 (set (if text 'value 'text) (buffer-substring (match-end 0) (line-end-position))) ; regexp did not capture this
1391 ;; peek ahead, if item continues on next line
1392 (forward-line 1)
1393 (if (looking-at org-list-full-item-re)
1394 (forward-line -1) ; already at next item; go back
1395 (setq next-line (buffer-substring (line-beginning-position) (line-end-position))))
1397 ;; clean up strings
1398 (mapc (lambda (x)
1399 (if (stringp (symbol-value x))
1400 (set x (org-trim (substring-no-properties (symbol-value x))))))
1401 '(text value next-line))
1403 (if next-line (setq text (concat text " " next-line))) ; append next line if
1405 (list (cons :indent indent) (cons :text text) (cons :value value) (cons :sym (intern text))))
1406 nil))
1409 (defun org-index--create-missing-index (&rest reasons)
1410 "Create a new empty index table with detailed explanation. Argument REASONS explains why."
1412 (org-index--ask-before-create-index "Cannot find your index table: "
1413 "new permanent" "."
1414 reasons)
1415 (org-index--create-index))
1418 (defun org-index--report-index-error (&rest reasons)
1419 "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
1421 (when org-index--buffer
1422 (pop-to-buffer-same-window org-index--buffer)
1423 (goto-char org-index--below-hline)
1424 (org-reveal t))
1425 (org-index--ask-before-create-index "The existing index contains this error: "
1426 "temporary" ", to compare with."
1427 reasons)
1428 (org-index--create-index t t))
1431 (defun org-index--ask-before-create-index (explanation type for-what reasons)
1432 ; checkdoc-params: (explanation type for-what reasons)
1433 "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
1434 (let (reason prompt)
1436 (setq reason (apply 'format reasons))
1438 (setq prompt (concat explanation reason "\n\n"
1439 "However, this assistant can help you to create a "
1440 type " index with detailed comments" for-what "\n\n"
1441 "Do you want to proceed ?"))
1443 (unless (let ((max-mini-window-height 1.0))
1444 (y-or-n-p prompt))
1445 (error (concat explanation reason)))))
1448 (defun org-index--create-index (&optional temporary compare)
1449 "Create a new empty index table with detailed explanation.
1450 specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
1451 (let (buffer
1452 title
1453 firstref
1456 (if temporary
1457 (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
1458 (buffer-name "*org-index-example-index*"))
1459 (setq buffer (get-buffer-create buffer-name))
1460 (with-current-buffer buffer
1461 ;; but it needs a file for its index to be found
1462 (unless (string= (buffer-file-name) file-name)
1463 (set-visited-file-name file-name))
1464 (rename-buffer buffer-name) ; name is change by line above
1466 (erase-buffer)
1467 (org-mode)))
1469 (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))))))
1471 (setq title (read-from-minibuffer "Please enter the title of the index node: "))
1473 (while (progn
1474 (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: "))
1475 (let (desc)
1476 (when (string-match "[[:blank:]]" firstref)
1477 (setq desc "Contains whitespace"))
1478 (when (string-match "[[:cntrl:]]" firstref)
1479 (setq desc "Contains control characters"))
1480 (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
1481 ;; firstref not okay, report details
1482 (setq desc
1483 (cond ((string= firstref "") "is empty")
1484 ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
1485 ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
1486 ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
1489 (if desc
1490 (progn
1491 (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
1493 nil))))
1495 (with-current-buffer buffer
1496 (goto-char (point-max))
1497 (insert (format "* %s %s\n" firstref title))
1498 (if temporary
1499 (insert "
1500 Below you find your temporary index table, which WILL NOT LAST LONGER
1501 THAN YOUR CURRENT EMACS SESSION.
1503 (insert "
1504 Below you find your initial index table, which will grow over time.
1506 (insert "
1507 You may start using it by adding some lines. Just move to
1508 another heading, invoke `org-index' and choose the command
1509 'add'. After adding a few nodes, try the command 'occur'
1510 to search among them.
1512 To gain further insight you may invoke the subcommand 'help', or
1513 read the description of `org-index'.
1515 Within the index table below, dhe sequence of columns does not
1516 matter. You may reorder them in any way you please. Columns are
1517 found by their heading. You may also add your own columns,
1518 which should start with a dot (e.g. '.custom').
1520 Following this explanations you will find the item-list
1521 `columns-and-flags', which influences the behaviour of
1522 `org-index'. See the explanations which are part of this list.
1524 This node needs not be a top level node; its name is completely
1525 at your choice; it is found through its ID only.
1527 (unless temporary
1528 (insert "
1529 Remark: These lines of explanation can be removed at any time.
1532 (setq id (org-id-get-create))
1533 (insert (format "
1537 | ref | category | keywords | count | last-accessed | created | id |
1538 | | | | | | | <4> |
1539 |-----+-----------+----------+-------+---------------+---------+------|
1540 | %s | | %s | | | %s | %s |
1543 org-index--sample-flags
1544 firstref
1545 "This node"
1546 (with-temp-buffer (org-insert-time-stamp nil nil t))
1547 id))
1549 ;; make sure, that node can be found
1550 (org-id-add-location id (buffer-file-name))
1551 (setq buffer-save-without-query t)
1552 (basic-save-buffer)
1554 (while (not (org-at-table-p)) (forward-line -1))
1555 (unless buffer-read-only (org-table-align))
1556 (while (not (org-at-heading-p)) (forward-line -1))
1558 ;; read back some info about new index
1559 (let ((org-index-id id))
1560 (org-index--verify-id))
1562 ;; remember at least for this session
1563 (setq org-index-id id)
1565 ;; present results to user
1566 (if temporary
1567 (progn
1568 ;; Present existing and temporary index together
1569 (when compare
1570 (pop-to-buffer-same-window org-index--buffer)
1571 (goto-char org-index--point)
1572 (org-index--unfold-buffer)
1573 (delete-other-windows)
1574 (select-window (split-window-vertically)))
1575 ;; show new index
1576 (pop-to-buffer-same-window buffer)
1577 (org-id-goto id)
1578 (org-index--unfold-buffer)
1579 (if compare
1580 (error "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
1581 (message "This is your new temporary index.")))
1582 (progn
1583 ;; Only show the new index
1584 (pop-to-buffer-same-window buffer)
1585 (delete-other-windows)
1586 (org-id-goto id)
1587 (org-index--unfold-buffer)
1588 (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 ? ")
1589 (progn
1590 (customize-save-variable 'org-index-id id)
1591 (error "Saved org-index-id '%s' to %s" id (or custom-file
1592 user-init-file)))
1593 (let (sq)
1594 (setq sq (format "(setq org-index-id \"%s\")" id))
1595 (kill-new sq)
1596 (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))))))))
1599 (defun org-index--unfold-buffer ()
1600 "Helper function to unfold buffer."
1601 (org-show-context)
1602 (org-show-subtree)
1603 (recenter 1)
1604 (save-excursion
1605 (org-back-to-heading)
1606 (forward-line) ;; on property drawer
1607 (org-cycle)
1608 (org-index--goto-list "columns-and-flags")
1609 (org-cycle)))
1612 (defun org-index--update-line (&optional ref-or-id)
1613 "Update columns count and last-accessed in line REF-OR-ID."
1615 (let ((newcount 0)
1616 initial)
1618 (with-current-buffer org-index--buffer
1619 (unless buffer-read-only
1621 ;; search reference or id, if given (or assume, that we are already positioned right)
1622 (when ref-or-id
1623 (setq initial (point))
1624 (goto-char org-index--below-hline)
1625 (while (and (org-at-table-p)
1626 (not (or (string= ref-or-id (org-index--get-or-set-field 'ref))
1627 (string= ref-or-id (org-index--get-or-set-field 'id)))))
1628 (forward-line)))
1630 (if (not (org-at-table-p))
1631 (error "Did not find reference or id '%s'" ref-or-id)
1632 (org-index--update-current-line))
1634 (if initial (goto-char initial))))))
1637 (defun org-index--update-current-line ()
1638 "Update current lines columns count and last-accessed."
1639 (let (newcount (count-field (org-index--get-or-set-field 'count)))
1641 ;; update count field only if number or empty
1642 (when (or (not count-field)
1643 (string-match "^[0-9]+$" count-field))
1644 (setq newcount (+ 1 (string-to-number (or count-field "0"))))
1645 (org-index--get-or-set-field 'count
1646 (number-to-string newcount)))
1648 ;; update timestamp
1649 (org-table-goto-column (org-index--column-num 'last-accessed))
1650 (org-table-blank-field)
1651 (org-insert-time-stamp nil t t)
1653 ;; move line according to new content
1654 (org-index--promote-current-line)
1655 (org-index--align-and-fontify-current-line)))
1658 (defun org-index--align-and-fontify-current-line ()
1659 "Make current line blend well among others."
1660 (let ((line (substring-no-properties (delete-and-extract-region (line-beginning-position) (line-end-position)))))
1661 ;; create minimum table with fixed-width columns to align and fontiry new line
1662 (insert (with-temp-buffer
1663 (org-set-font-lock-defaults)
1664 (insert org-index--headings-visible)
1665 (goto-char (point-min))
1666 ;; fill columns, so that aligning cannot shrink them
1667 (search-forward "|")
1668 (replace-string " " "." nil (point) (line-end-position))
1669 (replace-string ".|." " | " nil (line-beginning-position) (line-end-position))
1670 (replace-string "|." "| " nil (line-beginning-position) (line-end-position))
1671 (goto-char (point-max))
1672 (insert line)
1673 (forward-line 0)
1674 (org-table-align)
1675 (font-lock-fontify-region (point-min) (point-max))
1676 (goto-char (point-max))
1677 (forward-line -1)
1678 (buffer-substring (line-beginning-position) (line-end-position))))))
1681 (defun org-index--promote-current-line ()
1682 "Move current line up in table according to changed sort fields."
1683 (let (begin end key
1684 (to-skip 0))
1686 (forward-line 0) ; stay at beginning of line
1688 (setq key (org-index--get-sort-key))
1689 (setq begin (point))
1690 (setq end (line-beginning-position 2))
1692 (forward-line -1)
1693 (while (and (org-at-table-p)
1694 (not (org-at-table-hline-p))
1695 (string< (org-index--get-sort-key) key))
1697 (incf to-skip)
1698 (forward-line -1))
1699 (forward-line 1)
1701 ;; insert line at new position
1702 (when (> to-skip 0)
1703 (insert (delete-and-extract-region begin end))
1704 (forward-line -1))))
1707 (defun org-index--get-sort-key (&optional sort with-ref)
1708 "Get value for sorting from column SORT, optional WITH-REF."
1709 (let (ref
1710 ref-field
1711 key)
1713 (unless sort (setq sort org-index--last-sort)) ; use default value
1715 (when (or with-ref
1716 (eq sort 'ref))
1717 ;; get reference with leading zeroes, so it can be
1718 ;; sorted as text
1719 (setq ref-field (org-index--get-or-set-field 'ref))
1720 (string-match org-index--ref-regex ref-field)
1721 (setq ref (format
1722 "%06d"
1723 (string-to-number
1724 (or (match-string 1 ref-field)
1725 "0")))))
1727 (setq key
1728 (cond
1729 ((eq sort 'count)
1730 (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))
1731 ((eq sort 'ref)
1732 ref)
1733 ((eq sort 'id)
1734 (org-index--get-or-set-field sort))
1735 ((eq sort 'last-accessed)
1736 (org-index--get-or-set-field sort))
1737 ((eq sort 'created)
1738 (org-index--get-or-set-field sort))
1739 (t (error "This is a bug: unmatched case '%s'" sort))))
1741 (if with-ref (setq key (concat key ref)))
1743 key))
1746 (defun org-index--get-or-set-field (key &optional value)
1747 "Retrieve field KEY from index table or set it to VALUE."
1748 (let (field)
1749 (save-excursion
1750 (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value)))
1751 (if (string= field "") (setq field nil))
1753 (org-no-properties field))))
1756 (defun org-index--column-num (key)
1757 "Return number of column KEY."
1758 (if (numberp key)
1760 (cdr (assoc key org-index--columns))))
1763 (defun org-index--special-column (key)
1764 "Return column (not a number) for special column KEY."
1765 (cdr (assoc key org-index--special-columns)))
1768 (defun org-index--flag-p (flag column)
1769 "Check if COLUMN has FLAG set."
1770 (unless (memq flag org-index--all-flags)
1771 (error (format "Internal error: unknown flag %s" (symbol-name flag))))
1772 (memq column (assoc flag org-index--flagged-columns)))
1775 (defun org-index--make-guarded-search (ref &optional dont-quote)
1776 "Make robust search string from REF; DONT-QUOTE it, if requested."
1777 (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
1780 (defun org-index--do-statistics ()
1781 "Compute statistics about index table."
1782 (let ((total 0)
1783 ref-field ref min max message)
1786 ;; go through table and remove all refs, that we see
1787 (goto-char org-index--below-hline)
1788 (while (org-at-table-p)
1790 ;; get ref-field and number
1791 (setq ref-field (org-index--get-or-set-field 'ref))
1792 (if (and ref-field
1793 (string-match org-index--ref-regex ref-field))
1794 (setq ref (string-to-number (match-string 1 ref-field))))
1796 ;; record min and max
1797 (if (or (not min) (< ref min)) (setq min ref))
1798 (if (or (not max) (> ref max)) (setq max ref))
1800 ;; count
1801 (setq total (1+ total))
1803 (forward-line))
1805 (setq message (format "First reference is %s, last %s; %d values in between, %d of them are used (%d percent)"
1806 (format org-index--ref-format min)
1807 (format org-index--ref-format max)
1808 (1+ (- max min))
1809 total
1810 (truncate (* 100 (/ (float total) (1+ (- max min)))))
1814 (goto-char org-index--below-hline)
1815 message))
1818 (defun org-index--do-add-or-update ()
1819 "For current node or current line in index, add a new line to index table or update existing."
1821 (let* (id ref args yank ref-and-yank)
1823 ;; do the same things from within index and from outside
1824 (if org-index--within-node
1826 (progn
1827 (unless (org-at-table-p)
1828 (error "Within index node but not on table"))
1830 (setq id (org-index--get-or-set-field 'id))
1831 (setq ref (org-index--get-or-set-field 'ref))
1832 (setq args (org-index--collect-values-for-add-update-remote id))
1833 (org-index--write-fields-for-add-update args)
1834 (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add)))
1836 (cons (format "Updated index line %s" ref) yank))
1838 (unless (org-at-heading-p)
1839 (error "Not at headline"))
1841 (setq id (org-id-get-create))
1842 (setq ref (org-index--on 'id id (org-index--get-or-set-field 'ref)))
1843 (setq args (org-index--collect-values-for-add-update id ref))
1845 (if ref
1846 ;; already have a ref, find it in index and update fields
1847 (let ((kvs args)
1848 found-and-message)
1850 (org-index--on
1851 'ref ref
1852 (org-index--write-fields-for-add-update args)
1853 (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add))))
1855 (cons (format "Updated index line %s" ref) yank))
1857 ;; no ref here, create new line in index
1858 (setq ref-and-yank (apply 'org-index--do-new-line args))
1860 (cons (format "Added index line %s" (car ref-and-yank)) (concat (cdr ref-and-yank) " "))))))
1863 (defun org-index--check-ids ()
1864 "Check, that ids really point to a node."
1866 (let ((lines 0)
1867 id ids marker)
1869 (goto-char org-index--below-hline)
1871 (catch 'problem
1872 (while (org-at-table-p)
1874 (when (setq id (org-index--get-or-set-field 'id))
1876 ;; check for double ids
1877 (when (member id ids)
1878 (org-table-goto-column (org-index--column-num 'id))
1879 (throw 'problem "This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
1880 (incf lines)
1881 (setq ids (cons id ids))
1883 ;; check, if id is valid
1884 (setq marker (org-id-find id t))
1885 (unless marker
1886 (org-table-goto-column (org-index--column-num 'id))
1887 (throw 'problem "This id cannot be found")))
1889 (forward-line))
1891 (goto-char org-index--below-hline)
1892 nil)))
1895 (defun org-index--update-all-lines ()
1896 "Update all lines of index at once."
1898 (let ((lines 0)
1899 id ref kvs)
1901 ;; check for double ids
1903 (org-index--check-ids)
1905 (progn
1906 (goto-char org-index--below-hline)
1907 (while (org-at-table-p)
1909 ;; update single line
1910 (when (setq id (org-index--get-or-set-field 'id))
1911 (setq ref (org-index--get-or-set-field 'ref))
1912 (setq kvs (org-index--collect-values-for-add-update-remote id))
1913 (org-index--write-fields-for-add-update kvs)
1914 (incf lines))
1915 (forward-line))
1917 (goto-char org-index--below-hline)
1918 (org-table-align)
1919 (format "Updated %d lines" lines)))))
1922 (defun org-index--collect-values-for-add-update (id &optional silent category)
1923 "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
1925 (let ((args (list 'ref t 'id id))
1926 content)
1928 (dolist (col-num org-index--columns)
1930 (setq content "")
1932 (if (eq (car col-num) 'keywords)
1933 (setq content (nth 4 (org-heading-components))))
1935 (if (eq (car col-num) 'category)
1936 (setq content (or category org-index--category-before)))
1938 (if (eq (car col-num) 'level)
1939 (setq content (number-to-string (org-outline-level))))
1941 ;; Shift ref and timestamp ?
1942 (if (org-index--flag-p 'shift-ref-and-date-on-add (car col-num))
1943 (dotimes (i 2)
1944 (if (or (string-match (concat "^\\s-*" org-index--ref-regex) content)
1945 (string-match (concat org-ts-regexp-both) content))
1946 (setq content (substring content (match-end 0))))))
1948 (if (and (not silent) ; do not edit, if heading has already been added
1949 (org-index--flag-p 'edit-on-add (car col-num)))
1950 (setq content (read-from-minibuffer
1951 (format "Edit text for column '%s': " (symbol-name (car col-num)))
1952 content)))
1954 (if (not (string= content ""))
1955 (setq args (append (list (car col-num) content) args))))
1956 args))
1959 (defun org-index--collect-values-for-add-update-remote (id)
1960 "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
1962 (let (marker point args)
1964 (setq marker (org-id-find id t))
1965 ;; enter buffer and collect information
1966 (with-current-buffer (marker-buffer marker)
1967 (setq point (point))
1968 (goto-char marker)
1969 (setq args (org-index--collect-values-for-add-update id t (org-get-category (point) t)))
1970 (goto-char point))
1972 args))
1975 (defun org-index--write-fields-for-add-update (kvs)
1976 "Update current line with values from KVS (keys-values)."
1977 (while kvs
1978 (unless (eq (car kvs) 'ref)
1979 (org-index--get-or-set-field (car kvs) (org-trim (cadr kvs))))
1980 (setq kvs (cddr kvs))))
1983 (defun org-index--do-delete ()
1984 "Perform command delete."
1986 (unless (org-at-heading-p)
1987 (error "Not at headline"))
1989 (let* ((id (org-entry-get (point) "ID"))
1990 (ref (org-index--ref-from-id id)))
1992 ;; maybe delete from heading
1993 (if ref
1994 (save-excursion
1995 (end-of-line)
1996 (let ((end (point)))
1997 (beginning-of-line)
1998 (when (search-forward ref end t)
1999 (delete-char (- (length ref)))
2000 (just-one-space)))))
2002 ;; delete from index table
2003 (if (org-index--delete-line id)
2004 (format "Deleted index line %s" ref)
2005 (format "Did not find id %s in index" id))))
2008 (defun org-index--go (&optional column value)
2009 "Position cursor on index line where COLUMN equals VALUE.
2010 Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
2011 (let (found text)
2013 (unless (eq (current-buffer) org-index--buffer)
2014 (error "This is a bug: Not in index buffer"))
2016 ;; loop over lines
2017 (goto-char org-index--below-hline)
2018 (if column
2019 (progn
2020 (forward-line -1)
2021 (while (and (not found)
2022 (forward-line)
2023 (org-at-table-p))
2024 (setq found (string= value (org-index--get-or-set-field column)))))
2025 (setq found t))
2027 ;; return value
2028 (if found
2030 (goto-char org-index--below-hline)
2031 nil)))
2034 (defun org-index--do-head (ref id &optional other)
2035 "Perform command head: Find node with REF or ID and present it.
2036 If OTHER in separate window."
2038 (setq org-index--last-ref ref)
2040 (let (message marker)
2042 (setq marker (org-id-find id t))
2044 (if marker
2045 (progn
2046 (org-index--update-line id)
2047 (let (cb)
2048 (if other
2049 (progn
2050 (setq cb (current-buffer))
2051 (pop-to-buffer (marker-buffer marker)))
2052 (pop-to-buffer-same-window (marker-buffer marker)))
2054 (goto-char marker)
2055 (org-reveal t)
2056 (org-show-entry)
2057 (recenter))
2058 (setq message (format "Found headline %s" ref)))
2059 (setq message (format "Did not find headline %s" ref)))))
2062 (defun org-index--do-occur ()
2063 "Perform command occur."
2064 (let ((word "") ; last word to search for growing and shrinking on keystrokes
2065 (prompt "Search for: ")
2066 (lines-wanted (window-body-height))
2067 (lines-found 0) ; number of lines found
2068 words ; list words that should match
2069 occur-buffer
2070 begin ; position of first line
2071 narrow ; start of narrowed buffer
2072 help-text ; cons with help text short and long
2073 key-help ; for keys with special function
2074 search-text ; description of text to search for
2075 done ; true, if loop is done
2076 in-c-backspace ; true, while processing C-backspace
2077 show-headings ; true, if headings should be shown
2078 help-overlay ; Overlay with help text
2079 last-point ; Last position before end of search
2080 key ; input from user
2081 key-sequence) ; as a sequence
2084 ;; make and show buffer
2085 (if (get-buffer org-index--occur-buffer-name)
2086 (kill-buffer org-index--occur-buffer-name))
2087 (setq occur-buffer (make-indirect-buffer org-index--buffer org-index--occur-buffer-name))
2088 (pop-to-buffer-same-window occur-buffer)
2089 ;; avoid modifying direct buffer
2090 (setq buffer-read-only t)
2091 (toggle-truncate-lines 1)
2092 (setq font-lock-keywords-case-fold-search t)
2093 (setq case-fold-search t)
2095 ;; reset stack and overlays
2096 (setq org-index--occur-stack nil)
2097 (setq org-index--occur-tail-overlay nil)
2099 ;; narrow to table rows and one line before
2100 (goto-char (marker-position org-index--below-hline))
2101 (forward-line 0)
2102 (setq begin (point))
2103 (forward-line -1)
2104 (setq narrow (point))
2105 (while (org-at-table-p)
2106 (forward-line))
2107 (narrow-to-region narrow (point))
2108 (goto-char (point-min))
2109 (forward-line)
2111 ;; initialize help text
2112 (setq help-text (cons
2113 "Incremental occur; `?' toggles help and headlines.\n"
2114 (concat
2115 (org-index--wrap
2116 (concat
2117 "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"))
2118 org-index--headings)))
2120 ;; insert overlays for help text and to cover unsearched lines
2121 (setq help-overlay (make-overlay (point-min) begin))
2122 (overlay-put help-overlay 'display (car help-text))
2123 (overlay-put help-overlay 'face 'org-agenda-dimmed-todo-face)
2124 (setq org-index--occur-tail-overlay (make-overlay (point-max) (point-max)))
2125 (overlay-put org-index--occur-tail-overlay 'invisible t)
2127 (while (not done)
2129 (if in-c-backspace
2130 (setq key "<backspace>")
2131 (setq search-text (mapconcat 'identity (reverse (cons word words)) ","))
2132 ;; read key
2133 (setq key-sequence
2134 (vector (read-key
2135 (format "%s%s%s"
2136 prompt
2137 search-text
2138 (if (string= search-text "") "" " ")))))
2139 (setq key (key-description key-sequence)))
2141 (cond
2144 ((string= key "<C-backspace>")
2145 (setq in-c-backspace t))
2148 ((member key (list "<backspace>" "DEL")) ; erase last char
2150 (if (= (length word) 0)
2152 ;; nothing more to delete from current word; try next
2153 (progn
2154 (setq word (car words))
2155 (setq words (cdr words))
2156 (setq in-c-backspace nil))
2158 ;; unhighlight longer match
2159 (unhighlight-regexp (regexp-quote word))
2161 ;; some chars are left; shorten word
2162 (setq word (substring word 0 -1))
2163 (when (= (length word) 0) ; when nothing left, use next word from list
2164 (setq word (car words))
2165 (setq words (cdr words))
2166 (setq in-c-backspace nil))
2168 ;; free top list of overlays and remove list
2169 (setq lines-found (or (org-index--unhide) lines-wanted))
2170 (move-overlay org-index--occur-tail-overlay
2171 (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
2172 (point-max))
2173 (point-max))
2176 ;; highlight shorter word
2177 (unless (= (length word) 0)
2178 (highlight-regexp (regexp-quote word) 'isearch))
2180 ;; make sure, point is still visible
2181 (goto-char begin)))
2184 ((member key (list "SPC" ",")) ; space or comma: enter an additional search word
2186 ;; push current word and clear, no need to change display
2187 (setq words (cons word words))
2188 (setq word ""))
2191 ((string= key "?") ; question mark: toggle display of headlines and help
2192 (setq help-text (cons (cdr help-text) (car help-text)))
2193 (overlay-put help-overlay 'display (car help-text)))
2195 ((and (= (length key) 1)
2196 (aref printable-chars (elt key 0))) ; any printable char: add to current search word
2198 ;; unhighlight short word
2199 (unless (= (length word) 0)
2200 (unhighlight-regexp (regexp-quote word)))
2202 ;; add to word
2203 (setq word (concat word key))
2205 ;; make overlays to hide lines, that do not match longer word any more
2206 (goto-char begin)
2207 (setq lines-found (org-index--hide-with-overlays (cons word words) lines-wanted))
2208 (move-overlay org-index--occur-tail-overlay
2209 (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
2210 (point-max))
2211 (point-max))
2213 (goto-char begin)
2215 ;; highlight longer word
2216 (highlight-regexp (regexp-quote word) 'isearch)
2218 ;; make sure, point is on a visible line
2219 (line-move -1 t)
2220 (line-move 1 t))
2222 ;; anything else terminates loop
2223 (t (setq done t))))
2225 ;; put back input event, that caused the loop to end
2226 (unless (string= key "C-g")
2227 (setq unread-command-events (listify-key-sequence key-sequence))
2228 (message key))
2230 ;; postprocessing
2231 (setq last-point (point))
2233 ;; For performance reasons do not show matching lines for rest of table. So no code here.
2235 ;; make permanent copy
2236 ;; copy visible lines
2237 (let ((lines-collected 0)
2238 keymap line all-lines end-of-head)
2240 (setq cursor-type t)
2241 (goto-char begin)
2243 ;; collect all visible lines
2244 (while (and (not (eobp))
2245 (< lines-collected lines-wanted))
2246 ;; skip over invisible lines
2247 (while (and (invisible-p (point))
2248 (not (eobp)))
2249 (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
2250 (setq line (buffer-substring (line-beginning-position) (line-end-position)))
2251 (unless (string= line "")
2252 (incf lines-collected)
2253 (setq all-lines (cons (concat line
2254 "\n")
2255 all-lines)))
2256 (forward-line 1))
2258 (kill-buffer org-index--occur-buffer-name) ; cannot keep this buffer; might become stale soon
2260 ;; create new buffer
2261 (setq occur-buffer (get-buffer-create org-index--occur-buffer-name))
2262 (pop-to-buffer-same-window occur-buffer)
2263 (insert org-index--headings)
2264 (setq end-of-head (point))
2266 ;; insert into new buffer
2267 (save-excursion
2268 (apply 'insert (reverse all-lines))
2269 (if (= lines-collected lines-wanted)
2270 (insert "\n(more lines omitted)\n")))
2272 (org-mode)
2273 (setq truncate-lines t)
2274 (if (org-at-table-p) (org-table-align))
2275 (font-lock-fontify-buffer)
2277 ;; prepare help text
2278 (setq org-index--occur-help-overlay (make-overlay (point-min) end-of-head))
2279 (setq org-index--occur-help-text
2280 (cons
2281 (org-index--wrap
2282 (concat "Search is done; `?' toggles help and headlines.\n"))
2283 (concat
2284 (org-index--wrap (format (concat "Search is done. "
2285 (if (< lines-collected lines-wanted)
2286 " Showing all %d matches for "
2287 " Showing one window of matches for ")
2288 "\"" search-text
2289 "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> to matching line in index, <space> increments count.\n" )
2290 (length all-lines)))
2291 org-index--headings)))
2293 (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))
2294 (overlay-put org-index--occur-help-overlay 'face 'org-agenda-dimmed-todo-face)
2296 ;; highlight words
2297 (setq case-fold-search t)
2298 (setq font-lock-keywords-case-fold-search t)
2299 (mapc (lambda (w) (unless (or (not w) (string= w "")) (highlight-regexp (regexp-quote w) 'isearch)))
2300 (cons word words))
2302 (setq buffer-read-only t)
2304 ;; install keyboard-shortcuts
2305 (setq keymap (make-sparse-keymap))
2306 (set-keymap-parent keymap org-mode-map)
2308 (mapc (lambda (x) (define-key keymap (kbd x)
2309 (lambda () (interactive)
2310 (message "%s" (org-index--occur-to-head)))))
2311 (list "<return>" "RET"))
2313 (define-key keymap (kbd "<tab>")
2314 (lambda () (interactive)
2315 (message (org-index--occur-to-head t))))
2317 (define-key keymap (kbd "SPC")
2318 (lambda () (interactive)
2319 ;; increment in index
2320 (let ((ref (org-index--get-or-set-field 'ref))
2321 count)
2322 (org-index--on
2323 'ref ref
2324 (setq count (+ 1 (string-to-number (org-index--get-or-set-field 'count))))
2325 (org-index--get-or-set-field 'count (number-to-string count))
2326 (org-index--promote-current-line)
2327 (org-index--align-and-fontify-current-line))
2328 ;; increment in this buffer
2329 (let ((inhibit-read-only t))
2330 (org-index--get-or-set-field 'count (number-to-string count)))
2331 (message "Incremented count to %d" count))))
2333 (define-key keymap (kbd "<S-return>")
2334 (lambda () (interactive)
2335 (org-index 'enter (org-index--get-or-set-field 'ref))))
2337 (define-key keymap (kbd "?")
2338 (lambda () (interactive)
2339 (setq-local org-index--occur-help-text (cons (cdr org-index--occur-help-text) (car org-index--occur-help-text)))
2340 (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))))
2342 (use-local-map keymap))))
2345 (defun org-index--wrap (text)
2346 "Wrap TEXT at fill column."
2347 (with-temp-buffer
2348 (insert text)
2349 (fill-region (point-min) (point-max) nil t)
2350 (buffer-string)))
2353 (defun org-index--occur-to-head (&optional other)
2354 "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window."
2355 (let ((ref (org-index--get-or-set-field 'ref))
2356 (id (org-index--get-or-set-field 'id)))
2357 (if id
2358 (org-index--do-head ref id other)
2359 (message "Current line has no id."))))
2362 (defun org-index--hide-with-overlays (words lines-wanted)
2363 "Hide text that is currently visible and does not match WORDS by creating overlays; leave LINES-WANTED lines visible."
2364 (let ((lines-found 0)
2365 (end-of-visible (point))
2366 overlay overlays start matched)
2368 ;; main loop
2369 (while (and (not (eobp))
2370 (< lines-found lines-wanted))
2372 ;; skip invisible lines
2373 (while (and (not (eobp))
2374 (and
2375 (invisible-p (point))
2376 (< (point) (overlay-start org-index--occur-tail-overlay))))
2377 (goto-char (overlay-end (car (overlays-at (point))))))
2379 ;; find stretch of lines, that are currently visible but should be invisible now
2380 (setq matched nil)
2381 (setq start (point))
2382 (while (and (not (eobp))
2383 (not
2384 (and
2385 (invisible-p (point))
2386 (< (point) (overlay-start org-index--occur-tail-overlay))))
2387 (not (and (org-index--test-words words)
2388 (setq matched t)))) ; for its side effect
2389 (forward-line 1))
2391 ;; create overlay to hide this stretch
2392 (when (< start (point)) ; avoid creating an empty overlay
2393 (setq overlay (make-overlay start (point)))
2394 (overlay-put overlay 'invisible t)
2395 (setq overlays (cons overlay overlays)))
2397 ;; skip and count line, that matched
2398 (when matched
2399 (forward-line 1)
2400 (setq end-of-visible (point))
2401 (incf lines-found)))
2403 ;; put new list on top of stack
2404 (setq org-index--occur-stack
2405 (cons (list (cons :overlays overlays)
2406 (cons :end-of-visible end-of-visible)
2407 (cons :lines lines-found))
2408 org-index--occur-stack))
2410 lines-found))
2413 (defun org-index--unhide ()
2414 "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
2415 (when org-index--occur-stack
2416 ;; delete overlays and make visible again
2417 (mapc (lambda (y)
2418 (delete-overlay y))
2419 (cdr (assoc :overlays (car org-index--occur-stack))))
2420 ;; remove from stack
2421 (setq org-index--occur-stack (cdr org-index--occur-stack))
2422 ;; return number of lines, that are now visible
2423 (if org-index--occur-stack (cdr (assoc :lines (car org-index--occur-stack))))))
2426 (defun org-index--test-words (words)
2427 "Test current line for match against WORDS."
2428 (let (line)
2429 (setq line (downcase (buffer-substring (line-beginning-position) (line-beginning-position 2))))
2430 (catch 'not-found
2431 (dolist (w words)
2432 (or (search w line)
2433 (throw 'not-found nil)))
2434 t)))
2437 (defun org-index--create-new-line ()
2438 "Do the common work for `org-index-new-line' and `org-index'."
2440 (let (new)
2442 ;; construct new reference
2443 (unless new
2444 (setq new (format "%s%d%s" org-index--head (1+ org-index--maxref) org-index--tail)))
2446 ;; insert ref or id as last or first line, depending on sort-column
2447 (goto-char org-index--below-hline)
2448 (if (eq (org-index--special-column 'sort) 'count)
2449 (progn
2450 (while (org-at-table-p)
2451 (forward-line))
2452 (forward-line -1)
2453 (org-table-insert-row t))
2454 (org-table-insert-row))
2456 ;; insert some of the standard values
2457 (org-table-goto-column (org-index--column-num 'created))
2458 (org-insert-time-stamp nil nil t)
2459 (org-table-goto-column (org-index--column-num 'count))
2460 (insert "1")
2462 new))
2465 (defun org-index--sort-silent ()
2466 "Sort index for default column to remove any effects of temporary sorting."
2467 (save-excursion
2468 (org-index--verify-id)
2469 (org-index--parse-table)
2470 (org-index--on nil nil
2471 (org-index--do-sort-index (org-index--special-column 'sort))
2472 (org-table-align)
2473 (remove-hook 'before-save-hook 'org-index--sort-silent))))
2476 (defun org-index--copy-visible (beg end)
2477 "Copy the visible parts of the region without adding it to kill-ring; copy of `org-copy-visible'"
2478 (let (snippets s)
2479 (save-excursion
2480 (save-restriction
2481 (narrow-to-region beg end)
2482 (setq s (goto-char (point-min)))
2483 (while (not (= (point) (point-max)))
2484 (goto-char (org-find-invisible))
2485 (push (buffer-substring s (point)) snippets)
2486 (setq s (goto-char (org-find-visible))))))
2487 (apply 'concat (nreverse snippets))))
2490 (provide 'org-index)
2492 ;; Local Variables:
2493 ;; fill-column: 75
2494 ;; comment-column: 50
2495 ;; End:
2497 ;;; org-index.el ends here