org-index.el 83 KB

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