org-index.el 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179
  1. ;;; org-index.el --- A personal index for org and beyond
  2. ;; Copyright (C) 2011-2014 Free Software Foundation, Inc.
  3. ;; Author: Marc Ihm <org-index@2484.de>
  4. ;; Keywords: outlines, hypermedia, matching
  5. ;; Requires: org
  6. ;; Version: 2.4.0
  7. ;; This file is not part of GNU Emacs.
  8. ;;; License:
  9. ;; This program is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 3, or (at your option)
  12. ;; any later version.
  13. ;;
  14. ;; This program is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;;
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  21. ;;; Commentary:
  22. ;; Purpose:
  23. ;;
  24. ;; Mark and find your favorite org-locations and other points of interest
  25. ;; easily; create and update a lookup table of references and links. When
  26. ;; searching, frequently used entries appear at the the top and entering
  27. ;; some keywords narrows down to matching entries only, so that the
  28. ;; right one can be spotted easily.
  29. ;;
  30. ;; References are essentially small numbers (e.g. "R237" or "-455-"),
  31. ;; which are created by this package; they are well suited to be used
  32. ;; outside org. Links are normal org-mode links.
  33. ;;
  34. ;;
  35. ;; Setup:
  36. ;;
  37. ;; - Add these lines to your .emacs:
  38. ;;
  39. ;; ;; use the real path from your org-installation
  40. ;; (add-to-list 'load-path "~/path/to/orgdir/contrib/lisp" t)
  41. ;; (require 'org-index)
  42. ;;
  43. ;; - Restart your emacs to make these lines effective
  44. ;;
  45. ;; - Invoke `org-index', which will assist in creating your index
  46. ;; table. The variable org-index-id will be persisted within your
  47. ;; customization file (typically .emacs).
  48. ;;
  49. ;;
  50. ;; Further reading:
  51. ;;
  52. ;; See the documentation of `org-index', which can also be read
  53. ;; by invoking `org-index' and and choosing the help-command.
  54. ;;
  55. ;; For more documentation and working examples, see:
  56. ;;
  57. ;; http://orgmode.org/worg/org-contrib/org-index.html
  58. ;;
  59. ;;
  60. ;; Updates:
  61. ;;
  62. ;; The latest tested version of this file can always be found at:
  63. ;;
  64. ;; http://orgmode.org/w/org-mode.git?p=org-mode.git;a=blob;f=contrib/lisp/org-index.el;hb=HEAD
  65. ;;; Change Log:
  66. ;; [2014-01-02 Th] Version 2.4.0:
  67. ;; - New command "put" to store a nodes reference in a property
  68. ;; - New functions org-index-new-line and org-index-get-line
  69. ;; offer access to org-index from other lisp programs
  70. ;; - New flags p,x1,x2 and x3
  71. ;; - Major Code refactoring
  72. ;; - Regression tests with ert
  73. ;; - Lots of bugfixes
  74. ;;
  75. ;; [2013-10-04 Fr] Version 2.3.2:
  76. ;; - Bugfix: index-table created by assistant is found after
  77. ;; restart of emacs instead of invoking assistent again
  78. ;;
  79. ;; [2013-07-20 Sa] Version 2.3.0:
  80. ;; - Renamed from "org-favtable" to "org-index"
  81. ;; - Added an assistent to set up the index table
  82. ;; - occur is now incremental, searching as you type
  83. ;; - simplified the documentation and help-system
  84. ;; - Saving keystrokes, as "+g237" is now valid input
  85. ;; - Many bugfixes
  86. ;;
  87. ;; [2013-02-28 Th] Version 2.2.0:
  88. ;; - Allowed shortcuts like "h237" for command "head" with argument "237"
  89. ;; - Integrated with org-mark-ring-goto
  90. ;;
  91. ;; [2013-01-25 Fr] Version 2.1.0:
  92. ;; - Added full support for links
  93. ;; - New commands "missing" and "statistics"
  94. ;; - Renamed the package from "org-reftable" to "org-favtable"
  95. ;; - Additional columns are required (e.g. "link"). Error messages will
  96. ;; guide you
  97. ;;
  98. ;; [2012-12-07 Fr] Version 2.0.0:
  99. ;; - The format of the table of favorites has changed ! You need to bring
  100. ;; your existing table into the new format by hand (which however is
  101. ;; easy and explained below)
  102. ;; - Reference table can be sorted after usage count or date of last access
  103. ;; - Ask user explicitly, which command to invoke
  104. ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
  105. ;;
  106. ;; [2012-09-22 Sa] Version 1.5.0:
  107. ;; - New command "sort" to sort a buffer or region by reference number
  108. ;; - New commands "highlight" and "unhighlight" to mark references
  109. ;;
  110. ;; [2012-07-13 Fr] Version 1.4.0:
  111. ;; - New command "head" to find a headline with a reference number
  112. ;;
  113. ;; [2012-04-28 Sa] Version 1.3.0:
  114. ;; - New commands occur and multi-occur
  115. ;; - All commands can now be invoked explicitly
  116. ;; - New documentation
  117. ;; - Many bugfixes
  118. ;;
  119. ;; [2011-12-10 Sa] Version 1.2.0:
  120. ;; - Fixed a bug, which lead to a loss of newly created reference numbers
  121. ;; - Introduced single and double prefix arguments
  122. ;; - Started this Change Log
  123. ;;; Code:
  124. (require 'org-table)
  125. (require 'cl)
  126. (defcustom org-index-id nil
  127. "Id of the Org-mode node, which contains the index table."
  128. :group 'org
  129. :group 'org-index)
  130. ;; Variables to hold the configuration of the index table
  131. (defvar org-index--maxref) ; Maximum number from reference table (e.g. "153")
  132. (defvar org-index--head) ; Any header before number (e.g. "R")
  133. (defvar org-index--tail) ; Tail after number (e.g. "}" or "")
  134. (defvar org-index--numcols) ; Number of columns in index table
  135. (defvar org-index--ref-regex) ; Regular expression to match a reference
  136. (defvar org-index--has-reuse nil) ; True, if table contains a line for reuse
  137. (defvar org-index--ref-format) ; Format, that can print a reference
  138. (defvar org-index--columns nil) ; Columns of index-table
  139. (defvar org-index--special-columns nil) ; Columns with flags
  140. (defvar org-index--buffer) ; Buffer of index table
  141. (defvar org-index--point) ; Position at start of headline of index table
  142. (defvar org-index--below-hline) ; Position of first cell in first line below hline
  143. (defvar org-index--headings) ; Headlines of index-table as a string
  144. ;; Variables to hold context and state
  145. (defvar org-index--last-action nil) ; Last action performed by org-index
  146. (defvar org-index--text-to-yank nil) ; Text, that can be yanked after call (mostly a reference)
  147. (defvar org-index--last-ref) ; Last reference created or visited
  148. (defvar org-index--point-before nil) ; Point in buffer with index table
  149. (defvar org-index--silent nil) ; t, if user should not be queried
  150. (defvar org-index--preferred-command) ; command, that is presented first
  151. (defvar org-index--active-region) ; Active region, initially. I.e. what has been marked
  152. (defvar org-index--below-cursor) ; Word below cursor
  153. (defvar org-index--within-node) ; True, if we are within node of the index table
  154. (defvar org-index--active-window-index nil) ; Active window with index table (if any)
  155. (setq org-index--commands '(occur head ref link leave put enter goto help + reorder fill sort update highlight unhighlight missing statistics)) ; list of commands available
  156. (defun org-index (&optional ARG)
  157. "Mark and find your favorite things and org-locations easily:
  158. Create and update a lookup table of references and links. Often
  159. used entries bubble to the top; entering some keywords narrows
  160. down to matching entries only, so that the right one can be
  161. spotted easily.
  162. References are essentially small numbers (e.g. \"R237\" or \"-455-\"),
  163. which are created by this package; they are well suited to be used
  164. outside of org. Links are normal org-mode links.
  165. This is version 2.4.0 of org-index.
  166. The function `org-index' operates on a dedicated table, the index
  167. table, which lives within its own Org-mode node. The table and
  168. its node will be created, when you first invoke org-index.
  169. Each line in the index table contains:
  170. - A reference (e.g. \"R237\")
  171. - An optional link to another location in org
  172. - A number, counting, how often each reference has been
  173. used. This number is updated automatically and the table can
  174. be sorted after it, so that most frequently used references
  175. appear at the top of the table and can be spotted easily.
  176. - The creation date of the line
  177. - Date and time of last access. This column can alternatively be
  178. used to sort the table.
  179. - A column for your own comments
  180. The index table is found through the id of the containing
  181. node; this id is stored within the variable `org-index-id'.
  182. The function `org-index' is the only interactive function of this
  183. package and its main entry point; it offers several commands to
  184. create, find and look up line within the index table.
  185. Commands known:
  186. occur: Incremental search, that shows matching lines from the
  187. index table, updated after every keystroke. You may enter a
  188. list of words seperated by space or comma (\",\"), to select
  189. lines that contain all of the given words.
  190. If you supply a number (e.g. \"237\"): Apply emacs standard
  191. multi-occur operation on all org-mode buffers to search for
  192. this specific reference.
  193. You may also read the note at the end of this help on saving
  194. the keystroke RET with this frequent default command.
  195. head: If invoked outside the index table, ask for a reference
  196. number and search for an entry, which either has this
  197. reference contained in its heading or within its property
  198. org-index-ref. If invoked from within the index table dont
  199. ask; rather use the reference or link from the current line.
  200. ref: Create a new reference, copy any previously selected text.
  201. If already within index table, fill in ref-column.
  202. link: Create a new line in index table with a link to the
  203. current node. Do not populate the ref column; this can later
  204. be populated by calling the \"fill\" command from within the
  205. index table.
  206. leave: Leave the index table. If the last command has been
  207. \"ref\", the new reference is copied and ready to yank. This
  208. \"org-mark-ring-goto\" and can be called several times in
  209. succession. If you invoke org-index with a prefix argument,
  210. this command \"leave\" is executed without further questions.
  211. put: Put the reference, that was created last, as the value of
  212. property org-index-ref into the current node. That way it can
  213. be found by a later call to \"head\".
  214. enter: Just enter the node with the index table.
  215. goto: Enter index table and go to a specific reference.
  216. help: Show this text.
  217. +: Show all commands including the less frequently used ones
  218. given below. If \"+\" is followd by enough letters of such a
  219. command (e.g. \"+fi\"), then this command (e.g. \"fill\") is
  220. invoked directly.
  221. reorder: Temporarily reorder the index table, e.g. by count,
  222. reference or last access.
  223. fill: If either ref or link is missing in current line of index
  224. table, fill in the missing value.
  225. sort: Sort a set of lines (either from the active region or the
  226. whole buffer) by references found in each line.
  227. update: For the given reference, update the line in the
  228. index table, i.e. increment its count.
  229. highlight: Highlight references in active region or buffer.
  230. unhighlight: Remove those highlights.
  231. missing : Search for missing reference numbers (which do not
  232. appear in the reference table). If requested, add additional
  233. lines for them, so that the command \"ref\" is able to reuse
  234. them.
  235. statistics : Show some statistics (e.g. minimum and maximum
  236. reference) about index table.
  237. Two ways to save keystrokes:
  238. When prompting for a command, org-index puts the most likely
  239. one (e.g. \"occur\" or \"ref\") in front of the list, so that
  240. you may just type RET.
  241. If this first command in the list of commands needs additional
  242. input (like e.g. \"occur\"), you may supply this input right
  243. away, although you are still beeing prompted for the command. So,
  244. to do an occur for the string \"foo\", you can just enter \"foo\"
  245. RET, without even typing \"occur\".
  246. Another way to save keystrokes applies if you want to choose a
  247. command, that requrires a reference number and would normally
  248. prompt for it: In that case you may just enter enough characters
  249. from your command, so that it appears first in the list of
  250. matches; then immediately enter the number of the reference you
  251. are searching for. So the input \"h237\" would execute the
  252. command \"head\" for reference \"237\".
  253. "
  254. (interactive "P")
  255. (let ((org-index--silent nil) ; t, if user can be asked
  256. link-id ; link of starting node, if required
  257. what ; what to do
  258. search ; what to search for
  259. guarded-search ; with guard against additional digits
  260. search-ref ; search, if search is a reference
  261. search-link ; search, if search is a link
  262. what-adjusted ; true, if we had to adjust what
  263. what-input ; Input on what question (need not necessary be "what")
  264. reorder-once ; column to use for single time sorting
  265. kill-new-text ; text that will be appended to kill ring
  266. message-text ; text that will be issued as an explanation
  267. initial-ref-or-link ; initial position in index table
  268. )
  269. ;;
  270. ;; Initialize and parse
  271. ;;
  272. ;; creates index table, if necessary
  273. (org-index--verify-id)
  274. ;; store context information
  275. (org-index--retrieve-context)
  276. ;; Get configuration of index table
  277. (org-index--parse-table)
  278. ;;
  279. ;; Find out, what we are supposed to do
  280. ;;
  281. (if ARG
  282. (if (equal ARG '(4))
  283. (setq what 'leave)
  284. (if (and (symbolp ARG)
  285. (memq ARG org-index--commands))
  286. (setq what ARG)
  287. (error "Unknown command '%s' passed as argument, valid choices are a prefix argument or any of these symbols: %s"
  288. ARG (mapconcat 'symbol-name org-index--commands ","))))
  289. (let ((r (org-index--read-what what))) ; query user if not from argument
  290. (setq what (nth 0 r))
  291. (setq what-input (nth 1 r))
  292. (setq reorder-once (nth 2 r))))
  293. ;;
  294. ;; Get search, if required
  295. ;;
  296. ;; These actions need a search string:
  297. (when (memq what '(goto occur head update))
  298. ;; Maybe we've got a search string from the arguments
  299. (setq search (org-index--get-or-read-search search what what-input))
  300. (when search
  301. (when (string-match org-index--ref-regex search)
  302. (setq search-ref search)
  303. (setq guarded-search (org-index--make-guarded-search search)))
  304. (when (string-match "^[a-fA-F0-9]\\{8\\}-[a-fA-F0-9]\\{4\\}-[a-fA-F0-9]\\{4\\}-[a-fA-F0-9]\\{4\\}-[a-fA-F0-9]\\{12\\}$" search)
  305. (setq search-link search))))
  306. ;;
  307. ;; Do some sanity checking before really starting
  308. ;;
  309. ;; Correct requested action, if nothing to search
  310. (when (and (not search)
  311. (memq what '(search head)))
  312. (setq what 'enter)
  313. (setq what-adjusted t))
  314. ;; For a proper reference as input, we do multi-occur
  315. (if (and (eq what 'occur) search-ref)
  316. (setq what 'multi-occur))
  317. ;; Check for invalid combinations of arguments; try to be helpful
  318. (when (and (memq what '(head goto))
  319. (not search-ref)
  320. (not search-link))
  321. (error "Can do '%s' only for a reference or link (not '%s'), try 'occur' to search for text" what search))
  322. ;;
  323. ;; Sort and enter table
  324. ;;
  325. ;; Get link if required before moving in
  326. (if (eq what 'link)
  327. (let ((org-id-link-to-org-use-id t))
  328. (setq link-id (org-id-get-create))))
  329. ;; Save initial ref or link for later return
  330. (if (and org-index--within-node
  331. (org-at-table-p))
  332. (setq initial-ref-or-link
  333. (or (org-index--get-field :ref)
  334. (org-index--get-field :link))))
  335. ;; These commands enter index table only temporarily
  336. (when (memq what '(occur multi-occur statistics))
  337. (set-buffer org-index--buffer)
  338. (goto-char org-index--point)
  339. ;; Sort and align
  340. (org-index--sort reorder-once)
  341. (org-index--align))
  342. ;; These commands will leave user in index table after they are finished
  343. (when (memq what '(enter ref link goto missing))
  344. ;; Support orgmode-standard of going back (buffer and position)
  345. (org-mark-ring-push)
  346. (org-pop-to-buffer-same-window org-index--buffer)
  347. (goto-char org-index--point)
  348. (show-subtree)
  349. (org-show-context)
  350. ;; Sort and align
  351. (org-index--sort reorder-once)
  352. (org-index--align))
  353. ;; Return to initial position
  354. (when initial-ref-or-link
  355. (while (and (org-at-table-p)
  356. (not (or
  357. (string= initial-ref-or-link (org-index--get-field :ref))
  358. (string= initial-ref-or-link (org-index--get-field :link)))))
  359. (forward-line))
  360. ;; did not find ref, go back to top
  361. (if (not (org-at-table-p)) (goto-char org-index--point)))
  362. ;;
  363. ;; Actually do, what is requested
  364. ;;
  365. (cond
  366. ((eq what 'help)
  367. ;; bring up help-buffer for this function
  368. (describe-function 'org-index))
  369. ((eq what 'multi-occur)
  370. ;; Position point in index buffer on reference to search for
  371. (goto-char org-index--below-hline)
  372. (let (found (initial (point)))
  373. (while (and (not found)
  374. (forward-line)
  375. (org-at-table-p))
  376. (save-excursion
  377. (setq found (string= search
  378. (org-index--get-field :ref)))))
  379. (if found
  380. (org-index--update-line nil)
  381. (goto-char initial)))
  382. ;; Construct list of all org-buffers
  383. (let (buff org-buffers)
  384. (dolist (buff (buffer-list))
  385. (set-buffer buff)
  386. (if (string= major-mode "org-mode")
  387. (setq org-buffers (cons buff org-buffers))))
  388. ;; Do multi-occur
  389. (multi-occur org-buffers guarded-search)
  390. ;; Present results
  391. (if (get-buffer "*Occur*")
  392. (progn
  393. (setq message-text (format "multi-occur for '%s'" search))
  394. (other-window 1)
  395. (toggle-truncate-lines 1))
  396. (setq message-text (format "Did not find '%s'" search)))))
  397. ((eq what 'head)
  398. (let (link)
  399. (if (and org-index--within-node
  400. (org-at-table-p))
  401. (setq link (org-index--get-field :link))))
  402. (setq message-text (org-index--do-head search-ref search-link)))
  403. ((eq what 'leave)
  404. (setq kill-new-text org-index--text-to-yank)
  405. (setq org-index--text-to-yank nil)
  406. ;; If "leave" has been called two times in succession, make
  407. ;; org-mark-ring-goto believe it has been called two times too
  408. (if (eq org-index--last-action 'leave)
  409. (let ((this-command nil) (last-command nil))
  410. (org-mark-ring-goto 1))
  411. (org-mark-ring-goto))
  412. ;; Return to saved position in index buffer
  413. (when org-index--point-before
  414. ;; buffer displayed in window need to set point there first
  415. (if (eq (window-buffer org-index--active-window-index)
  416. org-index--buffer)
  417. (set-window-point org-index--active-window-index org-index--point-before))
  418. ;; set position in buffer in any case and second
  419. (with-current-buffer org-index--buffer
  420. (goto-char org-index--point-before)))
  421. (setq org-index--point-before nil))
  422. ((eq what 'goto)
  423. ;; Go downward in table to requested reference
  424. (let (found (initial (point)))
  425. (goto-char org-index--below-hline)
  426. (while (and (not found)
  427. (forward-line)
  428. (org-at-table-p))
  429. (save-excursion
  430. (setq found
  431. (string= search
  432. (org-index--get-field
  433. (if search-link :link :ref))))))
  434. (if found
  435. (progn
  436. (setq message-text (format "Found '%s'" search))
  437. (org-index--update-line nil)
  438. (org-table-goto-column (org-index--column-num :ref))
  439. (if (looking-back " ") (backward-char))
  440. ;; remember string to copy
  441. (setq org-index--text-to-yank
  442. (org-trim (org-table-get-field (org-index--column-num :copy)))))
  443. (setq message-text (format "Did not find '%s'" search))
  444. (goto-char initial)
  445. (forward-line)
  446. (setq what 'missed))))
  447. ((eq what 'occur)
  448. (org-index--do-occur what-input))
  449. ((memq what '(ref link))
  450. (let (new)
  451. ;; add a new row (or reuse existing one)
  452. (setq new (org-index--do-new-line (eq what 'ref)))
  453. ;; fill special columns with standard values
  454. (when (eq what 'ref)
  455. (org-table-goto-column (org-index--column-num :ref))
  456. (insert new)
  457. (setq org-index--last-ref new))
  458. (when (eq what 'link)
  459. (org-table-goto-column (org-index--column-num :link))
  460. (insert link-id))
  461. (org-index--align)
  462. ;; goto point-field or copy-field or first empty one or first field
  463. (if (org-index--special-column :point)
  464. (org-table-goto-column (org-index--column-num (org-index--special-column :point)))
  465. (if (org-index--special-column :copy)
  466. (org-table-goto-column (org-index--column-num (org-index--special-column :copy)))
  467. (unless (catch 'empty
  468. (dotimes (col org-index--numcols)
  469. (org-table-goto-column (+ col 1))
  470. (if (string= (org-trim (org-table-get-field)) "")
  471. (throw 'empty t))))
  472. ;; none found, goto first
  473. (org-table-goto-column 1))))
  474. (if org-index--active-region (setq kill-new-text org-index--active-region))
  475. (if (eq what 'ref)
  476. (setq message-text (format "Adding a new row with ref '%s'" new))
  477. (setq message-text (format "Adding a new row linked to '%s'" link-id)))))
  478. ((eq what 'put)
  479. ;; put latest reference into property
  480. (if org-index--last-ref
  481. (progn
  482. (org-entry-put (point) "org-index-ref" org-index--last-ref)
  483. (message "Reference '%s' has been stored in property org-index-ref" org-index--last-ref))
  484. (setq org-index--last-ref
  485. (read-from-minibuffer "Reference to be stored in this node: "))
  486. (unless org-index--last-ref
  487. (message "No reference has been given."))
  488. ))
  489. ((eq what 'enter)
  490. ;; simply go into table
  491. (goto-char org-index--below-hline)
  492. (show-subtree)
  493. (recenter)
  494. (if what-adjusted
  495. (setq message-text "Nothing to search for; at index table")
  496. (setq message-text "At index table")))
  497. ((eq what 'fill)
  498. ;; check, if within index table
  499. (unless (and org-index--within-node
  500. (org-at-table-p))
  501. (error "Not within index table"))
  502. ;; applies to missing refs and missing links alike
  503. (let ((ref (org-index--get-field :ref))
  504. (link (org-index--get-field :link)))
  505. (if (and (not ref)
  506. (not link))
  507. ;; have already checked this during parse, check here anyway
  508. (error "Columns ref and link are both empty in this line"))
  509. ;; fill in new ref
  510. (if (not ref)
  511. (progn
  512. (setq kill-new-text (format "%s%d%s" org-index--head (1+ org-index--maxref) org-index--tail))
  513. (org-index--get-field :ref kill-new-text)
  514. ;; remember for org-mark-ring-goto
  515. (setq org-index--text-to-yank kill-new-text)
  516. (org-id-goto link)
  517. (setq message-text "Filled field of index table with new reference"))
  518. ;; fill in new link
  519. (if (not link)
  520. (progn
  521. (setq guarded-search (org-index--make-guarded-search ref))
  522. (message (format "Scanning headlines for '%s' ..." ref))
  523. (let ((search (concat ".*" guarded-search))
  524. link)
  525. (if (catch 'found
  526. (org-map-entries
  527. (lambda ()
  528. (when (looking-at search)
  529. (setq link (org-id-get-create))
  530. (throw 'found t)))
  531. nil 'agenda)
  532. nil)
  533. (progn
  534. (org-index--get-field :link link)
  535. (setq message-text "Inserted link"))
  536. (setq message-text (format "Did not find reference '%s'" ref)))))
  537. ;; nothing is missing
  538. (setq message-text "Columns ref and link are already filled; nothing to do")))))
  539. ((eq what 'sort)
  540. ;; sort lines according to contained reference
  541. (let (begin end where)
  542. (catch 'aborted
  543. ;; either active region or whole buffer
  544. (if (and transient-mark-mode
  545. mark-active)
  546. ;; sort only region
  547. (progn
  548. (setq begin (region-beginning))
  549. (setq end (region-end))
  550. (setq where "region"))
  551. ;; sort whole buffer
  552. (setq begin (point-min))
  553. (setq end (point-max))
  554. (setq where "whole buffer")
  555. ;; make sure
  556. (unless (y-or-n-p "Sort whole buffer ")
  557. (setq message-text "Sort aborted")
  558. (throw 'aborted nil)))
  559. (save-excursion
  560. (save-restriction
  561. (goto-char (point-min))
  562. (narrow-to-region begin end)
  563. (sort-subr nil 'forward-line 'end-of-line
  564. (lambda ()
  565. (if (looking-at (concat ".*"
  566. (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
  567. (string-to-number (match-string 1))
  568. 0))))
  569. (highlight-regexp org-index--ref-regex 'isearch)
  570. (setq message-text (format "Sorted %s from character %d to %d, %d lines"
  571. where begin end
  572. (count-lines begin end)))))))
  573. ((eq what 'update)
  574. ;; simply update line in index table
  575. (save-excursion
  576. (let ((ref-or-link (if search-link "link" "reference")))
  577. (beginning-of-line)
  578. (if (org-index--update-line search)
  579. (setq message-text (format "Updated %s '%s'" ref-or-link search))
  580. (setq message-text (format "Did not find %s '%s'" ref-or-link search))))))
  581. ((memq what '(highlight unhighlight))
  582. (let ((where "buffer"))
  583. (save-excursion
  584. (save-restriction
  585. (when (and transient-mark-mode
  586. mark-active)
  587. (narrow-to-region (region-beginning) (region-end))
  588. (setq where "region"))
  589. (if (eq what 'highlight)
  590. (progn
  591. (highlight-regexp org-index--ref-regex 'isearch)
  592. (setq message-text (format "Highlighted references in %s" where)))
  593. (unhighlight-regexp org-index--ref-regex)
  594. (setq message-text (format "Removed highlights for references in %s" where)))))))
  595. ((memq what '(missing statistics))
  596. (setq message-text (org-index--do-statistics what)))
  597. (t (error "This is a bug: unmatched case '%s'" what)))
  598. ;; remember what we have done for next time
  599. (setq org-index--last-action what)
  600. ;; tell, what we have done and what can be yanked
  601. (if kill-new-text (setq kill-new-text
  602. (substring-no-properties kill-new-text)))
  603. (if (string= kill-new-text "") (setq kill-new-text nil))
  604. (let ((m (concat
  605. message-text
  606. (if (and message-text kill-new-text)
  607. " and r"
  608. (if kill-new-text "R" ""))
  609. (if kill-new-text (format "eady to yank '%s'" kill-new-text) ""))))
  610. (unless (string= m "") (message m)))
  611. (if kill-new-text (kill-new kill-new-text))))
  612. (defun org-index-new-line (&rest keys-values)
  613. "Create a new line within the index table, returning its reference.
  614. The function takes a varying number of arguments pairs; each pair
  615. is a symbol for an existing column heading followed by its value.
  616. their values.
  617. Example:
  618. (org-index-new-line :ref t :x1 \"foo\" :link \"7f480c3e\")
  619. Passing \":ref t\" will make the function create a new reference within the new line.
  620. "
  621. (let ((org-index--silent t))
  622. (save-excursion
  623. (org-index--retrieve-context)
  624. (with-current-buffer org-index--buffer
  625. (goto-char org-index--point)
  626. (org-index--parse-table)
  627. ;; check arguments early
  628. (let ((kvs keys-values)
  629. k v)
  630. (while kvs
  631. (setq k (car kvs))
  632. (setq v (cadr kvs))
  633. (if (eq k :ref)
  634. (unless (memq v '(t nil))
  635. (error "Argument :ref accepts only t or nil"))
  636. (if (or (not (symbolp k))
  637. (symbolp v))
  638. (error "Arguments must be alternation of key and value")))
  639. (unless (> (org-index--column-num k) 0)
  640. (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
  641. (setq kvs (cddr kvs))))
  642. (if (and (not (plist-get keys-values :ref))
  643. (not (stringp (plist-get keys-values :link))))
  644. (error "Need a link when not creating a ref"))
  645. (let (new)
  646. ;; create new line
  647. (setq new (org-index--do-new-line (plist-get keys-values :ref)))
  648. (plist-put keys-values :ref (or new ""))
  649. ;; fill columns
  650. (let ((kvs keys-values)
  651. k v n)
  652. (while kvs
  653. (setq k (car kvs))
  654. (setq v (cadr kvs))
  655. (setq n (org-index--column-num k))
  656. (org-table-goto-column n)
  657. (insert v)
  658. (setq kvs (cddr kvs))))
  659. (org-index--sort)
  660. new)))))
  661. (defun org-index-get-line (what value)
  662. "Retrieve an existing line within the index table by ref or
  663. link and return its contents as a property list.
  664. The function `plist-get' may be used to retrieve specific values.
  665. Example:
  666. (plist-get (org-index-get-line \"12\") :count)
  667. retrieves the value of the count-column for reference 12.
  668. "
  669. (interactive)
  670. (let ((org-index--silent t)
  671. found)
  672. ;; check arguments
  673. (unless (memq what '(:ref :link))
  674. (error "Argument what can only be :ref or :link"))
  675. (save-excursion
  676. (org-index--retrieve-context)
  677. (with-current-buffer org-index--buffer
  678. (goto-char org-index--point)
  679. (org-index--parse-table)
  680. (goto-char org-index--below-hline)
  681. (while (and (not found)
  682. (org-at-table-p))
  683. (when (string= (org-index--get-field what)
  684. value)
  685. (mapc (lambda (x)
  686. (if (and (numberp (cdr x))
  687. (> (cdr x) 0))
  688. (setq found (cons (car x) (cons (or (org-index--get-field (car x)) "") found)))
  689. )) (reverse org-index--columns)))
  690. (forward-line))
  691. found))))
  692. (defun org-index--read-what (what)
  693. "Find out, what we are supposed to do"
  694. (let (commands ; currently active set of selectable commands
  695. trailing-digits ; any digits, that are are appended to what-input
  696. reorder-once ; Column to use for single time sorting
  697. what-input) ; Input on what question (need not necessary be "what")
  698. ;; Set preferred action, that will be the default choice
  699. (setq org-index--preferred-command
  700. (if org-index--within-node
  701. (if (memq org-index--last-action '(ref link))
  702. 'leave
  703. 'goto)
  704. (if org-index--active-region
  705. 'ref
  706. (if (and org-index--below-cursor (string-match org-index--ref-regex org-index--below-cursor))
  707. 'occur
  708. nil))))
  709. ;; Ask user, what to do
  710. (if what
  711. (setq what-input (symbol-name what))
  712. ;; subset of most common commands for initial selection, ie. up to first plus
  713. (setq commands (copy-list org-index--commands))
  714. (let ((c commands))
  715. (while (and c (not (eq (car c) '+)))
  716. (setq c (cdr c)))
  717. (setcdr c nil))
  718. (while (let (completions starts-with-plus is-only-plus)
  719. (setq what-input
  720. (org-completing-read
  721. "Please choose: "
  722. (mapcar 'symbol-name
  723. ;; Construct unique list of commands with
  724. ;; preferred one at front
  725. (delq nil (delete-dups
  726. (append
  727. (list org-index--preferred-command)
  728. (copy-list commands)))))
  729. nil nil))
  730. ;; if input ends in digits, save them away and do completions on head of input
  731. ;; this allows input like "h224" to be accepted
  732. (when (string-match "^\\([^0-9]+\\)\\([0-9]+\\)\\s *$" what-input)
  733. ;; remember digits
  734. (setq trailing-digits (string-to-number (match-string 2 what-input)))
  735. ;; and use non-digits-part to find match
  736. (setq what-input (match-string 1 what-input)))
  737. ;; if input starts with "+", any command (not only some) may follow
  738. ;; this allows input like "+sort" to be accepted
  739. (when (and (> (length what-input) 0)
  740. (string= (substring what-input 0 1) "+"))
  741. ;; make all commands available for selection
  742. (setq commands (copy-list org-index--commands))
  743. (setq what-input (substring what-input 1))
  744. (setq starts-with-plus (> (length what-input) 0))
  745. (setq is-only-plus (not starts-with-plus)))
  746. ;; get list of possible completions for what-input; i.e.
  747. ;; all commands, that start with what-input
  748. (setq completions (delq nil (mapcar
  749. (lambda (x)
  750. (let ((where (search what-input (symbol-name x))))
  751. (if (and where
  752. (= where 0))
  753. x
  754. nil))) commands)))
  755. ;; if input starts with "+" and not just "+"
  756. (when starts-with-plus
  757. ;; use first completion, if unambigously
  758. (if (= (length completions) 1)
  759. (setq what-input (symbol-name (car completions)))
  760. (if completions
  761. (error "Input \"+%s\" matches multiple commands: %s"
  762. what-input
  763. (mapconcat 'symbol-name completions ", "))
  764. (error "Input \"+%s\" matches no commands" what-input))))
  765. ;; if input ends in digits, use first completion, even if ambigous
  766. ;; this allows input like "h224" to be accepted
  767. (when (and trailing-digits completions)
  768. ;; use first match as input, even if ambigously
  769. (setq org-index--preferred-command (first completions))
  770. (setq what-input (number-to-string trailing-digits)))
  771. ;; convert to symbol
  772. (setq what (intern what-input))
  773. (if is-only-plus (setq what '+))
  774. ;; user is not required to input one of the commands; if
  775. ;; not, take the first one and use the original input for
  776. ;; next question
  777. (if (memq what commands)
  778. ;; input matched one element of list, dont need original
  779. ;; input any more
  780. (setq what-input nil)
  781. ;; what-input will be used for next question, use first
  782. ;; command for what
  783. (setq what (or org-index--preferred-command
  784. (first commands)))
  785. ;; remove any trailing dot, that user might have added to
  786. ;; disambiguate his input
  787. (if (and (> (length what-input) 0)
  788. (equal (substring what-input -1) "."))
  789. ;; but do this only, if dot was really necessary to
  790. ;; disambiguate
  791. (let ((shortened-what-input (substring what-input 0 -1)))
  792. (unless (test-completion shortened-what-input
  793. (mapcar 'symbol-name
  794. commands))
  795. (setq what-input shortened-what-input)))))
  796. ;; ask for reorder in loop, because we have to ask for
  797. ;; what right again
  798. (if (eq what 'reorder)
  799. (setq reorder-once
  800. (intern
  801. (concat ":"
  802. (org-icompleting-read
  803. "Please choose column to reorder index table once: "
  804. (mapcar 'symbol-name '(ref count accessed))
  805. nil t)))))
  806. ;; maybe ask initial question again
  807. (memq what '(reorder +)))))
  808. (list what what-input reorder-once)))
  809. (defun org-index--get-or-read-search (search what what-input)
  810. "Get search string, maybe read from user"
  811. (let (search-from-table
  812. search-from-cursor)
  813. (unless search
  814. ;; Search string can come from several sources:
  815. ;; From link or ref columns of table
  816. (when org-index--within-node
  817. (setq search-from-table (or (org-index--get-field :link)
  818. (org-index--get-field :ref))))
  819. ;; From string below cursor
  820. (when (and (not org-index--within-node)
  821. org-index--below-cursor
  822. (string-match (concat "\\(" org-index--ref-regex "\\)")
  823. org-index--below-cursor))
  824. (setq search-from-cursor (match-string 1 org-index--below-cursor)))
  825. ;; Depending on requested action, get search from one of the sources above
  826. (cond ((eq what 'goto)
  827. (setq search (or what-input search-from-cursor)))
  828. ((memq what '(head occur))
  829. (setq search (or what-input search-from-table search-from-cursor)))))
  830. ;; If we still do not have a search string, ask user explicitly
  831. (unless search
  832. (if org-index--silent (error "Need to specify search, if silence is required"))
  833. (unless (eq what 'occur)
  834. (if what-input
  835. (setq search what-input)
  836. (setq search (read-from-minibuffer
  837. (cond ((eq what 'head)
  838. "Text or reference number to search for: ")
  839. ((eq what 'goto)
  840. "Reference number to search for, or enter \".\" for id of current node: ")
  841. ((eq what 'update)
  842. "Reference number to update: ")))))
  843. (if (string-match "^\\s *[0-9]+\\s *$" search)
  844. (setq search (format "%s%s%s" org-index--head search org-index--tail)))))
  845. ;; Clean up and examine search string
  846. (when search
  847. (setq search (org-trim search))
  848. (if (string= search "") (setq search nil))
  849. (when search
  850. (if (string-match "^[0-9]+$" search)
  851. (setq search (concat org-index--head search org-index--tail)))))
  852. ;; Check for special case
  853. (when (and (memq what '(head goto))
  854. (string= search "."))
  855. (setq search (org-id-get)))
  856. search))
  857. (defun org-index--verify-id ()
  858. ;; Check id
  859. (unless org-index-id
  860. (setq org-index-id (org-index--create-new-index
  861. t
  862. (format "No index table has been created yet." org-index-id))))
  863. ;; Find node
  864. (let (marker)
  865. (setq marker (org-id-find org-index-id 'marker))
  866. (unless marker (setq org-index-id (org-index--create-new-index
  867. t
  868. (format "Cannot find node with id \"%s\"" org-index-id))))
  869. ; Try again with new node
  870. (setq marker (org-id-find org-index-id 'marker))
  871. (unless marker (error "Could not create node"))
  872. (setq org-index--buffer (marker-buffer marker)
  873. org-index--point (marker-position marker))
  874. (move-marker marker nil)))
  875. (defun org-index--retrieve-context ()
  876. ;; Get the content of the active region or the word under cursor
  877. (setq org-index--active-region
  878. (if (and transient-mark-mode mark-active)
  879. (buffer-substring (region-beginning) (region-end))
  880. nil))
  881. (setq org-index--below-cursor (thing-at-point 'symbol))
  882. ;; Find out, if we are within favable or not
  883. (setq org-index--within-node (string= (org-id-get) org-index-id))
  884. ;; Check and remember, if active window contains buffer with index table
  885. (if (eq (window-buffer) org-index--buffer)
  886. (setq org-index--active-window-index (selected-window)))
  887. ;; get current position in index-buffer
  888. (with-current-buffer org-index--buffer
  889. (unless (string= (org-id-get) org-index-id)
  890. (unless org-index--point-before
  891. (setq org-index--point-before (point))))))
  892. (defun org-index--parse-table ()
  893. (let (ref-field
  894. link-field
  895. initial-point
  896. end-of-heading)
  897. (with-current-buffer org-index--buffer
  898. (setq org-index--maxref 0)
  899. (setq initial-point (point))
  900. (org-index--go-below-hline)
  901. (setq org-index--below-hline (point))
  902. (beginning-of-line)
  903. (setq end-of-heading (point))
  904. (while (org-at-table-p) (forward-line -1))
  905. (forward-line)
  906. (setq org-index--headings (buffer-substring (point) end-of-heading))
  907. (goto-char org-index--below-hline)
  908. ;; count columns
  909. (org-table-goto-column 100)
  910. (setq org-index--numcols (- (org-table-current-column) 1))
  911. ;; get contents of columns
  912. (forward-line -2)
  913. (unless (org-at-table-p)
  914. (org-index--create-new-index
  915. nil
  916. "Index table starts with a hline"))
  917. ;; check for optional line consisting solely of width specifications
  918. (beginning-of-line)
  919. (if (looking-at "\\s *|\\(\\(\\s *|\\)\\|\\(\\s *<[0-9]+>\\s *|\\)\\)+\\s *$")
  920. (forward-line -1))
  921. (org-table-goto-column 1)
  922. (org-index--parse-headings)
  923. ;; Go beyond end of table
  924. (while (org-at-table-p) (forward-line 1))
  925. ;; Retrieve any decorations around the number within the first nonempty ref-field
  926. (goto-char org-index--below-hline)
  927. (while (and (org-at-table-p)
  928. (not (setq ref-field (org-index--get-field :ref))))
  929. (forward-line))
  930. ;; Some Checking
  931. (unless ref-field
  932. (org-index--create-new-index
  933. nil
  934. "Reference column is empty"))
  935. (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
  936. (org-index--create-new-index
  937. nil
  938. (format "First reference in index table ('%s') does not contain a number" ref-field)))
  939. ;; These are the decorations used within the first ref of index
  940. (setq org-index--head (match-string 1 ref-field))
  941. (setq org-index--tail (match-string 3 ref-field))
  942. (setq org-index--ref-regex (concat (regexp-quote org-index--head)
  943. "\\([0-9]+\\)"
  944. (regexp-quote org-index--tail)))
  945. (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
  946. ;; Go through table to find maximum number and do some checking
  947. (let ((ref 0))
  948. (while (org-at-table-p)
  949. (setq ref-field (org-index--get-field :ref))
  950. (setq link-field (org-index--get-field :link))
  951. (when (and (not ref-field)
  952. (not link-field))
  953. (org-pop-to-buffer-same-window org-index--buffer)
  954. (org-reveal)
  955. (error "Columns ref and link are both empty in this line"))
  956. (if ref-field
  957. (if (string-match org-index--ref-regex ref-field)
  958. ;; grab number
  959. (setq ref (string-to-number (match-string 1 ref-field)))
  960. (org-pop-to-buffer-same-window org-index--buffer)
  961. (org-reveal)
  962. (error "Column ref does not contain a number")))
  963. ;; check, if higher ref
  964. (if (> ref org-index--maxref) (setq org-index--maxref ref))
  965. ;; check if ref is ment for reuse
  966. (if (string= (org-index--get-field :count) ":reuse:")
  967. (setq org-index--has-reuse t))
  968. (forward-line 1)))
  969. ;; go back to initial position
  970. (goto-char initial-point))))
  971. (defun org-index--sort (&optional sort-column)
  972. (unless sort-column (setq sort-column (org-index--special-column :sort)))
  973. (let (top
  974. bottom
  975. ref-field
  976. count-field
  977. count-special)
  978. (unless buffer-read-only
  979. ;; get boundaries of table
  980. (goto-char org-index--below-hline)
  981. (forward-line 0)
  982. (setq top (point))
  983. (while (org-at-table-p) (forward-line))
  984. ;; Kill all empty rows at bottom
  985. (while (progn
  986. (forward-line -1)
  987. (org-table-goto-column 1)
  988. (and
  989. (not (org-index--get-field :ref))
  990. (not (org-index--get-field :link))))
  991. (org-table-kill-row))
  992. (forward-line 1)
  993. (setq bottom (point))
  994. (save-restriction
  995. (narrow-to-region top bottom)
  996. (goto-char top)
  997. (sort-subr t
  998. 'forward-line
  999. 'end-of-line
  1000. (lambda ()
  1001. (let (ref
  1002. (ref-field (or (org-index--get-field :ref) ""))
  1003. (count-field (or (org-index--get-field :count) ""))
  1004. (count-special 0))
  1005. ;; get reference with leading zeroes, so it can be
  1006. ;; sorted as text
  1007. (string-match org-index--ref-regex ref-field)
  1008. (setq ref (format
  1009. "%06d"
  1010. (string-to-number
  1011. (or (match-string 1 ref-field)
  1012. "0"))))
  1013. ;; find out, if special token in count-column
  1014. (setq count-special (format "%d"
  1015. (- 2
  1016. (length (member count-field '(":missing:" ":reuse:"))))))
  1017. ;; Construct different sort-keys according to
  1018. ;; requested sort column; prepend count-special to
  1019. ;; sort special entries at bottom of table, append ref
  1020. ;; as a secondary sort key
  1021. (cond
  1022. ((eq sort-column :count)
  1023. (concat count-special
  1024. (format
  1025. "%08d"
  1026. (string-to-number (or (org-index--get-field :count)
  1027. "")))
  1028. ref))
  1029. ((eq sort-column :accessed)
  1030. (concat count-special
  1031. (org-index--get-field :accessed)
  1032. " "
  1033. ref))
  1034. ((eq sort-column :ref)
  1035. (concat count-special
  1036. ref))
  1037. (t (error "This is a bug: unmatched case '%s'" sort-column)))))
  1038. nil 'string<))
  1039. ;; sorting has moved point below hline
  1040. (org-index--go-below-hline)
  1041. (setq org-index--below-hline (point)))))
  1042. (defun org-index--go-below-hline ()
  1043. (goto-char org-index--point)
  1044. ;; go to heading of node
  1045. (while (not (org-at-heading-p)) (forward-line -1))
  1046. (forward-line 1)
  1047. ;; go to table within node, but make sure we do not get into another node
  1048. (while (and (not (org-at-heading-p))
  1049. (not (org-at-table-p))
  1050. (not (eq (point) (point-max))))
  1051. (forward-line 1))
  1052. ;; check, if there really is a table
  1053. (unless (org-at-table-p)
  1054. (org-index--create-new-index
  1055. t
  1056. (format "Cannot find index table within node %s" org-index-id)))
  1057. ;; go to first hline
  1058. (while (and (not (org-at-table-hline-p))
  1059. (org-at-table-p))
  1060. (forward-line 1))
  1061. ;; and check
  1062. (unless (org-at-table-hline-p)
  1063. (org-index--create-new-index
  1064. nil
  1065. "Cannot find hline within index table"))
  1066. (forward-line 1)
  1067. (org-table-goto-column 1))
  1068. (defun org-index--align ()
  1069. (unless buffer-read-only (org-table-align))
  1070. (org-index--go-below-hline)
  1071. (setq org-index--below-hline (point)))
  1072. (defun org-index--parse-headings ()
  1073. ;; Associate names of special columns with column-numbers
  1074. (setq org-index--columns (copy-tree '((:ref . 0) (:link . 0) (:first . 0) (:last . 0)
  1075. (:count . 0) (:x1 . 0) (:x2 . 0) (:x3 . 0))))
  1076. ;; Associate names of special columns with names of columns
  1077. (setq org-index--special-columns (copy-tree '((:sort . nil) (:copy . nil) (:point . nil))))
  1078. ;; For each column
  1079. (dotimes (col org-index--numcols)
  1080. (let* (field-flags ;; raw heading, consisting of file name and maybe
  1081. ;; flags (seperated by ";")
  1082. field ;; field name only
  1083. field-symbol ;; and as a symbol
  1084. flags ;; flags from field-flags
  1085. found)
  1086. ;; parse field-flags into field and flags
  1087. (setq field-flags (org-trim (org-table-get-field (+ col 1))))
  1088. (if (string-match "^\\([^;]*\\);\\([a-z]+\\)$" field-flags)
  1089. (progn
  1090. (setq field (downcase (or (match-string 1 field-flags) "")))
  1091. ;; get flags as list of characters
  1092. (setq flags (mapcar 'string-to-char
  1093. (split-string
  1094. (downcase (match-string 2 field-flags))
  1095. "" t))))
  1096. ;; no flags
  1097. (setq field field-flags))
  1098. (unless (string= field "") (setq field-symbol (intern (concat ":" (downcase field)))))
  1099. ;; aliases for backward compatability
  1100. (if (eq field-symbol :last-accessed) (setq field-symbol :last))
  1101. (if (eq field-symbol :created) (setq field-symbol :first))
  1102. (if (and field-symbol
  1103. (not (assoc field-symbol org-index--columns)))
  1104. (error "Column %s is not a valid heading" (symbol-name field-symbol)))
  1105. ;; Check, that no flags appear twice
  1106. (mapc (lambda (x)
  1107. (when (memq (car x) flags)
  1108. (if (cdr (assoc (cdr x) org-index--columns))
  1109. (org-index--create-new-index
  1110. nil
  1111. (format "More than one heading is marked with flag '%c'" (car x))))))
  1112. '((?s . sort)
  1113. (?c . copy)))
  1114. ;; Process flags
  1115. (if (memq ?s flags)
  1116. (setcdr (assoc :sort org-index--special-columns) (or field-symbol (+ col 1))))
  1117. (if (memq ?c flags)
  1118. (setcdr (assoc :copy org-index--special-columns) (or field-symbol (+ col 1))))
  1119. (if (memq ?p flags)
  1120. (setcdr (assoc :point org-index--special-columns) (or field-symbol (+ col 1))))
  1121. ;; Store columns in alist
  1122. (setq found (assoc field-symbol org-index--columns))
  1123. (when found
  1124. (if (> (cdr found) 0)
  1125. (org-index--create-new-index
  1126. nil
  1127. (format "'%s' appears two times as column heading" (downcase field))))
  1128. (setcdr found (+ col 1)))))
  1129. ;; check if all necessary informations have been specified
  1130. (mapc (lambda (col)
  1131. (unless (> (cdr (assoc col org-index--columns)) 0)
  1132. (org-index--create-new-index
  1133. nil
  1134. (format "column '%s' has not been set" col))))
  1135. (list :ref :link :count :first :last))
  1136. ;; use count as a default sort-column
  1137. (unless (cdr (assoc :sort org-index--special-columns))
  1138. (setcdr (assoc :sort org-index--special-columns) :count)))
  1139. (defun org-index--create-new-index (create-new-index reason)
  1140. "Create a new empty index table with detailed explanation."
  1141. (let (prompt buffer-name title firstref id)
  1142. ;; cannot proceed without querying user
  1143. (if org-index--silent (error "No valid index: %s" reason))
  1144. (setq prompt
  1145. (if create-new-index
  1146. (concat "There is this problem with the existing index table:\n\n " reason "\n\nThis assistant will guide you to create a new one.\n\nDo you want to proceed ?")
  1147. (concat "The existing index table contains this error:\n\n " reason "\n\nYou need to correct this error manually before trying again. However, this assistant will help you to create an new initial index table with detailed comments, so that you may fix the errors in your existing table more easily.\n\nDo you want to proceed ?")))
  1148. (unless (y-or-n-p prompt)
  1149. (error "Cannot proceed without a valid index table: %s" reason))
  1150. (setq buffer-name (org-completing-read "Please choose the buffer, where the new node for the index table should be created; the new node will be inserted at its end.\n\nBuffer: " (mapcar 'buffer-name (org-buffer-list)) nil nil))
  1151. (setq title (read-from-minibuffer "Please enter the title of the index node: "))
  1152. (while (progn
  1153. (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: "))
  1154. (let (desc)
  1155. (unless (equal '(95 119) (sort (delete-dups (mapcar (lambda (x) (char-syntax x)) (concat "-1" firstref))) '<))
  1156. (setq desc "Contains other characters than those allowed in symbols"))
  1157. (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
  1158. ;; firstref not okay, report details
  1159. (setq desc
  1160. (cond ((string= firstref "") "is empty")
  1161. ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
  1162. ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
  1163. ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
  1164. )))
  1165. (if desc
  1166. (progn
  1167. (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s. Please hit RET and try again" firstref desc))
  1168. t)
  1169. nil))))
  1170. (with-current-buffer buffer-name
  1171. (goto-char (point-max))
  1172. (insert (format "\n\n* %s %s\n" firstref title))
  1173. (insert "\n\n Below you find your initial index table, which will grow over time.\n"
  1174. " Following that your may read its detailed explanation, which will help you,\n"
  1175. " to adjust org-index to your needs. This however is optional reading and not\n"
  1176. " required to start using org-index.\n")
  1177. (setq id (org-id-get-create))
  1178. (insert (format "
  1179. | | | | | | comment |
  1180. | ref | link | first | count;s | last | ;c |
  1181. | | <4> | | | | |
  1182. |-----+------+-------+---------+------+---------|
  1183. | %s | %s | %s | | | %s |
  1184. "
  1185. firstref
  1186. id
  1187. (with-temp-buffer (org-insert-time-stamp nil nil t))
  1188. "This node"))
  1189. (insert "
  1190. Detailed explanation:
  1191. The index table above has three lines of headings above the first
  1192. hline:
  1193. - The first one is ignored by org-index, and you can use it to
  1194. give meaningful names to columns. In the table above only one
  1195. column has a name (\"comment\"). This line is optional.
  1196. - The second line is the most important one, because it
  1197. contains the configuration information for org-index; please
  1198. read further below for its format.
  1199. - The third line is again optional; it may only specify the
  1200. widths of the individual columns (e.g. <4>).
  1201. The columns get their meaning by the second line of headings;
  1202. specifically by one of the keywords (e.g. \"ref\") or a flag
  1203. seperated by a semicolon (e.g. \";s\").
  1204. The keywords and flags are:
  1205. - ref: This contains the reference, which consists of a decorated
  1206. number, which is incremented for each new line. References are
  1207. meant to be used in org-mode headlines or outside of org,
  1208. e.g. within folder names.
  1209. - link: org-mode link pointing to the matching location within org.
  1210. - first: When has this line been first accessed (i.e. created) ?
  1211. - count: How many times has this line been accessed ? The
  1212. trailing flag \"s\" makes the table beeing sorted after this
  1213. column this column, so that often used entries appear at the
  1214. top of the table.
  1215. - last: When has this line been accessed last ?
  1216. - The last column above has no keyword, only the flag \"c\",
  1217. which makes its content beeing copied under certain
  1218. conditions. It is typically used for comments.
  1219. The sequence of columns does not matter. You may reorder them any
  1220. way you like. Columns are found by their name, which appears in
  1221. the second line of headings.
  1222. You can add further columns or even remove the last column. All
  1223. other columns are required.
  1224. Finally: This node needs not be a top level node; its name is
  1225. completely at you choice; it is found through its ID only.
  1226. ")
  1227. (while (not (org-at-table-p)) (forward-line -1))
  1228. (unless buffer-read-only (org-table-align))
  1229. (while (not (org-at-heading-p)) (forward-line -1))
  1230. ;; present results to user
  1231. (if create-new-index
  1232. (progn
  1233. ;; Only show the new index
  1234. (org-pop-to-buffer-same-window buffer-name)
  1235. (delete-other-windows)
  1236. (org-id-goto id)
  1237. (org-show-context)
  1238. (show-subtree)
  1239. (recenter 1)
  1240. (if (y-or-n-p "This is your new index table; Do you want to save its id to make it permanent ? ")
  1241. (progn
  1242. (customize-save-variable 'org-index-id id)
  1243. (message "Saved org-index-id '%s' to %s" org-index-id custom-file))
  1244. (let (sq)
  1245. (setq sq (format "(setq org-index-id \"%s\")" org-index-id))
  1246. (kill-new sq)
  1247. (message "Did not make the id of the new index permamanent; you may want to put\n\n %s\n\ninto your own initialization; it is copied already, just yank it." sq))
  1248. id))
  1249. ;; we had an error with the existing index table, so present old
  1250. ;; and new one together
  1251. ;; show existing index
  1252. (org-pop-to-buffer-same-window org-index--buffer)
  1253. (goto-char org-index--point)
  1254. (org-show-context)
  1255. (show-subtree)
  1256. (recenter 1)
  1257. (delete-other-windows)
  1258. ;; show new index
  1259. (select-window (split-window-vertically))
  1260. (org-pop-to-buffer-same-window buffer-name)
  1261. (org-id-goto id)
  1262. (org-show-context)
  1263. (show-subtree)
  1264. (recenter 1)
  1265. (error "Please compare your existing index (upper window) and a temporary new one (lower window) to correct the previous error (\"%s\"); the explanations following the new index table should help." reason)))))
  1266. (defun org-index--update-line (ref-or-link)
  1267. (let (initial
  1268. found
  1269. count-field)
  1270. (with-current-buffer org-index--buffer
  1271. (unless buffer-read-only
  1272. ;; search reference or link, if given (or assume, that we are already positioned right)
  1273. (when ref-or-link
  1274. (setq initial (point))
  1275. (goto-char org-index--below-hline)
  1276. (while (and (org-at-table-p)
  1277. (not (or (string= ref-or-link (org-index--get-field :ref))
  1278. (string= ref-or-link (org-index--get-field :link)))))
  1279. (forward-line)))
  1280. (if (not (org-at-table-p))
  1281. (error "Did not find reference or link '%s'" ref-or-link)
  1282. (setq count-field (org-index--get-field :count))
  1283. ;; update count field only if number or empty; leave :missing: and :reuse: as is
  1284. (if (or (not count-field)
  1285. (string-match "^[0-9]+$" count-field))
  1286. (org-index--get-field :count
  1287. (number-to-string
  1288. (+ 1 (string-to-number (or count-field "0"))))))
  1289. ;; update timestamp
  1290. (org-table-goto-column (org-index--column-num :last))
  1291. (org-table-blank-field)
  1292. (org-insert-time-stamp nil t t)
  1293. (setq found t))
  1294. (if initial (goto-char initial))
  1295. found))))
  1296. (defun org-index--get-field (key &optional value)
  1297. (let (field)
  1298. (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value)))
  1299. (if (string= field "") (setq field nil))
  1300. (org-no-properties field)))
  1301. (defun org-index--column-num (key)
  1302. (if (numberp key)
  1303. key
  1304. (cdr (assoc key org-index--columns))))
  1305. (defun org-index--special-column (key)
  1306. (cdr (assoc key org-index--special-columns)))
  1307. (defun org-index--make-guarded-search (ref &optional dont-quote)
  1308. (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
  1309. (defun org-index--do-statistics (what)
  1310. (let ((total 0)
  1311. missing
  1312. ref-field
  1313. ref
  1314. min
  1315. max
  1316. message-text)
  1317. ;; start with list of all references
  1318. (setq missing (mapcar (lambda (x) (format "%s%d%s" org-index--head x org-index--tail))
  1319. (number-sequence 1 org-index--maxref)))
  1320. ;; go through table and remove all refs, that we see
  1321. (goto-char org-index--below-hline)
  1322. (while (org-at-table-p)
  1323. ;; get ref-field and number
  1324. (setq ref-field (org-index--get-field :ref))
  1325. (if (and ref-field
  1326. (string-match org-index--ref-regex ref-field))
  1327. (setq ref (string-to-number (match-string 1 ref-field))))
  1328. ;; remove existing refs from list
  1329. (if ref-field (setq missing (delete ref-field missing)))
  1330. ;; record min and max
  1331. (if (or (not min) (< ref min)) (setq min ref))
  1332. (if (or (not max) (> ref max)) (setq max ref))
  1333. ;; count
  1334. (setq total (1+ total))
  1335. (forward-line))
  1336. ;; insert them, if requested
  1337. (forward-line -1)
  1338. (if (eq what 'statistics)
  1339. (setq message-text (format "Found %d references from %s to %s. %d references below highest do not appear in table. "
  1340. total
  1341. (format org-index--ref-format min)
  1342. (format org-index--ref-format max)
  1343. (length missing)))
  1344. (if (y-or-n-p (format "Found %d missing references; do you wish to append them to the index table"
  1345. (length missing)))
  1346. (let (type)
  1347. (setq type (org-icompleting-read
  1348. "Insert new lines for reuse by command \"new\" or just as missing ? " '("reuse" "missing")))
  1349. (mapc (lambda (x)
  1350. (let (org-table-may-need-update) (org-table-insert-row t))
  1351. (org-index--get-field :ref x)
  1352. (org-index--get-field :count (format ":%s:" type)))
  1353. missing)
  1354. (org-index--align)
  1355. (setq message-text (format "Inserted %d new lines for missing refernces" (length missing))))
  1356. (setq message-text (format "%d missing references." (length missing)))))
  1357. message-text))
  1358. (defun org-index--do-head (ref link)
  1359. (if ref (setq org-index--last-ref ref))
  1360. (let (message-text)
  1361. ;; Use link if available
  1362. (if link
  1363. (progn
  1364. (org-index--update-line link)
  1365. (org-id-goto link)
  1366. (org-reveal)
  1367. (if (eq (current-buffer) org-index--buffer)
  1368. (setq org-index--point-before nil))
  1369. (setq message-text "Followed link"))
  1370. (message (format "Scanning headlines for '%s' ..." ref))
  1371. (org-index--update-line ref)
  1372. (let ((search (concat ".*" (org-index--make-guarded-search ref)))
  1373. (org-trust-scanner-tags t)
  1374. buffer point)
  1375. (if (catch 'found
  1376. (progn
  1377. ;; loop over all headlines, stop on first match
  1378. (org-map-entries
  1379. (lambda ()
  1380. (when (or (looking-at search)
  1381. (eq ref (org-entry-get (point) "org-index-ref")))
  1382. ;; If this is not an inlinetask ...
  1383. (when (< (org-element-property :level (org-element-at-point))
  1384. org-inlinetask-min-level)
  1385. ;; ... remember location and bail out
  1386. (setq buffer (current-buffer))
  1387. (setq point (point))
  1388. (throw 'found t))))
  1389. nil 'agenda)
  1390. nil))
  1391. (progn
  1392. (if (eq buffer org-index--buffer)
  1393. (setq org-index--point-before nil))
  1394. (setq message-text (format "Found '%s'" (or ref link)))
  1395. (org-pop-to-buffer-same-window buffer)
  1396. (goto-char point)
  1397. (org-reveal))
  1398. (setq message-text (format "Did not find '%s'" (or ref link))))))
  1399. message-text))
  1400. (defun org-index--do-occur (initial-search)
  1401. (let ((occur-buffer-name "*org-index-occur*")
  1402. (word "") ; last word to search for growing and shrinking on keystrokes
  1403. (prompt "Search for: ")
  1404. (hint "")
  1405. words ; list of other words that must match too
  1406. occur-buffer
  1407. lines-to-show ; number of lines to show in window
  1408. start-of-lines ; position, where lines begin
  1409. start-of-help ; start of displayed help (if any)
  1410. left-off-at ; stack of last positions in index table
  1411. after-inserted ; in occur-buffer
  1412. lines-visible ; in occur-buffer
  1413. below-hline-bol ; below-hline and at bol
  1414. exit-gracefully ; true if normal exit
  1415. in-c-backspace ; true while processing C-backspace
  1416. show-headings ; true, if headings should be shown
  1417. fun-on-ret ; function to be executed, if return has been pressed
  1418. ret from to key)
  1419. ;; clear buffer
  1420. (if (get-buffer "*org-index-occur*")
  1421. (kill-buffer occur-buffer-name))
  1422. (setq occur-buffer (get-buffer-create "*org-index-occur*"))
  1423. ;; install keyboard-shortcuts within occur-buffer
  1424. (with-current-buffer occur-buffer
  1425. (let ((keymap (make-sparse-keymap)))
  1426. (set-keymap-parent keymap org-mode-map)
  1427. (setq fun-on-ret (lambda () (interactive)
  1428. (let ((ref (org-index--get-field :ref))
  1429. (link (org-index--get-field :link)))
  1430. (message (org-index--do-head ref link)))))
  1431. (define-key keymap (kbd "RET") fun-on-ret)
  1432. (use-local-map keymap)))
  1433. (with-current-buffer org-index--buffer
  1434. (let ((initial (point)))
  1435. (goto-char org-index--below-hline)
  1436. (forward-line 0)
  1437. (setq below-hline-bol (point))
  1438. (goto-char initial)))
  1439. (org-pop-to-buffer-same-window occur-buffer)
  1440. (toggle-truncate-lines 1)
  1441. (unwind-protect ; to reset cursor-shape even in case of errors
  1442. (progn
  1443. ;; fill in header
  1444. (erase-buffer)
  1445. (insert (concat "Incremental search, showing one window of matches. TAB toggles help.\n\n"))
  1446. (setq start-of-lines (point))
  1447. (setq start-of-help start-of-lines)
  1448. (setq cursor-type 'hollow)
  1449. ;; get window size of occur-buffer as number of lines to be searched
  1450. (setq lines-to-show (+ (- (window-body-height) (line-number-at-pos)) 1))
  1451. ;; fill initially
  1452. (setq ret (org-index--get-matching-lines nil lines-to-show below-hline-bol))
  1453. (when (car ret)
  1454. (insert (cdr ret))
  1455. (setq left-off-at (cons (car ret) nil))
  1456. (setq after-inserted (cons (point) nil)))
  1457. ;; read keys
  1458. (while
  1459. (progn
  1460. (goto-char start-of-lines)
  1461. (setq lines-visible 0)
  1462. ;; use initial-search (if present) to simulate keyboard input
  1463. (if (and initial-search
  1464. (> (length initial-search) 0))
  1465. (progn
  1466. (setq key (string-to-char (substring initial-search 0 1)))
  1467. (if (length initial-search)
  1468. (setq initial-search (substring initial-search 1))))
  1469. (if in-c-backspace
  1470. (setq key 'backspace)
  1471. (let ((search-text (mapconcat 'identity (reverse (cons word words)) ",")))
  1472. (setq key (read-key
  1473. (format "%s%s%s%s"
  1474. prompt
  1475. search-text
  1476. (if (string= search-text "") "" " ")
  1477. hint))))
  1478. (setq hint "")
  1479. (setq exit-gracefully (member key (list 'up 'down 'left 'right 'RET ?\C-g ?\C-m)))))
  1480. (not exit-gracefully))
  1481. (cond
  1482. ((eq key 'C-backspace)
  1483. (setq in-c-backspace t))
  1484. ((member key (list 'backspace 'deletechar ?\C-?)) ; erase last char
  1485. (if (= (length word) 0)
  1486. ;; nothing more to delete from current word; try next
  1487. (progn
  1488. (setq word (car words))
  1489. (setq words (cdr words))
  1490. (setq in-c-backspace nil))
  1491. ;; unhighlight longer match
  1492. (let ((case-fold-search t))
  1493. (unhighlight-regexp (regexp-quote word)))
  1494. ;; some chars are left; shorten word
  1495. (setq word (substring word 0 -1))
  1496. (when (= (length word) 0) ; when nothing left, use next word from list
  1497. (setq word (car words))
  1498. (setq words (cdr words))
  1499. (setq in-c-backspace nil))
  1500. ;; remove everything, that has been added for char just deleted
  1501. (when (cdr after-inserted)
  1502. (setq after-inserted (cdr after-inserted))
  1503. (goto-char (car after-inserted))
  1504. (delete-region (point) (point-max)))
  1505. ;; back up last position in index table too
  1506. (when (cdr left-off-at)
  1507. (setq left-off-at (cdr left-off-at)))
  1508. ;; go through buffer and check, if any invisible line should now be shown
  1509. (goto-char start-of-lines)
  1510. (while (< (point) (point-max))
  1511. (if (outline-invisible-p)
  1512. (progn
  1513. (setq from (line-beginning-position)
  1514. to (line-beginning-position 2))
  1515. ;; check for matches
  1516. (when (org-index--test-words (cons word words) (buffer-substring from to))
  1517. (when (<= lines-visible lines-to-show) ; show, if more lines required
  1518. (outline-flag-region from to nil)
  1519. (incf lines-visible))))
  1520. ;; already visible, just count
  1521. (incf lines-visible))
  1522. (forward-line 1))
  1523. ;; highlight shorter word
  1524. (unless (= (length word) 0)
  1525. (let ((case-fold-search t))
  1526. (highlight-regexp (regexp-quote word) 'isearch)))))
  1527. ((member key (list ?\s ?,)) ; space or comma: enter an additional search word
  1528. ;; push current word and clear, no need to change display
  1529. (setq words (cons word words))
  1530. (setq word ""))
  1531. ((member key (list 'TAB ?\C-i)) ; tab: toggle display of headlines
  1532. (setq show-headings (not show-headings))
  1533. (goto-char start-of-lines)
  1534. (if show-headings
  1535. (progn
  1536. (forward-line -1)
  1537. (kill-line)
  1538. (setq start-of-help (point))
  1539. (if (display-graphic-p)
  1540. (insert "<backspace> and <c-backspace> erase, cursor keys move. RET finds node, C-RET all matches.\nComma seperates words, any other key adds to search word.\n\n")
  1541. (insert "BACKSPACE to erase, to finish. Then cursor keys and RET to find node.\n\n"))
  1542. (insert org-index--headings))
  1543. (delete-region start-of-help start-of-lines)
  1544. (insert "\n"))
  1545. (setq start-of-lines (point)))
  1546. ((and (integerp key)
  1547. (aref printable-chars key)) ; any printable char: add to current search word
  1548. ;; unhighlight short word
  1549. (unless (= (length word) 0)
  1550. (let ((case-fold-search t))
  1551. (unhighlight-regexp (regexp-quote word))))
  1552. ;; add to word
  1553. (setq word (concat word (char-to-string key)))
  1554. ;; hide lines, that do not match longer word any more
  1555. (while (< (point) (point-max))
  1556. (unless (outline-invisible-p)
  1557. (setq from (line-beginning-position)
  1558. to (line-beginning-position 2))
  1559. ;; check for matches
  1560. (if (org-index--test-words (list word) (buffer-substring from to))
  1561. (incf lines-visible) ; count as visible
  1562. (outline-flag-region from to t))) ; hide
  1563. (forward-line 1))
  1564. ;; duplicate top of stacks; eventually overwritten below
  1565. (setq left-off-at (cons (car left-off-at) left-off-at))
  1566. (setq after-inserted (cons (car after-inserted) after-inserted))
  1567. ;; get new lines from index table
  1568. (when (< lines-visible lines-to-show)
  1569. (setq ret (org-index--get-matching-lines (cons word words)
  1570. (- lines-to-show lines-visible)
  1571. (car left-off-at)))
  1572. (when (car ret)
  1573. (insert (cdr ret))
  1574. (setcar left-off-at (car ret))
  1575. (setcar after-inserted (point))))
  1576. ;; highlight longer word
  1577. (let ((case-fold-search t))
  1578. (highlight-regexp (regexp-quote word) 'isearch)))
  1579. (t ; non-printable chars
  1580. (setq hint (format "(cannot search for key '%s', use %s to quit)"
  1581. (if (symbolp key)
  1582. key
  1583. (key-description (char-to-string key)))
  1584. (substitute-command-keys "\\[keyboard-quit]"))))))
  1585. ;; search is done collect and brush up results
  1586. ;; remove any lines, that are still invisible
  1587. (goto-char start-of-lines)
  1588. (while (< (point) (point-max))
  1589. (if (outline-invisible-p)
  1590. (delete-region (line-beginning-position) (line-beginning-position 2))
  1591. (forward-line 1)))
  1592. ;; get all the rest
  1593. (when (eq key 'C-return)
  1594. (message "Getting all matches ...")
  1595. (setq ret (org-index--get-matching-lines (cons word words) 0 (car left-off-at)))
  1596. (message "done.")
  1597. (insert (cdr ret))))
  1598. ;; postprocessing even for non graceful exit
  1599. (setq cursor-type t)
  1600. ;; replace previous heading
  1601. (let ((numlines (count-lines (point) start-of-lines)))
  1602. (goto-char start-of-lines)
  1603. (delete-region (point-min) (point))
  1604. (insert (format (concat (if exit-gracefully "Search is done;" "Search aborted;")
  1605. (if (eq key 'C-return)
  1606. " showing all %d matches."
  1607. " showing only some matches.")
  1608. " Use cursor keys to move, press RET to find node.\n\n")
  1609. numlines))
  1610. (if show-headings (insert "\n\n" org-index--headings)))
  1611. (forward-line))
  1612. (setq buffer-read-only t)
  1613. ;; perform action according to last char
  1614. (forward-line -1)
  1615. (cond
  1616. ((member key (list 'RET ?\C-m))
  1617. (funcall fun-on-ret))
  1618. ((eq key 'up)
  1619. (forward-line -1))
  1620. ((eq key 'down)
  1621. (forward-line 1))
  1622. ((eq key 'left)
  1623. (forward-char -1))
  1624. ((eq key 'right)
  1625. (forward-char 1)))))
  1626. (defun org-index--do-new-line (create-ref)
  1627. "Do the common work for org-index-new-line and org-index"
  1628. (let (new)
  1629. (when create-ref
  1630. ;; go through table to find first entry to be reused
  1631. (when org-index--has-reuse
  1632. (goto-char org-index--below-hline)
  1633. ;; go through table
  1634. (while (and (org-at-table-p)
  1635. (not new))
  1636. (when (string=
  1637. (org-index--get-field :count)
  1638. ":reuse:")
  1639. (setq new (org-index--get-field :ref))
  1640. (if new (org-table-kill-row)))
  1641. (forward-line)))
  1642. ;; no ref to reuse; construct new reference
  1643. (unless new
  1644. (setq new (format "%s%d%s" org-index--head (1+ org-index--maxref) org-index--tail)))
  1645. ;; remember for org-mark-ring-goto
  1646. (setq org-index--text-to-yank new))
  1647. ;; insert ref or link as very first row
  1648. (goto-char org-index--below-hline)
  1649. (org-table-insert-row)
  1650. ;; insert some of the standard values
  1651. (org-table-goto-column (org-index--column-num :first))
  1652. (org-insert-time-stamp nil nil t)
  1653. (org-table-goto-column (org-index--column-num :count))
  1654. (insert "1")
  1655. new))
  1656. (defun org-index--get-matching-lines (words numlines start-from)
  1657. (let ((numfound 0)
  1658. pos
  1659. initial line lines)
  1660. (with-current-buffer org-index--buffer
  1661. ;; remember initial pos and start at requested
  1662. (setq initial (point))
  1663. (goto-char start-from)
  1664. ;; loop over buffer until we have found enough lines
  1665. (while (and (or (< numfound numlines)
  1666. (= numlines 0))
  1667. (org-at-table-p))
  1668. ;; check each word
  1669. (setq line (buffer-substring (line-beginning-position) (line-beginning-position 2)))
  1670. (when (org-index--test-words words line)
  1671. (setq lines (concat lines line))
  1672. (incf numfound))
  1673. (forward-line 1)
  1674. (setq pos (point)))
  1675. ;; return to initial position
  1676. (goto-char initial))
  1677. (unless lines (setq lines ""))
  1678. (cons pos lines)))
  1679. (defun org-index--test-words (words line)
  1680. (let ((found-all t))
  1681. (setq line (downcase line))
  1682. (catch 'not-found
  1683. (dolist (w words)
  1684. (or (search w line)
  1685. (throw 'not-found nil)))
  1686. t)))
  1687. (defun org-index--dump-variables ()
  1688. "Dump variables of org-index; mostly for debugging"
  1689. (interactive)
  1690. "Dump all variables of org-index for debugging"
  1691. (let ((buff (get-buffer-create "*org-index-dump-variables*"))
  1692. (maxlen 0)
  1693. vars name value)
  1694. (with-current-buffer buff
  1695. (erase-buffer)
  1696. (mapatoms (lambda (s) (when (and (boundp s)
  1697. (string-prefix-p "org-index-" (symbol-name s)))
  1698. (setq name (symbol-name s))
  1699. (setq value (symbol-value s))
  1700. (setq vars (cons (cons name value) vars))
  1701. (if (> (length name) maxlen)
  1702. (setq maxlen (length name))))))
  1703. (setq vars (sort vars (lambda (x y) (string< (car x) (car y)))))
  1704. (mapc (lambda (x) (insert (format (format "%%-%ds: %%s\n" (+ maxlen 1)) (car x) (cdr x))))
  1705. vars)
  1706. (pop-to-buffer buff))))
  1707. (defadvice org-mark-ring-goto (after org-index--advice-text-to-yank activate)
  1708. "Make text from org-index available for yank."
  1709. (when org-index--text-to-yank
  1710. (kill-new org-index--text-to-yank)
  1711. (message (format "Ready to yank '%s'" org-index--text-to-yank))
  1712. (setq org-index--text-to-yank nil)))
  1713. (provide 'org-index)
  1714. ;; Local Variables:
  1715. ;; fill-column: 75
  1716. ;; comment-column: 50
  1717. ;; End:
  1718. ;;; org-index.el ends here