org-index.el 79 KB

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