New command add, new structure of index table, many fixes and enhancements.
[org-mode/org-tableheadings.git] / contrib / lisp / org-index.el
blob34ac628945030b23b982b2b5cab7ed429f9070e1
1 ;;; org-index.el --- A personal index for org and beyond
3 ;; Copyright (C) 2011-2014 Free Software Foundation, Inc.
5 ;; Author: Marc Ihm <org-index@2484.de>
6 ;; Version: 3.0
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 ;; Mark and find your favorite things and org-locations easily:
31 ;; Create and update an index table of references and links. When
32 ;; searching, frequently used entries appear at the top and entering
33 ;; some keywords narrows down to matching entries only, so that the
34 ;; right one can be spotted easily.
36 ;; References are essentially small numbers (e.g. "R237" or "-455-"),
37 ;; as created by this package; they are well suited to be used
38 ;; outside of org. Links are normal org-mode links.
41 ;; Setup:
43 ;; - Add these lines to your .emacs (modify appropriately):
45 ;; (require 'org-index)
46 ;; (org-index-default-keybindings) ; optional
48 ;; - Restart your Emacs to make these lines effective.
50 ;; - Invoke `org-index', which will assist in creating your index
51 ;; table. The variable org-index-id will be persisted within your
52 ;; customization file (typically .emacs).
55 ;; Further reading:
57 ;; See the documentation of `org-index', which can also be read
58 ;; by invoking `org-index' and choosing the help-command.
61 ;; Updates:
63 ;; The latest tested version of this file can always be found at:
65 ;; http://orgmode.org/w/org-mode.git?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
67 ;;; Change Log:
69 ;; [2014-12-07 Sa] Version 3.0.0:
70 ;; - New commands "add" and "delete" to easily add and remove
71 ;; the current node to or from your index.
72 ;; - New command "example" to create an example index.
73 ;; - Moved flags to a list within the same node as the index table;
74 ;; this breaks compatibility to prior versions of the package.
75 ;; - Several new flags that are explained within index node.
76 ;; - Removed commands "reuse", "missing", "put", "goto",
77 ;; "update", "link", "fill", "unhighlight"
78 ;; - New function `org-index-default-keybindings'
80 ;; [2014-04-26 Sa] Version 2.4.3:
81 ;; - Some Bug fixes and enhancements for occur-command
82 ;; - Fixes for assistant to create index table
84 ;; [2014-02-01 Sa] Version 2.4.2:
85 ;; - Follow mode in occur-buffer
86 ;; - Reorder for x-columns
88 ;; [2014-01-02 Th] Version 2.4.0:
89 ;; - New command "put" to store a nodes reference in a property
90 ;; - New functions org-index-new-line and org-index-get-line
91 ;; offer access to org-index from other lisp programs
92 ;; - New flag p, new columns x1,x2 and x3
93 ;; - Major Code refactoring
94 ;; - Regression tests with ert
95 ;; - Lots of bug fixes
97 ;; [2013-10-04 Fr] Version 2.3.2:
98 ;; - Bug fix: index-table created by assistant is found after
99 ;; restart of emacs instead of invoking assistant again
101 ;; [2013-07-20 Sa] Version 2.3.0:
102 ;; - Renamed from "org-favtable" to "org-index"
103 ;; - Added an assistant to set up the index table
104 ;; - occur is now incremental, searching as you type
105 ;; - simplified the documentation and help-system
106 ;; - Saving keystrokes, as "+g237" is now valid input
107 ;; - Many bug fixes
109 ;; [2013-02-28 Th] Version 2.2.0:
110 ;; - Allowed shortcuts like "h237" for command "head" with argument "237"
111 ;; - Integrated with org-mark-ring-goto
113 ;; [2013-01-25 Fr] Version 2.1.0:
114 ;; - Added full support for links
115 ;; - New commands "statistics"
116 ;; - Renamed the package from "org-reftable" to "org-favtable"
117 ;; - Additional columns are required (e.g. "link"). Error messages will
118 ;; guide you
120 ;; [2012-12-07 Fr] Version 2.0.0:
121 ;; - The format of the table of favorites has changed ! You need to bring
122 ;; your existing table into the new format by hand (which however is
123 ;; easy and explained below)
124 ;; - Reference table can be sorted after usage count or date of last access
125 ;; - Ask user explicitly, which command to invoke
126 ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
128 ;; [2012-09-22 Sa] Version 1.5.0:
129 ;; - New command "sort" to sort a buffer or region by reference number
130 ;; - New commands "highlight" and "unhighlight" to mark references
132 ;; [2012-07-13 Fr] Version 1.4.0:
133 ;; - New command "head" to find a headline with a reference number
135 ;; [2012-04-28 Sa] Version 1.3.0:
136 ;; - New commands occur and multi-occur
137 ;; - All commands can now be invoked explicitly
138 ;; - New documentation
139 ;; - Many bugfixes
141 ;; [2011-12-10 Sa] Version 1.2.0:
142 ;; - Fixed a bug, which lead to a loss of newly created reference numbers
143 ;; - Introduced single and double prefix arguments
144 ;; - Started this Change Log
146 ;;; Code:
148 (require 'org-table)
149 (require 'cl)
151 (defcustom org-index-id nil
152 "Id of the Org-mode node, which contains the index table."
153 :group 'org
154 :group 'org-index)
156 ;; Variables to hold the configuration of the index table
157 (defvar org-index--maxref nil "Maximum number from reference table (e.g. \"153\").")
158 (defvar org-index--head nil "Any header before number (e.g. \"R\").")
159 (defvar org-index--tail nil "Tail after number (e.g. \"}\" or \")\".")
160 (defvar org-index--numcols nil "Number of columns in index table.")
161 (defvar org-index--ref-regex nil "Regular expression to match a reference.")
162 (defvar org-index--ref-format nil "Format, that can print a reference.")
163 (defvar org-index--columns nil "Columns of index-table.")
164 (defvar org-index--special-columns nil "Columns with flags, that may appear only once.")
165 (defvar org-index--flagged-columns nil "Columns with flags, that may appear multiple times.")
166 (defvar org-index--buffer nil "Buffer of index table.")
167 (defvar org-index--point nil "Position at start of headline of index table.")
168 (defvar org-index--below-hline nil "Position of first cell in first line below hline.")
169 (defvar org-index--headings nil "Headlines of index-table as a string.")
170 (defvar org-index-map nil "Keymap for shortcuts for some commands of `org-index'. Can be activated and filled by org-index-default-keybings.")
172 ;; Variables to hold context and state
173 (defvar org-index--last-action nil "Last action performed by `org-index'.")
174 (defvar org-index--text-to-yank nil "Text, that can be yanked after call (mostly a reference).")
175 (defvar org-index--last-ref nil "Last reference created or visited.")
176 (defvar org-index--point-before nil "Point in buffer with index table.")
177 (defvar org-index--point-saved nil "Saved point if we want to return.")
178 (defvar org-index--category-before nil "Category of node before.")
179 (defvar org-index--silent nil "Set to t, if user should not be queried.")
180 (defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
181 (defvar org-index--below-cursor nil "Word below cursor.")
182 (defvar org-index--within-node nil "True, if we are within node of the index table.")
183 (defvar org-index--active-window-index nil "Active window with index table (if any).")
184 (defvar org-index--occur-follow-mode nil "True, if follow mode in occur-buffer is on.")
185 (defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
188 ;; static information for this program package
189 (defconst org-index--commands '(occur add delete head enter leave ref help example reorder sort multi-occur highlight statistics) "List of commands available.")
190 (defconst org-index--required-flags '(sort) "Flags that are required.")
191 (defconst org-index--single-flags '(sort point-on-add yank-after-add) "Flags, that may only appear once; these can appear as special-columns.")
192 (defconst org-index--multiple-flags '(edit-on-add get-category-on-add get-heading-on-add) "Flags, that might appear multiple times.")
193 (defconst org-index--all-flags (append org-index--single-flags org-index--multiple-flags) "All flags.")
194 (defconst org-index--valid-headings '(ref link created last-accessed count keywords) "All valid headings.")
195 (defconst org-index--required-headings org-index--valid-headings "All required headings.")
196 (defconst org-index--sample-flags
198 - columns-and-flags :: associate columns of index table with flags
199 - ref
200 - yank-after-add
201 - .category
202 - get-category-on-add
203 - edit-on-add
204 - keywords
205 - get-heading-on-add
206 - edit-on-add
207 - point-on-add
208 - count
209 - sort
210 - last-accessed
211 - created
212 - link
213 - all-columns-explained :: All columns of the index table and their meaning
214 - ref :: The reference number; will be generated automatically
215 - link :: link to the node, that this line represents
216 - created :: When has this entry been created ?
217 - last-accessed :: When has this entry been accessed last ?
218 - count :: How many times has this entry been picked ?
219 - keywords :: List of keywords, which may match your input during occur
220 - all-flags-explained :: All flags, that can be associated with columns
221 - sort :: Sort whole table after this column
222 - yank-after-add :: Let this column be yanked after picking this line
223 - edit-on-add :: Edit this line when adding a new one
224 - point-on-add :: Point will land here, when adding a new line
225 - get-category-on-add :: This column will receive the nodes category during add
226 - get-heading-on-add :: This column will receive the nodes heading during add"
227 "A sample string of flags.")
230 (defun org-index (&optional command)
231 "Mark and find your favorite things and org-locations easily:
232 Create and update an index table of references and links. When
233 searching, frequently used entries appear at the top and entering
234 some keywords narrows down to matching entries only, so that the
235 right one can be spotted easily.
237 References are essentially small numbers (e.g. \"R237\" or \"-455-\"),
238 as created by this package; they are well suited to be used
239 outside of org. Links are normal `org-mode' links.
242 This is version 3.0 of org-index.el .
245 The function `org-index' operates on a dedicated table, the index
246 table, which lives within its own Org-mode node. The table and
247 its containing node will be created, when you first invoke
248 `org-index'. The node will have some comments, describing the
249 columns of the index table and their associated flags. The index
250 table is found through the id of the containing node, which is
251 stored within the variable `org-index-id'.
254 The function `org-index' is the only interactive function of this
255 package and its main entry point; once invoked it asks, which of
256 it subcommands to execute:
258 occur: Incremental search, that shows matching lines from the
259 index table, updated after every keystroke. You may enter a
260 list of words seperated by space or comma (\",\"), to select
261 lines that contain all of the given words.
263 add: Add the current node to your index, so that it can be
264 found through the subcommand \"occur\".
266 delete: Delete the current node from your index.
268 head: Ask for a reference number and search for an entry, which
269 either has this reference contained in its heading or within
270 its property org-index-ref.
272 enter: Enter index table and maybe go to a specific reference.
274 leave: Leave the index table and return to your previous location.
276 ref: Create a new reference.
278 help: Show this text.
280 example: Create a temporary index, that will not be saved, but
281 may serve as an example.
283 reorder: Temporarily reorder the index table, e.g. by count,
284 reference or last access.
286 sort: Sort a set of lines (either from the active region or the
287 whole buffer) by references found in each line.
289 multi-occur: Apply Emacs standard `multi-occur' operation on all
290 `org-mode' buffers to search for the given reference.
292 highlight: Highlight or unhiglight references in active region or buffer.
294 statistics : Show some statistics (e.g. minimum and maximum
295 reference) about index table.
297 If you invoke `org-index' for the first time, an assistant will be
298 invoked, that helps you to create your own, commented index.
300 Use `org-index-default-keybindings' to establish convenient
301 keyboard shortcuts.
303 Optional argument COMMAND is a symbol naming the command to execute."
305 (interactive "P")
307 (let ((org-index--silent nil) ; t, if user can be asked
308 prefix-arg ; prefix arg
309 link-id ; link of starting node, if required
310 search ; what to search for
311 guarded-search ; with guard against additional digits
312 search-ref ; search, if search is a reference
313 search-link ; search, if search is a link
314 reorder-once ; column to use for single time sorting
315 kill-new-text ; text that will be appended to kill ring
316 initial-ref-or-link ; initial position in index table
317 message-text) ; text that will be issued as an explanation
321 ;; Initialize and parse
324 ;; creates index table, if necessary
325 (org-index--verify-id)
327 ;; Get configuration of index table
328 (org-index--parse-table)
330 ;; store context information
331 (org-index--retrieve-context)
335 ;; Find out, what we are supposed to do
338 (when (equal command '(4))
339 (setq prefix-arg command)
340 (setq command nil))
342 (if command
343 (unless (memq command org-index--commands)
344 (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
345 command (mapconcat 'symbol-name org-index--commands ",")))
346 (let ((r (org-index--read-command))) ; query user if not from argument
347 (setq command (car r))
348 (setq reorder-once (cdr r))))
352 ;; Get search, if required
355 ;; These actions need a search string:
356 (when (memq command '(enter head))
357 ;; Maybe we've got a search string from the arguments
358 (setq search (org-index--get-or-read-search search command))
360 (when search
361 (when (string-match org-index--ref-regex search)
362 (setq search-ref search)
363 (setq guarded-search (org-index--make-guarded-search search)))
364 (when (string-match "^[a-fA-F0-9]\\{8\\}-[a-fA-F0-9]\\{4\\}-[a-fA-F0-9]\\{4\\}-[a-fA-F0-9]\\{4\\}-[a-fA-F0-9]\\{12\\}$" search)
365 (setq search-link search))))
369 ;; Check for invalid combinations of arguments; try to be helpful
372 (when (and (eq command 'head)
373 (not search-ref)
374 (not search-link))
375 (error "Can do 'head' only for a reference or link (not '%s'), try 'occur' to search for text" search))
379 ;; Sort and enter table
382 ;; Get link if required before moving in
383 (if (eq command 'add)
384 (setq link-id (org-id-get-create)))
386 ;; Save initial ref or link for later return
387 (if (and org-index--within-node
388 (org-at-table-p))
389 (setq initial-ref-or-link
390 (or (org-index--get-field 'ref)
391 (org-index--get-field 'link))))
393 ;; These commands enter index table only temporarily
394 (when (memq command '(occur multi-occur statistics example))
396 (set-buffer org-index--buffer)
397 (goto-char org-index--point)
399 ;; Sort and align
400 (org-index--sort reorder-once)
401 (org-index--align))
403 ;; These commands will leave user in index table after they are finished
404 (when (memq command '(enter ref))
406 ;; Support orgmode-standard of going back (buffer and position)
407 (org-mark-ring-push)
409 (org-pop-to-buffer-same-window org-index--buffer)
410 (goto-char org-index--point)
411 (org-index--unfold-buffer)
413 ;; Sort and align
414 (org-index--sort reorder-once)
415 (org-index--align)
417 ;; Remember position for leave
418 (if org-index--point-before
419 (setq org-index--point-saved org-index--point-before)))
421 ;; prepare to return to initial position in index table
422 (when initial-ref-or-link
423 (while (and (org-at-table-p)
424 (not (or
425 (string= initial-ref-or-link (org-index--get-field 'ref))
426 (string= initial-ref-or-link (org-index--get-field 'link)))))
427 (forward-line))
428 ;; did not find ref, go back to top
429 (if (not (org-at-table-p)) (goto-char org-index--point)))
433 ;; Actually do, what is requested
436 (cond
439 ((eq command 'help)
441 ;; bring up help-buffer for this function
442 (describe-function 'org-index))
445 ((eq command 'multi-occur)
447 ;; Position point in index buffer on reference to search for
448 (goto-char org-index--below-hline)
449 (let (found (initial (point)))
450 (while (and (not found)
451 (forward-line)
452 (org-at-table-p))
453 (save-excursion
454 (setq found (string= search
455 (org-index--get-field 'ref)))))
456 (if found
457 (org-index--update-line nil)
458 (goto-char initial)))
460 ;; Construct list of all org-buffers
461 (let (buff org-buffers)
462 (dolist (buff (buffer-list))
463 (set-buffer buff)
464 (if (string= major-mode "org-mode")
465 (setq org-buffers (cons buff org-buffers))))
467 ;; Do multi-occur
468 (multi-occur org-buffers guarded-search)
470 ;; Present results
471 (if (get-buffer "*Occur*")
472 (progn
473 (setq message-text (format "multi-occur for '%s'" search))
474 (other-window 1)
475 (toggle-truncate-lines 1))
476 (setq message-text (format "Did not find '%s'" search)))))
479 ((eq command 'add)
481 (setq kill-new-text (org-index--do-add link-id)))
484 ((eq command 'delete)
486 (org-index--do-delete))
489 ((eq command 'head)
491 (let (link)
492 (if (and org-index--within-node
493 (org-at-table-p))
494 (setq link (org-index--get-field 'link))))
496 (setq message-text (org-index--do-head search-ref search-link)))
499 ((eq command 'leave)
501 (setq kill-new-text org-index--text-to-yank)
502 (setq org-index--text-to-yank nil)
504 ;; If "leave" has been called two times in succession, make
505 ;; org-mark-ring-goto believe it has been called two times too
506 (if (eq org-index--last-action 'leave)
507 (let ((this-command nil) (last-command nil))
508 (org-mark-ring-goto 1))
509 (org-mark-ring-goto))
511 ;; Return to saved position in index buffer
512 (when org-index--point-saved
513 ;; buffer displayed in window need to set point there first
514 (if (eq (window-buffer org-index--active-window-index)
515 org-index--buffer)
516 (set-window-point org-index--active-window-index (marker-position org-index--point-saved)))
517 ;; set position in buffer in any case and second
518 (with-current-buffer org-index--buffer
519 (goto-char org-index--point-saved)))
520 (setq org-index--point-saved nil))
523 ((eq command 'enter)
525 ;; Go downward in table to requested reference
526 (goto-char org-index--below-hline)
527 (if search
528 (let (found (initial (point)))
529 (while (and (not found)
530 (forward-line)
531 (org-at-table-p))
532 (save-excursion
533 (setq found
534 (string= search
535 (org-index--get-field
536 (if search-link 'link 'ref))))))
537 (if found
538 (progn
539 (setq message-text (format "Found '%s'" search))
540 (org-index--update-line nil)
541 (org-table-goto-column (org-index--column-num 'ref))
542 (if (looking-back " ") (backward-char))
543 ;; remember string to copy
544 (setq org-index--text-to-yank
545 (org-trim (org-table-get-field (org-index--column-num 'copy)))))
546 (setq message-text (format "Did not find '%s'" search))
547 (goto-char initial)
548 (forward-line)
549 (setq command 'missed)))
551 ;; simply go into table
552 (setq message-text "At index table"))
554 (recenter))
557 ((eq command 'occur)
559 (org-index--do-occur))
562 ((eq command 'ref)
564 (let (new)
566 ;; add a new row
567 (setq new (org-index--create-new-line (eq command 'ref)))
569 ;; fill special columns with standard values
570 (org-table-goto-column (org-index--column-num 'ref))
571 (insert new)
572 (setq org-index--last-ref new)
574 (org-index--align)
576 ;; goto point-field or first empty one or first field
577 (if (org-index--special-column 'point-on-add)
578 (org-table-goto-column (org-index--column-num (org-index--special-column 'point-on-add)))
579 (unless (catch 'empty
580 (dotimes (col org-index--numcols)
581 (org-table-goto-column (+ col 1))
582 (if (string= (org-trim (org-table-get-field)) "")
583 (throw 'empty t))))
584 ;; none found, goto first
585 (org-table-goto-column 1)))
587 (if org-index--active-region (setq kill-new-text org-index--active-region))
588 (setq message-text (format "Adding a new row with ref '%s'" new))))
591 ((eq command 'sort)
593 ;; sort lines according to contained reference
594 (let (begin end where)
595 (catch 'aborted
596 ;; either active region or whole buffer
597 (if (and transient-mark-mode
598 mark-active)
599 ;; sort only region
600 (progn
601 (setq begin (region-beginning))
602 (setq end (region-end))
603 (setq where "region"))
604 ;; sort whole buffer
605 (setq begin (point-min))
606 (setq end (point-max))
607 (setq where "whole buffer")
608 ;; make sure
609 (unless (y-or-n-p "Sort whole buffer? ")
610 (setq message-text "Sort aborted")
611 (throw 'aborted nil)))
613 (save-excursion
614 (save-restriction
615 (goto-char (point-min))
616 (narrow-to-region begin end)
617 (sort-subr nil 'forward-line 'end-of-line
618 (lambda ()
619 (if (looking-at (concat ".*"
620 (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
621 (string-to-number (match-string 1))
622 0))))
623 (highlight-regexp org-index--ref-regex 'isearch)
624 (setq message-text (format "Sorted %s from character %d to %d, %d lines"
625 where begin end
626 (count-lines begin end)))))))
630 ((eq command 'highlight)
632 (let ((where "buffer"))
633 (save-excursion
634 (save-restriction
635 (when (and transient-mark-mode
636 mark-active)
637 (narrow-to-region (region-beginning) (region-end))
638 (setq where "region"))
640 (if prefix-arg
641 (progn
642 (unhighlight-regexp org-index--ref-regex)
643 (setq message-text (format "Removed highlights for references in %s" where)))
644 (highlight-regexp org-index--ref-regex 'isearch)
645 (setq message-text (format "Highlighted references in %s" where)))))))
648 ((eq command 'statistics)
650 (setq message-text (org-index--do-statistics)))
653 ((eq command 'example)
655 (if (y-or-n-p "This assistand will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
656 (org-index--create-index t)))
659 (t (error "This is a bug: unmatched case '%s'" command)))
662 ;; remember what we have done for next time
663 (setq org-index--last-action command)
665 ;; tell, what we have done and what can be yanked
666 (if kill-new-text (setq kill-new-text
667 (substring-no-properties kill-new-text)))
668 (if (string= kill-new-text "") (setq kill-new-text nil))
669 (let ((m (concat
670 message-text
671 (if (and message-text kill-new-text)
672 " and r"
673 (if kill-new-text "R" ""))
674 (if kill-new-text (format "eady to yank '%s'" kill-new-text) ""))))
675 (unless (string= m "")
676 (message m)
677 (setq org-index--message-text m)))
678 (if kill-new-text (kill-new kill-new-text))))
681 (defun org-index-default-keybindings ()
682 "Set default keybindings for `org-index'.
684 Establish the common prefix key `C-c i' which is followed by the
685 first letter of a subcommand, so that `C-c i a' invokes the
686 subcommand \"add\". Subcommands available are occur, add, delete,
687 head, enter, leave and ref. As a special case `C-c i i' invokes
688 `org-index' to let you choose."
689 (define-prefix-command 'org-index-map)
690 (global-set-key (kbd "C-c i") 'org-index-map)
691 (define-key org-index-map (kbd "i") (lambda () (interactive) (org-index)))
692 (define-key org-index-map (kbd "o") (lambda () (interactive) (org-index 'occur)))
693 (define-key org-index-map (kbd "a") (lambda () (interactive) (org-index 'add)))
694 (define-key org-index-map (kbd "d") (lambda () (interactive) (org-index 'delete)))
695 (define-key org-index-map (kbd "h") (lambda () (interactive) (org-index 'head)))
696 (define-key org-index-map (kbd "e") (lambda () (interactive) (org-index 'enter)))
697 (define-key org-index-map (kbd "l") (lambda () (interactive) (org-index 'leave)))
698 (define-key org-index-map (kbd "r") (lambda () (interactive) (org-index 'ref))))
701 (defun org-index-new-line (&rest keys-values)
702 "Create a new line within the index table, returning its reference.
704 The function takes a varying number of argument pairs; each pair
705 is a symbol for an existing column heading followed by its value.
707 Example:
709 (org-index-new-line 'ref t 'link \"7f480c3e\")
711 Passing \"'ref t\" will make the function create a new reference
712 within the new line.
714 Optional argument KEYS-VALUES specifies content of new line."
716 (org-index--verify-id)
717 (org-index--parse-table)
719 (car (org-index--do-new-line keys-values)))
722 (defun org-index--do-new-line (&rest keys-values)
723 "Do the work for `org-index-new-line'.
724 Optional argument KEYS-VALUES specifies content of new line."
726 (let ((org-index--silent t))
728 (save-excursion
729 (org-index--retrieve-context)
730 (with-current-buffer org-index--buffer
731 (goto-char org-index--point)
733 ;; check arguments early
734 (let ((kvs keys-values)
735 k v)
736 (while kvs
737 (setq k (car kvs))
738 (setq v (cadr kvs))
739 (if (eq k 'ref)
740 (unless (memq v '(t nil))
741 (error "Column 'ref' accepts only t or nil"))
742 (if (or (not (symbolp k))
743 (and (symbolp v) (not (eq v t)) (not (eq v nil))))
744 (error "Arguments must be alternation of key and value")))
745 (unless (org-index--column-num k)
746 (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
747 (setq kvs (cddr kvs))))
749 (if (and (not (plist-get keys-values 'ref))
750 (not (stringp (plist-get keys-values 'link))))
751 (error "Need a link when not creating a ref"))
753 (let (ref yank)
754 ;; create new line
755 (setq ref (org-index--create-new-line (plist-get keys-values 'ref)))
756 (plist-put keys-values 'ref (or ref ""))
758 ;; fill columns
759 (let ((kvs keys-values)
760 k v n)
761 (while kvs
762 (setq k (car kvs))
763 (setq v (cadr kvs))
764 (setq n (org-index--column-num k))
765 (org-table-goto-column n)
766 (insert v)
767 (setq kvs (cddr kvs))))
769 ;; get column to yank
770 (setq yank (org-trim (org-table-get-field (org-index--column-num (org-index--special-column 'yank-after-add)))))
772 (org-index--sort)
773 (cons ref yank))))))
776 (defun org-index-get-line (type value)
777 "Retrieve an existing line within the index table by ref or link.
778 Return its contents as a property list.
780 The function `plist-get' may be used to retrieve specific elements
781 from the result.
783 Example:
785 (plist-get (org-index-get-line 'ref \"12\") 'count)
787 retrieves the value of the count-column for reference 12.
789 Argument TYPE is a symbol, either ref or link,
790 argument VALUE specifies the value to search for."
791 ;; check arguments
792 (unless (memq type '(ref link))
793 (error "Argument can only be 'ref' or 'link'"))
795 (org-index--verify-id)
796 (org-index--parse-table)
798 (org-index--get-or-delete-line 'get type value))
801 (defun org-index--get-or-delete-line (command type value)
802 "Get or delete (according to COMMAND) a line by TYPE and VALUE."
803 (let ((org-index--silent t)
804 found)
806 (save-excursion
807 (org-index--retrieve-context)
808 (with-current-buffer org-index--buffer
809 (goto-char org-index--point)
811 (goto-char org-index--below-hline)
812 (while (and (not found)
813 (org-at-table-p))
814 (when (string= (org-index--get-field type)
815 value)
816 ;; found matching line
817 (if (eq command 'get)
818 ;; get its fields
819 (mapc (lambda (x)
820 (if (and (numberp (cdr x))
821 (> (cdr x) 0))
822 (setq found (cons (car x) (cons (or (org-index--get-field (car x)) "") found)))
823 )) (reverse org-index--columns))
824 ;; or delete it
825 (let ((start (point)))
826 (beginning-of-line)
827 (forward-line)
828 (delete-region start (point)))))
829 (forward-line))))
830 found))
833 (defun org-index--read-command ()
834 "Find out, what we are supposed to do."
836 (let (reorder-once ; Column to use for single time sorting
837 command
838 input)
840 ;; Ask user, what to do
841 (while (progn
843 (setq input
844 (org-completing-read
845 "Please choose: "
846 (mapcar 'symbol-name org-index--commands)
847 nil nil))
849 ;; convert to symbol
850 (setq command (intern input))
852 ;; ask for reorder in loop, because we may have to ask for command right again
853 (if (eq command 'reorder)
854 (setq reorder-once
855 (intern
856 (org-icompleting-read
857 "Please choose column to reorder index table once: "
858 (list "ref" "count" "created" "last-accessed")
859 nil t))))
861 ;; maybe ask initial question again
862 (eq command 'reorder)))
863 (cons command reorder-once)))
866 (defun org-index--get-or-read-search (search command)
867 "Get SEARCH string, maybe read from user; respect COMMAND that will be executed."
869 (let (search-from-table
870 search-from-cursor)
872 (unless search
873 ;; Search string can come from several sources:
874 ;; From link or ref columns of table
875 (when (and org-index--within-node
876 (org-at-table-p))
877 (setq search-from-table (or (org-index--get-field 'link)
878 (org-index--get-field 'ref))))
880 ;; From string below cursor
881 (when (and (not org-index--within-node)
882 org-index--below-cursor
883 (string-match (concat "\\(" org-index--ref-regex "\\)")
884 org-index--below-cursor))
885 (setq search-from-cursor (match-string 1 org-index--below-cursor)))
887 ;; Depending on requested action, get search from one of the sources above
888 (cond ((eq command 'enter)
889 (setq search search-from-cursor))
890 ((memq command '(head occur))
891 (setq search (or search-from-table search-from-cursor)))))
894 ;; If we still do not have a search string, ask user explicitly
895 (unless search
897 (if org-index--silent (error "Need to specify search, if silence is required"))
899 (unless (eq command 'occur)
901 (setq search (read-from-minibuffer
902 (cond ((eq command 'head)
903 "Text or reference number to search for: ")
904 ((eq command 'enter)
905 "Reference number to search for (or <empty> for id of current node, `l' for last ref created, `t' for top of index table): "))))))
907 ;; Check for special case
908 (when (eq command 'enter)
909 (if (string= search "") (setq search (org-id-get)))
910 (if (string= search "t") (setq search nil))
911 (if (string= search "l") (setq search (number-to-string org-index--maxref))))
913 ;; Clean up and examine search string
914 (when search
915 (setq search (org-trim search))
916 (if (string= search "") (setq search nil))
917 (when search
918 (if (string-match "^[0-9]+$" search)
919 (setq search (concat org-index--head search org-index--tail)))))
921 search))
924 (defun org-index--verify-id ()
925 "Check, that we have a valid id."
927 ;; Check id
928 (unless org-index-id
929 (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet."))
931 ;; Find node
932 (let (marker)
933 (setq marker (org-id-find org-index-id 'marker))
934 (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
935 ; Try again with new node
936 (setq marker (org-id-find org-index-id 'marker))
937 (unless marker (error "Could not create node"))
938 (setq org-index--buffer (marker-buffer marker)
939 org-index--point (marker-position marker))
940 (move-marker marker nil)))
943 (defun org-index--retrieve-context ()
944 "Collect context information before starting with command."
946 ;; Get the content of the active region or the word under cursor
947 (setq org-index--active-region
948 (if (and transient-mark-mode mark-active)
949 (buffer-substring (region-beginning) (region-end))
950 nil))
951 (setq org-index--below-cursor (thing-at-point 'symbol))
953 ;; get category of current node
954 (setq org-index--category-before
955 (save-excursion ; workaround: org-get-category does not give category when at end of buffer
956 (beginning-of-line)
957 (org-get-category)))
959 ;; Find out, if we are within index table or not
960 (setq org-index--within-node (string= (org-id-get) org-index-id))
962 ;; Check and remember, if active window contains buffer with index table
963 (if (eq (window-buffer) org-index--buffer)
964 (setq org-index--active-window-index (selected-window)))
966 ;; get current position in index-buffer
967 (with-current-buffer org-index--buffer
968 (setq org-index--point-before
969 (if (string= (org-id-get) org-index-id)
971 (point-marker)))))
974 (defun org-index--parse-table ()
975 "Parse content of index table."
977 (let (ref-field
978 link-field
979 initial-point
980 end-of-headings
981 start-of-headings)
983 (with-current-buffer org-index--buffer
985 (setq org-index--maxref 0)
986 (setq initial-point (point))
988 (org-index--go-below-hline)
989 (beginning-of-line)
991 ;; get headings to display during occur
992 (setq end-of-headings (point))
993 (while (org-at-table-p) (forward-line -1))
994 (forward-line)
995 (setq start-of-headings (point))
996 (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
998 ;; count columns
999 (org-table-goto-column 100)
1000 (setq org-index--numcols (- (org-table-current-column) 1))
1002 ;; go to top of table
1003 (while (org-at-table-p)
1004 (forward-line -1))
1005 (forward-line)
1007 ;; parse line of headings
1008 (org-index--parse-headings)
1009 (forward-line 2)
1011 ;; parse list of flags
1012 (goto-char org-index--point)
1013 (org-index--parse-flags)
1015 (org-index--go-below-hline)
1016 (setq org-index--below-hline (point-marker))
1018 ;; Retrieve any decorations around the number within the first nonempty ref-field
1019 (goto-char org-index--below-hline)
1020 (while (and (org-at-table-p)
1021 (not (setq ref-field (org-index--get-field 'ref))))
1022 (forward-line))
1024 ;; Some Checking
1025 (unless ref-field
1026 (org-index--report-index-error "Reference column is empty"))
1028 (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
1029 (org-index--report-index-error
1030 "First reference in index table ('%s') does not contain a number" ref-field))
1032 ;; These are the decorations used within the first ref of index
1033 (setq org-index--head (match-string 1 ref-field))
1034 (setq org-index--tail (match-string 3 ref-field))
1035 (setq org-index--ref-regex (concat (regexp-quote org-index--head)
1036 "\\([0-9]+\\)"
1037 (regexp-quote org-index--tail)))
1038 (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
1040 ;; Go through table to find maximum number and do some checking
1041 (let ((ref 0))
1043 (while (org-at-table-p)
1045 (setq ref-field (org-index--get-field 'ref))
1046 (setq link-field (org-index--get-field 'link))
1048 (when (and (not ref-field)
1049 (not link-field))
1050 (kill-whole-line)
1051 (message "Removing line from index-table with both ref and link empty"))
1053 (if ref-field
1054 (if (string-match org-index--ref-regex ref-field)
1055 ;; grab number
1056 (setq ref (string-to-number (match-string 1 ref-field)))
1057 (kill-whole-line)
1058 (message "Removing line from index-table whose ref does not contain a number")))
1060 ;; check, if higher ref
1061 (if (> ref org-index--maxref) (setq org-index--maxref ref))
1063 (forward-line 1)))
1065 ;; go back to initial position
1066 (goto-char initial-point))))
1069 (defun org-index--sort (&optional sort-column)
1070 "Sort index table maybe according to SORT-COLUMN."
1072 (unless sort-column (setq sort-column (org-index--special-column 'sort)))
1074 (let ((is-modified (buffer-modified-p))
1076 bottom
1077 ref-field
1078 count-field)
1080 (unless buffer-read-only
1082 ;; get boundaries of table
1083 (goto-char org-index--below-hline)
1084 (forward-line 0)
1085 (setq top (point))
1086 (while (org-at-table-p) (forward-line))
1088 ;; Kill all empty rows at bottom
1089 (while (progn
1090 (forward-line -1)
1091 (org-table-goto-column 1)
1092 (and
1093 (not (org-index--get-field 'ref))
1094 (not (org-index--get-field 'link))))
1095 (org-table-kill-row))
1096 (forward-line 1)
1097 (setq bottom (point))
1099 (save-restriction
1100 (narrow-to-region top bottom)
1101 (goto-char top)
1102 (sort-subr t
1103 'forward-line
1104 'end-of-line
1105 (lambda ()
1106 (let (ref
1107 (ref-field (or (org-index--get-field 'ref) ""))
1108 (count-field (or (org-index--get-field 'count) "")))
1110 ;; get reference with leading zeroes, so it can be
1111 ;; sorted as text
1112 (string-match org-index--ref-regex ref-field)
1113 (setq ref (format
1114 "%06d"
1115 (string-to-number
1116 (or (match-string 1 ref-field)
1117 "0"))))
1119 ;; Construct different sort-keys according to
1120 ;; requested sort column
1121 (cond
1123 ((eq sort-column 'count)
1124 (concat (format
1125 "%08d"
1126 (string-to-number (or (org-index--get-field 'count)
1127 "")))
1128 ref))
1130 ((eq sort-column 'ref)
1131 ref)
1133 ((eq sort-column 'last-accessed)
1134 (concat (org-index--get-field sort-column)
1136 ref))
1138 (t (error "This is a bug: unmatched case '%s'" sort-column)))))
1140 nil 'string<))
1142 ;; restore modification state
1143 (set-buffer-modified-p is-modified))))
1146 (defun org-index--go-below-hline ()
1147 "Move below hline in index-table."
1149 (let ((count 0)
1150 (errstring (format "index table within node %s" org-index-id)))
1152 (goto-char org-index--point)
1154 ;; go to heading of node
1155 (while (not (org-at-heading-p)) (forward-line -1))
1156 (forward-line 1)
1158 ;; go to first table, but make sure we do not get into another node
1159 (while (and (not (org-at-table-p))
1160 (not (org-at-heading-p))
1161 (not (eobp)))
1162 (forward-line))
1164 ;; check, if there really is a table
1165 (unless (org-at-table-p)
1166 (org-index--create-missing-index "Cannot find %s." errstring))
1168 ;; go just after hline
1169 (while (and (not (org-at-table-hline-p))
1170 (org-at-table-p))
1171 (forward-line))
1172 (forward-line)
1174 ;; and check
1175 (unless (org-at-table-p)
1176 (org-index--report-index-error "Cannot find a hline within %s" errstring))
1178 (org-table-goto-column 1)))
1181 (defun org-index--align ()
1182 "Align index table without setting its buffer modified."
1183 (let ((is-modified (buffer-modified-p)))
1184 (unless buffer-read-only (org-table-align))
1185 (set-buffer-modified-p is-modified)
1186 (org-index--go-below-hline)
1187 (setq org-index--below-hline (point-marker))))
1190 (defun org-index--parse-headings ()
1191 "Parse headings of index table."
1193 (let (field ;; field content
1194 field-symbol ;; and as a symbol
1195 found)
1197 (setq org-index--columns nil)
1199 ;; For each column
1200 (dotimes (col org-index--numcols)
1202 (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
1204 (if (string= field "")
1205 (error "Column name cannot be empty"))
1206 (if (and (not (string= (substring field 0 1) "."))
1207 (not (member (intern field) org-index--valid-headings)))
1208 (error "Column name '%s' is not a valid heading (custom headings may start with a dot (e.g. '.foo')" field))
1210 (setq field-symbol (intern field))
1212 ;; check if heading has already appeared
1213 (if (assoc field-symbol org-index--columns)
1214 (org-index--report-index-error
1215 "'%s' appears two times as column heading" (downcase field))
1216 ;; add it to list at front, reverse later
1217 (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
1219 (setq org-index--columns (reverse org-index--columns))
1221 ;; check if all necessary headings have appeared
1222 (mapc (lambda (head)
1223 (unless (cdr (assoc head org-index--columns))
1224 (org-index--report-index-error "No column has heading '%s'" head)))
1225 org-index--required-headings))
1228 (defun org-index--parse-flags ()
1229 "Parse list of flags in index table."
1231 (let (parent parent-is-comment child)
1233 ;; reset configuration variables
1234 (setq org-index--special-columns nil)
1235 (setq org-index--flagged-columns nil)
1237 (org-index--goto-list "columns-and-flags" t)
1238 (forward-line 1)
1240 ;; outer loop over columns
1241 (while (and (setq parent (org-index--parse-list-item))
1242 parent
1243 (> (cdr (assoc :indent parent)) 0))
1245 (setq parent-is-comment (member (cdr (assoc :text parent)) '("all-columns-explained" "all-flags-explained")))
1247 ;; check, that we have a valid heading
1248 (unless (or parent-is-comment
1249 (assoc (cdr (assoc :sym parent)) org-index--columns))
1250 (org-index--report-index-error "'%s' is not a valid column" (cdr (assoc :text parent))))
1252 ;; inner loop over children
1253 (while (and (forward-line 1)
1254 (setq child (org-index--parse-list-item))
1255 child
1256 (> (cdr (assoc :indent child))
1257 (cdr (assoc :indent parent))))
1259 (unless parent-is-comment
1260 ;; check, that we have a valid flag
1261 (unless (memq (cdr (assoc :sym child)) org-index--all-flags)
1262 (org-index--report-index-error "'%s' is not a valid flag" (cdr (assoc :text child))))
1264 ;; process flag with respect to current index-column
1265 (if (memq (cdr (assoc :sym child)) org-index--single-flags)
1266 ;; Check, that none of org-index--single-flags appears twice
1267 (if (assoc (cdr (assoc :sym child)) org-index--special-columns)
1268 (org-index--report-index-error
1269 "More than one column is marked with flag '%s'" (cdr (assoc :text child)))
1270 ;; add it to list
1271 (setq org-index--special-columns (cons (cons (cdr (assoc :sym child)) (cdr (assoc :sym parent)))
1272 org-index--special-columns))))
1274 ;; all flags are stored in org-index--flagged-columns
1275 (let ((l (assoc (cdr (assoc :sym child)) org-index--flagged-columns))) ;; list of flag and columns, that carry this flag
1276 (unless l
1277 ;; no list of columns with this flag is present, create one
1278 (setq org-index--flagged-columns
1279 (cons (cons (cdr (assoc :sym child)) nil)
1280 org-index--flagged-columns))
1281 (setq l (car org-index--flagged-columns)))
1282 ;; prepend this column to list of columns with this flag
1283 (setcdr l (cons (cdr (assoc :sym parent)) (cdr l)))))))
1285 ;; check, that all needed flags have been specified
1286 (mapc (lambda (x)
1287 (unless (assoc x org-index--special-columns)
1288 (org-index--report-index-error "Required flag '%s' does not appear" (substring (symbol-name x) 1))))
1289 org-index--required-flags)))
1292 (defun org-index--goto-list (name &optional required non-top)
1293 "Goto list NAME (maybe NON-TOP Level) in index node, err if REQUIRED list is not present."
1294 (goto-char org-index--point)
1296 ;; go to heading of node
1297 (while (not (org-at-heading-p)) (forward-line -1))
1298 (forward-line 1)
1300 ;; go to named list
1301 (while (and (not (let ((item (org-index--parse-list-item)))
1302 (if item
1303 (and (or non-top (= (cdr (assoc :indent item)) 0)) ;; accept only toplevel ?
1304 (string= (cdr (assoc :text item)) name)) ;; with requested name
1305 nil)))
1306 (not (org-at-table-p))
1307 (not (org-at-heading-p))
1308 (not (eobp)))
1309 (forward-line 1))
1311 (if (org-at-item-p)
1313 (if required
1314 (org-index--report-index-error "Could not find required list '%s'" name)
1315 nil)))
1318 (defun org-index--parse-list-item ()
1319 "Parse a list item into an assoc array (indent, checkbox, text, value)."
1321 (if (looking-at org-list-full-item-re)
1323 ;; retrieve interesting parts of list item from match data
1324 (let (alist indent checkbox text value)
1326 (setq indent (save-excursion
1327 (goto-char (match-beginning 1))
1328 (current-column)))
1329 (decf indent (+ (save-match-data (org-current-level)) 1))
1330 (add-to-list 'alist (cons :indent indent))
1332 (setq checkbox (match-string 3))
1334 (setq text (match-string 4))
1335 (setq value (buffer-substring
1336 (match-end 0)
1337 (save-excursion (end-of-line) (point))))
1339 (when (not text)
1340 (setq text value)
1341 (setq value nil))
1343 (add-to-list 'alist (cons :text text))
1344 (add-to-list 'alist (cons :value value))
1346 (add-to-list 'alist (cons :sym (intern text)))
1348 ;; clean up strings
1349 (mapc (lambda (x) (if (stringp (cdr x)) (setf (cdr x) (org-trim (substring-no-properties (cdr x)))))) alist)
1351 alist)
1353 nil))
1357 (defun org-index--create-missing-index (&rest reasons)
1358 "Create a new empty index table with detailed explanation. Argument REASONS explains why."
1360 (org-index--ask-before-create-index "Cannot find your index table: "
1361 "new permanent" "."
1362 reasons)
1363 (org-index--create-index))
1367 (defun org-index--report-index-error (&rest reasons)
1368 "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
1370 (org-index--ask-before-create-index "The existing index contains this error: "
1371 "temporary" ", to compare with."
1372 reasons)
1373 (org-index--create-index t t))
1377 (defun org-index--ask-before-create-index (explanation type for-what reasons)
1378 ; checkdoc-params: (explanation type for-what reasons)
1379 "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
1380 (let (reason prompt)
1382 (setq reason (apply 'format reasons))
1383 (if org-index--silent (error (concat explanation reason))) ; cannot proceed without querying the user
1385 (setq prompt (concat explanation reason "\n\n"
1386 "However, this assistant can help you to create a "
1387 type " index with detailed comments" for-what "\n\n"
1388 "Do you want to proceed ?"))
1390 (unless (let ((max-mini-window-height 1.0))
1391 (y-or-n-p prompt))
1392 (error explanation reason))))
1396 (defun org-index--create-index (&optional temporary compare)
1397 "Create a new empty index table with detailed explanation.
1398 specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
1399 (let (buffer
1400 title
1401 firstref
1404 (if temporary
1405 (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
1406 (buffer-name "*org-index-example-index*"))
1407 (setq buffer (get-buffer-create buffer-name))
1408 (with-current-buffer buffer
1409 ;; but it needs a file for its index to be found
1410 (unless (string= (buffer-file-name) file-name)
1411 (set-visited-file-name file-name))
1412 (rename-buffer buffer-name) ; name is change by line above
1414 (erase-buffer)
1415 (org-mode)))
1417 (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)) nil nil))))
1419 (setq title (read-from-minibuffer "Please enter the title of the index node: "))
1421 (while (progn
1422 (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: "))
1423 (let (desc)
1424 (when (string-match "[[:blank:]]" firstref)
1425 (setq desc "Contains whitespace"))
1426 (when (string-match "[[:cntrl:]]" firstref)
1427 (setq desc "Contains control characters"))
1428 (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
1429 ;; firstref not okay, report details
1430 (setq desc
1431 (cond ((string= firstref "") "is empty")
1432 ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
1433 ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
1434 ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
1437 (if desc
1438 (progn
1439 (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
1441 nil))))
1443 (with-current-buffer buffer
1444 (goto-char (point-max))
1445 (insert (format "* %s %s\n" firstref title))
1446 (if temporary
1447 (insert "
1448 Below you find your temporary index table, which will not last longer
1449 than your current emacs session.
1451 (insert "
1452 Below you find your initial index table, which will grow over time.
1454 (insert "
1455 You may start using it by adding some lines. Just move to
1456 another heading, invoke `org-index' and choose the command
1457 \"add\". After adding a few nodes, try the command \"occur\"
1458 to search among them.
1460 To gain further insight you may invoke the subcommand \"help\", or
1461 read the description of `org-index'.
1463 Within the index table below, dhe sequence of columns does not
1464 matter. You may reorder them any way you like. Columns are
1465 found by their heading. You may also add your own columns.
1467 Following these explanations there is the item-list
1468 `columns-and-flags', which influences the behaviour of
1469 `org-index'. See the explanations which are part of this list.
1471 This node needs not be a top level node; its name is completely
1472 at your choice; it is found through its ID only.
1474 Remark: These lines of explanation can be removed at any time.
1477 (setq id (org-id-get-create))
1478 (insert (format "
1482 | ref | .category | keywords | count | last-accessed | created | link |
1483 | | | | | | | <4> |
1484 |-----+-----------+----------+-------+---------------+---------+------|
1485 | %s | | %s | | | %s | %s |
1488 org-index--sample-flags
1489 firstref
1490 "This node"
1491 (with-temp-buffer (org-insert-time-stamp nil nil t))
1492 id))
1494 (save-excursion(org-index--goto-list "columns-and-flags")
1496 ;; make sure, that node can be found
1497 (org-id-add-location id (buffer-file-name))
1498 (setq buffer-save-without-query t)
1499 (basic-save-buffer)
1501 (while (not (org-at-table-p)) (forward-line -1))
1502 (unless buffer-read-only (org-table-align))
1503 (while (not (org-at-heading-p)) (forward-line -1))
1505 ;; present results to user
1506 (if temporary
1507 (progn
1508 ;; Present existing and temporary index together
1509 (when compare
1510 (org-pop-to-buffer-same-window org-index--buffer)
1511 (goto-char org-index--point)
1512 (org-index--unfold-buffer)
1513 (delete-other-windows)
1514 (select-window (split-window-vertically)))
1515 ;; show new index
1516 (org-pop-to-buffer-same-window buffer)
1517 (org-id-goto id)
1518 (org-index--unfold-buffer)
1519 (if compare
1520 (error "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
1521 (message "This is your new temporary index.")))
1522 (progn
1523 ;; Only show the new index
1524 (org-pop-to-buffer-same-window buffer)
1525 (delete-other-windows)
1526 (org-id-goto id)
1527 (org-index--unfold-buffer)
1528 (setq org-index-id id)
1529 (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 ? ")
1530 (progn
1531 (customize-save-variable 'org-index-id id)
1532 (error "Saved org-index-id '%s' to %s" id custom-file))
1533 (let (sq)
1534 (setq sq (format "(setq org-index-id \"%s\")" id))
1535 (kill-new sq)
1536 (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))))))))
1539 (defun org-index--unfold-buffer ()
1540 "Helper function to unfold buffer."
1541 (org-show-context)
1542 (org-show-subtree)
1543 (recenter 1)
1544 (save-excursion
1545 (org-back-to-heading)
1546 (forward-line) ;; on property drawer
1547 (org-cycle)
1548 (org-index--goto-list "columns-and-flags")
1549 (org-cycle)))
1552 (defun org-index--update-line (ref-or-link)
1553 "Update columns count and last-accessed in line REF-OR-LINK."
1555 (let ((newcount 0)
1556 initial)
1558 (with-current-buffer org-index--buffer
1559 (unless buffer-read-only
1561 ;; search reference or link, if given (or assume, that we are already positioned right)
1562 (when ref-or-link
1563 (setq initial (point))
1564 (goto-char org-index--below-hline)
1565 (while (and (org-at-table-p)
1566 (not (or (string= ref-or-link (org-index--get-field 'ref))
1567 (string= ref-or-link (org-index--get-field 'link)))))
1568 (forward-line)))
1570 (if (not (org-at-table-p))
1571 (error "Did not find reference or link '%s'" ref-or-link)
1572 (org-index--update-current-line))
1574 (if initial (goto-char initial))))))
1577 (defun org-index--update-current-line ()
1578 "Update current lines columns count and last-accessed."
1579 (let (newcount (count-field (org-index--get-field 'count)))
1581 ;; update count field only if number or empty
1582 (when (or (not count-field)
1583 (string-match "^[0-9]+$" count-field))
1584 (setq newcount (+ 1 (string-to-number (or count-field "0"))))
1585 (org-index--get-field 'count
1586 (number-to-string newcount)))
1588 ;; update timestamp
1589 (org-table-goto-column (org-index--column-num 'last-accessed))
1590 (org-table-blank-field)
1591 (org-insert-time-stamp nil t t)))
1594 (defun org-index--get-field (key &optional value)
1595 "Retrieve field KEY from index table or set it to VALUE."
1596 (let (field)
1597 (save-excursion
1598 (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value)))
1599 (if (string= field "") (setq field nil))
1601 (org-no-properties field))))
1604 (defun org-index--column-num (key)
1605 "Return number of column KEY."
1606 (if (numberp key)
1608 (cdr (assoc key org-index--columns))))
1611 (defun org-index--special-column (key)
1612 "Return column (not a number) for special column KEY."
1613 (cdr (assoc key org-index--special-columns)))
1616 (defun org-index--flag-p (flag column)
1617 "Check if COLUMN has FLAG set."
1618 (unless (memq flag org-index--all-flags)
1619 (error (format "Internal error: unknown flag %s" (symbol-name flag))))
1620 (memq column (assoc flag org-index--flagged-columns)))
1623 (defun org-index--make-guarded-search (ref &optional dont-quote)
1624 "Make robust search string from REF; DONT-QUOTE it, if requested."
1625 (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
1628 (defun org-index--do-statistics ()
1629 "Compute statistics about index table."
1630 (let ((total 0)
1631 ref-field
1635 message)
1638 ;; go through table and remove all refs, that we see
1639 (goto-char org-index--below-hline)
1640 (while (org-at-table-p)
1642 ;; get ref-field and number
1643 (setq ref-field (org-index--get-field 'ref))
1644 (if (and ref-field
1645 (string-match org-index--ref-regex ref-field))
1646 (setq ref (string-to-number (match-string 1 ref-field))))
1648 ;; record min and max
1649 (if (or (not min) (< ref min)) (setq min ref))
1650 (if (or (not max) (> ref max)) (setq max ref))
1652 ;; count
1653 (setq total (1+ total))
1655 (forward-line))
1657 (setq message (format "Found %d references from %s to %s."
1658 total
1659 (format org-index--ref-format min)
1660 (format org-index--ref-format max)))
1662 message))
1665 (defun org-index--do-add (link-id)
1666 "For current node (with id LINK-ID): add a new line to index table."
1668 (let ((args (list 'ref t 'link link-id))
1669 ref-and-yank content)
1671 (unless (org-at-heading-p)
1672 (error "Not at headline"))
1674 ;; some fields want to be edited
1675 (dolist (col-num org-index--columns)
1677 (setq content "")
1679 ;; copy heading ?
1680 (if (org-index--flag-p 'get-heading-on-add (car col-num))
1681 (setq content (nth 4 (org-heading-components))))
1683 ;; copy category ?
1684 (if (org-index--flag-p 'get-category-on-add (car col-num))
1685 (setq content org-index--category-before))
1687 (if (org-index--flag-p 'edit-on-add (car col-num))
1688 (read-from-minibuffer
1689 (format "Edit text for column '%s': " (symbol-name (car col-num)))
1690 content))
1692 (if (not (string= content ""))
1693 (setq args (append (list (car col-num) content) args))))
1695 ;; new line in index table
1696 (setq ref-and-yank (apply 'org-index--do-new-line args))
1698 ;; insert reference
1699 (org-entry-put (point) "org-index-ref" (car ref-and-yank))
1701 (cdr ref-and-yank)))
1704 (defun org-index--do-delete ()
1705 "Perform command delete."
1707 (unless (org-at-heading-p)
1708 (error "Not at headline"))
1710 (let ((ref (org-entry-get (point) "org-index-ref")))
1712 ;; delete from index table
1713 (org-index--get-or-delete-line 'delete 'ref ref)
1715 ;; delete from property
1716 (org-entry-delete (point) "org-index-ref")
1718 ;; maybe delete from heading
1719 (save-excursion
1720 (end-of-line)
1721 (let ((end (point)))
1722 (beginning-of-line)
1723 (when (search-forward ref end t)
1724 (delete-char (- (length ref)))
1725 (just-one-space))))))
1728 (defun org-index--do-head (ref link &optional other)
1729 "Perform command head: Find node with REF or LINK and present it; if OTHER in separate window."
1731 (if ref (setq org-index--last-ref ref))
1733 (let (message)
1734 ;; Use link if available
1735 (if link
1736 (progn
1737 (org-index--update-line link)
1738 (org-id-goto link)
1739 (org-reveal)
1740 (setq message "Followed link"))
1742 (message (format "Scanning headlines for '%s' ..." ref))
1743 (org-index--update-line ref)
1744 (let ((search (concat ".*" (org-index--make-guarded-search ref)))
1745 (org-trust-scanner-tags t)
1746 buffer point)
1747 (if (catch 'found
1748 (progn
1749 ;; loop over all headlines, stop on first match
1750 (org-map-entries
1751 (lambda ()
1752 (when (or (looking-at search)
1753 (eq ref (org-entry-get (point) "org-index-ref")))
1754 ;; If this is not an inlinetask ...
1755 (when (< (org-element-property :level (org-element-at-point))
1756 org-inlinetask-min-level)
1757 ;; ... remember location and bail out
1758 (setq buffer (current-buffer))
1759 (setq point (point))
1760 (throw 'found t))))
1761 nil 'agenda)
1762 nil))
1764 (progn
1765 (setq message (format "Found '%s'" (or ref link)))
1766 (if other
1767 (progn
1768 (pop-to-buffer buffer)
1769 (goto-char point)
1770 (org-reveal t)
1771 (recenter)
1772 (pop-to-buffer "*org-index-occur*"))
1773 (org-pop-to-buffer-same-window buffer)
1774 (goto-char point)
1775 (org-reveal t)
1776 (recenter)))
1777 (setq message (format "Did not find '%s'" (or ref link))))))
1778 message))
1781 (defun org-index--do-occur ()
1782 "Perform command occur."
1783 (let ((occur-buffer-name "*org-index-occur*")
1784 (word "") ; last word to search for growing and shrinking on keystrokes
1785 (prompt "Search for: ")
1786 (hint "")
1787 (key-help "<up>, <down> move. <return> finds node, <tab> finds in other window.\n")
1788 words ; list of other words that must match too
1789 occur-buffer
1790 lines-to-show ; number of lines to show in window
1791 start-of-lines ; position, where lines begin
1792 start-of-help ; start of displayed help (if any)
1793 left-off-at ; stack of last positions in index table
1794 after-inserted ; in occur-buffer
1795 at-end ; in occur-buffer
1796 lines-visible ; in occur-buffer
1797 below-hline-bol ; below-hline and at bol
1798 exit-gracefully ; true if normal exit
1799 in-c-backspace ; true while processing C-backspace
1800 show-headings ; true, if headings should be shown
1801 fun-on-ret ; function to be executed, if return is pressed
1802 fun-on-s-ret ; shift
1803 fun-on-m-ret ; shift
1804 fun-on-tab ; function to be executed, if tab is pressed
1805 ret from to key)
1807 ;; clear buffer
1808 (if (get-buffer "*org-index-occur*")
1809 (kill-buffer occur-buffer-name))
1810 (setq occur-buffer (get-buffer-create "*org-index-occur*"))
1812 ;; install keyboard-shortcuts within occur-buffer
1813 (with-current-buffer occur-buffer
1814 (let ((keymap (make-sparse-keymap)))
1816 (set-keymap-parent keymap org-mode-map)
1817 (setq fun-on-ret (lambda () (interactive) (org-index--occur-find-heading nil)))
1818 (define-key keymap [return] fun-on-ret)
1819 (setq fun-on-tab (lambda () (interactive)
1820 (org-index--occur-find-heading t)
1821 (setq org-index--occur-follow-mode (not org-index--occur-follow-mode))))
1822 (define-key keymap [tab] fun-on-tab)
1823 (define-key keymap [(control ?i)] fun-on-tab)
1824 (define-key keymap [up] (lambda () (interactive)
1825 (forward-line -1)
1826 (if org-index--occur-follow-mode (org-index--occur-find-heading t))))
1827 (define-key keymap [down] (lambda () (interactive)
1828 (forward-line 1)
1829 (if org-index--occur-follow-mode (org-index--occur-find-heading t))))
1830 (use-local-map keymap)))
1832 (with-current-buffer org-index--buffer
1833 (let ((initial (point)))
1834 (goto-char org-index--below-hline)
1835 (forward-line 0)
1836 (setq below-hline-bol (point))
1837 (goto-char initial)))
1839 (org-pop-to-buffer-same-window occur-buffer)
1840 (toggle-truncate-lines 1)
1842 (unwind-protect ; to reset cursor-shape even in case of errors
1843 (progn
1845 ;; fill in header
1846 (erase-buffer)
1847 (insert (concat "Incremental search, showing one window of matches. '?' toggles help.\n\n"))
1848 (setq start-of-lines (point-marker))
1849 (setq start-of-help start-of-lines)
1850 (setq cursor-type 'hollow)
1852 ;; get window size of occur-buffer as number of lines to be searched
1853 (setq lines-to-show (+ (- (window-body-height) (line-number-at-pos)) 1))
1855 ;; fill initially
1856 (setq ret (org-index--get-matching-lines nil lines-to-show below-hline-bol))
1857 (when (nth 0 ret)
1858 (insert (nth 1 ret))
1859 (setq left-off-at (cons (nth 0 ret) nil))
1860 (setq after-inserted (cons (point) nil)))
1862 ;; read keys
1863 (while
1864 (progn
1865 (goto-char start-of-lines)
1866 (setq lines-visible 0)
1868 (if in-c-backspace
1869 (setq key 'backspace)
1870 (let ((search-text (mapconcat 'identity (reverse (cons word words)) ",")))
1871 (setq key (read-key
1872 (format "%s%s%s%s"
1873 prompt
1874 search-text
1875 (if (string= search-text "") "" " ")
1876 hint))))
1877 (setq hint "")
1878 (setq exit-gracefully (member key (list 'up 'down 'left 'right 'RET ?\C-g ?\C-m
1879 'C-return 'S-return ?\C-i 'TAB))))
1882 (not exit-gracefully))
1884 (cond
1886 ((eq key 'C-backspace)
1888 (setq in-c-backspace t))
1890 ((member key (list 'backspace 'deletechar ?\C-?)) ; erase last char
1892 (if (= (length word) 0)
1894 ;; nothing more to delete from current word; try next
1895 (progn
1896 (setq word (car words))
1897 (setq words (cdr words))
1898 (setq in-c-backspace nil))
1900 ;; unhighlight longer match
1901 (let ((case-fold-search t))
1902 (unhighlight-regexp (regexp-quote word)))
1904 ;; some chars are left; shorten word
1905 (setq word (substring word 0 -1))
1906 (when (= (length word) 0) ; when nothing left, use next word from list
1907 (setq word (car words))
1908 (setq words (cdr words))
1909 (setq in-c-backspace nil))
1911 ;; remove everything, that has been added for char just deleted
1912 (when (cdr after-inserted)
1913 (setq after-inserted (cdr after-inserted))
1914 (goto-char (car after-inserted))
1915 (delete-region (point) (point-max)))
1917 ;; back up last position in index table too
1918 (when (cdr left-off-at)
1919 (setq left-off-at (cdr left-off-at)))
1921 ;; go through buffer and check, if any invisible line should now be shown
1922 (goto-char start-of-lines)
1923 (while (< (point) (point-max))
1924 (if (outline-invisible-p)
1925 (progn
1926 (setq from (line-beginning-position)
1927 to (line-beginning-position 2))
1929 ;; check for matches
1930 (when (org-index--test-words (cons word words) (buffer-substring from to))
1931 (when (<= lines-visible lines-to-show) ; show, if more lines required
1932 (outline-flag-region from to nil)
1933 (incf lines-visible))))
1935 ;; already visible, just count
1936 (incf lines-visible))
1938 (forward-line 1))
1940 ;; highlight shorter word
1941 (unless (= (length word) 0)
1942 (let ((case-fold-search t))
1943 (highlight-regexp (regexp-quote word) 'isearch)))))
1946 ((member key (list ?\s ?,)) ; space or comma: enter an additional search word
1948 ;; push current word and clear, no need to change display
1949 (setq words (cons word words))
1950 (setq word ""))
1953 ((eq key ??) ; question mark: toggle display of headlines and help
1954 (setq show-headings (not show-headings))
1955 (goto-char start-of-lines)
1956 (if show-headings
1957 (progn
1958 (forward-line -1)
1959 ; (kill-line)
1960 (setq start-of-help (point-marker))
1961 (insert "Normal keys add to search word, SPACE or COMMA start new word, BACKSPACE and C-BACKSPACE erase char or word. Every other key ends search. ")
1962 (insert key-help)
1963 (goto-char start-of-help)
1964 (fill-paragraph)
1965 (goto-char start-of-lines)
1966 (insert org-index--headings))
1967 (delete-region start-of-help start-of-lines)
1968 (insert "\n\n"))
1969 (setq start-of-lines (point-marker)))
1972 ((and (integerp key)
1973 (aref printable-chars key)) ; any printable char: add to current search word
1975 ;; unhighlight short word
1976 (unless (= (length word) 0)
1977 (let ((case-fold-search t))
1978 (unhighlight-regexp (regexp-quote word))))
1980 ;; add to word
1981 (setq word (concat word (char-to-string key)))
1983 ;; hide lines, that do not match longer word any more
1984 (while (< (point) (point-max))
1985 (unless (outline-invisible-p)
1986 (setq from (line-beginning-position)
1987 to (line-beginning-position 2))
1989 ;; check for matches
1990 (if (org-index--test-words (list word) (buffer-substring from to))
1991 (incf lines-visible) ; count as visible
1992 (outline-flag-region from to t))) ; hide
1994 (forward-line 1))
1996 ;; duplicate top of stacks; eventually overwritten below
1997 (setq left-off-at (cons (car left-off-at) left-off-at))
1998 (setq after-inserted (cons (car after-inserted) after-inserted))
2000 ;; get new lines from index table
2001 (when (< lines-visible lines-to-show)
2002 (setq ret (org-index--get-matching-lines (cons word words)
2003 (- lines-to-show lines-visible)
2004 (car left-off-at)))
2006 (when (nth 0 ret)
2007 (insert (nth 1 ret))
2008 (setq at-end (nth 2 ret))
2009 (setcar left-off-at (nth 0 ret))
2010 (setcar after-inserted (point))))
2012 ;; highlight longer word
2013 (let ((case-fold-search t))
2014 (highlight-regexp (regexp-quote word) 'isearch)))
2017 (t ; non-printable chars
2018 (setq hint (format "(cannot search for key '%s', use %s to quit)"
2019 (if (symbolp key)
2021 (key-description (char-to-string key)))
2022 (substitute-command-keys "\\[keyboard-quit]"))))))
2024 ;; search is done collect and brush up results
2025 ;; remove any lines, that are still invisible
2026 (goto-char start-of-lines)
2027 (while (< (point) (point-max))
2028 (if (outline-invisible-p)
2029 (delete-region (line-beginning-position) (line-beginning-position 2))
2030 (forward-line 1))))
2032 ;; postprocessing even for non graceful exit
2033 (setq cursor-type t)
2034 ;; replace previous heading
2035 (let ((numlines (count-lines (point) start-of-lines)))
2036 (goto-char start-of-lines)
2037 (delete-region (point-min) (point))
2038 (insert (format (concat (if exit-gracefully "Search is done;" "Search aborted;")
2039 (if at-end
2040 " showing all %d matches. "
2041 " showing one window of matches. ")
2042 key-help)
2043 numlines))
2044 (insert "\n")
2045 (setq start-of-lines (point-marker))
2046 (goto-char (point-min))
2047 (fill-paragraph)
2048 (goto-char start-of-lines)
2049 (if show-headings (insert "\n\n" org-index--headings)))
2050 (forward-line))
2052 ;; perform action according to last char
2053 (forward-line -1)
2054 (cond
2056 ((member key (list 'RET ?\C-m))
2057 (funcall fun-on-ret))
2059 ((member key (list 'TAB ?\C-i))
2060 (funcall fun-on-tab))
2062 ((eq key 'up)
2063 (forward-line -1))
2065 ((eq key 'down)
2066 (forward-line 1)))))
2069 (defun org-index--occur-find-heading (x)
2070 "Helper for keymap of occur: find heading, if X in other window."
2071 (interactive)
2072 (save-excursion
2073 (let ((ref (org-index--get-field 'ref))
2074 (link (org-index--get-field 'link)))
2075 (message (org-index--do-head ref link x)))))
2078 (defun org-index--create-new-line (create-ref)
2079 "Do the common work for `org-index-new-line' and `org-index'. CREATE-REF asks for new reference."
2081 (let (new)
2083 (when create-ref
2085 ;; construct new reference
2086 (unless new
2087 (setq new (format "%s%d%s" org-index--head (1+ org-index--maxref) org-index--tail)))
2089 ;; remember for org-mark-ring-goto
2090 (setq org-index--text-to-yank new))
2092 ;; insert ref or link as very first row
2093 (goto-char org-index--below-hline)
2094 (org-table-insert-row)
2096 ;; insert some of the standard values
2097 (org-table-goto-column (org-index--column-num 'created))
2098 (org-insert-time-stamp nil nil t)
2099 (org-table-goto-column (org-index--column-num 'count))
2100 (insert "1")
2102 new))
2105 (defun org-index--get-matching-lines (words numlines start-from)
2106 "Helper for occur: search for WORDS and get NUMLINES lines from index table, starting at START-FROM."
2107 (let ((numfound 0)
2109 initial line lines at-end)
2111 (with-current-buffer org-index--buffer
2113 ;; remember initial pos and start at requested
2114 (setq initial (point))
2115 (goto-char start-from)
2117 ;; loop over buffer until we have found enough lines
2118 (while (and (or (< numfound numlines)
2119 (= numlines 0))
2120 (org-at-table-p))
2122 ;; check each word
2123 (setq line (buffer-substring (line-beginning-position) (line-beginning-position 2)))
2124 (when (org-index--test-words words line)
2125 (setq lines (concat lines line))
2126 (incf numfound))
2127 (forward-line 1)
2128 (setq pos (point)))
2130 (setq at-end (not (org-at-table-p)))
2132 ;; return to initial position
2133 (goto-char initial))
2135 (unless lines (setq lines ""))
2136 (list pos lines at-end)))
2139 (defun org-index--test-words (words line)
2140 "Test LINE for match against WORDS."
2141 (let ((found-all t))
2142 (setq line (downcase line))
2143 (catch 'not-found
2144 (dolist (w words)
2145 (or (search w line)
2146 (throw 'not-found nil)))
2147 t)))
2150 (defadvice org-mark-ring-goto (after org-index--advice-text-to-yank activate)
2151 "Make text from `org-index' available for yank."
2152 (when org-index--text-to-yank
2153 (kill-new org-index--text-to-yank)
2154 (message (format "Ready to yank '%s'" org-index--text-to-yank))
2155 (setq org-index--text-to-yank nil)))
2158 (provide 'org-index)
2160 ;; Local Variables:
2161 ;; fill-column: 75
2162 ;; comment-column: 50
2163 ;; End:
2165 ;;; org-index.el ends here