org-index.el 78 KB

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