org-index.el 78 KB

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