org-index.el 79 KB

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