org-index.el 74 KB

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