1 ;;; org-index.el --- A personal index for org
3 ;; Copyright (C) 2011-2016 Free Software Foundation, Inc.
5 ;; Author: Marc Ihm <org-index@2484.de>
7 ;; Keywords: outlines index
9 ;; This file is not part of GNU Emacs.
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)
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/>.
30 ;; Fast search for selected org nodes and things outside of org.
32 ;; org-index creates and updates an index table with keywords; each line
33 ;; either points to a heading in org, references something outside or
34 ;; carries a snippet of text to yank. When searching the index, the set
35 ;; of matching lines is updated with every keystroke; results are sorted
36 ;; by usage count and date, so that frequently used entries appear first
37 ;; in the list of results.
39 ;; References are decorated numbers (e.g. 'R237' or '--455--'); they are
40 ;; well suited to be used outside of org, e.g. in folder names, ticket
41 ;; systems or on printed documents.
43 ;; On first invocation org-index will assist you in creating the index
46 ;; To start using your index, invoke subcommands 'add', 'ref' and 'yank'
47 ;; to create entries and 'occur' to find them.
52 ;; - Place this file in a directory from your load-path,
53 ;; e.g. org-mode/contrib/lisp.
55 ;; - Add these lines to your .emacs:
57 ;; (require 'org-index)
58 ;; (org-index-default-keybindings) ; optional
60 ;; - Maybe restart your Emacs to make these lines effective.
62 ;; - Invoke `org-index'; on first run it will assist in creating your
65 ;; - Optionally invoke `M-x org-customize' to tune some settings (choose
69 ;; Further information:
71 ;; - Watch the screencast at http://2484.de/org-index.html.
73 ;; - See the documentation of `org-index', which can also be read
74 ;; by invoking `org-index' and choosing the help-command.
79 ;; The latest published version of this file can always be found at:
81 ;; http://orgmode.org/w/?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
85 ;; [2015-12-29 Tu] Version 5.0.2
86 ;; - New commands yank, column and edit
88 ;; - All columns are now required
89 ;; - References are now optional
90 ;; - Subcommand enter has been renamed to index
91 ;; - Subcommands kill and edit can be invoked from an occur buffer
93 ;; - Added link to screencast
95 ;; [2015-08-20 Th] Version 4.3.0
96 ;; - Configuration is done now via standard customize
97 ;; - New sorting strategy 'mixed'
98 ;; - Silenced some compiler warnings
100 ;; [2015-03-18 We] Version 4.2.1
101 ;; - No garbage in kill-ring
102 ;; - No recentering after add
104 ;; [2015-03-08 Su] Version 4.2.0
105 ;; - Reference numbers for subcommands can be passed as a prefix argument
106 ;; - New variable org-index-default-keybindings-list with a list of
107 ;; default keybindings for org-index-default-keybindings
108 ;; - Added new column level
109 ;; - removed flags get-category-on-add and get-heading-on-add
111 ;; [2015-02-26 Th] to [2015-03-05 Th] Version 4.0.0 to 4.1.2
112 ;; - Removed command "leave"; rather go back with org-mark-ring-goto
113 ;; - Renamed column "link" to "id"
114 ;; - Added maintainance options to find duplicate rows, to check ids,
115 ;; update index or remove property org-index-ref from nodes
116 ;; - Shortened versin history
118 ;; [2014-12-08 Mo] to [2015-01-31 Sa] Version 3.0.0 to 3.2.0:
119 ;; - Complete sorting of index only occurs in idle-timer
120 ;; - New command "maintain" with some subcommands
121 ;; - Rewrote command "occur" with overlays in an indirect buffer
122 ;; - Command "add" updates index, if node is already present
123 ;; - New commands "add" and "delete" to easily add and remove
124 ;; the current node to or from your index.
125 ;; - New command "example" to create an example index.
126 ;; - Several new flags that are explained within index node.
127 ;; - Removed commands "reuse", "missing", "put", "goto",
128 ;; "update", "link", "fill", "unhighlight"
129 ;; - New function `org-index-default-keybindings'
131 ;; [2012-12-07 Fr] to [2014-04-26 Sa] Version 2.0.0 to 2.4.3:
132 ;; - New functions org-index-new-line and org-index-get-line
133 ;; offer access to org-index from other lisp programs
134 ;; - Regression tests with ert
135 ;; - Renamed from "org-favtable" to "org-index"
136 ;; - Added an assistant to set up the index table
137 ;; - occur is now incremental, searching as you type
138 ;; - Integrated with org-mark-ring-goto
139 ;; - Added full support for ids
140 ;; - Renamed the package from "org-reftable" to "org-favtable"
141 ;; - Additional columns are required (e.g. "link"). Error messages will
143 ;; - Ask user explicitly, which command to invoke
144 ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
146 ;; [2011-12-10 Sa] to [2012-09-22 Sa] Version Version 1.2.0 to 1.5.0:
147 ;; - New command "sort" to sort a buffer or region by reference number
148 ;; - New commands "highlight" and "unhighlight" to mark references
149 ;; - New command "head" to find a headline with a reference number
150 ;; - New commands occur and multi-occur
151 ;; - Started this Change Log
159 ;; Version of this package
160 (defvar org-index-version
"5.0.2" "Version of `org-index', format is major.minor.bugfix, where \"major\" are incompatible changes and \"minor\" are new features.")
162 ;; customizable options
163 (defgroup org-index nil
164 "Options concerning the optional index for org."
168 (defcustom org-index-id nil
169 "Id of the Org-mode node, which contains the index table."
172 (defcustom org-index-sort-by
'mixed
173 "Strategy for sorting index table (and whence entries in occur).
176 last-access Sort index by date and time of last access; show
177 more recent entries first.
178 count Sort by usage count; more often used entries first.
179 mixed First, show all index entries, which have been
180 used today; sort them by last access. Then show
181 older entries sorted by usage count."
185 (if (and org-index-id
187 (functionp 'org-index--sort-silent
))
188 (org-index--sort-silent)))
189 :initialize
'custom-initialize-default
191 (const last-accessed
)
195 (defcustom org-index-yank-after-add
'ref
196 "Specifies which column should be yanked after adding a new index row.
197 Valid values are some columns of index table."
204 (defcustom org-index-point-on-add
'keywords
205 "Specifies in which column point will land when adding a new index row.
206 Valid values are some columns of index table."
212 (defcustom org-index-copy-heading-to-keywords t
213 "When adding a new node to index: Copy heading to keywords-column ?"
215 :type
'(choice (const :tag
"Yes" t
)
216 (const :tag
"No" nil
)))
218 (defcustom org-index-strip-ref-and-date-from-heading t
219 "When adding a node to index: strip leading ref or timestamps ?
221 This can be useful, if you have the habit of adding refs and
222 dates to the start of your headings; then, if you change your
223 heading and want to update your index, you do not need to remove
226 :type
'(choice (const :tag
"Yes" t
)
227 (const :tag
"No" nil
)))
229 (defcustom org-index-edit-on-add
'(category keywords
)
230 "List of columns to edit when adding a new row."
232 :type
'(repeat (choice
236 (defcustom org-index-edit-on-yank
'(yank keywords
)
237 "List of columns to edit when adding new text to yank."
239 :type
'(repeat (choice
244 (defcustom org-index-edit-on-ref
'(category keywords
)
245 "List of columns to edit when adding new ref."
247 :type
'(repeat (choice
251 ;; Variables to hold the configuration of the index table
252 (defvar org-index--maxrefnum nil
"Maximum number from reference table, e.g. 153.")
253 (defvar org-index--nextref nil
"Next reference, that can be used, e.g. 'R154'.")
254 (defvar org-index--head nil
"Header before number (e.g. 'R').")
255 (defvar org-index--tail nil
"Tail after number (e.g. '}' or ')'.")
256 (defvar org-index--numcols nil
"Number of columns in index table.")
257 (defvar org-index--ref-regex nil
"Regular expression to match a reference.")
258 (defvar org-index--ref-format nil
"Format, that can print a reference.")
259 (defvar org-index--columns nil
"Columns of index-table.")
260 (defvar org-index--buffer nil
"Buffer of index table.")
261 (defvar org-index--point nil
"Position at start of headline of index table.")
262 (defvar org-index--below-hline nil
"Position of first cell in first line below hline.")
263 (defvar org-index--headings nil
"Headlines of index-table as a string.")
264 (defvar org-index--headings-visible nil
"Visible part of headlines of index-table as a string.")
265 (defvar org-index--keymap nil
"Keymap for shortcuts for some commands of `org-index'. Filled and activated by `org-index-default-keybings'.")
267 ;; Variables to hold context and state
268 (defvar org-index--last-fingerprint nil
"Fingerprint of last line created.")
269 (defvar org-index--category-before nil
"Category of node before.")
270 (defvar org-index--active-region nil
"Active region, initially. I.e. what has been marked.")
271 (defvar org-index--below-cursor nil
"Word below cursor.")
272 (defvar org-index--within-node nil
"True, if we are within node of the index table.")
273 (defvar org-index--within-occur nil
"True, if we are within the occur-buffer.")
274 (defvar org-index--message-text nil
"Text that was issued as an explanation; helpful for regression tests.")
275 (defvar org-index--occur-help-text nil
"Text for help in occur buffer.")
276 (defvar org-index--occur-help-overlay nil
"Overlay for help in occur buffer.")
277 (defvar org-index--occur-stack nil
"Stack with overlays for hiding lines.")
278 (defvar org-index--occur-tail-overlay nil
"Overlay to cover invisible lines.")
279 (defvar org-index--occur-lines-collected
0 "Number of lines collected in occur buffer; helpful for tests.")
280 (defvar org-index--last-sort nil
"Last column, the index has been sorted after.")
281 (defvar org-index--sort-timer nil
"Timer to sort index in correct order.")
282 (defvar org-index--aligned nil
"Remember for this Emacs session, if table has been aligned at least once.")
283 (defvar org-index--edit-widgets nil
"List of widgets used to edit.")
284 (defvar org-index--context-index nil
"Position and line used for index in edit buffer.")
285 (defvar org-index--context-occur nil
"Position and line used for occur in edit buffer.")
286 (defvar org-index--context-node nil
"Buffer and position for node in edit buffer.")
288 ;; static information for this program package
289 (defconst org-index--commands
'(occur add kill head ping index ref yank column edit help example sort multi-occur highlight maintain
) "List of commands available.")
290 (defconst org-index--valid-headings
'(ref id created last-accessed count keywords category level yank tags
) "All valid headings.")
291 (defconst org-index--occur-buffer-name
"*org-index-occur*" "Name of occur buffer.")
292 (defconst org-index--edit-buffer-name
"*org-index-edit*" "Name of edit buffer.")
293 (defconst org-index--sort-idle-delay
300 "Delay in seconds after which buffer will sorted.")
294 (defvar org-index-default-keybindings-list
'(("a" .
'add
) ("i" .
'index
) ("SPC" . nil
) ("o" .
'occur
) ("a" .
'add
) ("k" .
'kill
) ("h" .
'head
) ("p" .
'ping
) ("." .
'ping
) ("r" .
'ref
) ("y" .
'yank
) ("c" .
'column
) ("e" .
'edit
) ("?" .
'help
)) "One-letter short cuts for selected subcommands of `org-index', put in effect by `org-index-default-keybindings'.")
296 (defmacro org-index--on
(column value
&rest body
)
297 "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
298 The value returned is the value of the last form in BODY or nil,
299 if VALUE cannot be found."
300 (declare (indent 2) (debug t
))
301 (let ((pointvar (make-symbol "point")) ; avoid clash with same-named variables in body
302 (foundvar (make-symbol "found"))
303 (retvar (make-symbol "ret")))
304 `(save-current-buffer
305 (let ((,pointvar
(point))
309 (set-buffer org-index--buffer
)
311 (setq ,foundvar
(org-index--go ,column
,value
))
313 (setq ,retvar
(progn ,@body
)))
315 (goto-char ,pointvar
)
320 (defun org-index (&optional command search-ref arg
)
321 "Fast search index for selected org nodes and things outside of org.
323 org-index creates and updates an index table with keywords; each line
324 either points to a heading in org, references something outside or
325 carries a snippet of text to yank. The index table is searched for
326 keywords through an incremental occur; results are sorted by usage
327 count and date, so that frequently used entries appear first among
330 References are decorated numbers (e.g. 'R237' or '--455--'); they are
331 well suited to be used outside of org, e.g. in folder names, ticket
332 systems or on printed documents.
334 On first invocation org-index will help to create a dedicated node
337 To start building up your index, use subcommands 'add', 'ref' and
338 'yank' to create entries and use 'occur' to find them.
340 This is version 5.0.2 of org-index.el.
343 The function `org-index' is the only interactive function of this
344 package and its main entry point; it will present you with a list
345 of subcommands to choose from:
347 occur: Incremental search, that shows matching lines from the
348 index table. It is updated after every keystroke. You may
349 enter a list of words seperated by space or comma (`,'), to
350 select lines that contain all of the given words.
352 add: Add the current node to your index, so that it can be
353 found through the subcommand \"occur\". Update index,
354 if node is already present.
356 kill: Kill (delete) the current node from your index. Can be
357 invoked from index, from occur or from a headline.
359 head: Ask for a reference number and search for this heading.
361 index: Enter index table and maybe go to a specific reference;
362 use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
364 ping: Echo line from index table for current node or first of
365 its ancestors from index.
367 ref: Create a new index line with a reference.
369 yank: Store a new string, that can be yanked when an index row
370 is chosen during occur.
372 column: If within index table, read another character and jump
375 edit: Present current line in a seperate buffer. Can be invoked
376 from index, from occur or from a headline.
378 help: Show this text.
380 example: Create a temporary index, that will not be saved, but
381 may serve as an example.
383 sort: Sort lines in index, in region or buffer by contained
384 reference, or sort index by count, reference or last access.
386 multi-occur: Apply Emacs standard `multi-occur' operation on all
387 `org-mode' buffers to search for the given reference.
389 highlight: Highlight or unhighlight references in active region
390 or buffer. Call with prefix argument (`C-u') to remove
393 maintain: Offers some choices to check, update or fix your index.
395 If you invoke `org-index' for the first time, an assistant will be
396 invoked, that helps you to create your own index.
398 Invoke `org-customize' to tweak the behaviour of org-index.
399 Call `org-index-default-keybindings' from within your init-file
400 to establish convenient keyboard shortcuts.
402 A numeric prefix argument is used as a reference number for
403 commands, that need one (e.g. 'head').
405 Use from elisp: Optional argument COMMAND is a symbol naming the
406 command to execute. SEARCH-REF specifies a reference to search
407 for, if needed. ARG allows passing in a prefix argument as in
410 (interactive "i\ni\nP")
412 (let (search-id ; id to search for
413 search-fingerprint
; fingerprint to search for
414 sort-what
; sort what ?
415 kill-new-text
; text that will be appended to kill ring
416 message-text
) ; text that will be issued as an explanation
421 ;; Initialize and parse
424 ;; creates index table, if necessary
425 (org-index--verify-id)
427 ;; Get configuration of index table
428 (org-index--parse-table)
430 ;; store context information
431 (org-index--retrieve-context)
435 ;; Arrange for proper sorting of index
438 ;; lets assume, that it has been sorted this way (we try hard to make sure)
439 (unless org-index--last-sort
(setq org-index--last-sort org-index-sort-by
))
440 ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
441 (unless org-index--sort-timer
442 (setq org-index--sort-timer
443 (run-with-idle-timer org-index--sort-idle-delay t
'org-index--sort-silent
)))
447 ;; Find out, what we are supposed to do
450 ;; Check or read command
452 (unless (memq command org-index--commands
)
453 (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
454 command
(mapconcat 'symbol-name org-index--commands
",")))
455 (setq command
(intern (org-completing-read
457 (mapcar 'symbol-name org-index--commands
)))))
461 ;; Get search string, if required; process possible sources one after
462 ;; another (lisp argument, prefix argument, user input).
465 ;; Try prefix, if no lisp argument given
466 (if (and (not search-ref
)
468 (setq search-ref
(format "%s%d%s" org-index--head arg org-index--tail
)))
470 ;; These actions really need a search string and may even prompt for it
471 (when (memq command
'(index head multi-occur
))
473 ;; search from surrounding text ?
475 (if org-index--within-node
478 (setq search-ref
(org-index--get-or-set-field 'ref
)))
480 (if (and org-index--below-cursor
481 (string-match (concat "\\(" org-index--ref-regex
"\\)")
482 org-index--below-cursor
))
483 (setq search-ref
(match-string 1 org-index--below-cursor
)))))
485 ;; If we still do not have a search string, ask user explicitly
487 (if (eq command
'index
)
488 (let ((r (org-index--read-search-for-index)))
489 (setq search-ref
(first r
))
490 (setq search-id
(second r
))
491 (setq search-fingerprint
(third r
)))
492 (setq search-ref
(read-from-minibuffer "Search reference number: "))))
494 ;; Clean up search string
496 (setq search-ref
(org-trim search-ref
))
497 (if (string-match "^[0-9]+$" search-ref
)
498 (setq search-ref
(concat org-index--head search-ref org-index--tail
)))
499 (if (string= search-ref
"") (setq search-ref nil
)))
501 (if (and (not search-ref
)
502 (not (eq command
'index
)))
503 (error "Command %s needs a reference number" command
)))
507 ;; Command sort needs to know in advance, what to sort for
510 (when (eq command
'sort
)
511 (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
))))
518 ;; Arrange for beeing able to return
519 (when (and (memq command
'(occur head index example sort maintain
))
520 (not (string= (buffer-name) org-index--occur-buffer-name
)))
521 (org-mark-ring-push))
523 ;; These commands will leave user in index table after they are finished
524 (when (or (memq command
'(index maintain
))
525 (and (eq command
'sort
)
526 (eq sort-what
'index
)))
528 (pop-to-buffer-same-window org-index--buffer
)
529 (goto-char org-index--point
)
530 (org-index--unfold-buffer))
534 ;; Actually do, what is requested
542 ;; bring up help-buffer for this function
543 (describe-function 'org-index
))
546 ((eq command
'multi-occur
)
548 ;; Construct list of all org-buffers
549 (let (buff org-buffers
)
550 (dolist (buff (buffer-list))
552 (if (string= major-mode
"org-mode")
553 (setq org-buffers
(cons buff org-buffers
))))
556 (multi-occur org-buffers
(org-index--make-guarded-search search-ref
))
559 (if (get-buffer "*Occur*")
561 (setq message-text
(format "multi-occur for '%s'" search-ref
))
563 (toggle-truncate-lines 1))
564 (setq message-text
(format "Did not find '%s'" search-ref
)))))
569 (let ((r (org-index--do-add-or-update (if (equal arg
'(4)) t nil
)
570 (if (numberp arg
) arg nil
))))
571 (setq message-text
(car r
))
572 (setq kill-new-text
(cdr r
))))
576 (setq message-text
(org-index--do-kill)))
581 (if (and org-index--within-node
583 (setq search-id
(org-index--get-or-set-field 'id
)))
585 (if (and (not search-id
) search-ref
)
586 (setq search-id
(org-index--id-from-ref search-ref
)))
590 (org-index--find-id search-id
)
591 "Current line has no id")))
596 (goto-char org-index--below-hline
)
601 (if (org-index--go 'ref search-ref
)
603 (org-index--update-current-line)
604 (org-table-goto-column (org-index--column-num 'ref
))
605 (format "Found index line '%s'" search-ref
))
606 (format "Did not find index line with reference '%s'" search-ref
))
609 (if (org-index--go 'id search-id
)
611 (org-index--update-current-line)
612 (org-table-goto-column (org-index--column-num 'ref
))
613 (format "Found index line '%s'" (org-index--get-or-set-field 'ref
)))
614 (format "Did not find index line with id '%s'" search-id
))
616 (if search-fingerprint
617 (if (org-index--go 'fingerprint org-index--last-fingerprint
)
619 (org-index--update-current-line)
621 (format "Found latest index line"))
622 (format "Did not find index line"))
624 ;; simply go into table
632 (let ((moved-up 0) id info reached-top
)
634 (unless (string= major-mode
"org-mode") (error "No node at point"))
635 ;; take id from current node or reference
636 (setq id
(if search-ref
637 (org-index--id-from-ref search-ref
)
640 ;; move up until we find a node in index
642 (outline-back-to-heading)
646 (setq info
(org-index--on 'id id
647 (mapcar (lambda (x) (org-index--get-or-set-field x
))
648 (list 'ref
'count
'created
'last-accessed
'category
'keywords
'ref
)))))
650 (setq reached-top
(= (org-outline-level) 1))
654 (outline-up-heading 1 t
)
657 (setq id
(org-id-get))))
663 (append (list "'%s'%shas been accessed %s times between %s and %s; category is '%s', keywords are '%s'"
665 (if (> moved-up
0) (format " (parent node, %d level up) " moved-up
) " "))
667 (setq kill-new-text
(car (last info
))))
668 (setq message-text
"Neither this node nor any of its parents is part of index"))))
673 (set-buffer org-index--buffer
)
674 (org-index--do-occur))
681 (setq args
(org-index--collect-values-from-user org-index-edit-on-ref
))
682 (setq args
(plist-put args
'category
"yank"))
683 (setq args
(plist-put args
'ref org-index--nextref
))
684 (apply 'org-index--do-new-line args
)
686 (setq kill-new-text org-index--nextref
)
688 (setq message-text
(format "Added new row with ref '%s'" org-index--nextref
))))
695 (setq args
(org-index--collect-values-from-user org-index-edit-on-yank
))
696 (if (plist-get args
'yank
)
697 (plist-put args
'yank
(replace-regexp-in-string "|" (regexp-quote "\\vert") (plist-get args
'yank
) nil
'literal
)))
698 (setq args
(plist-put args
'category
"yank"))
699 (apply 'org-index--do-new-line args
)
701 (setq message-text
"Added new row with text to yank")))
704 ((eq command
'column
)
706 (if (and org-index--within-node
709 (setq char
(read-char "Please specify, which column to go to (r=ref, k=keywords, c=category, y=yank): "))
710 (unless (memq char
(list ?r ?k ?c ?y
))
711 (error (format "Invalid char '%c', cannot goto this column" char
)))
712 (setq col
(cdr (assoc char
'((?r . ref
) (?k . keywords
) (?c . category
) (?y . yank
)))))
713 (setq num
(org-index--column-num col
))
716 (org-table-goto-column num
)
717 (setq message-text
(format "At column %s" (symbol-name col
))))
719 (error (format "Column '%s' is not present" col
))))
720 (error "Need to be in index table to go to a specific column")))
725 (setq message-text
(org-index--do-edit)))
730 (let ((sorts (list "count" "last-accessed" "mixed" "id" "ref"))
731 sort groups-and-counts
)
734 ((eq sort-what
'index
)
737 (org-icompleting-read
738 "Please choose column to sort index table: "
740 nil t nil nil
(symbol-name org-index-sort-by
))))
742 (org-index--do-sort-index sort
)
743 (org-table-goto-column (org-index--column-num (if (eq sort
'mixed
) 'last-access sort
)))
744 ;; When saving index, it should again be sorted correctly
745 (with-current-buffer org-index--buffer
746 (add-hook 'before-save-hook
'org-index--sort-silent t
))
750 (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
751 (if groups-and-counts
752 "; %d groups with equal %s and a total of %d lines have been found"
756 org-index--sort-idle-delay
757 (second groups-and-counts
)
759 (third groups-and-counts
))))
761 ((memq sort-what
'(region buffer
))
762 (org-index--do-sort-lines sort-what
)
763 (setq message-text
(format "Sorted %s by contained references" sort-what
))))))
766 ((eq command
'highlight
)
768 (let ((where "buffer"))
771 (when (and transient-mark-mode
773 (narrow-to-region (region-beginning) (region-end))
774 (setq where
"region"))
778 (unhighlight-regexp org-index--ref-regex
)
779 (setq message-text
(format "Removed highlights for references in %s" where
)))
780 (highlight-regexp org-index--ref-regex
'isearch
)
781 (setq message-text
(format "Highlighted references in %s" where
)))))))
784 ((eq command
'maintain
)
785 (setq message-text
(org-index--do-maintain)))
788 ((eq command
'example
)
790 (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
791 (org-index--create-index t
)))
794 (t (error "Unknown subcommand '%s'" command
)))
797 ;; tell, what we have done and what can be yanked
798 (if kill-new-text
(setq kill-new-text
799 (substring-no-properties kill-new-text
)))
800 (if (string= kill-new-text
"") (setq kill-new-text nil
))
803 (if (and message-text kill-new-text
)
805 (if kill-new-text
"R" ""))
806 (if kill-new-text
(format "eady to yank '%s'." kill-new-text
) (if message-text
"." "")))))
807 (unless (string= m
"")
809 (setq org-index--message-text m
)))
810 (if kill-new-text
(kill-new kill-new-text
)))))
813 (defun org-index-default-keybindings (&optional prefix
)
814 "Set default keybindings for `org-index'.
816 Invoke subcommands of org index with a single key
817 sequence. Establish the common prefix key 'C-c i' which should be
818 followed by the first letter of a subcommand.
820 The ist of letters and subcommands is specified in within
821 `org-index-default-keybindings-list'.
823 See `org-index' for a description of all subcommands.
825 Optional argument PREFIX specifies common prefix, defaults to 'C-c i'"
828 (define-prefix-command 'org-index--keymap
)
830 (global-set-key (kbd (or prefix
"C-c i")) 'org-index--keymap
)
831 ;; loop over subcommands
834 (define-key org-index--keymap
(kbd (car x
))
835 `(lambda (arg) (interactive "P")
837 (org-index ,(cdr x
) nil arg
))))
838 org-index-default-keybindings-list
))
841 (defun org-index-new-line (&rest keys-values
)
842 "Create a new line within the index table, returning its reference.
844 The function takes a varying number of argument pairs; each pair
845 is a symbol for an existing column heading followed by its value.
846 The return value is the new reference.
850 (message \"Created reference %s\"
851 (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
853 Optional argument KEYS-VALUES specifies content of new line."
855 (let ((ref (plist-get keys-values
'ref
)))
856 (org-index--verify-id)
857 (org-index--parse-table)
858 (if (not (memq ref
'(t nil
)))
859 (error "Column 'ref' accepts only 't' or 'nil'"))
861 (setq ref org-index--nextref
)
862 (setq keys-values
(plist-put keys-values
'ref ref
)))
864 (apply 'org-index--do-new-line keys-values
)
868 (defun org-index--do-edit ()
869 "Perform command edit."
870 (let ((maxlen 0) cols-vals buffer-keymap field-keymap keywords-pos val
)
872 (org-index--check-can-edit-or-kill "edit")
874 ;; change to index, if whithin occur
875 (if org-index--within-occur
876 (let ((pos (get-text-property (point) 'org-index-lbp
)))
877 (org-index--occur-test-stale pos
)
878 (setq org-index--context-occur
(cons (point) (org-index--line-in-canonical-form)))
879 (set-buffer org-index--buffer
)
881 (setq org-index--context-occur nil
))
883 ;; change to index, if on headline
884 (if (org-at-heading-p)
885 (let ((id (org-id-get)))
886 (setq org-index--context-node
(cons (current-buffer) (point)))
887 (set-buffer org-index--buffer
)
888 (unless (and id
(org-index--go 'id id
))
889 (setq org-index--context-node nil
)
890 (error "This node is not in index")))
891 (setq org-index--context-node nil
))
893 ;; retrieve current content of index line
894 (dolist (col (mapcar 'car
(reverse org-index--columns
)))
895 (if (> (length (symbol-name col
)) maxlen
)
896 (setq maxlen
(length (symbol-name col
))))
897 (setq val
(org-index--get-or-set-field col
))
898 (if (and val
(eq col
'yank
)) (setq val
(replace-regexp-in-string (regexp-quote "\\vert") "|" val nil
'literal
)))
899 (setq cols-vals
(cons (cons col val
)
902 ;; we need two different keymaps
903 (setq buffer-keymap
(make-sparse-keymap))
904 (set-keymap-parent buffer-keymap widget-keymap
)
905 (define-key buffer-keymap
(kbd "C-c C-c") 'org-index--edit-c-c-c-c
)
906 (define-key buffer-keymap
(kbd "C-c C-k") 'org-index--edit-c-c-c-k
)
908 (setq field-keymap
(make-sparse-keymap))
909 (set-keymap-parent field-keymap widget-field-keymap
)
910 (define-key field-keymap
(kbd "C-c C-c") 'org-index--edit-c-c-c-c
)
911 (define-key field-keymap
(kbd "C-c C-k") 'org-index--edit-c-c-c-k
)
914 (setq org-index--context-index
(cons (point) (org-index--line-in-canonical-form)))
915 (if (get-buffer org-index--edit-buffer-name
) (kill-buffer org-index--edit-buffer-name
))
916 (switch-to-buffer (get-buffer-create org-index--edit-buffer-name
))
918 ;; create and fill widgets
919 (setq org-index--edit-widgets nil
)
920 (widget-insert "Edit this line from index; type C-c C-c when done, C-c C-k to abort.\n\n")
921 (dolist (col-val cols-vals
)
922 (if (eq (car col-val
) 'keywords
) (setq keywords-pos
(point)))
923 (setq org-index--edit-widgets
(cons
925 (widget-create 'editable-field
926 :format
(format (format "%%%ds: %%%%v" maxlen
) (symbol-name (car col-val
)))
928 (or (cdr col-val
) "")))
929 org-index--edit-widgets
)))
932 (goto-char keywords-pos
)
934 (forward-char (+ maxlen
2))
935 (use-local-map buffer-keymap
)
936 "Editing a single line from index"))
939 (defun org-index--edit-c-c-c-c ()
940 "Function to invoked on C-c C-c in Edit buffer."
943 (let ((obuf (get-buffer org-index--occur-buffer-name
))
946 ;; Time might have passed
947 (org-index--refresh-parse-table)
949 (with-current-buffer org-index--buffer
951 ;; check, if buffer has become stale
953 (goto-char (car org-index--context-index
))
954 (unless (string= (cdr org-index--context-index
)
955 (org-index--line-in-canonical-form))
956 (switch-to-buffer org-index--edit-buffer-name
)
957 (error "Index table has changed: Cannot find line, that this buffer is editing")))
959 (pop-to-buffer-same-window org-index--buffer
)
960 (goto-char (car org-index--context-index
))
962 ;; write back line to index
963 (dolist (col-widget org-index--edit-widgets
)
964 (setq val
(widget-value (cdr col-widget
)))
965 (if (eq (car col-widget
) 'yank
) (setq val
(replace-regexp-in-string "|" (regexp-quote "\\vert") val
)))
966 (org-index--get-or-set-field (car col-widget
) val
))
968 (setq line
(org-index--align-and-fontify-current-line))
971 ;; write line to occur if appropriate
972 (if org-index--context-occur
974 (if (string= (cdr org-index--context-index
)
975 (cdr org-index--context-occur
))
977 (pop-to-buffer-same-window obuf
)
978 (goto-char (car org-index--context-occur
))
980 (let ((inhibit-read-only t
))
981 (delete-region (line-beginning-position) (line-end-position))
983 (put-text-property (line-beginning-position) (line-end-position)
984 'org-index-lbp
(cdr org-index--context-index
))))
985 (error "Occur buffer and index buffer do not match any longer"))
986 (message "Occur buffer has gone, cannot switch back."))
987 (setq org-index--context-occur nil
))
989 ;; return to node, if invoked from there
990 (when org-index--context-node
991 (pop-to-buffer-same-window (car org-index--context-node
))
992 (goto-char (cdr org-index--context-node
)))
995 (kill-buffer org-index--edit-buffer-name
)
996 (setq org-index--context-index nil
)
997 (setq org-index--edit-widgets nil
)
999 (message "Index line has been edited.")))
1002 (defun org-index--edit-c-c-c-k ()
1003 "Function to invoked on C-c C-k in Edit buffer."
1005 (kill-buffer org-index--edit-buffer-name
)
1006 (setq org-index--context-index nil
)
1007 (setq org-index--edit-widgets nil
)
1009 (message "Edit aborted."))
1012 (defun org-index--do-new-line (&rest keys-values
)
1013 "Do the work for `org-index-new-line'.
1014 Optional argument KEYS-VALUES specifies content of new line."
1017 (org-index--retrieve-context)
1018 (with-current-buffer org-index--buffer
1019 (goto-char org-index--point
)
1021 ;; check arguments early; they might come from userland
1022 (let ((kvs keys-values
)
1027 (if (or (not (symbolp k
))
1028 (and (symbolp v
) (not (eq v t
)) (not (eq v nil
))))
1029 (error "Arguments must be alternation of key and value"))
1030 (unless (org-index--column-num k
)
1031 (error "Unknown column or column not defined in table: '%s'" (symbol-name k
)))
1032 (setq kvs
(cddr kvs
))))
1036 (org-index--create-new-line)
1039 (let ((kvs keys-values
)
1044 (org-table-goto-column (org-index--column-num k
))
1045 (insert (org-trim (or v
"")))
1046 (setq kvs
(cddr kvs
))))
1048 ;; align and fontify line
1049 (org-index--promote-current-line)
1050 (org-index--align-and-fontify-current-line)
1052 ;; remember fingerprint to be able to return
1053 (setq org-index--last-fingerprint
(org-index--get-or-set-field 'fingerprint
))
1055 ;; get column to yank
1056 (setq yank
(org-index--get-or-set-field org-index-yank-after-add
))
1061 (defun org-index-get-line (column value
)
1062 "Retrieve an existing line within the index table by ref or id.
1063 Return its contents as a property list.
1065 The function `plist-get' may be used to retrieve specific elements
1070 (plist-get (org-index-get-line 'ref \"R12\") 'count)
1072 retrieves the value of the count-column for reference number 12.
1074 Argument COLUMN is a symbol, either ref or id,
1075 argument VALUE specifies the value to search for."
1077 (unless (memq column
'(ref id
))
1078 (error "Argument column can only be 'ref' or 'id'"))
1081 (error "Need a value to search for"))
1083 (org-index--verify-id)
1084 (org-index--parse-table)
1086 (org-index--get-line column value
))
1089 (defun org-index--get-line (column value
)
1090 "Find a line by ID, return its contents.
1091 Argument COLUMN and VALUE specify line to get."
1096 (if (and (numberp (cdr x
))
1098 (setq content
(cons (car x
) (cons (or (org-index--get-or-set-field (car x
)) "") content
)))))
1099 (reverse org-index--columns
)))
1103 (defun org-index--ref-from-id (id)
1104 "Get reference from line ID."
1105 (org-index--on 'id id
(org-index--get-or-set-field 'ref
)))
1108 (defun org-index--id-from-ref (ref)
1109 "Get id from line REF."
1110 (org-index--on 'ref ref
(org-index--get-or-set-field 'id
)))
1113 (defun org-index--get-fingerprint ()
1114 "Get fingerprint of current line."
1115 (replace-regexp-in-string
1117 (mapconcat (lambda (x) (org-index--get-or-set-field x
)) '(id ref yank keywords created
) "")))
1120 (defun org-index--read-search-for-index ()
1121 "Special input routine for command index."
1123 ;; Accept single char commands or switch to reading a sequence of digits
1124 (let (char prompt search-ref search-id search-fingerprint
)
1126 ;; start with short prompt but give more help on next iteration
1127 (setq prompt
"Please specify, where to go in index (0-9.,space,backspace,return or ? for help): ")
1129 ;; read one character
1130 (while (not (memq char
(append (number-sequence ?
0 ?
9) (list ?\d ?
\b ?
\r ?\j ?\s ?.
))))
1131 (setq char
(read-char prompt
))
1132 (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: "))
1134 (if (memq char
(number-sequence ?
0 ?
9))
1135 ;; read rest of digits
1136 (setq search-ref
(read-from-minibuffer "Search reference number: " (char-to-string char
))))
1137 ;; decode single chars
1138 (if (memq char
'(?
\r ?
\n ?.
)) (setq search-id
(org-id-get)))
1139 (if (memq char
'(?\d ?
\b)) (setq search-fingerprint org-index--last-fingerprint
))
1141 (list search-ref search-id search-fingerprint
)))
1144 (defun org-index--verify-id ()
1145 "Check, that we have a valid id."
1148 (unless org-index-id
1149 (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")))
1150 (if (string= answer
"create-index")
1151 (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
1152 (describe-function 'org-index
))))
1156 (setq marker
(org-id-find org-index-id
'marker
))
1157 (unless marker
(org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id
))
1158 ; Try again with new node
1159 (setq marker
(org-id-find org-index-id
'marker
))
1160 (unless marker
(error "Could not create node"))
1161 (setq org-index--buffer
(marker-buffer marker
)
1162 org-index--point
(marker-position marker
))
1163 (move-marker marker nil
)))
1166 (defun org-index--retrieve-context ()
1167 "Collect context information before starting with command."
1169 ;; Get the content of the active region or the word under cursor
1170 (setq org-index--active-region
1171 (if (and transient-mark-mode mark-active
)
1172 (buffer-substring (region-beginning) (region-end))
1174 (setq org-index--below-cursor
(thing-at-point 'symbol
))
1176 ;; get category of current node
1177 (setq org-index--category-before
1178 (save-excursion ; workaround: org-get-category does not give category when at end of buffer
1180 (org-get-category (point) t
)))
1182 ;; Find out, if we are within index table or occur buffer
1183 (setq org-index--within-node
(string= (org-id-get) org-index-id
))
1184 (setq org-index--within-occur
(string= (buffer-name) org-index--occur-buffer-name
)))
1187 (defun org-index--parse-table ()
1188 "Parse content of index table."
1196 (with-current-buffer org-index--buffer
1198 (setq org-index--maxrefnum
0)
1199 (setq initial-point
(point))
1201 (org-index--go-below-hline)
1203 ;; align and fontify table once for this emacs session
1204 (unless org-index--aligned
1205 (org-table-align) ; needs to happen before fontification to be effective ?
1206 (let ((is-modified (buffer-modified-p))
1208 (while (org-at-table-p)
1210 (font-lock-fontify-region below
(point))
1211 (org-index--go-below-hline)
1212 (setq org-index--aligned t
)
1213 (set-buffer-modified-p is-modified
)))
1215 (org-index--go-below-hline)
1218 ;; get headings to display during occur
1219 (setq end-of-headings
(point))
1220 (while (org-at-table-p) (forward-line -
1))
1222 (setq start-of-headings
(point))
1223 (setq org-index--headings-visible
(substring-no-properties (org-index--copy-visible start-of-headings end-of-headings
)))
1224 (setq org-index--headings
(buffer-substring start-of-headings end-of-headings
))
1227 (org-table-goto-column 100)
1228 (setq org-index--numcols
(- (org-table-current-column) 1))
1230 ;; go to top of table
1231 (while (org-at-table-p)
1235 ;; parse line of headings
1236 (org-index--parse-headings)
1238 ;; parse list of flags
1239 (goto-char org-index--point
)
1241 ;; Retrieve any decorations around the number within the first nonempty ref-field
1242 (goto-char org-index--below-hline
)
1243 (while (and (org-at-table-p)
1244 (not (setq ref-field
(org-index--get-or-set-field 'ref
))))
1249 (org-index--report-index-error "Reference column is empty"))
1251 (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field
)
1252 (org-index--report-index-error
1253 "First reference in index table ('%s') does not contain a number" ref-field
))
1255 ;; These are the decorations used within the first ref of index
1256 (setq org-index--head
(match-string 1 ref-field
))
1257 (setq org-index--tail
(match-string 3 ref-field
))
1258 (setq org-index--ref-regex
(concat (regexp-quote org-index--head
)
1260 (regexp-quote org-index--tail
)))
1261 (setq org-index--ref-format
(concat org-index--head
"%d" org-index--tail
))
1263 ;; check if the table still seems to be sorted mixed
1264 (goto-char org-index--below-hline
)
1265 (when (eq org-index-sort-by
'mixed
)
1266 (org-index--go-below-hline)
1267 (if (string< (org-index--get-or-set-field 'last-accessed
)
1268 (org-index--get-mixed-time))
1269 (org-index--do-sort-index org-index-sort-by
)))
1271 ;; Go through table to find maximum number and do some checking
1274 (while (org-at-table-p)
1276 (setq ref-field
(org-index--get-or-set-field 'ref
))
1277 (setq id-field
(org-index--get-or-set-field 'id
))
1280 (if (string-match org-index--ref-regex ref-field
)
1282 (setq refnum
(string-to-number (match-string 1 ref-field
)))
1284 (message "Removing line from index-table whose ref does not contain a number")))
1286 ;; check, if higher ref
1287 (if (> refnum org-index--maxrefnum
) (setq org-index--maxrefnum refnum
))
1291 (setq org-index--nextref
(format "%s%d%s" org-index--head
(1+ org-index--maxrefnum
) org-index--tail
))
1292 ;; go back to initial position
1293 (goto-char initial-point
))))
1296 (defun org-index--refresh-parse-table ()
1297 "Fast refresh of selected results of parsing of index table."
1299 (setq org-index--point
(marker-position (org-id-find org-index-id
'marker
)))
1300 (with-current-buffer org-index--buffer
1302 (org-index--go-below-hline))))
1305 (defun org-index--do-maintain ()
1306 "Choose among and perform some tasks to maintain index."
1307 (let ((check-what) (max-mini-window-height 1.0) message-text
)
1308 (setq check-what
(intern (org-completing-read "These checks and fixes are available:\n - statistics : compute statistics about index table\n - check : check ids by visiting their nodes\n - duplicates : check index for duplicate rows (ref or id)\n - clean : remove obsolete property org-index-id\n - update : update content of index lines, with an id \nPlease choose: " (list "statistics" "check" "duplicates" "clean" "update") nil t nil nil
"statistics")))
1312 ((eq check-what
'check
)
1313 (setq message-text
(or (org-index--check-ids)
1314 "No problems found")))
1316 ((eq check-what
'statistics
)
1317 (setq message-text
(org-index--do-statistics)))
1319 ((eq check-what
'duplicates
)
1320 (setq message-text
(org-index--find-duplicates)))
1322 ((eq check-what
'clean
)
1326 (when (org-entry-get (point) "org-index-ref")
1328 (org-entry-delete (point) "org-index-ref")))
1330 (setq message-text
(format "Removed property 'org-index-ref' from %d lines" lines
))))
1332 ((eq check-what
'update
)
1333 (if (y-or-n-p "Updating your index will overwrite certain columns with content from the associated heading and category. If unsure, you may try this for a single, already existing line of your index by invoking `add'. Are you SURE to proceed for ALL INDEX LINES ? ")
1334 (setq message-text
(org-index--update-all-lines))
1335 (setq message-text
"Canceled."))))
1339 (defun org-index--get-mixed-time ()
1340 "Get timestamp for sorting order mixed."
1342 (org-time-stamp-format t t
)
1343 (apply 'encode-time
(append '(0 0 0) (nthcdr 3 (decode-time))))))
1346 (defun org-index--do-sort-index (sort)
1347 "Sort index table according to SORT."
1349 (let ((is-modified (buffer-modified-p))
1356 (unless buffer-read-only
1358 (message "Sorting index table for %s..." (symbol-name sort
))
1361 (let ((message-log-max nil
)) ; we have just issued a message, dont need those of sort-subr
1363 ;; if needed for mixed sort
1364 (if (eq sort
'mixed
)
1365 (setq mixed-time
(org-index--get-mixed-time)))
1367 ;; get boundaries of table
1368 (org-index--go-below-hline)
1371 (while (org-at-table-p) (forward-line))
1373 ;; kill all empty rows at bottom
1376 (org-table-goto-column 1)
1378 (not (org-index--get-or-set-field 'ref
))
1379 (not (org-index--get-or-set-field 'id
))
1380 (not (org-index--get-or-set-field 'yank
))))
1381 (org-table-kill-row))
1383 (setq bottom
(point))
1387 (narrow-to-region top bottom
)
1393 (org-index--get-sort-key sort t mixed-time
))
1396 (goto-char (point-min))
1398 ;; restore modification state
1399 (set-buffer-modified-p is-modified
)))
1401 (setq org-index--last-sort sort
))))
1404 (defun org-index--do-sort-lines (what)
1405 "Sort lines in WHAT according to contained reference."
1409 (if (region-active-p)
1410 (narrow-to-region (region-beginning) (region-end))
1411 (error "No active region, cannot sort")))
1413 (unless (y-or-n-p "Sort whole current buffer ? ")
1415 (narrow-to-region (point-min) (point-max))))
1417 (goto-char (point-min))
1418 (sort-subr nil
'forward-line
'end-of-line
1420 (if (looking-at (concat ".*"
1421 (org-index--make-guarded-search org-index--ref-regex
'dont-quote
)))
1422 (string-to-number (match-string 1))
1426 (defun org-index--go-below-hline ()
1427 "Move below hline in index-table."
1430 (errstring (format "index table within node %s" org-index-id
)))
1432 (goto-char org-index--point
)
1434 ;; go to heading of node
1435 (while (not (org-at-heading-p)) (forward-line -
1))
1438 ;; go to first table, but make sure we do not get into another node
1439 (while (and (not (org-at-table-p))
1440 (not (org-at-heading-p))
1444 ;; check, if there really is a table
1445 (unless (org-at-table-p)
1446 (org-index--create-missing-index "Cannot find %s." errstring
))
1448 ;; go just after hline
1449 (while (and (not (org-at-table-hline-p))
1455 (unless (org-at-table-p)
1456 (org-index--report-index-error "Cannot find a hline within %s" errstring
))
1458 (org-table-goto-column 1)
1459 (setq org-index--below-hline
(point))))
1462 (defun org-index--parse-headings ()
1463 "Parse headings of index table."
1465 (let (field ;; field content
1466 field-symbol
;; and as a symbol
1469 (setq org-index--columns nil
)
1472 (dotimes (col org-index--numcols
)
1474 (setq field
(substring-no-properties (downcase (org-trim (org-table-get-field (+ col
1))))))
1476 (if (string= field
"")
1477 (error "Heading of column cannot be empty"))
1478 (if (and (not (string= (substring field
0 1) "."))
1479 (not (member (intern field
) org-index--valid-headings
)))
1480 (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field
))
1482 (setq field-symbol
(intern field
))
1484 ;; check if heading has already appeared
1485 (if (assoc field-symbol org-index--columns
)
1486 (org-index--report-index-error
1487 "'%s' appears two times as column heading" (downcase field
))
1488 ;; add it to list at front, reverse later
1489 (setq org-index--columns
(cons (cons field-symbol
(+ col
1)) org-index--columns
)))))
1491 (setq org-index--columns
(reverse org-index--columns
))
1493 ;; check if all necessary headings have appeared
1494 (mapc (lambda (head)
1495 (unless (cdr (assoc head org-index--columns
))
1496 (org-index--report-index-error "No column has heading '%s'" head
)))
1497 org-index--valid-headings
))
1500 (defun org-index--create-missing-index (&rest reasons
)
1501 "Create a new empty index table with detailed explanation. Argument REASONS explains why."
1503 (org-index--ask-before-create-index "Cannot find index table: "
1506 (org-index--create-index))
1509 (defun org-index--report-index-error (&rest reasons
)
1510 "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
1512 (when org-index--buffer
1513 (pop-to-buffer-same-window org-index--buffer
)
1514 (goto-char org-index--below-hline
)
1516 (org-index--ask-before-create-index "The existing index contains this error: "
1517 "temporary" ", to compare with."
1519 (org-index--create-index t t
))
1522 (defun org-index--ask-before-create-index (explanation type for-what reasons
)
1523 ; checkdoc-params: (explanation type for-what reasons)
1524 "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
1525 (let (reason prompt
)
1527 (setq reason
(apply 'format reasons
))
1529 (setq prompt
(concat explanation reason
"\n\n"
1530 "However, this assistant can help you to create a "
1531 type
" index with detailed comments" for-what
"\n\n"
1532 "Do you want to proceed ?"))
1534 (unless (let ((max-mini-window-height 1.0))
1536 (error (concat explanation reason
)))))
1539 (defun org-index--create-index (&optional temporary compare
)
1540 "Create a new empty index table with detailed explanation.
1541 specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
1549 (let ((file-name (concat temporary-file-directory
"org-index--example-index.org"))
1550 (buffer-name "*org-index-example-index*"))
1551 (setq buffer
(get-buffer-create buffer-name
))
1552 (with-current-buffer buffer
1553 ;; but it needs a file for its index to be found
1554 (unless (string= (buffer-file-name) file-name
)
1555 (set-visited-file-name file-name
))
1556 (rename-buffer buffer-name
) ; name is change by line above
1561 (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))))))
1563 (setq title
(read-from-minibuffer "Please enter the title of the index node: "))
1566 (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 frequently within your existing notes, to avoid too many false hits when searching.\n\nPlease choose: "))
1568 (when (string-match "[[:blank:]]" firstref
)
1569 (setq desc
"Contains whitespace"))
1570 (when (string-match "[[:cntrl:]]" firstref
)
1571 (setq desc
"Contains control characters"))
1572 (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref
)
1573 ;; firstref not okay, report details
1575 (cond ((string= firstref
"") "is empty")
1576 ((not (string-match "^[^0-9]+" firstref
)) "starts with a digit")
1577 ((not (string-match "^[^0-9]+[0-9]+" firstref
)) "does not contain a number")
1578 ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref
)) "contains more than one sequence of digits")
1583 (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc
))
1587 (setq with-explanation
(y-or-n-p "Do you want an explanation within your index-table (can later be removed easily) ? "))
1589 (with-current-buffer buffer
1590 (goto-char (point-max))
1591 (insert (format "* %s %s\n" firstref title
))
1592 (when with-explanation
1595 Below you find your temporary index table, which WILL NOT LAST LONGER
1596 THAN YOUR CURRENT EMACS SESSION; please use it only for evaluation.
1599 Below you find your initial index table, which will grow over time.
1601 (insert " You may start using it by adding some lines. Just
1602 move to another heading within org, invoke `org-index' and
1603 choose the command 'add'. After adding a few nodes, try the
1604 command 'occur' to search among them.
1606 To gain further insight you may invoke the subcommand 'help', or
1607 (same content) read the help of `org-index'.
1609 Within the index table below, the sequence of columns does not
1610 matter. You may reorder them in any way you like. You may also
1611 add your own columns, which should start with a dot
1612 (e.g. '.my-column').
1614 Invoke `org-customize' to tweak the behaviour of org-index
1615 (see the group org-index).
1617 This node needs not be a top level node; its name is completely
1618 at your choice; it is found through its ID only.
1622 Remark: These lines of explanation can be removed at any time.
1625 (setq id
(org-id-get-create))
1628 | ref | category | keywords | tags | count | level | last-accessed | created | id | yank |
1629 | | | | | | | | | <4> | <4> |
1630 |-----+----------+----------+------+-------+-------+---------------+---------+-----+------|
1631 | %s | | %s | | | | | %s | %s | |
1636 (with-temp-buffer (org-insert-time-stamp nil nil t
))
1639 ;; make sure, that node can be found
1640 (org-id-add-location id
(buffer-file-name))
1641 (setq buffer-save-without-query t
)
1644 (while (not (org-at-table-p)) (forward-line -
1))
1645 (unless buffer-read-only
(org-table-align))
1646 (while (not (org-at-heading-p)) (forward-line -
1))
1648 ;; read back some info about new index
1649 (let ((org-index-id id
))
1650 (org-index--verify-id))
1652 ;; remember at least for this session
1653 (setq org-index-id id
)
1655 ;; present results to user
1658 ;; Present existing and temporary index together
1660 (pop-to-buffer-same-window org-index--buffer
)
1661 (goto-char org-index--point
)
1662 (org-index--unfold-buffer)
1663 (delete-other-windows)
1664 (select-window (split-window-vertically)))
1666 (pop-to-buffer-same-window buffer
)
1668 (org-index--unfold-buffer)
1671 (message "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
1672 (throw 'new-index nil
))
1673 (message "This is your new temporary index, use command add to populate, occur to search.")))
1675 ;; Only show the new index
1676 (pop-to-buffer-same-window buffer
)
1677 (delete-other-windows)
1679 (org-index--unfold-buffer)
1680 (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 ? ")
1682 (customize-save-variable 'org-index-id id
)
1683 (message "Saved org-index-id '%s' to %s" id
(or custom-file
1685 (throw 'new-index nil
))
1687 (setq sq
(format "(setq org-index-id \"%s\")" id
))
1689 (message "Did not make the id of this new index permanent; you may want to put\n\n %s\n\ninto your own initialization; it is copied already, just yank it" sq
)
1690 (throw 'new-index nil
))))))))
1693 (defun org-index--unfold-buffer ()
1694 "Helper function to unfold buffer."
1699 (org-back-to-heading)
1700 (forward-line) ;; on property drawer
1704 (defun org-index--update-line (&optional ref-or-id-or-pos
)
1705 "Update columns count and last-accessed in line REF-OR-ID-OR-POS."
1710 (with-current-buffer org-index--buffer
1711 (unless buffer-read-only
1713 ;; search reference or id, if given (or assume, that we are already positioned right)
1714 (when ref-or-id-or-pos
1715 (setq initial
(point))
1716 (goto-char org-index--below-hline
)
1717 (while (and (org-at-table-p)
1718 (not (if (integerp ref-or-id-or-pos
)
1719 (and (>= ref-or-id-or-pos
(line-beginning-position))
1720 (< ref-or-id-or-pos
(line-end-position)))
1721 (or (string= ref-or-id-or-pos
(org-index--get-or-set-field 'ref
))
1722 (string= ref-or-id-or-pos
(org-index--get-or-set-field 'id
))))))
1725 (if (not (org-at-table-p))
1726 (error "Did not find reference or id '%s'" ref-or-id-or-pos
)
1727 (org-index--update-current-line))
1729 (if initial
(goto-char initial
))))))
1732 (defun org-index--update-current-line ()
1733 "Update current lines columns count and last-accessed."
1734 (let (newcount (count-field (org-index--get-or-set-field 'count
)))
1736 ;; update count field only if number or empty
1737 (when (or (not count-field
)
1738 (string-match "^[0-9]+$" count-field
))
1739 (setq newcount
(+ 1 (string-to-number (or count-field
"0"))))
1740 (org-index--get-or-set-field 'count
1741 (number-to-string newcount
)))
1744 (org-table-goto-column (org-index--column-num 'last-accessed
))
1745 (org-table-blank-field)
1746 (org-insert-time-stamp nil t t
)
1748 ;; move line according to new content
1749 (org-index--promote-current-line)
1750 (org-index--align-and-fontify-current-line)))
1753 (defun org-index--align-and-fontify-current-line (&optional num
)
1754 "Make current line (or NUM lines) blend well among others."
1756 ;; get current content
1757 (unless num
(setq num
1))
1758 (setq lines
(delete-and-extract-region (line-beginning-position) (line-end-position num
)))
1759 ;; create minimum table with fixed-width columns to align and fontify new line
1760 (insert (with-temp-buffer
1761 (org-set-font-lock-defaults)
1762 (insert org-index--headings-visible
)
1763 ;; fill columns, so that aligning cannot shrink them
1764 (goto-char (point-min))
1765 (search-forward "|")
1766 (while (search-forward " " (line-end-position) t
)
1767 (replace-match "." nil t
))
1768 (goto-char (point-min))
1769 (while (search-forward ".|." (line-end-position) t
)
1770 (replace-match " | " nil t
))
1771 (goto-char (point-min))
1772 (while (search-forward "|." (line-end-position) t
)
1773 (replace-match "| " nil t
))
1774 (goto-char (point-max))
1777 (let ((start (point)))
1778 (while (re-search-forward "^\s +|-" nil t
)
1779 (replace-match "| -"))
1783 (font-lock-fontify-region (point-min) (point-max))
1784 (goto-char (point-max))
1785 (if (eq -
1 (skip-chars-backward "\n"))
1787 (forward-line (- 1 num
))
1788 (buffer-substring (line-beginning-position) (line-end-position num
))))
1792 (defun org-index--promote-current-line ()
1793 "Move current line up in table according to changed sort fields."
1797 (forward-line 0) ; stay at beginning of line
1799 (setq key
(org-index--get-sort-key))
1800 (setq begin
(point))
1801 (setq end
(line-beginning-position 2))
1804 (while (and (org-at-table-p)
1805 (not (org-at-table-hline-p))
1806 (string< (org-index--get-sort-key) key
))
1812 ;; insert line at new position
1814 (insert (delete-and-extract-region begin end
))
1815 (forward-line -
1))))
1818 (defun org-index--get-sort-key (&optional sort with-ref mixed-time
)
1819 "Get value for sorting from column SORT, optional WITH-REF; if mixes use MIXED-TIME."
1824 (unless sort
(setq sort org-index--last-sort
)) ; use default value
1828 ;; get reference with leading zeroes, so it can be
1830 (setq ref-field
(org-index--get-or-set-field 'ref
))
1833 (string-match org-index--ref-regex ref-field
)
1837 (match-string 1 ref-field
)))))
1838 (setq ref
"000000")))
1843 (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count
) ""))))
1845 (let ((last-accessed (org-index--get-or-set-field 'last-accessed
)))
1846 (unless mixed-time
(setq mixed-time
(org-index--get-mixed-time)))
1848 (if (string< mixed-time last-accessed
) last-accessed mixed-time
)
1849 (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count
) ""))))))
1852 ((memq sort
'(id last-accessed created
))
1853 (org-index--get-or-set-field sort
))
1854 (t (error "This is a bug: unmatched case '%s'" sort
))))
1856 (if with-ref
(setq key
(concat key ref
)))
1861 (defun org-index--get-or-set-field (key &optional value
)
1862 "Retrieve field KEY from index table or set it to VALUE."
1865 (if (eq key
'fingerprint
)
1867 (if value
(error "Internal error, pseudo-column fingerprint cannot be set"))
1868 (setq field
(org-index--get-fingerprint)))
1869 (setq field
(org-trim (org-table-get-field (cdr (assoc key org-index--columns
)) value
))))
1870 (if (string= field
"") (setq field nil
))
1872 (org-no-properties field
))))
1875 (defun org-index--column-num (key)
1876 "Return number of column KEY."
1879 (cdr (assoc key org-index--columns
))))
1882 (defun org-index--make-guarded-search (ref &optional dont-quote
)
1883 "Make robust search string from REF; DONT-QUOTE it, if requested."
1884 (concat "\\_<" (if dont-quote ref
(regexp-quote ref
)) "\\_>"))
1887 (defun org-index--find-duplicates ()
1888 "Find duplicate references or ids in index table."
1889 (let (ref-duplicates id-duplicates message
)
1891 (setq ref-duplicates
(org-index--find-duplicates-helper 'ref
))
1892 (setq id-duplicates
(org-index--find-duplicates-helper 'id
))
1893 (goto-char org-index--below-hline
)
1894 (if (or ref-duplicates id-duplicates
)
1897 (pop-to-buffer-same-window
1898 (get-buffer-create "*org-index-duplicates*"))
1899 (when ref-duplicates
1900 (insert "These references appear more than once:\n")
1901 (mapc (lambda (x) (insert " " x
"\n")) ref-duplicates
)
1904 (insert "These ids appear more than once:\n")
1905 (mapc (lambda (x) (insert " " x
"\n")) id-duplicates
))
1907 "Some references or ids are duplicates")
1908 "No duplicate references or ids found")))
1911 (defun org-index--find-duplicates-helper (column)
1912 "Helper for `org-index--find-duplicates': Go through table and count given COLUMN."
1913 (let (counts duplicates field found
)
1916 (goto-char org-index--below-hline
)
1917 (while (org-at-table-p)
1920 (setq field
(org-index--get-or-set-field column
))
1923 (setq found
(assoc field counts
))
1925 (cl-incf (cdr found
))
1926 (setq counts
(cons (cons field
1) counts
)))
1930 (mapc (lambda (x) (if (and (> (cdr x
) 1)
1932 (setq duplicates
(cons (car x
) duplicates
)))) counts
)
1937 (defun org-index--do-statistics ()
1938 "Compute statistics about index table."
1939 (let ((total-lines 0) (total-refs 0)
1940 ref ref-field min max message
)
1943 (goto-char org-index--below-hline
)
1944 (while (org-at-table-p)
1947 (setq ref-field
(org-index--get-or-set-field 'ref
))
1950 (string-match org-index--ref-regex ref-field
)
1951 (setq ref
(string-to-number (match-string 1 ref-field
)))
1953 ;; record min and max
1954 (if (or (not min
) (< ref min
)) (setq min ref
))
1955 (if (or (not max
) (> ref max
)) (setq max ref
))
1957 (setq total-refs
(1+ total-refs
)))
1960 (setq total-lines
(1+ total-lines
))
1964 (setq message
(format "%d Lines in index table. First reference is %s, last %s; %d of them are used (%d percent)"
1966 (format org-index--ref-format min
)
1967 (format org-index--ref-format max
)
1969 (truncate (* 100 (/ (float total-refs
) (1+ (- max min
)))))))
1971 (goto-char org-index--below-hline
)
1975 (defun org-index--do-add-or-update (&optional create-ref tag-with-ref
)
1976 "For current node or current line in index, add or update in index table.
1977 CREATE-REF and TAG-WITH-REF if given."
1979 (let* (id id-from-index ref args yank
)
1981 ;; do the same things from within index and from outside
1982 (if org-index--within-node
1985 (unless (org-at-table-p)
1986 (error "Within index node but not on table"))
1988 (setq id
(org-index--get-or-set-field 'id
))
1989 (setq ref
(org-index--get-or-set-field 'ref
))
1990 (setq args
(org-index--collect-values-for-add-update-remote id
))
1991 (org-index--write-fields args
)
1992 (setq yank
(org-index--get-or-set-field org-index-yank-after-add
))
1995 (cons (format "Updated index line %s" ref
) yank
)
1996 (cons "Updated index line" nil
)))
1998 (unless (org-at-heading-p)
1999 (error "Not at headline"))
2001 (setq id
(org-id-get-create))
2002 (org-index--refresh-parse-table)
2003 (setq id-from-index
(org-index--on 'id id id
))
2004 (setq ref
(org-index--on 'id id
(org-index--get-or-set-field 'ref
)))
2007 (org-toggle-tag (format "%s%d%s" org-index--head tag-with-ref org-index--tail
) 'on
))
2008 (setq args
(org-index--collect-values-for-add-update id
))
2010 (when (and create-ref
2012 (setq ref org-index--nextref
)
2013 (setq args
(plist-put args
'ref ref
)))
2017 ;; already have an id in index, find it and update fields
2018 (let (found-and-message)
2022 (org-index--write-fields args
)
2023 (setq yank
(org-index--get-or-set-field org-index-yank-after-add
)))
2026 (cons (format "Updated index line %s" ref
) yank
)
2027 (cons "Updated index line" nil
)))
2029 ;; no id here, create new line in index
2030 (if ref
(setq ref
(plist-put args
'ref org-index--nextref
)))
2031 (setq yank
(apply 'org-index--do-new-line args
))
2035 (format "Added new index line %s" ref
)
2038 "Added new index line"
2042 (defun org-index--check-ids ()
2043 "Check, that ids really point to a node."
2048 (goto-char org-index--below-hline
)
2051 (while (org-at-table-p)
2053 (when (setq id
(org-index--get-or-set-field 'id
))
2055 ;; check for double ids
2056 (when (member id ids
)
2057 (org-table-goto-column (org-index--column-num 'id
))
2058 (throw 'problem
"This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
2060 (setq ids
(cons id ids
))
2062 ;; check, if id is valid
2063 (setq marker
(org-id-find id t
))
2065 (org-table-goto-column (org-index--column-num 'id
))
2066 (throw 'problem
"This id cannot be found")))
2070 (goto-char org-index--below-hline
)
2074 (defun org-index--update-all-lines ()
2075 "Update all lines of index at once."
2080 ;; check for double ids
2082 (org-index--check-ids)
2085 (goto-char org-index--below-hline
)
2086 (while (org-at-table-p)
2088 ;; update single line
2089 (when (setq id
(org-index--get-or-set-field 'id
))
2090 (setq ref
(org-index--get-or-set-field 'ref
))
2091 (setq kvs
(org-index--collect-values-for-add-update-remote id
))
2092 (org-index--write-fields kvs
)
2096 (goto-char org-index--below-hline
)
2098 (format "Updated %d lines" lines
)))))
2101 (defun org-index--collect-values-for-add-update (id &optional silent category
)
2102 "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
2104 (let ((args (list 'id id
))
2107 (dolist (col (mapcar 'car org-index--columns
))
2113 (if org-index-copy-heading-to-keywords
2114 (setq content
(nth 4 (org-heading-components))))
2116 ;; Shift ref and timestamp ?
2117 (if org-index-strip-ref-and-date-from-heading
2119 (if (or (string-match (concat "^\\s-*" org-index--ref-regex
) content
)
2120 (string-match (concat org-ts-regexp-both
) content
))
2121 (setq content
(substring content
(match-end 0)))))))
2124 (setq content
(or category org-index--category-before
)))
2127 (setq content
(number-to-string (org-outline-level))))
2130 (setq content
(org-get-tags-string))))
2132 (unless (string= content
"")
2133 (setq args
(plist-put args col content
))))
2136 (let ((args-edited (org-index--collect-values-from-user org-index-edit-on-add args
)))
2137 (setq args
(append args-edited args
))))
2142 (defun org-index--collect-values-for-add-update-remote (id)
2143 "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
2145 (let (marker point args
)
2147 (setq marker
(org-id-find id t
))
2148 ;; enter buffer and collect information
2149 (with-current-buffer (marker-buffer marker
)
2150 (setq point
(point))
2152 (setq args
(org-index--collect-values-for-add-update id t
(org-get-category (point) t
)))
2158 (defun org-index--collect-values-from-user (list-of-columns-to-edit &optional default-values
)
2159 "Collect values for adding a new yank-line."
2163 (dolist (col list-of-columns-to-edit
)
2167 (setq content
(read-from-minibuffer
2168 (format "Enter text for column '%s': " (symbol-name col
))
2169 (plist-get col default-values
)))
2171 (unless (string= content
"")
2172 (setq args
(plist-put args col content
))))
2176 (defun org-index--write-fields (kvs)
2177 "Update current line with values from KVS (keys-values)."
2179 (org-index--get-or-set-field (car kvs
) (org-trim (cadr kvs
)))
2180 (setq kvs
(cddr kvs
))))
2183 (defun org-index--do-kill ()
2184 "Perform command kill from within occur, index or node."
2186 (let (id ref pos chars-deleted-index text-deleted-from pos-in-index
)
2188 (org-index--check-can-edit-or-kill "kill")
2189 (setq pos
(org-index--save-positions))
2192 ;; Collect information: What should be deleted ?
2193 (if (or org-index--within-occur
2194 org-index--within-node
)
2197 (if org-index--within-node
2199 (setq pos-in-index
(point))
2201 (setq pos-in-index
(get-text-property (point) 'org-index-lbp
))
2202 (org-index--occur-test-stale pos-in-index
)
2203 (set-buffer org-index--buffer
)
2204 (goto-char pos-in-index
))
2205 ;; In Index (maybe moved there)
2206 (setq id
(org-index--get-or-set-field 'id
))
2207 (setq ref
(org-index--get-or-set-field 'ref
)))
2210 (setq id
(org-entry-get (point) "ID"))
2211 (setq ref
(org-index--ref-from-id id
))
2212 (setq pos-in-index
(org-index--on 'id id
(point)))
2213 (unless pos-in-index
(error "This node is not in index")))
2215 ;; Remark: Current buffer is not certain here, but we have all the information to delete
2219 (let ((m (org-id-find id
'marker
)))
2220 (set-buffer (marker-buffer m
))
2223 (unless (string= (org-id-get) id
)
2224 (error "Could not find node with id %s" id
)))
2226 (org-index--delete-any-ref-from-tags)
2227 (if ref
(org-index--delete-ref-from-heading ref
))
2228 (setq text-deleted-from
(cons "node" text-deleted-from
)))
2230 ;; Delete from index
2231 (set-buffer org-index--buffer
)
2232 (unless pos-in-index
"Internal error, pos-in-index should be defined here")
2233 (goto-char pos-in-index
)
2234 (setq chars-deleted-index
(length (delete-and-extract-region (line-beginning-position) (line-beginning-position 2))))
2235 (setq text-deleted-from
(cons "index" text-deleted-from
))
2237 ;; Delete from occur only if we started there, accept that it will be stale otherwise
2238 (if org-index--within-occur
2239 (let ((inhibit-read-only t
))
2240 (set-buffer org-index--occur-buffer-name
)
2241 (delete-region (line-beginning-position) (line-beginning-position 2))
2242 ;; correct positions
2243 (while (org-at-table-p)
2244 (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp
2245 (- (get-text-property (point) 'org-index-lbp
) chars-deleted-index
))
2247 (setq text-deleted-from
(cons "occur" text-deleted-from
))))
2249 (org-index--restore-positions pos
)
2250 (concat "Deleted from: " (mapconcat 'identity
(sort text-deleted-from
'string
<) ","))))
2253 (defun org-index--save-positions ()
2254 "Save current buffer and positions in index and node; not occur."
2256 (setq buf
(current-buffer))
2257 (setq pn
(point)) ; not guaranteed to be on node
2258 (set-buffer org-index--buffer
)
2264 (defun org-index--restore-positions (pos)
2265 "Restore positions as saved by `org-index--save-positions'."
2267 (setq buf
(current-buffer))
2268 (set-buffer (first pos
))
2269 (goto-char (second pos
))
2270 (set-buffer org-index--buffer
)
2271 (goto-char (third pos
))
2275 (defun org-index--check-can-edit-or-kill (what)
2276 "Check, if edit or kill can be performed for current position."
2278 (when (not (or (org-at-heading-p)
2279 (and (org-at-table-p)
2280 (or org-index--within-occur
2281 org-index--within-node
))))
2282 (if (not (org-at-table-p)) (error "Cannot %s: Not at table" what
))
2283 (if (not (org-at-heading-p)) (error "Cannot %s: Not at headline" what
))
2284 (error "Cannot %s: Neither in index nor in occur buffer" what
)))
2287 (defun org-index--delete-ref-from-heading (ref)
2288 "Delete given REF from current heading."
2291 (let ((end (point)))
2293 (when (search-forward ref end t
)
2294 (delete-char (- (length ref
)))
2295 (just-one-space)))))
2298 (defun org-index--delete-any-ref-from-tags ()
2299 "Delete any reference from list of tags."
2302 (unless (string-match org-index--ref-regex tag
)
2303 (setq new-tags
(cons tag new-tags
) )))
2305 (org-set-tags-to new-tags
)))
2308 (defun org-index--go (&optional column value
)
2309 "Position cursor on index line where COLUMN equals VALUE.
2310 Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
2313 (unless (eq (current-buffer) org-index--buffer
)
2314 (error "This is a bug: Not in index buffer"))
2317 (goto-char org-index--below-hline
)
2321 (while (and (not found
)
2324 (setq found
(string= value
(org-index--get-or-set-field column
)))))
2330 (goto-char org-index--below-hline
)
2334 (defun org-index--find-id (id &optional other
)
2335 "Perform command head: Find node with REF or ID and present it.
2336 If OTHER in separate window."
2338 (let (message marker
)
2340 (setq marker
(org-id-find id t
))
2344 (org-index--update-line id
)
2347 (pop-to-buffer (marker-buffer marker
)))
2348 (pop-to-buffer-same-window (marker-buffer marker
)))
2354 (unless (string= (org-id-get) id
)
2355 (setq message
(format "Could not go to node with id %s (narrowed ?)" id
)))
2356 (setq message
"Found headline"))
2357 (setq message
(format "Did not find node with %s" id
)))
2361 (defun org-index--do-occur ()
2362 "Perform command occur."
2363 (let ((word "") ; last word to search for growing and shrinking on keystrokes
2364 (prompt "Search for: ")
2365 (these-commands "These commands of org-index, if invoked from the occur buffer, update it accordingly: edit, kill.")
2366 (lines-wanted (window-body-height))
2367 (lines-found 0) ; number of lines found
2368 words
; list words that should match
2370 begin
; position of first line
2371 narrow
; start of narrowed buffer
2372 help-text
; cons with help text short and long
2373 key-help
; for keys with special function
2374 search-text
; description of text to search for
2375 done
; true, if loop is done
2376 in-c-backspace
; true, while processing C-backspace
2377 show-headings
; true, if headings should be shown
2378 help-overlay
; Overlay with help text
2379 last-point
; Last position before end of search
2380 initial-frame
; Frame when starting occur
2381 key
; input from user in various forms
2386 ;; make and show buffer
2387 (if (get-buffer org-index--occur-buffer-name
)
2388 (kill-buffer org-index--occur-buffer-name
))
2389 (setq occur-buffer
(make-indirect-buffer org-index--buffer org-index--occur-buffer-name
))
2390 (pop-to-buffer-same-window occur-buffer
)
2391 (setq initial-frame
(selected-frame))
2393 ;; avoid modifying direct buffer
2394 (setq buffer-read-only t
)
2395 (toggle-truncate-lines 1)
2396 (setq font-lock-keywords-case-fold-search t
)
2397 (setq case-fold-search t
)
2399 ;; reset stack and overlays
2400 (setq org-index--occur-stack nil
)
2401 (setq org-index--occur-tail-overlay nil
)
2403 ;; narrow to table rows and one line before
2404 (goto-char org-index--below-hline
)
2406 (setq begin
(point))
2408 (setq narrow
(point))
2409 (while (org-at-table-p)
2411 (narrow-to-region narrow
(point))
2412 (goto-char (point-min))
2415 ;; initialize help text
2416 (setq help-text
(cons
2418 (propertize "Incremental occur" 'face
'org-todo
)
2419 (propertize "; `?' toggles help and headlines.\n" 'face
'org-agenda-dimmed-todo-face
))
2424 "Normal keys add to search word; <space> or <comma> start additional word; <backspace> erases last char, <C-backspace> last word; <return> jumps to heading, <tab> jumps to heading in other window, <S-return> jumps to matching line in index; all other keys end search." these-commands
"\n"))
2425 'face
'org-agenda-dimmed-todo-face
)
2426 org-index--headings
)))
2428 ;; insert overlays for help text and to cover unsearched lines
2429 (setq help-overlay
(make-overlay (point-min) begin
))
2430 (overlay-put help-overlay
'display
(car help-text
))
2431 (setq org-index--occur-tail-overlay
(make-overlay (point-max) (point-max)))
2432 (overlay-put org-index--occur-tail-overlay
'invisible t
)
2437 (setq key
"<backspace>")
2438 (setq search-text
(mapconcat 'identity
(reverse (cons word words
)) ","))
2441 ;; read key, if selected frame has not changed
2442 (if (eq initial-frame
(selected-frame))
2445 (let ((echo-keystrokes 0)
2446 (full-prompt (format "%s%s%s"
2449 (if (string= search-text
"") "" " "))))
2450 (read-key-sequence full-prompt nil nil t t
)))
2451 (setq key
(key-description key-sequence
))
2452 (setq key-sequence-raw
(this-single-command-raw-keys)))
2454 (setq key-sequence nil
)
2456 (setq key-sequence-raw nil
)))
2462 ((string= key
"<C-backspace>")
2463 (setq in-c-backspace t
))
2466 ((member key
(list "<backspace>" "DEL")) ; erase last char
2468 (if (= (length word
) 0)
2470 ;; nothing more to delete from current word; try next
2472 (setq word
(car words
))
2473 (setq words
(cdr words
))
2474 (setq in-c-backspace nil
))
2476 ;; unhighlight longer match
2477 (unhighlight-regexp (regexp-quote word
))
2479 ;; some chars are left; shorten word
2480 (setq word
(substring word
0 -
1))
2481 (when (= (length word
) 0) ; when nothing left, use next word from list
2482 (setq word
(car words
))
2483 (setq words
(cdr words
))
2484 (setq in-c-backspace nil
))
2486 ;; free top list of overlays and remove list
2487 (setq lines-found
(or (org-index--unhide) lines-wanted
))
2488 (move-overlay org-index--occur-tail-overlay
2489 (if org-index--occur-stack
(cdr (assoc :end-of-visible
(car org-index--occur-stack
)))
2494 ;; highlight shorter word
2495 (unless (= (length word
) 0)
2496 (highlight-regexp (regexp-quote word
) 'isearch
))
2498 ;; make sure, point is still visible
2502 ((member key
(list "SPC" ",")) ; space or comma: enter an additional search word
2504 ;; push current word and clear, no need to change display
2505 (unless (string= word
"")
2506 (setq words
(cons word words
))
2510 ((string= key
"?") ; question mark: toggle display of headlines and help
2511 (setq help-text
(cons (cdr help-text
) (car help-text
)))
2512 (overlay-put help-overlay
'display
(car help-text
)))
2514 ((and (= (length key
) 1)
2515 (aref printable-chars
(elt key
0))) ; any printable char: add to current search word
2517 ;; unhighlight short word
2518 (unless (= (length word
) 0)
2519 (unhighlight-regexp (regexp-quote word
)))
2522 (setq word
(concat word key
))
2524 ;; make overlays to hide lines, that do not match longer word any more
2526 (setq lines-found
(org-index--hide-with-overlays (cons word words
) lines-wanted
))
2527 (move-overlay org-index--occur-tail-overlay
2528 (if org-index--occur-stack
(cdr (assoc :end-of-visible
(car org-index--occur-stack
)))
2534 ;; highlight longer word
2535 (highlight-regexp (regexp-quote word
) 'isearch
)
2537 ;; make sure, point is on a visible line
2541 ;; anything else terminates loop
2544 ;; put back input event, that caused the loop to end
2545 (unless (string= key
"C-g")
2546 (setq unread-command-events
(listify-key-sequence key-sequence-raw
))
2550 (setq last-point
(point))
2552 ;; For performance reasons do not show matching lines for rest of table. So no code here.
2554 ;; make permanent copy
2555 ;; copy visible lines
2556 (let ((lines-collected 0)
2557 keymap line all-lines all-lines-lbp header-lines lbp
)
2559 (setq cursor-type t
)
2562 ;; collect all visible lines
2563 (while (and (not (eobp))
2564 (< lines-collected lines-wanted
))
2565 ;; skip over invisible lines
2566 (while (and (invisible-p (point))
2568 (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
2569 (setq lbp
(line-beginning-position))
2570 (setq line
(buffer-substring-no-properties lbp
(line-end-position)))
2571 (unless (string= line
"")
2572 (cl-incf lines-collected
)
2573 (setq all-lines
(cons (concat line
2576 (setq all-lines-lbp
(cons lbp all-lines-lbp
)))
2579 (kill-buffer org-index--occur-buffer-name
) ; cannot keep this buffer; might become stale soon
2581 ;; create new buffer
2582 (setq occur-buffer
(get-buffer-create org-index--occur-buffer-name
))
2583 (pop-to-buffer-same-window occur-buffer
)
2584 (insert org-index--headings
)
2585 (setq header-lines
(line-number-at-pos))
2587 ;; insert into new buffer
2589 (apply 'insert
(reverse all-lines
))
2590 (if (= lines-collected lines-wanted
)
2591 (insert "\n(more lines omitted)\n")))
2592 (setq org-index--occur-lines-collected lines-collected
)
2595 (setq truncate-lines t
)
2596 (if all-lines
(org-index--align-and-fontify-current-line (length all-lines
)))
2597 (font-lock-fontify-buffer)
2599 (while (not (org-at-table-p))
2601 (while all-lines-lbp
2602 (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp
(car all-lines-lbp
))
2603 (setq all-lines-lbp
(cdr all-lines-lbp
))
2606 ;; prepare help text
2607 (goto-char (point-min))
2608 (forward-line (1- header-lines
))
2609 (setq org-index--occur-help-overlay
(make-overlay (point-min) (point)))
2610 (setq org-index--occur-help-text
2613 (propertize "Search is done; `?' toggles help and headlines.\n" 'face
'org-agenda-dimmed-todo-face
))
2618 (concat "Search is done."
2619 (if (< lines-collected lines-wanted
)
2620 " Showing all %d matches for "
2621 " Showing one window of matches for ")
2623 "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> jumps to matching line in index, <space> increments count." these-commands
"\n")
2625 'face
'org-agenda-dimmed-todo-face
))
2626 org-index--headings
)))
2628 (overlay-put org-index--occur-help-overlay
'display
(car org-index--occur-help-text
))
2631 (setq case-fold-search t
)
2632 (setq font-lock-keywords-case-fold-search t
)
2633 (mapc (lambda (w) (unless (or (not w
) (string= w
"")) (highlight-regexp (regexp-quote w
) 'isearch
)))
2636 (setq buffer-read-only t
)
2638 ;; install keyboard-shortcuts
2639 (setq keymap
(make-sparse-keymap))
2640 (set-keymap-parent keymap org-mode-map
)
2642 (mapc (lambda (x) (define-key keymap
(kbd x
)
2643 (lambda () (interactive)
2644 (message "%s" (org-index--occur-action)))))
2645 (list "<return>" "RET"))
2647 (define-key keymap
(kbd "<tab>")
2648 (lambda () (interactive)
2649 (message (org-index--occur-action t
))))
2651 (define-key keymap
(kbd "SPC")
2652 (lambda () (interactive)
2653 (org-index--refresh-parse-table)
2654 ;; increment in index
2655 (let ((ref (org-index--get-or-set-field 'ref
))
2659 (setq count
(+ 1 (string-to-number (org-index--get-or-set-field 'count
))))
2660 (org-index--get-or-set-field 'count
(number-to-string count
))
2661 (org-index--promote-current-line)
2662 (org-index--align-and-fontify-current-line))
2663 ;; increment in this buffer
2664 (let ((inhibit-read-only t
))
2665 (org-index--get-or-set-field 'count
(number-to-string count
)))
2666 (message "Incremented count to %d" count
))))
2668 (define-key keymap
(kbd "<S-return>")
2669 (lambda () (interactive)
2670 (let ((pos (get-text-property (point) 'org-index-lbp
)))
2671 (org-index--refresh-parse-table)
2672 (org-index--occur-test-stale pos
)
2673 (pop-to-buffer org-index--buffer
)
2676 (org-index--update-current-line))))
2678 (define-key keymap
(kbd "?")
2679 (lambda () (interactive)
2680 (org-index--refresh-parse-table)
2681 (setq-local org-index--occur-help-text
(cons (cdr org-index--occur-help-text
) (car org-index--occur-help-text
)))
2682 (overlay-put org-index--occur-help-overlay
'display
(car org-index--occur-help-text
))))
2684 (use-local-map keymap
))))
2687 (defun org-index--occur-test-stale (pos)
2688 "Test, if current line in occur buffer has become stale at POS."
2690 (org-index--refresh-parse-table)
2691 (setq here
(org-index--line-in-canonical-form))
2692 (with-current-buffer org-index--buffer
2694 (setq there
(org-index--line-in-canonical-form)))
2695 (unless (string= here there
)
2696 (error "Occur buffer has become stale"))))
2699 (defun org-index--line-in-canonical-form ()
2700 "Return current line in its canonical form."
2701 (org-trim (substring-no-properties (replace-regexp-in-string "\s +" " " (buffer-substring (line-beginning-position) (line-beginning-position 2))))))
2704 (defun org-index--wrap (text)
2705 "Wrap TEXT at fill column."
2708 (fill-region (point-min) (point-max) nil t
)
2712 (defun org-index--occur-action (&optional other
)
2713 "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window; or copy yank column."
2714 (if (org-at-table-p)
2715 (let ((id (org-index--get-or-set-field 'id
))
2716 (ref (org-index--get-or-set-field 'ref
))
2717 (yank (org-index--get-or-set-field 'yank
)))
2719 (org-index--find-id id other
)
2722 (org-mark-ring-goto)
2723 (format "Found reference %s" ref
))
2726 (org-index--update-line (get-text-property (point) 'org-index-lbp
))
2727 (setq yank
(replace-regexp-in-string (regexp-quote "\\vert") "|" yank nil
'literal
))
2729 (org-mark-ring-goto)
2730 (format "Copied '%s'" yank
))
2731 (error "Internal error, this line contains neither id, nor reference, nor text to yank")))))
2732 (message "Not at table")))
2735 (defun org-index--hide-with-overlays (words lines-wanted
)
2736 "Hide text that is currently visible and does not match WORDS by creating overlays; leave LINES-WANTED lines visible."
2737 (let ((lines-found 0)
2738 (end-of-visible (point))
2739 overlay overlays start matched
)
2742 (while (and (not (eobp))
2743 (< lines-found lines-wanted
))
2745 ;; skip invisible lines
2746 (while (and (not (eobp))
2748 (invisible-p (point))
2749 (< (point) (overlay-start org-index--occur-tail-overlay
))))
2750 (goto-char (overlay-end (car (overlays-at (point))))))
2752 ;; find stretch of lines, that are currently visible but should be invisible now
2754 (setq start
(point))
2755 (while (and (not (eobp))
2758 (invisible-p (point))
2759 (< (point) (overlay-start org-index--occur-tail-overlay
))))
2760 (not (and (org-index--test-words words
)
2761 (setq matched t
)))) ; for its side effect
2764 ;; create overlay to hide this stretch
2765 (when (< start
(point)) ; avoid creating an empty overlay
2766 (setq overlay
(make-overlay start
(point)))
2767 (overlay-put overlay
'invisible t
)
2768 (setq overlays
(cons overlay overlays
)))
2770 ;; skip and count line, that matched
2773 (setq end-of-visible
(point))
2774 (cl-incf lines-found
)))
2776 ;; put new list on top of stack
2777 (setq org-index--occur-stack
2778 (cons (list (cons :overlays overlays
)
2779 (cons :end-of-visible end-of-visible
)
2780 (cons :lines lines-found
))
2781 org-index--occur-stack
))
2786 (defun org-index--unhide ()
2787 "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
2788 (when org-index--occur-stack
2789 ;; delete overlays and make visible again
2792 (cdr (assoc :overlays
(car org-index--occur-stack
))))
2793 ;; remove from stack
2794 (setq org-index--occur-stack
(cdr org-index--occur-stack
))
2795 ;; return number of lines, that are now visible
2796 (if org-index--occur-stack
(cdr (assoc :lines
(car org-index--occur-stack
))))))
2799 (defun org-index--test-words (words)
2800 "Test current line for match against WORDS."
2802 (setq line
(downcase (buffer-substring (line-beginning-position) (line-beginning-position 2))))
2805 (or (cl-search w line
)
2806 (throw 'not-found nil
)))
2810 (defun org-index--create-new-line (&optional args
)
2811 "Do the common work for `org-index-new-line' and `org-index'."
2813 ;; insert ref or id as last or first line, depending on sort-column
2814 (goto-char org-index--below-hline
)
2815 (if (eq org-index-sort-by
'count
)
2817 (while (org-at-table-p)
2820 (org-table-insert-row t
))
2821 (org-table-insert-row))
2823 ;; insert some of the standard values
2824 (org-table-goto-column (org-index--column-num 'created
))
2825 (org-insert-time-stamp nil nil t
)
2826 (org-table-goto-column (org-index--column-num 'count
))
2829 (if args
(org-index--write-fields args
)))
2832 (defun org-index--sort-silent ()
2833 "Sort index for default column to remove any effects of temporary sorting."
2835 (org-index--verify-id)
2836 (org-index--parse-table)
2837 (org-index--on nil nil
2838 (org-index--do-sort-index org-index-sort-by
)
2840 (remove-hook 'before-save-hook
'org-index--sort-silent
))))
2843 (defun org-index--copy-visible (beg end
)
2844 "Copy the visible parts of the region between BEG and END without adding it to `kill-ring'; copy of `org-copy-visible'."
2848 (narrow-to-region beg end
)
2849 (setq s
(goto-char (point-min)))
2850 (while (not (= (point) (point-max)))
2851 (goto-char (org-find-invisible))
2852 (push (buffer-substring s
(point)) snippets
)
2853 (setq s
(goto-char (org-find-visible))))))
2854 (apply 'concat
(nreverse snippets
))))
2857 (provide 'org-index
)
2861 ;; comment-column: 50
2864 ;;; org-index.el ends here