org-index.el 83 KB

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