org-index.el 86 KB

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