org-index.el 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473
  1. ;;; org-index.el --- A personal index for org and more
  2. ;; Copyright (C) 2011-2015 Free Software Foundation, Inc.
  3. ;; Author: Marc Ihm <org-index@2484.de>
  4. ;; Version: 4.3.0
  5. ;; Keywords: outlines index
  6. ;; This file is not part of GNU Emacs.
  7. ;;; License:
  8. ;; This program is free software; you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation; either version 3, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  20. ;;; Commentary:
  21. ;; Purpose:
  22. ;;
  23. ;; Fast search for selected org headings and things outside of org.
  24. ;;
  25. ;; This package creates and updates an index table of headings or
  26. ;; keywords, references and ids. Each line points to a heading within
  27. ;; org or references something outside. This index table can be sorted
  28. ;; by usage count, so that frequently used lines appear first among the
  29. ;; search results.
  30. ;;
  31. ;; References are decorated numbers (e.g. 'R237' or '--455--'), as
  32. ;; created by this package; they are well suited to be used outside of
  33. ;; org, e.g. in folder names, ticket systems or on printed documents.
  34. ;;
  35. ;; On first invocation org-index will help to create a dedicated node
  36. ;; for its index table.
  37. ;;
  38. ;; For basic usage, subcommands 'add' and 'occur' are most important.
  39. ;;
  40. ;;
  41. ;; Setup:
  42. ;;
  43. ;; - Add these lines to your .emacs:
  44. ;;
  45. ;; (require 'org-index)
  46. ;; (org-index-default-keybindings) ; optional
  47. ;;
  48. ;; - Restart your Emacs to make these lines effective.
  49. ;;
  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).
  53. ;;
  54. ;; - Optionally customize some settings (group org-index):
  55. ;;
  56. ;; M-x org-customize
  57. ;;
  58. ;;
  59. ;; Further reading:
  60. ;;
  61. ;; See the documentation of `org-index', which can also be read
  62. ;; by invoking `org-index' and choosing the help-command.
  63. ;;
  64. ;;
  65. ;; Updates:
  66. ;;
  67. ;; The latest tested version of this file can always be found at:
  68. ;;
  69. ;; http://orgmode.org/w/org-mode.git?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
  70. ;;; Change Log:
  71. ;; [2015-08-20 Th] Version 4.3.0
  72. ;; - Configuration is done now via standard customize
  73. ;; - New sorting strategy 'mixed'
  74. ;; - Silenced some compiler warnings
  75. ;;
  76. ;; [2015-03-18 We] Version 4.2.1
  77. ;; - No garbage in kill-ring
  78. ;; - No recentering after add
  79. ;;
  80. ;; [2015-03-08 Su] Version 4.2.0
  81. ;; - Reference numbers for subcommands can be passed as a prefix argument
  82. ;; - New variable org-index-default-keybindings-list with a list of
  83. ;; default keybindings for org-index-default-keybindings
  84. ;; - Added new column level
  85. ;; - removed flags get-category-on-add and get-heading-on-add
  86. ;;
  87. ;; [2015-02-26 Th] to [2015-03-05 Th] Version 4.0.0 to 4.1.2
  88. ;; - Removed command "leave"; rather go back with org-mark-ring-goto
  89. ;; - Renamed column "link" to "id"
  90. ;; - Added maintainance options to find duplicate rows, to check ids,
  91. ;; update index or remove property org-index-ref from nodes
  92. ;; - Shortened versin history
  93. ;;
  94. ;; [2014-12-07 Sa] to [2015-01-31 Sa] Version 3.0.0 to 3.2.0:
  95. ;; - Complete sorting of index only occurs in idle-timer
  96. ;; - New command "maintain" with some subcommands
  97. ;; - Rewrote command "occur" with overlays in an indirect buffer
  98. ;; - Command "add" updates index, if node is already present
  99. ;; - New commands "add" and "delete" to easily add and remove
  100. ;; the current node to or from your index.
  101. ;; - New command "example" to create an example index.
  102. ;; - Several new flags that are explained within index node.
  103. ;; - Removed commands "reuse", "missing", "put", "goto",
  104. ;; "update", "link", "fill", "unhighlight"
  105. ;; - New function `org-index-default-keybindings'
  106. ;;
  107. ;; [2012-12-07 Fr] to [2014-04-26 Sa] Version 2.0.0 to 2.4.3:
  108. ;; - New functions org-index-new-line and org-index-get-line
  109. ;; offer access to org-index from other lisp programs
  110. ;; - Regression tests with ert
  111. ;; - Renamed from "org-favtable" to "org-index"
  112. ;; - Added an assistant to set up the index table
  113. ;; - occur is now incremental, searching as you type
  114. ;; - Integrated with org-mark-ring-goto
  115. ;; - Added full support for ids
  116. ;; - Renamed the package from "org-reftable" to "org-favtable"
  117. ;; - Additional columns are required (e.g. "link"). Error messages will
  118. ;; guide you
  119. ;; - Ask user explicitly, which command to invoke
  120. ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
  121. ;;
  122. ;; [2011-12-10 Sa] to [2012-09-22 Sa] Version Version 1.2.0 to 1.5.0:
  123. ;; - New command "sort" to sort a buffer or region by reference number
  124. ;; - New commands "highlight" and "unhighlight" to mark references
  125. ;; - New command "head" to find a headline with a reference number
  126. ;; - New commands occur and multi-occur
  127. ;; - Started this Change Log
  128. ;;; Code:
  129. (require 'org-table)
  130. (require 'cl-lib)
  131. ;; Version of this package
  132. (defvar org-index-version "4.3.0" "Version of `org-index', format is major.minor.bugfix, where \"major\" is a change in index-table and \"minor\" are new features.")
  133. ;; customizable options
  134. (defgroup org-index nil
  135. "Options concerning the optional index for org."
  136. :tag "Org Index"
  137. :group 'org)
  138. (defcustom org-index-id nil
  139. "Id of the Org-mode node, which contains the index table."
  140. :group 'org-index)
  141. (defcustom org-index-sort-by 'mixed
  142. "Strategy for sorting index table (and whence entries in occur).
  143. Valid values are:
  144. last-access Sort index by date and time of last access; show
  145. more recent entries first.
  146. count Sort by usage count; more often used entries first.
  147. mixed First, show all index entries, which have been
  148. used today; sort them by last access. Then show
  149. older entries sorted by usage count."
  150. :group 'org-index
  151. :set (lambda (s v)
  152. (set-default s v)
  153. (if (and org-index-id
  154. (functionp 'org-index--sort-silent))
  155. (org-index--sort-silent)))
  156. :type '(choice
  157. (const last-accessed)
  158. (const count)
  159. (const mixed)))
  160. (defcustom org-index-yank-after-add 'ref
  161. "Specifies which column should be yanked after adding a new index row.
  162. Valid values are some columns of index table."
  163. :group 'org-index
  164. :type '(choice
  165. (const ref)
  166. (const category)
  167. (const keywords)))
  168. (defcustom org-index-point-on-add 'keywords
  169. "Specifies in which column point will land when adding a new index row.
  170. Valid values are some columns of index table."
  171. :group 'org-index
  172. :type '(choice
  173. (const category)
  174. (const keywords)))
  175. (defcustom org-index-copy-heading-to-keywords t
  176. "When adding a new node to index: Copy heading to keywords-column ?"
  177. :group 'org-index
  178. :type '(choice (const :tag "Yes" t)
  179. (const :tag "No" nil)))
  180. (defcustom org-index-strip-ref-and-date-from-heading t
  181. "When adding a headline as keywords for a new index row: remove
  182. leading reference or timestamps ?
  183. This can be useful, if you have the habit of adding refs and
  184. dates to the start of your headings; then, if you change your
  185. heading and want to update your index, you do not need to remove
  186. those pieces."
  187. :group 'org-index
  188. :type '(choice (const :tag "Yes" t)
  189. (const :tag "No" nil)))
  190. (defcustom org-index-edit-on-add '(category keywords)
  191. "List of columns to edit when adding a new row."
  192. :group 'org-index
  193. :type '(repeat (choice
  194. (const category)
  195. (const keywords))))
  196. ;; Variables to hold the configuration of the index table
  197. (defvar org-index--maxref nil "Maximum number from reference table (e.g. '153').")
  198. (defvar org-index--head nil "Any header before number (e.g. 'R').")
  199. (defvar org-index--tail nil "Tail after number (e.g. '}' or ')'.")
  200. (defvar org-index--numcols nil "Number of columns in index table.")
  201. (defvar org-index--ref-regex nil "Regular expression to match a reference.")
  202. (defvar org-index--ref-format nil "Format, that can print a reference.")
  203. (defvar org-index--columns nil "Columns of index-table.")
  204. (defvar org-index--buffer nil "Buffer of index table.")
  205. (defvar org-index--point nil "Position at start of headline of index table.")
  206. (defvar org-index--below-hline nil "Position of first cell in first line below hline.")
  207. (defvar org-index--headings nil "Headlines of index-table as a string.")
  208. (defvar org-index--headings-visible nil "Visible part of headlines of index-table as a string.")
  209. (defvar org-index--keymap nil "Keymap for shortcuts for some commands of `org-index'. Filled and activated by `org-index-default-keybings'.")
  210. ;; Variables to hold context and state
  211. (defvar org-index--last-ref nil "Last reference created or visited.")
  212. (defvar org-index--category-before nil "Category of node before.")
  213. (defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
  214. (defvar org-index--below-cursor nil "Word below cursor.")
  215. (defvar org-index--within-node nil "True, if we are within node of the index table.")
  216. (defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
  217. (defvar org-index--occur-help-text nil "Text for help in occur buffer.")
  218. (defvar org-index--occur-help-overlay nil "Overlay for help in occur buffer.")
  219. (defvar org-index--occur-stack nil "Stack with overlays for hiding lines.")
  220. (defvar org-index--occur-tail-overlay nil "Overlay to cover invisible lines.")
  221. (defvar org-index--last-sort nil "Last column, the index has been sorted after.")
  222. (defvar org-index--sort-timer nil "Timer to sort index in correct order.")
  223. (defvar org-index--aligned nil "Remember for this Emacs session, if table has been aligned at least once.")
  224. ;; static information for this program package
  225. (defconst org-index--commands '(occur add delete head ping enter ref help example sort multi-occur highlight maintain) "List of commands available.")
  226. (defconst org-index--required-headings '(ref id created last-accessed count) "All required headings.")
  227. (defconst org-index--valid-headings (append org-index--required-headings '(keywords category level)) "All valid headings.")
  228. (defconst org-index--occur-buffer-name "*org-index-occur*" "Name of occur buffer.")
  229. (defconst org-index--sort-idle-delay 300 "Delay in seconds after which buffer will sorted.")
  230. (defvar org-index-default-keybindings-list '(("a" . 'add) ("i " . nil) ("o" . 'occur) ("a" . 'add) ("d" . 'delete) ("h" . 'head) ("e" . 'enter) ("p." . 'ping) ("r" . 'ref) ("?" . 'help)) "One-letter short cuts for selected subcommands of `org-index', put in effect by `org-index-default-keybindings'.")
  231. (defmacro org-index--on (column value &rest body)
  232. "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
  233. The value returned is the value of the last form in BODY or nil,
  234. if VALUE cannot be found."
  235. (declare (indent 2) (debug t))
  236. (let ((pointvar (make-symbol "point")) ; avoid clash with same-named variables in body
  237. (foundvar (make-symbol "found"))
  238. (retvar (make-symbol "ret")))
  239. `(save-current-buffer
  240. (let ((,pointvar (point))
  241. ,foundvar
  242. ,retvar)
  243. (set-buffer org-index--buffer)
  244. (setq ,foundvar (org-index--go ,column ,value))
  245. (when ,foundvar
  246. (setq ,retvar (progn ,@body)))
  247. (goto-char ,pointvar)
  248. ,retvar))))
  249. (defun org-index (&optional command search-ref arg)
  250. "Fast search for selected org headings and things outside of org.
  251. This package creates and updates an index table of headings or
  252. keywords, references and ids, where each line points to a heading
  253. within org or references something outside. This table can be sorted
  254. by usage count, so that frequently used lines appear among the first
  255. search results.
  256. References are decorated numbers (e.g. 'R237' or '--455--'), as
  257. created by this package; they are well suited to be used outside of
  258. org, e.g. in folder names, ticket systems or on printed documents.
  259. On first invocation org-index will help to create a dedicated node
  260. for its index table.
  261. For basic usage, subcommands 'add' and 'occur' are most important.
  262. This is version 4.3.0 of org-index.el.
  263. \\<org-mode-map>
  264. The function `org-index' operates on a dedicated table, the index
  265. table, which lives within its own Org-mode node. The table and
  266. its containing node will be created, when you first invoke
  267. `org-index'. The node also contains a commented list, describing
  268. the columns of the index table and their associated flags. The
  269. node is found through its id, which is stored within the variable
  270. `org-index-id'.
  271. The function `org-index' is the only interactive function of this
  272. package and its main entry point; it will present you with a list
  273. of subcommands to choose from:
  274. occur: Incremental search, that shows matching lines from the
  275. index table. It is updated after every keystroke. You may
  276. enter a list of words seperated by space or comma (`,'), to
  277. select lines that contain all of the given words.
  278. add: Add the current node to your index, so that it can be
  279. found through the subcommand \"occur\". Update index,
  280. if node has already been present.
  281. delete: Delete the current node from your index.
  282. head: Ask for a reference number and search for this heading.
  283. enter: Enter index table and maybe go to a specific reference;
  284. use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
  285. ping: Echo line from index table for current node or first of
  286. its ancestor from index.
  287. ref: Create a new reference.
  288. help: Show this text.
  289. example: Create a temporary index, that will not be saved, but
  290. may serve as an example.
  291. sort: Sort lines in index, in region or buffer by contained
  292. reference, or sort index by count, reference or last access.
  293. multi-occur: Apply Emacs standard `multi-occur' operation on all
  294. `org-mode' buffers to search for the given reference.
  295. highlight: Highlight or unhiglight references in active region or buffer.
  296. Call with prefix argument (`C-u') to remove highlights.
  297. maintain: Offers some choices to check, update or fix your index.
  298. If you invoke `org-index' for the first time, an assistant will be
  299. invoked, that helps you to create your own, commented index.
  300. Invoke `org-customize' to tweak the behaviour of org-index.
  301. Call `org-index-default-keybindings' from within your init-file
  302. to establish convenient keyboard shortcuts.
  303. A numeric prefix argument is used as a reference number for
  304. commands, that need one (e.g. 'head').
  305. Optional arguments for use from elisp: COMMAND is a symbol naming
  306. the command to execute. SEARCH-REF specifies a reference to
  307. search for, if needed. ARG allows passing in a prefix argument
  308. as in interactive calls."
  309. (interactive "i\ni\nP")
  310. (let (search-id ; id to search for
  311. sort-what ; sort what ?
  312. kill-new-text ; text that will be appended to kill ring
  313. message-text) ; text that will be issued as an explanation
  314. ;;
  315. ;; Initialize and parse
  316. ;;
  317. ;; creates index table, if necessary
  318. (org-index--verify-id)
  319. ;; Get configuration of index table
  320. (org-index--parse-table)
  321. ;; store context information
  322. (org-index--retrieve-context)
  323. ;;
  324. ;; Arrange for proper sorting of index
  325. ;;
  326. ;; lets assume, that it has been sorted this way (we try hard to make sure)
  327. (unless org-index--last-sort (setq org-index--last-sort org-index-sort-by))
  328. ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
  329. (unless org-index--sort-timer
  330. (setq org-index--sort-timer
  331. (run-with-idle-timer org-index--sort-idle-delay t 'org-index--sort-silent)))
  332. ;;
  333. ;; Find out, what we are supposed to do
  334. ;;
  335. ;; check or read command
  336. (if command
  337. (unless (memq command org-index--commands)
  338. (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
  339. command (mapconcat 'symbol-name org-index--commands ",")))
  340. (setq command (intern (org-completing-read
  341. "Please choose: "
  342. (mapcar 'symbol-name org-index--commands)))))
  343. ;;
  344. ;; Get search string, if required; process possible sources one after
  345. ;; another (lisp argument, prefix argumen, user input).
  346. ;;
  347. ;; Try prefix, if no lisp argument given
  348. (if (and (not search-ref)
  349. (numberp arg))
  350. (setq search-ref (format "%s%d%s" org-index--head arg org-index--tail)))
  351. ;; These actions really need a search string and may even prompt for it
  352. (when (memq command '(enter head multi-occur))
  353. ;; search from surrounding text ?
  354. (unless search-ref
  355. (if org-index--within-node
  356. (if (org-at-table-p)
  357. (setq search-ref (org-index--get-or-set-field 'ref)))
  358. (if (and org-index--below-cursor
  359. (string-match (concat "\\(" org-index--ref-regex "\\)")
  360. org-index--below-cursor))
  361. (setq search-ref (match-string 1 org-index--below-cursor)))))
  362. ;; If we still do not have a search string, ask user explicitly
  363. (unless search-ref
  364. (if (eq command 'enter)
  365. (let ((r (org-index--read-search-for-enter)))
  366. (setq search-ref (car r))
  367. (setq search-id (cdr r)))
  368. (setq search-ref (read-from-minibuffer "Search reference number: "))))
  369. ;; Clean up search string
  370. (when search-ref
  371. (setq search-ref (org-trim search-ref))
  372. (if (string-match "^[0-9]+$" search-ref)
  373. (setq search-ref (concat org-index--head search-ref org-index--tail)))
  374. (if (string= search-ref "") (setq search-ref nil)))
  375. (if (and (not search-ref)
  376. (not (eq command 'enter)))
  377. (error "Command %s needs a reference number" command)))
  378. ;;
  379. ;; Command sort needs to know in advance, what to sort for
  380. ;;
  381. (when (eq command 'sort)
  382. (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))))
  383. ;;
  384. ;; Enter table
  385. ;;
  386. ;; Arrange for beeing able to return
  387. (when (and (memq command '(occur head enter ref example sort maintain))
  388. (not (string= (buffer-name) org-index--occur-buffer-name)))
  389. (org-mark-ring-push))
  390. ;; These commands will leave user in index table after they are finished
  391. (when (or (memq command '(enter ref maintain))
  392. (and (eq command 'sort)
  393. (eq sort-what 'index)))
  394. (pop-to-buffer-same-window org-index--buffer)
  395. (goto-char org-index--point)
  396. (org-index--unfold-buffer))
  397. ;;
  398. ;; Actually do, what is requested
  399. ;;
  400. (cond
  401. ((eq command 'help)
  402. ;; bring up help-buffer for this function
  403. (describe-function 'org-index))
  404. ((eq command 'multi-occur)
  405. ;; Construct list of all org-buffers
  406. (let (buff org-buffers)
  407. (dolist (buff (buffer-list))
  408. (set-buffer buff)
  409. (if (string= major-mode "org-mode")
  410. (setq org-buffers (cons buff org-buffers))))
  411. ;; Do multi-occur
  412. (multi-occur org-buffers (org-index--make-guarded-search search-ref))
  413. ;; Present results
  414. (if (get-buffer "*Occur*")
  415. (progn
  416. (setq message-text (format "multi-occur for '%s'" search-ref))
  417. (other-window 1)
  418. (toggle-truncate-lines 1))
  419. (setq message-text (format "Did not find '%s'" search-ref)))))
  420. ((eq command 'add)
  421. (let ((r (org-index--do-add-or-update)))
  422. (setq message-text (car r))
  423. (setq kill-new-text (cdr r))))
  424. ((eq command 'delete)
  425. (setq message-text (org-index--do-delete)))
  426. ((eq command 'head)
  427. (if (and org-index--within-node
  428. (org-at-table-p))
  429. (setq search-id (org-index--get-or-set-field 'id)))
  430. (setq search-id (or search-id (org-index--id-from-ref search-ref)))
  431. (setq message-text
  432. (if search-id
  433. (org-index--do-head search-ref search-id)
  434. (message "Current line has no id."))))
  435. ((eq command 'enter)
  436. (goto-char org-index--below-hline)
  437. (setq message-text
  438. (if search-ref
  439. (if (org-index--go 'ref search-ref)
  440. (progn
  441. (org-index--update-current-line)
  442. (org-table-goto-column (org-index--column-num 'ref))
  443. (format "Found index line '%s'" search-ref))
  444. (format "Did not find index line with reference '%s'" search-ref))
  445. (if search-id
  446. (if (org-index--go 'id search-id)
  447. (progn
  448. (org-index--update-current-line)
  449. (org-table-goto-column (org-index--column-num 'ref))
  450. (format "Found index line '%s'" (org-index--get-or-set-field 'ref)))
  451. (format "Did not find index line with id '%s'" search-id))
  452. ;; simply go into table
  453. (setq message-text "At index table"))))
  454. (recenter))
  455. ((eq command 'ping)
  456. (let ((moved-up 0) id info reached-top)
  457. (unless (string= major-mode "org-mode") (error "No node at point"))
  458. ;; take id from current node or reference
  459. (setq id (if search-ref
  460. (org-index--id-from-ref search-ref)
  461. (org-id-get)))
  462. ;; move up until we find a node in index
  463. (save-excursion
  464. (outline-back-to-heading)
  465. (while (not (or info
  466. reached-top))
  467. (if id
  468. (setq info (org-index--on 'id id
  469. (mapcar (lambda (x) (org-index--get-or-set-field x))
  470. (list 'ref 'count 'created 'last-accessed 'category 'keywords 'ref)))))
  471. (setq reached-top (= (org-outline-level) 1))
  472. (unless (or info
  473. reached-top)
  474. (outline-up-heading 1 t)
  475. (incf moved-up))
  476. (setq id (org-id-get))))
  477. (if info
  478. (progn
  479. (setq message-text
  480. (apply 'format
  481. (append (list "'%s'%shas been accessed %s times between %s and %s; category is '%s', keywords are '%s'"
  482. (pop info)
  483. (if (> moved-up 0) (format " (parent node, %d level up) " moved-up) " "))
  484. info)))
  485. (setq kill-new-text (car (last info))))
  486. (setq message-text "Neither this node nor any of its parents is part of index"))))
  487. ((eq command 'occur)
  488. (set-buffer org-index--buffer)
  489. (org-index--do-occur))
  490. ((eq command 'ref)
  491. (let (new)
  492. ;; add a new row
  493. (setq new (org-index--create-new-line))
  494. ;; fill special columns with standard values
  495. (org-table-goto-column (org-index--column-num 'ref))
  496. (insert new)
  497. (setq org-index--last-ref new)
  498. ;; goto point-field or first empty one or first field
  499. (if org-index-point-on-add
  500. (org-table-goto-column (org-index--column-num org-index-point-on-add))
  501. (unless (catch 'empty
  502. (dotimes (col org-index--numcols)
  503. (org-table-goto-column (+ col 1))
  504. (if (string= (org-trim (org-table-get-field)) "")
  505. (throw 'empty t))))
  506. ;; none found, goto first
  507. (org-table-goto-column 1)))
  508. (if org-index--active-region (setq kill-new-text org-index--active-region))
  509. (setq message-text (format "Adding a new row with ref '%s'" new))))
  510. ((eq command 'sort)
  511. (let ((sorts (list "count" "last-accessed" "mixed" "id" "ref"))
  512. sort groups-and-counts)
  513. (cond
  514. ((eq sort-what 'index)
  515. (setq sort
  516. (intern
  517. (org-icompleting-read
  518. "Please choose column to sort index table: "
  519. (cl-copy-list sorts)
  520. nil t nil nil (symbol-name org-index-sort-by))))
  521. (org-index--do-sort-index sort)
  522. (org-table-goto-column (org-index--column-num (if (eq sort 'mixed) 'last-access sort)))
  523. ;; When saving index, it should again be sorted correctly
  524. (with-current-buffer org-index--buffer
  525. (add-hook 'before-save-hook 'org-index--sort-silent t))
  526. (setq message-text
  527. (format
  528. (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
  529. (if groups-and-counts
  530. "; %d groups with equal %s and a total of %d lines have been found"
  531. ""))
  532. (symbol-name sort)
  533. org-index-sort-by
  534. org-index--sort-idle-delay
  535. (second groups-and-counts)
  536. (symbol-name sort)
  537. (third groups-and-counts))))
  538. ((memq sort-what '(region buffer))
  539. (org-index--do-sort-lines sort-what)
  540. (setq message-text (format "Sorted %s by contained references" sort-what))))))
  541. ((eq command 'highlight)
  542. (let ((where "buffer"))
  543. (save-excursion
  544. (save-restriction
  545. (when (and transient-mark-mode
  546. mark-active)
  547. (narrow-to-region (region-beginning) (region-end))
  548. (setq where "region"))
  549. (if arg
  550. (progn
  551. (unhighlight-regexp org-index--ref-regex)
  552. (setq message-text (format "Removed highlights for references in %s" where)))
  553. (highlight-regexp org-index--ref-regex 'isearch)
  554. (setq message-text (format "Highlighted references in %s" where)))))))
  555. ((eq command 'maintain)
  556. (setq message-text (org-index--do-maintain)))
  557. ((eq command 'example)
  558. (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
  559. (org-index--create-index t)))
  560. (t (error "Unknown subcommand '%s'" command)))
  561. ;; tell, what we have done and what can be yanked
  562. (if kill-new-text (setq kill-new-text
  563. (substring-no-properties kill-new-text)))
  564. (if (string= kill-new-text "") (setq kill-new-text nil))
  565. (let ((m (concat
  566. message-text
  567. (if (and message-text kill-new-text)
  568. " and r"
  569. (if kill-new-text "R" ""))
  570. (if kill-new-text (format "eady to yank '%s'." kill-new-text) (if message-text "." "")))))
  571. (unless (string= m "")
  572. (message m)
  573. (setq org-index--message-text m)))
  574. (if kill-new-text (kill-new kill-new-text))))
  575. (defun org-index-default-keybindings (&optional prefix)
  576. "Set default keybindings for `org-index'.
  577. Invoke subcommands of org index with a single key
  578. sequence. Establish the common prefix key 'C-c i' which should be
  579. followed by the first letter of a subcommand.
  580. The ist of letters and subcommands is specified in within
  581. `org-index-default-keybindings-list'.
  582. See `org-index' for a description of all subcommands.
  583. Optional argument PREFIX specifies common prefix, defaults to 'C-c i'"
  584. (interactive)
  585. (define-prefix-command 'org-index--keymap)
  586. ;; prefix command
  587. (global-set-key (kbd (or prefix "C-c i")) 'org-index--keymap)
  588. ;; loop over subcommands
  589. (mapcar
  590. (lambda (x)
  591. ;; loop over letters, that invoke the same subcommand
  592. (mapcar (lambda (c)
  593. (define-key org-index--keymap (kbd (char-to-string c))
  594. `(lambda (arg) (interactive "P")
  595. (message nil)
  596. (org-index ,(cdr x) nil arg))))
  597. (car x)))
  598. org-index-default-keybindings-list))
  599. (defun org-index-new-line (&rest keys-values)
  600. "Create a new line within the index table, returning its reference.
  601. The function takes a varying number of argument pairs; each pair
  602. is a symbol for an existing column heading followed by its value.
  603. The return value is the new reference.
  604. Example:
  605. (message \"Created reference %s\"
  606. (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
  607. Optional argument KEYS-VALUES specifies content of new line."
  608. (org-index--verify-id)
  609. (org-index--parse-table)
  610. (car (apply 'org-index--do-new-line keys-values)))
  611. (defun org-index--do-new-line (&rest keys-values)
  612. "Do the work for `org-index-new-line'.
  613. Optional argument KEYS-VALUES specifies content of new line."
  614. (save-excursion
  615. (org-index--retrieve-context)
  616. (with-current-buffer org-index--buffer
  617. (goto-char org-index--point)
  618. ;; check arguments early; they might come from lisp-user
  619. (let ((kvs keys-values)
  620. k v)
  621. (while kvs
  622. (setq k (car kvs))
  623. (setq v (cadr kvs))
  624. (if (eq k 'ref)
  625. (unless (memq v '(t nil))
  626. (error "Column 'ref' accepts only \"t\" or \"nil\""))
  627. (if (or (not (symbolp k))
  628. (and (symbolp v) (not (eq v t)) (not (eq v nil))))
  629. (error "Arguments must be alternation of key and value")))
  630. (unless (org-index--column-num k)
  631. (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
  632. (setq kvs (cddr kvs))))
  633. (let (ref yank)
  634. ;; create new line
  635. (setq ref (org-index--create-new-line))
  636. (plist-put keys-values 'ref ref)
  637. ;; fill columns
  638. (let ((kvs keys-values)
  639. k v n)
  640. (while kvs
  641. (setq k (car kvs))
  642. (setq v (cadr kvs))
  643. (org-table-goto-column (org-index--column-num k))
  644. (insert (org-trim v))
  645. (setq kvs (cddr kvs))))
  646. ;; align and fontify line
  647. (org-index--promote-current-line)
  648. (org-index--align-and-fontify-current-line)
  649. ;; get column to yank
  650. (setq yank (org-index--get-or-set-field org-index-yank-after-add))
  651. (cons ref yank)))))
  652. (defun org-index-get-line (column value)
  653. "Retrieve an existing line within the index table by ref or id.
  654. Return its contents as a property list.
  655. The function `plist-get' may be used to retrieve specific elements
  656. from the result.
  657. Example:
  658. (plist-get (org-index-get-line 'ref \"R12\") 'count)
  659. retrieves the value of the count-column for reference number 12.
  660. Argument COLUMN is a symbol, either ref or id,
  661. argument VALUE specifies the value to search for."
  662. ;; check arguments
  663. (unless (memq column '(ref id))
  664. (error "Argument column can only be 'ref' or 'id'"))
  665. (unless value
  666. (error "Need a value to search for"))
  667. (org-index--verify-id)
  668. (org-index--parse-table)
  669. (org-index--get-line column value))
  670. (defun org-index--get-line (column value)
  671. "Find a line by ID, return its contents.
  672. Argument COLUMN and VALUE specify line to get."
  673. (let (content)
  674. (org-index--on
  675. column value
  676. (mapc (lambda (x)
  677. (if (and (numberp (cdr x))
  678. (> (cdr x) 0))
  679. (setq content (cons (car x) (cons (or (org-index--get-or-set-field (car x)) "") content)))))
  680. (reverse org-index--columns)))
  681. content))
  682. (defun org-index--delete-line (id)
  683. "Delete a line specified by ID."
  684. (let (content)
  685. (org-index--on
  686. 'id id
  687. (let ((start (line-beginning-position)))
  688. (beginning-of-line)
  689. (forward-line)
  690. (delete-region start (point))
  691. t))))
  692. (defun org-index--ref-from-id (id)
  693. "Get reference from line ID."
  694. (org-index--on 'id id (org-index--get-or-set-field 'ref)))
  695. (defun org-index--id-from-ref (ref)
  696. "Get id from line REF."
  697. (org-index--on 'ref ref (org-index--get-or-set-field 'id)))
  698. (defun org-index--read-search-for-enter ()
  699. "Special input routine for command enter."
  700. ;; Accept single char commands or switch to reading a sequence of digits
  701. (let (char prompt search-ref search-id)
  702. ;; start with short prompt but give more help on next iteration
  703. (setq prompt "Please specify, where to go in index (0-9.,space,backspace,return or ? for help): ")
  704. ;; read one character
  705. (while (not (memq char (append (number-sequence ?0 ?9) (list ?\d ?\b ?\r ?\j ?\s ?.))))
  706. (setq char (read-char prompt))
  707. (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: "))
  708. (if (memq char (number-sequence ?0 ?9))
  709. ;; read rest of digits
  710. (setq search-ref (read-from-minibuffer "Search reference number: " (char-to-string char))))
  711. ;; decode single chars
  712. (if (memq char '(?\r ?\n ?.)) (setq search-id (org-id-get)))
  713. (if (memq char '(?\d ?\b)) (setq search-ref (number-to-string org-index--maxref)))
  714. (cons search-ref search-id)))
  715. (defun org-index--verify-id ()
  716. "Check, that we have a valid id."
  717. ;; Check id
  718. (unless org-index-id
  719. (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")))
  720. (if (string= "create-index" answer)
  721. (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
  722. (describe-function 'org-index))))
  723. ;; Find node
  724. (let (marker)
  725. (setq marker (org-id-find org-index-id 'marker))
  726. (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
  727. ; Try again with new node
  728. (setq marker (org-id-find org-index-id 'marker))
  729. (unless marker (error "Could not create node"))
  730. (setq org-index--buffer (marker-buffer marker)
  731. org-index--point (marker-position marker))
  732. (move-marker marker nil)))
  733. (defun org-index--retrieve-context ()
  734. "Collect context information before starting with command."
  735. ;; Get the content of the active region or the word under cursor
  736. (setq org-index--active-region
  737. (if (and transient-mark-mode mark-active)
  738. (buffer-substring (region-beginning) (region-end))
  739. nil))
  740. (setq org-index--below-cursor (thing-at-point 'symbol))
  741. ;; get category of current node
  742. (setq org-index--category-before
  743. (save-excursion ; workaround: org-get-category does not give category when at end of buffer
  744. (beginning-of-line)
  745. (org-get-category (point) t)))
  746. ;; Find out, if we are within index table or not
  747. (setq org-index--within-node (string= (org-id-get) org-index-id)))
  748. (defun org-index--parse-table ()
  749. "Parse content of index table."
  750. (let (ref-field
  751. id-field
  752. initial-point
  753. end-of-headings
  754. start-of-headings)
  755. (with-current-buffer org-index--buffer
  756. (setq org-index--maxref 0)
  757. (setq initial-point (point))
  758. (org-index--go-below-hline)
  759. ;; align and fontify table once for this emacs session
  760. (unless org-index--aligned
  761. (org-table-align) ; needs to happen before fontification to be effective ?
  762. (let ((is-modified (buffer-modified-p))
  763. (below (point)))
  764. (while (org-at-table-p)
  765. (forward-line))
  766. (font-lock-fontify-region below (point))
  767. (org-index--go-below-hline)
  768. (setq org-index--aligned t)
  769. (set-buffer-modified-p is-modified)))
  770. (org-index--go-below-hline)
  771. (setq org-index--below-hline (point))
  772. (beginning-of-line)
  773. ;; get headings to display during occur
  774. (setq end-of-headings (point))
  775. (while (org-at-table-p) (forward-line -1))
  776. (forward-line)
  777. (setq start-of-headings (point))
  778. (setq org-index--headings-visible (substring-no-properties (org-index--copy-visible start-of-headings end-of-headings)))
  779. (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
  780. ;; count columns
  781. (org-table-goto-column 100)
  782. (setq org-index--numcols (- (org-table-current-column) 1))
  783. ;; go to top of table
  784. (while (org-at-table-p)
  785. (forward-line -1))
  786. (forward-line)
  787. ;; parse line of headings
  788. (org-index--parse-headings)
  789. ;; parse list of flags
  790. (goto-char org-index--point)
  791. ;; Retrieve any decorations around the number within the first nonempty ref-field
  792. (goto-char org-index--below-hline)
  793. (while (and (org-at-table-p)
  794. (not (setq ref-field (org-index--get-or-set-field 'ref))))
  795. (forward-line))
  796. ;; Some Checking
  797. (unless ref-field
  798. (org-index--report-index-error "Reference column is empty"))
  799. (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
  800. (org-index--report-index-error
  801. "First reference in index table ('%s') does not contain a number" ref-field))
  802. ;; These are the decorations used within the first ref of index
  803. (setq org-index--head (match-string 1 ref-field))
  804. (setq org-index--tail (match-string 3 ref-field))
  805. (setq org-index--ref-regex (concat (regexp-quote org-index--head)
  806. "\\([0-9]+\\)"
  807. (regexp-quote org-index--tail)))
  808. (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
  809. ;; check if the table still seems to be sorted mixed
  810. (goto-char org-index--below-hline)
  811. (when (eq org-index-sort-by 'mixed)
  812. (org-index--go-below-hline)
  813. (if (string< (org-index--get-or-set-field 'last-accessed)
  814. (org-index--get-mixed-time))
  815. (org-index--do-sort-index org-index-sort-by)))
  816. ;; Go through table to find maximum number and do some checking
  817. (let ((ref 0))
  818. (while (org-at-table-p)
  819. (setq ref-field (org-index--get-or-set-field 'ref))
  820. (setq id-field (org-index--get-or-set-field 'id))
  821. (when (and (not ref-field)
  822. (not id-field))
  823. (kill-whole-line)
  824. (message "Removing line from index-table with both ref and id empty"))
  825. (if ref-field
  826. (if (string-match org-index--ref-regex ref-field)
  827. ;; grab number
  828. (setq ref (string-to-number (match-string 1 ref-field)))
  829. (kill-whole-line)
  830. (message "Removing line from index-table whose ref does not contain a number")))
  831. ;; check, if higher ref
  832. (if (> ref org-index--maxref) (setq org-index--maxref ref))
  833. (forward-line 1)))
  834. ;; go back to initial position
  835. (goto-char initial-point))))
  836. (defun org-index--do-maintain ()
  837. "Choose among and perform some tasks to maintain index."
  838. (let ((check-what) (max-mini-window-height 1.0) message-text)
  839. (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")))
  840. (message nil)
  841. (cond
  842. ((eq check-what 'check)
  843. (setq message-text (or (org-index--check-ids)
  844. "No problems found")))
  845. ((eq check-what 'statistics)
  846. (setq message-text (org-index--do-statistics)))
  847. ((eq check-what 'duplicates)
  848. (setq message-text (org-index--find-duplicates)))
  849. ((eq check-what 'clean)
  850. (let ((lines 0))
  851. (org-map-entries
  852. (lambda ()
  853. (when (org-entry-get (point) "org-index-ref")
  854. (incf lines)
  855. (org-entry-delete (point) "org-index-ref")))
  856. nil 'agenda)
  857. (setq message-text (format "Removed property 'org-index-ref' from %d lines" lines))))
  858. ((eq check-what 'update)
  859. (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 ? ")
  860. (setq message-text (org-index--update-all-lines))
  861. (setq message-text "Canceled."))))
  862. message-text))
  863. (defun org-index--get-mixed-time ()
  864. "Get timestamp for sorting order mixed."
  865. (format-time-string
  866. (org-time-stamp-format t t)
  867. (apply 'encode-time (append '(0 0 0) (nthcdr 3 (decode-time))))))
  868. (defun org-index--do-sort-index (sort)
  869. "Sort index table according to SORT."
  870. (let ((is-modified (buffer-modified-p))
  871. top
  872. bottom
  873. ref-field
  874. count-field
  875. mixed-time)
  876. (unless buffer-read-only
  877. (message "Sorting index table for %s..." (symbol-name sort))
  878. (undo-boundary)
  879. (let ((message-log-max nil)) ; we have just issued a message, dont need those of sort-subr
  880. ;; if needed for mixed sort
  881. (if (eq sort 'mixed)
  882. (setq mixed-time (org-index--get-mixed-time)))
  883. ;; get boundaries of table
  884. (org-index--go-below-hline)
  885. (forward-line 0)
  886. (setq top (point))
  887. (while (org-at-table-p) (forward-line))
  888. ;; kill all empty rows at bottom
  889. (while (progn
  890. (forward-line -1)
  891. (org-table-goto-column 1)
  892. (and
  893. (not (org-index--get-or-set-field 'ref))
  894. (not (org-index--get-or-set-field 'id))))
  895. (org-table-kill-row))
  896. (forward-line 1)
  897. (setq bottom (point))
  898. ;; sort lines
  899. (save-restriction
  900. (narrow-to-region top bottom)
  901. (goto-char top)
  902. (sort-subr t
  903. 'forward-line
  904. 'end-of-line
  905. (lambda ()
  906. (org-index--get-sort-key sort t mixed-time))
  907. nil
  908. 'string<)
  909. (goto-char (point-min))
  910. ;; restore modification state
  911. (set-buffer-modified-p is-modified)))
  912. (setq org-index--last-sort sort))))
  913. (defun org-index--do-sort-lines (what)
  914. "Sort lines in WHAT according to contained reference."
  915. (save-restriction
  916. (cond
  917. ((eq what 'region)
  918. (if (region-active-p)
  919. (narrow-to-region (region-beginning) (region-end))
  920. (error "No active region, cannot sort")))
  921. ((eq what 'buffer)
  922. (unless (y-or-n-p "Sort whole current buffer ? ")
  923. (error "Canceled"))
  924. (narrow-to-region (point-min) (point-max))))
  925. (goto-char (point-min))
  926. (sort-subr nil 'forward-line 'end-of-line
  927. (lambda ()
  928. (if (looking-at (concat ".*"
  929. (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
  930. (string-to-number (match-string 1))
  931. 0)))))
  932. (defun org-index--go-below-hline ()
  933. "Move below hline in index-table."
  934. (let ((count 0)
  935. (errstring (format "index table within node %s" org-index-id)))
  936. (goto-char org-index--point)
  937. ;; go to heading of node
  938. (while (not (org-at-heading-p)) (forward-line -1))
  939. (forward-line 1)
  940. ;; go to first table, but make sure we do not get into another node
  941. (while (and (not (org-at-table-p))
  942. (not (org-at-heading-p))
  943. (not (eobp)))
  944. (forward-line))
  945. ;; check, if there really is a table
  946. (unless (org-at-table-p)
  947. (org-index--create-missing-index "Cannot find %s." errstring))
  948. ;; go just after hline
  949. (while (and (not (org-at-table-hline-p))
  950. (org-at-table-p))
  951. (forward-line))
  952. (forward-line)
  953. ;; and check
  954. (unless (org-at-table-p)
  955. (org-index--report-index-error "Cannot find a hline within %s" errstring))
  956. (org-table-goto-column 1)))
  957. (defun org-index--parse-headings ()
  958. "Parse headings of index table."
  959. (let (field ;; field content
  960. field-symbol ;; and as a symbol
  961. found)
  962. (setq org-index--columns nil)
  963. ;; For each column
  964. (dotimes (col org-index--numcols)
  965. (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
  966. (if (string= field "")
  967. (error "Heading of column cannot be empty"))
  968. (if (and (not (string= (substring field 0 1) "."))
  969. (not (member (intern field) org-index--valid-headings)))
  970. (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field))
  971. (setq field-symbol (intern field))
  972. ;; check if heading has already appeared
  973. (if (assoc field-symbol org-index--columns)
  974. (org-index--report-index-error
  975. "'%s' appears two times as column heading" (downcase field))
  976. ;; add it to list at front, reverse later
  977. (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
  978. (setq org-index--columns (reverse org-index--columns))
  979. ;; check if all necessary headings have appeared
  980. (mapc (lambda (head)
  981. (unless (cdr (assoc head org-index--columns))
  982. (org-index--report-index-error "No column has heading '%s'" head)))
  983. org-index--required-headings))
  984. (defun org-index--goto-list (name &optional required non-top)
  985. "Goto list NAME (maybe NON-TOP Level) in index node, err if REQUIRED list is not present."
  986. (goto-char org-index--point)
  987. ;; go to heading of node
  988. (while (not (org-at-heading-p)) (forward-line -1))
  989. (forward-line 1)
  990. ;; go to named list
  991. (while (and (not (let ((item (org-index--parse-list-item)))
  992. (if item
  993. (and (or non-top (= (cdr (assoc :indent item)) 0)) ;; accept only toplevel ?
  994. (string= (cdr (assoc :text item)) name)) ;; with requested name
  995. nil)))
  996. (not (org-at-table-p))
  997. (not (org-at-heading-p))
  998. (not (eobp)))
  999. (forward-line 1))
  1000. (if (org-at-item-p)
  1001. t
  1002. (if required
  1003. (org-index--report-index-error "Could not find required list '%s'" name)
  1004. nil)))
  1005. (defun org-index--parse-list-item ()
  1006. "Parse a list item into an assoc array (indent, checkbox, text, value)."
  1007. ;; matche full list-item, maybe with checkbox and double-colon
  1008. (if (looking-at org-list-full-item-re)
  1009. ;; retrieve interesting parts of list item from match data
  1010. (let (indent checkbox text value next-line)
  1011. (setq indent
  1012. (- (save-excursion (goto-char (match-beginning 1)) (current-column)) ; first column
  1013. (save-match-data (org-current-level)) ; indent-level
  1014. 1))
  1015. (setq checkbox (match-string 3))
  1016. (setq text (match-string 4))
  1017. (set (if text 'value 'text) (buffer-substring (match-end 0) (line-end-position))) ; regexp did not capture this
  1018. ;; peek ahead, if item continues on next line
  1019. (forward-line 1)
  1020. (if (looking-at org-list-full-item-re)
  1021. (forward-line -1) ; already at next item; go back
  1022. (setq next-line (buffer-substring (line-beginning-position) (line-end-position))))
  1023. ;; clean up strings
  1024. (mapc (lambda (x)
  1025. (if (stringp (symbol-value x))
  1026. (set x (org-trim (substring-no-properties (symbol-value x))))))
  1027. '(text value next-line))
  1028. (if next-line (setq text (concat text " " next-line))) ; append next line if
  1029. (list (cons :indent indent) (cons :text text) (cons :value value) (cons :sym (intern text))))
  1030. nil))
  1031. (defun org-index--create-missing-index (&rest reasons)
  1032. "Create a new empty index table with detailed explanation. Argument REASONS explains why."
  1033. (org-index--ask-before-create-index "Cannot find your index table: "
  1034. "new permanent" "."
  1035. reasons)
  1036. (org-index--create-index))
  1037. (defun org-index--report-index-error (&rest reasons)
  1038. "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
  1039. (when org-index--buffer
  1040. (pop-to-buffer-same-window org-index--buffer)
  1041. (goto-char org-index--below-hline)
  1042. (org-reveal t))
  1043. (org-index--ask-before-create-index "The existing index contains this error: "
  1044. "temporary" ", to compare with."
  1045. reasons)
  1046. (org-index--create-index t t))
  1047. (defun org-index--ask-before-create-index (explanation type for-what reasons)
  1048. ; checkdoc-params: (explanation type for-what reasons)
  1049. "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
  1050. (let (reason prompt)
  1051. (setq reason (apply 'format reasons))
  1052. (setq prompt (concat explanation reason "\n\n"
  1053. "However, this assistant can help you to create a "
  1054. type " index with detailed comments" for-what "\n\n"
  1055. "Do you want to proceed ?"))
  1056. (unless (let ((max-mini-window-height 1.0))
  1057. (y-or-n-p prompt))
  1058. (error (concat explanation reason)))))
  1059. (defun org-index--create-index (&optional temporary compare)
  1060. "Create a new empty index table with detailed explanation.
  1061. specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
  1062. (let (buffer
  1063. title
  1064. firstref
  1065. id)
  1066. (if temporary
  1067. (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
  1068. (buffer-name "*org-index-example-index*"))
  1069. (setq buffer (get-buffer-create buffer-name))
  1070. (with-current-buffer buffer
  1071. ;; but it needs a file for its index to be found
  1072. (unless (string= (buffer-file-name) file-name)
  1073. (set-visited-file-name file-name))
  1074. (rename-buffer buffer-name) ; name is change by line above
  1075. (erase-buffer)
  1076. (org-mode)))
  1077. (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))))))
  1078. (setq title (read-from-minibuffer "Please enter the title of the index node: "))
  1079. (while (progn
  1080. (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: "))
  1081. (let (desc)
  1082. (when (string-match "[[:blank:]]" firstref)
  1083. (setq desc "Contains whitespace"))
  1084. (when (string-match "[[:cntrl:]]" firstref)
  1085. (setq desc "Contains control characters"))
  1086. (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
  1087. ;; firstref not okay, report details
  1088. (setq desc
  1089. (cond ((string= firstref "") "is empty")
  1090. ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
  1091. ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
  1092. ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
  1093. )))
  1094. (if desc
  1095. (progn
  1096. (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
  1097. t)
  1098. nil))))
  1099. (with-current-buffer buffer
  1100. (goto-char (point-max))
  1101. (insert (format "* %s %s\n" firstref title))
  1102. (if temporary
  1103. (insert "
  1104. Below you find your temporary index table, which WILL NOT LAST LONGER
  1105. THAN YOUR CURRENT EMACS SESSION; please use it only to compare it to
  1106. your existing index.
  1107. ")
  1108. (insert "
  1109. Below you find your initial index table, which will grow over time.
  1110. "))
  1111. (insert "
  1112. You may start using it by adding some lines. Just move to
  1113. another heading, invoke `org-index' and choose the command
  1114. 'add'. After adding a few nodes, try the command 'occur'
  1115. to search among them.
  1116. To gain further insight you may invoke the subcommand 'help', or
  1117. read the description of `org-index'.
  1118. Within the index table below, the sequence of columns does not
  1119. matter. You may reorder them in any way you please.
  1120. You may also add your own columns, which should start
  1121. with a dot (e.g. '.my-column').
  1122. Invoke `org-customize' to tweak the behaviour of org-index
  1123. (see group org-index).
  1124. This node needs not be a top level node; its name is completely
  1125. at your choice; it is found through its ID only.
  1126. ")
  1127. (unless temporary
  1128. (insert "
  1129. Remark: These lines of explanation can be removed at any time.
  1130. "))
  1131. (setq id (org-id-get-create))
  1132. (insert (format "
  1133. | ref | category | keywords | count | last-accessed | created | id |
  1134. | | | | | | | <4> |
  1135. |-----+-----------+----------+-------+---------------+---------+------|
  1136. | %s | | %s | | | %s | %s |
  1137. "
  1138. firstref
  1139. "This node"
  1140. (with-temp-buffer (org-insert-time-stamp nil nil t))
  1141. id))
  1142. ;; make sure, that node can be found
  1143. (org-id-add-location id (buffer-file-name))
  1144. (setq buffer-save-without-query t)
  1145. (basic-save-buffer)
  1146. (while (not (org-at-table-p)) (forward-line -1))
  1147. (unless buffer-read-only (org-table-align))
  1148. (while (not (org-at-heading-p)) (forward-line -1))
  1149. ;; read back some info about new index
  1150. (let ((org-index-id id))
  1151. (org-index--verify-id))
  1152. ;; remember at least for this session
  1153. (setq org-index-id id)
  1154. ;; present results to user
  1155. (if temporary
  1156. (progn
  1157. ;; Present existing and temporary index together
  1158. (when compare
  1159. (pop-to-buffer-same-window org-index--buffer)
  1160. (goto-char org-index--point)
  1161. (org-index--unfold-buffer)
  1162. (delete-other-windows)
  1163. (select-window (split-window-vertically)))
  1164. ;; show new index
  1165. (pop-to-buffer-same-window buffer)
  1166. (org-id-goto id)
  1167. (org-index--unfold-buffer)
  1168. (if compare
  1169. (error "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
  1170. (message "This is your new temporary index.")))
  1171. (progn
  1172. ;; Only show the new index
  1173. (pop-to-buffer-same-window buffer)
  1174. (delete-other-windows)
  1175. (org-id-goto id)
  1176. (org-index--unfold-buffer)
  1177. (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 ? ")
  1178. (progn
  1179. (customize-save-variable 'org-index-id id)
  1180. (error "Saved org-index-id '%s' to %s" id (or custom-file
  1181. user-init-file)))
  1182. (let (sq)
  1183. (setq sq (format "(setq org-index-id \"%s\")" id))
  1184. (kill-new sq)
  1185. (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))))))))
  1186. (defun org-index--unfold-buffer ()
  1187. "Helper function to unfold buffer."
  1188. (org-show-context)
  1189. (org-show-subtree)
  1190. (recenter 1)
  1191. (save-excursion
  1192. (org-back-to-heading)
  1193. (forward-line) ;; on property drawer
  1194. (org-cycle)
  1195. (org-index--goto-list "columns-and-flags")
  1196. (org-cycle)))
  1197. (defun org-index--update-line (&optional ref-or-id)
  1198. "Update columns count and last-accessed in line REF-OR-ID."
  1199. (let ((newcount 0)
  1200. initial)
  1201. (with-current-buffer org-index--buffer
  1202. (unless buffer-read-only
  1203. ;; search reference or id, if given (or assume, that we are already positioned right)
  1204. (when ref-or-id
  1205. (setq initial (point))
  1206. (goto-char org-index--below-hline)
  1207. (while (and (org-at-table-p)
  1208. (not (or (string= ref-or-id (org-index--get-or-set-field 'ref))
  1209. (string= ref-or-id (org-index--get-or-set-field 'id)))))
  1210. (forward-line)))
  1211. (if (not (org-at-table-p))
  1212. (error "Did not find reference or id '%s'" ref-or-id)
  1213. (org-index--update-current-line))
  1214. (if initial (goto-char initial))))))
  1215. (defun org-index--update-current-line ()
  1216. "Update current lines columns count and last-accessed."
  1217. (let (newcount (count-field (org-index--get-or-set-field 'count)))
  1218. ;; update count field only if number or empty
  1219. (when (or (not count-field)
  1220. (string-match "^[0-9]+$" count-field))
  1221. (setq newcount (+ 1 (string-to-number (or count-field "0"))))
  1222. (org-index--get-or-set-field 'count
  1223. (number-to-string newcount)))
  1224. ;; update timestamp
  1225. (org-table-goto-column (org-index--column-num 'last-accessed))
  1226. (org-table-blank-field)
  1227. (org-insert-time-stamp nil t t)
  1228. ;; move line according to new content
  1229. (org-index--promote-current-line)
  1230. (org-index--align-and-fontify-current-line)))
  1231. (defun org-index--align-and-fontify-current-line ()
  1232. "Make current line blend well among others."
  1233. (let ((line (substring-no-properties (delete-and-extract-region (line-beginning-position) (line-end-position)))))
  1234. ;; create minimum table with fixed-width columns to align and fontify new line
  1235. (insert (with-temp-buffer
  1236. (org-set-font-lock-defaults)
  1237. (insert org-index--headings-visible)
  1238. ;; fill columns, so that aligning cannot shrink them
  1239. (goto-char (point-min))
  1240. (search-forward "|")
  1241. (while (search-forward " " (line-end-position) t)
  1242. (replace-match "." nil t))
  1243. (goto-char (point-min))
  1244. (while (search-forward ".|." (line-end-position) t)
  1245. (replace-match " | " nil t))
  1246. (goto-char (point-min))
  1247. (while (search-forward "|." (line-end-position) t)
  1248. (replace-match "| " nil t))
  1249. (goto-char (point-max))
  1250. (insert line)
  1251. (forward-line 0)
  1252. (org-table-align)
  1253. (font-lock-fontify-region (point-min) (point-max))
  1254. (goto-char (point-max))
  1255. (forward-line -1)
  1256. (buffer-substring (line-beginning-position) (line-end-position))))))
  1257. (defun org-index--promote-current-line ()
  1258. "Move current line up in table according to changed sort fields."
  1259. (let (begin end key
  1260. (to-skip 0))
  1261. (forward-line 0) ; stay at beginning of line
  1262. (setq key (org-index--get-sort-key))
  1263. (setq begin (point))
  1264. (setq end (line-beginning-position 2))
  1265. (forward-line -1)
  1266. (while (and (org-at-table-p)
  1267. (not (org-at-table-hline-p))
  1268. (string< (org-index--get-sort-key) key))
  1269. (incf to-skip)
  1270. (forward-line -1))
  1271. (forward-line 1)
  1272. ;; insert line at new position
  1273. (when (> to-skip 0)
  1274. (insert (delete-and-extract-region begin end))
  1275. (forward-line -1))))
  1276. (defun org-index--get-sort-key (&optional sort with-ref mixed-time)
  1277. "Get value for sorting from column SORT, optional WITH-REF; if mixes use MIXED-TIME."
  1278. (let (ref
  1279. ref-field
  1280. key)
  1281. (unless sort (setq sort org-index--last-sort)) ; use default value
  1282. (when (or with-ref
  1283. (eq sort 'ref))
  1284. ;; get reference with leading zeroes, so it can be
  1285. ;; sorted as text
  1286. (setq ref-field (org-index--get-or-set-field 'ref))
  1287. (string-match org-index--ref-regex ref-field)
  1288. (setq ref (format
  1289. "%06d"
  1290. (string-to-number
  1291. (match-string 1 ref-field)))))
  1292. (setq key
  1293. (cond
  1294. ((eq sort 'count)
  1295. (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))
  1296. ((eq sort 'mixed)
  1297. (let ((last-accessed (org-index--get-or-set-field 'last-accessed)))
  1298. (unless mixed-time (setq mixed-time (org-index--get-mixed-time)))
  1299. (concat
  1300. (if (string< mixed-time last-accessed) last-accessed mixed-time)
  1301. (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))))
  1302. ((eq sort 'ref)
  1303. ref)
  1304. ((memq sort '(id last-accessed created))
  1305. (org-index--get-or-set-field sort))
  1306. (t (error "This is a bug: unmatched case '%s'" sort))))
  1307. (if with-ref (setq key (concat key ref)))
  1308. key))
  1309. (defun org-index--get-or-set-field (key &optional value)
  1310. "Retrieve field KEY from index table or set it to VALUE."
  1311. (let (field)
  1312. (save-excursion
  1313. (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value)))
  1314. (if (string= field "") (setq field nil))
  1315. (org-no-properties field))))
  1316. (defun org-index--column-num (key)
  1317. "Return number of column KEY."
  1318. (if (numberp key)
  1319. key
  1320. (cdr (assoc key org-index--columns))))
  1321. (defun org-index--make-guarded-search (ref &optional dont-quote)
  1322. "Make robust search string from REF; DONT-QUOTE it, if requested."
  1323. (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
  1324. (defun org-index--find-duplicates ()
  1325. "Find duplicate references or ids in index table."
  1326. (let (ref-duplicates id-duplicates message)
  1327. (setq ref-duplicates (org-index--find-duplicates-helper 'ref))
  1328. (setq id-duplicates (org-index--find-duplicates-helper 'id))
  1329. (goto-char org-index--below-hline)
  1330. (if (or ref-duplicates id-duplicates)
  1331. (progn
  1332. ;; show results
  1333. (pop-to-buffer-same-window
  1334. (get-buffer-create "*org-index-duplicates*"))
  1335. (when ref-duplicates
  1336. (insert "These references appear more than once:\n")
  1337. (mapc (lambda (x) (insert " " x "\n")) ref-duplicates)
  1338. (insert "\n\n"))
  1339. (when id-duplicates
  1340. (insert "These ids appear more than once:\n")
  1341. (mapc (lambda (x) (insert " " x "\n")) id-duplicates))
  1342. "Some references or ids are duplicates")
  1343. "No duplicate references or ids found")))
  1344. (defun org-index--find-duplicates-helper (column)
  1345. "Helper for `org-index--find-duplicates': Go through table and count given COLUMN."
  1346. (let (counts duplicates field found)
  1347. ;; go through table
  1348. (goto-char org-index--below-hline)
  1349. (while (org-at-table-p)
  1350. ;; get column
  1351. (setq field (org-index--get-or-set-field column))
  1352. ;; and increment
  1353. (setq found (assoc field counts))
  1354. (if found
  1355. (incf (cdr found))
  1356. (setq counts (cons (cons field 1) counts)))
  1357. (forward-line))
  1358. (mapc (lambda (x) (if (and (> (cdr x) 1)
  1359. (car x))
  1360. (setq duplicates (cons (car x) duplicates)))) counts)
  1361. duplicates))
  1362. (defun org-index--do-statistics ()
  1363. "Compute statistics about index table."
  1364. (let ((total 0)
  1365. ref ref-field min max message)
  1366. ;; go through table
  1367. (goto-char org-index--below-hline)
  1368. (while (org-at-table-p)
  1369. ;; get ref
  1370. (setq ref-field (org-index--get-or-set-field 'ref))
  1371. (string-match org-index--ref-regex ref-field)
  1372. (setq ref (string-to-number (match-string 1 ref-field)))
  1373. ;; record min and max
  1374. (if (or (not min) (< ref min)) (setq min ref))
  1375. (if (or (not max) (> ref max)) (setq max ref))
  1376. ;; count
  1377. (setq total (1+ total))
  1378. (forward-line))
  1379. (setq message (format "First reference is %s, last %s; %d values in between, %d of them are used (%d percent)"
  1380. (format org-index--ref-format min)
  1381. (format org-index--ref-format max)
  1382. (1+ (- max min))
  1383. total
  1384. (truncate (* 100 (/ (float total) (1+ (- max min)))))))
  1385. (goto-char org-index--below-hline)
  1386. message))
  1387. (defun org-index--do-add-or-update ()
  1388. "For current node or current line in index, add a new line to index table or update existing."
  1389. (let* (id ref args yank ref-and-yank)
  1390. ;; do the same things from within index and from outside
  1391. (if org-index--within-node
  1392. (progn
  1393. (unless (org-at-table-p)
  1394. (error "Within index node but not on table"))
  1395. (setq id (org-index--get-or-set-field 'id))
  1396. (setq ref (org-index--get-or-set-field 'ref))
  1397. (setq args (org-index--collect-values-for-add-update-remote id))
  1398. (org-index--write-fields-for-add-update args)
  1399. (setq yank (org-index--get-or-set-field org-index-yank-after-add))
  1400. (cons (format "Updated index line %s" ref) yank))
  1401. (unless (org-at-heading-p)
  1402. (error "Not at headline"))
  1403. (setq id (org-id-get-create))
  1404. (setq ref (org-index--on 'id id (org-index--get-or-set-field 'ref)))
  1405. (setq args (org-index--collect-values-for-add-update id ref))
  1406. (if ref
  1407. ;; already have a ref, find it in index and update fields
  1408. (let ((kvs args)
  1409. found-and-message)
  1410. (org-index--on
  1411. 'ref ref
  1412. (org-index--write-fields-for-add-update args)
  1413. (setq yank (org-index--get-or-set-field org-index-yank-after-add)))
  1414. (cons (format "Updated index line %s" ref) yank))
  1415. ;; no ref here, create new line in index
  1416. (setq ref-and-yank (apply 'org-index--do-new-line args))
  1417. (cons (format "Added index line %s" (car ref-and-yank)) (concat (cdr ref-and-yank) " "))))))
  1418. (defun org-index--check-ids ()
  1419. "Check, that ids really point to a node."
  1420. (let ((lines 0)
  1421. id ids marker)
  1422. (goto-char org-index--below-hline)
  1423. (catch 'problem
  1424. (while (org-at-table-p)
  1425. (when (setq id (org-index--get-or-set-field 'id))
  1426. ;; check for double ids
  1427. (when (member id ids)
  1428. (org-table-goto-column (org-index--column-num 'id))
  1429. (throw 'problem "This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
  1430. (incf lines)
  1431. (setq ids (cons id ids))
  1432. ;; check, if id is valid
  1433. (setq marker (org-id-find id t))
  1434. (unless marker
  1435. (org-table-goto-column (org-index--column-num 'id))
  1436. (throw 'problem "This id cannot be found")))
  1437. (forward-line))
  1438. (goto-char org-index--below-hline)
  1439. nil)))
  1440. (defun org-index--update-all-lines ()
  1441. "Update all lines of index at once."
  1442. (let ((lines 0)
  1443. id ref kvs)
  1444. ;; check for double ids
  1445. (or
  1446. (org-index--check-ids)
  1447. (progn
  1448. (goto-char org-index--below-hline)
  1449. (while (org-at-table-p)
  1450. ;; update single line
  1451. (when (setq id (org-index--get-or-set-field 'id))
  1452. (setq ref (org-index--get-or-set-field 'ref))
  1453. (setq kvs (org-index--collect-values-for-add-update-remote id))
  1454. (org-index--write-fields-for-add-update kvs)
  1455. (incf lines))
  1456. (forward-line))
  1457. (goto-char org-index--below-hline)
  1458. (org-table-align)
  1459. (format "Updated %d lines" lines)))))
  1460. (defun org-index--collect-values-for-add-update (id &optional silent category)
  1461. "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
  1462. (let ((args (list 'ref t 'id id))
  1463. content)
  1464. (dolist (col-num org-index--columns)
  1465. (setq content "")
  1466. (when (eq (car col-num) 'keywords)
  1467. (if org-index-copy-heading-to-keywords
  1468. (setq content (nth 4 (org-heading-components))))
  1469. ;; Shift ref and timestamp ?
  1470. (if org-index-strip-ref-and-date-from-heading
  1471. (dotimes (i 2)
  1472. (if (or (string-match (concat "^\\s-*" org-index--ref-regex) content)
  1473. (string-match (concat org-ts-regexp-both) content))
  1474. (setq content (substring content (match-end 0)))))))
  1475. (if (eq (car col-num) 'category)
  1476. (setq content (or category org-index--category-before)))
  1477. (if (eq (car col-num) 'level)
  1478. (setq content (number-to-string (org-outline-level))))
  1479. (if (and (not silent) ; do not edit, if heading has already been added
  1480. (memq (car col-num) org-index-edit-on-add))
  1481. (setq content (read-from-minibuffer
  1482. (format "Edit text for column '%s': " (symbol-name (car col-num)))
  1483. content)))
  1484. (if (not (string= content ""))
  1485. (setq args (append (list (car col-num) content) args))))
  1486. args))
  1487. (defun org-index--collect-values-for-add-update-remote (id)
  1488. "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
  1489. (let (marker point args)
  1490. (setq marker (org-id-find id t))
  1491. ;; enter buffer and collect information
  1492. (with-current-buffer (marker-buffer marker)
  1493. (setq point (point))
  1494. (goto-char marker)
  1495. (setq args (org-index--collect-values-for-add-update id t (org-get-category (point) t)))
  1496. (goto-char point))
  1497. args))
  1498. (defun org-index--write-fields-for-add-update (kvs)
  1499. "Update current line with values from KVS (keys-values)."
  1500. (while kvs
  1501. (unless (eq (car kvs) 'ref)
  1502. (org-index--get-or-set-field (car kvs) (org-trim (cadr kvs))))
  1503. (setq kvs (cddr kvs))))
  1504. (defun org-index--do-delete ()
  1505. "Perform command delete."
  1506. (unless (org-at-heading-p)
  1507. (error "Not at headline"))
  1508. (let* ((id (org-entry-get (point) "ID"))
  1509. (ref (org-index--ref-from-id id)))
  1510. ;; maybe delete from heading
  1511. (if ref
  1512. (save-excursion
  1513. (end-of-line)
  1514. (let ((end (point)))
  1515. (beginning-of-line)
  1516. (when (search-forward ref end t)
  1517. (delete-char (- (length ref)))
  1518. (just-one-space)))))
  1519. ;; delete from index table
  1520. (if (org-index--delete-line id)
  1521. (format "Deleted index line %s" ref)
  1522. (format "Did not find id %s in index" id))))
  1523. (defun org-index--go (&optional column value)
  1524. "Position cursor on index line where COLUMN equals VALUE.
  1525. Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
  1526. (let (found text)
  1527. (unless (eq (current-buffer) org-index--buffer)
  1528. (error "This is a bug: Not in index buffer"))
  1529. ;; loop over lines
  1530. (goto-char org-index--below-hline)
  1531. (if column
  1532. (progn
  1533. (forward-line -1)
  1534. (while (and (not found)
  1535. (forward-line)
  1536. (org-at-table-p))
  1537. (setq found (string= value (org-index--get-or-set-field column)))))
  1538. (setq found t))
  1539. ;; return value
  1540. (if found
  1541. t
  1542. (goto-char org-index--below-hline)
  1543. nil)))
  1544. (defun org-index--do-head (ref id &optional other)
  1545. "Perform command head: Find node with REF or ID and present it.
  1546. If OTHER in separate window."
  1547. (setq org-index--last-ref ref)
  1548. (let (message marker)
  1549. (setq marker (org-id-find id t))
  1550. (if marker
  1551. (progn
  1552. (org-index--update-line id)
  1553. (let (cb)
  1554. (if other
  1555. (progn
  1556. (setq cb (current-buffer))
  1557. (pop-to-buffer (marker-buffer marker)))
  1558. (pop-to-buffer-same-window (marker-buffer marker)))
  1559. (goto-char marker)
  1560. (org-reveal t)
  1561. (org-show-entry)
  1562. (recenter))
  1563. (setq message (format "Found headline %s" ref)))
  1564. (setq message (format "Did not find headline %s" ref)))))
  1565. (defun org-index--do-occur ()
  1566. "Perform command occur."
  1567. (let ((word "") ; last word to search for growing and shrinking on keystrokes
  1568. (prompt "Search for: ")
  1569. (lines-wanted (window-body-height))
  1570. (lines-found 0) ; number of lines found
  1571. words ; list words that should match
  1572. occur-buffer
  1573. begin ; position of first line
  1574. narrow ; start of narrowed buffer
  1575. help-text ; cons with help text short and long
  1576. key-help ; for keys with special function
  1577. search-text ; description of text to search for
  1578. done ; true, if loop is done
  1579. in-c-backspace ; true, while processing C-backspace
  1580. show-headings ; true, if headings should be shown
  1581. help-overlay ; Overlay with help text
  1582. last-point ; Last position before end of search
  1583. initial-frame ; Frame when starting occur
  1584. key ; input from user in various forms
  1585. key-sequence
  1586. key-sequence-raw)
  1587. ;; make and show buffer
  1588. (if (get-buffer org-index--occur-buffer-name)
  1589. (kill-buffer org-index--occur-buffer-name))
  1590. (setq occur-buffer (make-indirect-buffer org-index--buffer org-index--occur-buffer-name))
  1591. (pop-to-buffer-same-window occur-buffer)
  1592. (setq initial-frame (selected-frame))
  1593. ;; avoid modifying direct buffer
  1594. (setq buffer-read-only t)
  1595. (toggle-truncate-lines 1)
  1596. (setq font-lock-keywords-case-fold-search t)
  1597. (setq case-fold-search t)
  1598. ;; reset stack and overlays
  1599. (setq org-index--occur-stack nil)
  1600. (setq org-index--occur-tail-overlay nil)
  1601. ;; narrow to table rows and one line before
  1602. (goto-char org-index--below-hline)
  1603. (forward-line 0)
  1604. (setq begin (point))
  1605. (forward-line -1)
  1606. (setq narrow (point))
  1607. (while (org-at-table-p)
  1608. (forward-line))
  1609. (narrow-to-region narrow (point))
  1610. (goto-char (point-min))
  1611. (forward-line)
  1612. ;; initialize help text
  1613. (setq help-text (cons
  1614. "Incremental occur; `?' toggles help and headlines.\n"
  1615. (concat
  1616. (org-index--wrap
  1617. (concat
  1618. "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> to matching line in index; all other keys end search.\n"))
  1619. org-index--headings)))
  1620. ;; insert overlays for help text and to cover unsearched lines
  1621. (setq help-overlay (make-overlay (point-min) begin))
  1622. (overlay-put help-overlay 'display (car help-text))
  1623. (overlay-put help-overlay 'face 'org-agenda-dimmed-todo-face)
  1624. (setq org-index--occur-tail-overlay (make-overlay (point-max) (point-max)))
  1625. (overlay-put org-index--occur-tail-overlay 'invisible t)
  1626. (while (not done)
  1627. (if in-c-backspace
  1628. (setq key "<backspace>")
  1629. (setq search-text (mapconcat 'identity (reverse (cons word words)) ","))
  1630. ;; read key, if selected frame has not changed
  1631. (if (eq initial-frame (selected-frame))
  1632. (progn
  1633. (setq key-sequence
  1634. (let ((echo-keystrokes 0))
  1635. (read-key-sequence
  1636. (format "%s%s%s"
  1637. prompt
  1638. search-text
  1639. (if (string= search-text "") "" " "))
  1640. nil nil t t)))
  1641. (setq key (key-description key-sequence))
  1642. (setq key-sequence-raw (this-single-command-raw-keys)))
  1643. (setq done t)
  1644. (setq key-sequence nil)
  1645. (setq key nil)
  1646. (setq key-sequence-raw nil)))
  1647. (cond
  1648. ((string= key "<C-backspace>")
  1649. (setq in-c-backspace t))
  1650. ((member key (list "<backspace>" "DEL")) ; erase last char
  1651. (if (= (length word) 0)
  1652. ;; nothing more to delete from current word; try next
  1653. (progn
  1654. (setq word (car words))
  1655. (setq words (cdr words))
  1656. (setq in-c-backspace nil))
  1657. ;; unhighlight longer match
  1658. (unhighlight-regexp (regexp-quote word))
  1659. ;; some chars are left; shorten word
  1660. (setq word (substring word 0 -1))
  1661. (when (= (length word) 0) ; when nothing left, use next word from list
  1662. (setq word (car words))
  1663. (setq words (cdr words))
  1664. (setq in-c-backspace nil))
  1665. ;; free top list of overlays and remove list
  1666. (setq lines-found (or (org-index--unhide) lines-wanted))
  1667. (move-overlay org-index--occur-tail-overlay
  1668. (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
  1669. (point-max))
  1670. (point-max))
  1671. ;; highlight shorter word
  1672. (unless (= (length word) 0)
  1673. (highlight-regexp (regexp-quote word) 'isearch))
  1674. ;; make sure, point is still visible
  1675. (goto-char begin)))
  1676. ((member key (list "SPC" ",")) ; space or comma: enter an additional search word
  1677. ;; push current word and clear, no need to change display
  1678. (unless (string= word "")
  1679. (setq words (cons word words))
  1680. (setq word "")))
  1681. ((string= key "?") ; question mark: toggle display of headlines and help
  1682. (setq help-text (cons (cdr help-text) (car help-text)))
  1683. (overlay-put help-overlay 'display (car help-text)))
  1684. ((and (= (length key) 1)
  1685. (aref printable-chars (elt key 0))) ; any printable char: add to current search word
  1686. ;; unhighlight short word
  1687. (unless (= (length word) 0)
  1688. (unhighlight-regexp (regexp-quote word)))
  1689. ;; add to word
  1690. (setq word (concat word key))
  1691. ;; make overlays to hide lines, that do not match longer word any more
  1692. (goto-char begin)
  1693. (setq lines-found (org-index--hide-with-overlays (cons word words) lines-wanted))
  1694. (move-overlay org-index--occur-tail-overlay
  1695. (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
  1696. (point-max))
  1697. (point-max))
  1698. (goto-char begin)
  1699. ;; highlight longer word
  1700. (highlight-regexp (regexp-quote word) 'isearch)
  1701. ;; make sure, point is on a visible line
  1702. (line-move -1 t)
  1703. (line-move 1 t))
  1704. ;; anything else terminates loop
  1705. (t (setq done t))))
  1706. ;; put back input event, that caused the loop to end
  1707. (unless (string= key "C-g")
  1708. (setq unread-command-events (listify-key-sequence key-sequence-raw))
  1709. (message key))
  1710. ;; postprocessing
  1711. (setq last-point (point))
  1712. ;; For performance reasons do not show matching lines for rest of table. So no code here.
  1713. ;; make permanent copy
  1714. ;; copy visible lines
  1715. (let ((lines-collected 0)
  1716. keymap line all-lines end-of-head)
  1717. (setq cursor-type t)
  1718. (goto-char begin)
  1719. ;; collect all visible lines
  1720. (while (and (not (eobp))
  1721. (< lines-collected lines-wanted))
  1722. ;; skip over invisible lines
  1723. (while (and (invisible-p (point))
  1724. (not (eobp)))
  1725. (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
  1726. (setq line (buffer-substring (line-beginning-position) (line-end-position)))
  1727. (unless (string= line "")
  1728. (incf lines-collected)
  1729. (setq all-lines (cons (concat line
  1730. "\n")
  1731. all-lines)))
  1732. (forward-line 1))
  1733. (kill-buffer org-index--occur-buffer-name) ; cannot keep this buffer; might become stale soon
  1734. ;; create new buffer
  1735. (setq occur-buffer (get-buffer-create org-index--occur-buffer-name))
  1736. (pop-to-buffer-same-window occur-buffer)
  1737. (insert org-index--headings)
  1738. (setq end-of-head (point))
  1739. ;; insert into new buffer
  1740. (save-excursion
  1741. (apply 'insert (reverse all-lines))
  1742. (if (= lines-collected lines-wanted)
  1743. (insert "\n(more lines omitted)\n")))
  1744. (org-mode)
  1745. (setq truncate-lines t)
  1746. (if (org-at-table-p) (org-table-align))
  1747. (font-lock-fontify-buffer)
  1748. ;; prepare help text
  1749. (setq org-index--occur-help-overlay (make-overlay (point-min) end-of-head))
  1750. (setq org-index--occur-help-text
  1751. (cons
  1752. (org-index--wrap
  1753. (concat "Search is done; `?' toggles help and headlines.\n"))
  1754. (concat
  1755. (org-index--wrap (format (concat "Search is done. "
  1756. (if (< lines-collected lines-wanted)
  1757. " Showing all %d matches for "
  1758. " Showing one window of matches for ")
  1759. "\"" search-text
  1760. "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> to matching line in index, <space> increments count.\n" )
  1761. (length all-lines)))
  1762. org-index--headings)))
  1763. (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))
  1764. (overlay-put org-index--occur-help-overlay 'face 'org-agenda-dimmed-todo-face)
  1765. ;; highlight words
  1766. (setq case-fold-search t)
  1767. (setq font-lock-keywords-case-fold-search t)
  1768. (mapc (lambda (w) (unless (or (not w) (string= w "")) (highlight-regexp (regexp-quote w) 'isearch)))
  1769. (cons word words))
  1770. (setq buffer-read-only t)
  1771. ;; install keyboard-shortcuts
  1772. (setq keymap (make-sparse-keymap))
  1773. (set-keymap-parent keymap org-mode-map)
  1774. (mapc (lambda (x) (define-key keymap (kbd x)
  1775. (lambda () (interactive)
  1776. (message "%s" (org-index--occur-to-head)))))
  1777. (list "<return>" "RET"))
  1778. (define-key keymap (kbd "<tab>")
  1779. (lambda () (interactive)
  1780. (message (org-index--occur-to-head t))))
  1781. (define-key keymap (kbd "SPC")
  1782. (lambda () (interactive)
  1783. ;; increment in index
  1784. (let ((ref (org-index--get-or-set-field 'ref))
  1785. count)
  1786. (org-index--on
  1787. 'ref ref
  1788. (setq count (+ 1 (string-to-number (org-index--get-or-set-field 'count))))
  1789. (org-index--get-or-set-field 'count (number-to-string count))
  1790. (org-index--promote-current-line)
  1791. (org-index--align-and-fontify-current-line))
  1792. ;; increment in this buffer
  1793. (let ((inhibit-read-only t))
  1794. (org-index--get-or-set-field 'count (number-to-string count)))
  1795. (message "Incremented count to %d" count))))
  1796. (define-key keymap (kbd "<S-return>")
  1797. (lambda () (interactive)
  1798. (org-index 'enter (org-index--get-or-set-field 'ref))))
  1799. (define-key keymap (kbd "?")
  1800. (lambda () (interactive)
  1801. (setq-local org-index--occur-help-text (cons (cdr org-index--occur-help-text) (car org-index--occur-help-text)))
  1802. (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))))
  1803. (use-local-map keymap))))
  1804. (defun org-index--wrap (text)
  1805. "Wrap TEXT at fill column."
  1806. (with-temp-buffer
  1807. (insert text)
  1808. (fill-region (point-min) (point-max) nil t)
  1809. (buffer-string)))
  1810. (defun org-index--occur-to-head (&optional other)
  1811. "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window."
  1812. (let ((ref (org-index--get-or-set-field 'ref))
  1813. (id (org-index--get-or-set-field 'id)))
  1814. (if id
  1815. (org-index--do-head ref id other)
  1816. (message "Current line has no id."))))
  1817. (defun org-index--hide-with-overlays (words lines-wanted)
  1818. "Hide text that is currently visible and does not match WORDS by creating overlays; leave LINES-WANTED lines visible."
  1819. (let ((lines-found 0)
  1820. (end-of-visible (point))
  1821. overlay overlays start matched)
  1822. ;; main loop
  1823. (while (and (not (eobp))
  1824. (< lines-found lines-wanted))
  1825. ;; skip invisible lines
  1826. (while (and (not (eobp))
  1827. (and
  1828. (invisible-p (point))
  1829. (< (point) (overlay-start org-index--occur-tail-overlay))))
  1830. (goto-char (overlay-end (car (overlays-at (point))))))
  1831. ;; find stretch of lines, that are currently visible but should be invisible now
  1832. (setq matched nil)
  1833. (setq start (point))
  1834. (while (and (not (eobp))
  1835. (not
  1836. (and
  1837. (invisible-p (point))
  1838. (< (point) (overlay-start org-index--occur-tail-overlay))))
  1839. (not (and (org-index--test-words words)
  1840. (setq matched t)))) ; for its side effect
  1841. (forward-line 1))
  1842. ;; create overlay to hide this stretch
  1843. (when (< start (point)) ; avoid creating an empty overlay
  1844. (setq overlay (make-overlay start (point)))
  1845. (overlay-put overlay 'invisible t)
  1846. (setq overlays (cons overlay overlays)))
  1847. ;; skip and count line, that matched
  1848. (when matched
  1849. (forward-line 1)
  1850. (setq end-of-visible (point))
  1851. (incf lines-found)))
  1852. ;; put new list on top of stack
  1853. (setq org-index--occur-stack
  1854. (cons (list (cons :overlays overlays)
  1855. (cons :end-of-visible end-of-visible)
  1856. (cons :lines lines-found))
  1857. org-index--occur-stack))
  1858. lines-found))
  1859. (defun org-index--unhide ()
  1860. "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
  1861. (when org-index--occur-stack
  1862. ;; delete overlays and make visible again
  1863. (mapc (lambda (y)
  1864. (delete-overlay y))
  1865. (cdr (assoc :overlays (car org-index--occur-stack))))
  1866. ;; remove from stack
  1867. (setq org-index--occur-stack (cdr org-index--occur-stack))
  1868. ;; return number of lines, that are now visible
  1869. (if org-index--occur-stack (cdr (assoc :lines (car org-index--occur-stack))))))
  1870. (defun org-index--test-words (words)
  1871. "Test current line for match against WORDS."
  1872. (let (line)
  1873. (setq line (downcase (buffer-substring (line-beginning-position) (line-beginning-position 2))))
  1874. (catch 'not-found
  1875. (dolist (w words)
  1876. (or (cl-search w line)
  1877. (throw 'not-found nil)))
  1878. t)))
  1879. (defun org-index--create-new-line ()
  1880. "Do the common work for `org-index-new-line' and `org-index'."
  1881. (let (new)
  1882. ;; construct new reference
  1883. (unless new
  1884. (setq new (format "%s%d%s" org-index--head (1+ org-index--maxref) org-index--tail)))
  1885. ;; insert ref or id as last or first line, depending on sort-column
  1886. (goto-char org-index--below-hline)
  1887. (if (eq org-index-sort-by 'count)
  1888. (progn
  1889. (while (org-at-table-p)
  1890. (forward-line))
  1891. (forward-line -1)
  1892. (org-table-insert-row t))
  1893. (org-table-insert-row))
  1894. ;; insert some of the standard values
  1895. (org-table-goto-column (org-index--column-num 'created))
  1896. (org-insert-time-stamp nil nil t)
  1897. (org-table-goto-column (org-index--column-num 'count))
  1898. (insert "1")
  1899. new))
  1900. (defun org-index--sort-silent ()
  1901. "Sort index for default column to remove any effects of temporary sorting."
  1902. (save-excursion
  1903. (org-index--verify-id)
  1904. (org-index--parse-table)
  1905. (org-index--on nil nil
  1906. (org-index--do-sort-index org-index-sort-by)
  1907. (org-table-align)
  1908. (remove-hook 'before-save-hook 'org-index--sort-silent))))
  1909. (defun org-index--copy-visible (beg end)
  1910. "Copy the visible parts of the region between BEG and END without adding it to `kill-ring'; copy of `org-copy-visible'."
  1911. (let (snippets s)
  1912. (save-excursion
  1913. (save-restriction
  1914. (narrow-to-region beg end)
  1915. (setq s (goto-char (point-min)))
  1916. (while (not (= (point) (point-max)))
  1917. (goto-char (org-find-invisible))
  1918. (push (buffer-substring s (point)) snippets)
  1919. (setq s (goto-char (org-find-visible))))))
  1920. (apply 'concat (nreverse snippets))))
  1921. (provide 'org-index)
  1922. ;; Local Variables:
  1923. ;; fill-column: 75
  1924. ;; comment-column: 50
  1925. ;; End:
  1926. ;;; org-index.el ends here