org-index.el 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865
  1. ;;; org-index.el --- A personal index for org
  2. ;; Copyright (C) 2011-2015 Free Software Foundation, Inc.
  3. ;; Author: Marc Ihm <org-index@2484.de>
  4. ;; Version: 5.0.2
  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. ;; Fast search for selected org nodes and things outside of org.
  24. ;;
  25. ;; org-index creates and updates an index table with keywords; each line
  26. ;; either points to a heading in org, references something outside or
  27. ;; carries a snippet of text to yank. When searching the index, the set
  28. ;; of matching lines is updated with every keystroke; results are sorted
  29. ;; by usage count and date, so that frequently used entries appear first
  30. ;; in the list of results.
  31. ;;
  32. ;; References are decorated numbers (e.g. 'R237' or '--455--'); they are
  33. ;; well suited to be used outside of org, e.g. in folder names, ticket
  34. ;; systems or on printed documents.
  35. ;;
  36. ;; On first invocation org-index will assist you in creating the index
  37. ;; table.
  38. ;;
  39. ;; To start using your index, invoke subcommands 'add', 'ref' and 'yank'
  40. ;; to create entries and 'occur' to find them.
  41. ;;
  42. ;;
  43. ;; Setup:
  44. ;;
  45. ;; - Place this file in a directory from your load-path,
  46. ;; e.g. org-mode/contrib/lisp.
  47. ;;
  48. ;; - Add these lines to your .emacs:
  49. ;;
  50. ;; (require 'org-index)
  51. ;; (org-index-default-keybindings) ; optional
  52. ;;
  53. ;; - Maybe restart your Emacs to make these lines effective.
  54. ;;
  55. ;; - Invoke `org-index'; on first run it will assist in creating your
  56. ;; index table.
  57. ;;
  58. ;; - Optionally invoke `M-x org-customize' to tune some settings (choose
  59. ;; group org-index).
  60. ;;
  61. ;;
  62. ;; Further information:
  63. ;;
  64. ;; - Watch the screencast at http://2484.de/org-index.html.
  65. ;;
  66. ;; - See the documentation of `org-index', which can also be read
  67. ;; by invoking `org-index' and choosing the help-command.
  68. ;;
  69. ;;
  70. ;; Updates:
  71. ;;
  72. ;; The latest published version of this file can always be found at:
  73. ;;
  74. ;; http://orgmode.org/w/?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
  75. ;;; Change Log:
  76. ;; [2015-12-29 Tu] Version 5.0.2
  77. ;; - New commands yank, column and edit
  78. ;; - New column tags
  79. ;; - All columns are now required
  80. ;; - References are now optional
  81. ;; - Subcommand enter has been renamed to index
  82. ;; - Subcommands kill and edit can be invoked from an occur buffer
  83. ;; - Many Bugfixes
  84. ;; - Added link to screencast
  85. ;;
  86. ;; [2015-08-20 Th] Version 4.3.0
  87. ;; - Configuration is done now via standard customize
  88. ;; - New sorting strategy 'mixed'
  89. ;; - Silenced some compiler warnings
  90. ;;
  91. ;; [2015-03-18 We] Version 4.2.1
  92. ;; - No garbage in kill-ring
  93. ;; - No recentering after add
  94. ;;
  95. ;; [2015-03-08 Su] Version 4.2.0
  96. ;; - Reference numbers for subcommands can be passed as a prefix argument
  97. ;; - New variable org-index-default-keybindings-list with a list of
  98. ;; default keybindings for org-index-default-keybindings
  99. ;; - Added new column level
  100. ;; - removed flags get-category-on-add and get-heading-on-add
  101. ;;
  102. ;; [2015-02-26 Th] to [2015-03-05 Th] Version 4.0.0 to 4.1.2
  103. ;; - Removed command "leave"; rather go back with org-mark-ring-goto
  104. ;; - Renamed column "link" to "id"
  105. ;; - Added maintainance options to find duplicate rows, to check ids,
  106. ;; update index or remove property org-index-ref from nodes
  107. ;; - Shortened versin history
  108. ;;
  109. ;; [2014-12-08 Mo] to [2015-01-31 Sa] Version 3.0.0 to 3.2.0:
  110. ;; - Complete sorting of index only occurs in idle-timer
  111. ;; - New command "maintain" with some subcommands
  112. ;; - Rewrote command "occur" with overlays in an indirect buffer
  113. ;; - Command "add" updates index, if node is already present
  114. ;; - New commands "add" and "delete" to easily add and remove
  115. ;; the current node to or from your index.
  116. ;; - New command "example" to create an example index.
  117. ;; - Several new flags that are explained within index node.
  118. ;; - Removed commands "reuse", "missing", "put", "goto",
  119. ;; "update", "link", "fill", "unhighlight"
  120. ;; - New function `org-index-default-keybindings'
  121. ;;
  122. ;; [2012-12-07 Fr] to [2014-04-26 Sa] Version 2.0.0 to 2.4.3:
  123. ;; - New functions org-index-new-line and org-index-get-line
  124. ;; offer access to org-index from other lisp programs
  125. ;; - Regression tests with ert
  126. ;; - Renamed from "org-favtable" to "org-index"
  127. ;; - Added an assistant to set up the index table
  128. ;; - occur is now incremental, searching as you type
  129. ;; - Integrated with org-mark-ring-goto
  130. ;; - Added full support for ids
  131. ;; - Renamed the package from "org-reftable" to "org-favtable"
  132. ;; - Additional columns are required (e.g. "link"). Error messages will
  133. ;; guide you
  134. ;; - Ask user explicitly, which command to invoke
  135. ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
  136. ;;
  137. ;; [2011-12-10 Sa] to [2012-09-22 Sa] Version Version 1.2.0 to 1.5.0:
  138. ;; - New command "sort" to sort a buffer or region by reference number
  139. ;; - New commands "highlight" and "unhighlight" to mark references
  140. ;; - New command "head" to find a headline with a reference number
  141. ;; - New commands occur and multi-occur
  142. ;; - Started this Change Log
  143. ;;; Code:
  144. (require 'org-table)
  145. (require 'cl-lib)
  146. (require 'widget)
  147. ;; Version of this package
  148. (defvar org-index-version "5.0.2" "Version of `org-index', format is major.minor.bugfix, where \"major\" are incompatible changes and \"minor\" are new features.")
  149. ;; customizable options
  150. (defgroup org-index nil
  151. "Options concerning the optional index for org."
  152. :tag "Org Index"
  153. :group 'org)
  154. (defcustom org-index-id nil
  155. "Id of the Org-mode node, which contains the index table."
  156. :group 'org-index)
  157. (defcustom org-index-sort-by 'mixed
  158. "Strategy for sorting index table (and whence entries in occur).
  159. Valid values are:
  160. last-access Sort index by date and time of last access; show
  161. more recent entries first.
  162. count Sort by usage count; more often used entries first.
  163. mixed First, show all index entries, which have been
  164. used today; sort them by last access. Then show
  165. older entries sorted by usage count."
  166. :group 'org-index
  167. :set (lambda (s v)
  168. (set-default s v)
  169. (if (and org-index-id
  170. org-index--buffer
  171. (functionp 'org-index--sort-silent))
  172. (org-index--sort-silent)))
  173. :initialize 'custom-initialize-default
  174. :type '(choice
  175. (const last-accessed)
  176. (const count)
  177. (const mixed)))
  178. (defcustom org-index-yank-after-add 'ref
  179. "Specifies which column should be yanked after adding a new index row.
  180. Valid values are some columns of index table."
  181. :group 'org-index
  182. :type '(choice
  183. (const ref)
  184. (const category)
  185. (const keywords)))
  186. (defcustom org-index-point-on-add 'keywords
  187. "Specifies in which column point will land when adding a new index row.
  188. Valid values are some columns of index table."
  189. :group 'org-index
  190. :type '(choice
  191. (const category)
  192. (const keywords)))
  193. (defcustom org-index-copy-heading-to-keywords t
  194. "When adding a new node to index: Copy heading to keywords-column ?"
  195. :group 'org-index
  196. :type '(choice (const :tag "Yes" t)
  197. (const :tag "No" nil)))
  198. (defcustom org-index-strip-ref-and-date-from-heading t
  199. "When adding a headline as keywords for a new index row: remove
  200. leading reference or timestamps ?
  201. This can be useful, if you have the habit of adding refs and
  202. dates to the start of your headings; then, if you change your
  203. heading and want to update your index, you do not need to remove
  204. those pieces."
  205. :group 'org-index
  206. :type '(choice (const :tag "Yes" t)
  207. (const :tag "No" nil)))
  208. (defcustom org-index-edit-on-add '(category keywords)
  209. "List of columns to edit when adding a new row."
  210. :group 'org-index
  211. :type '(repeat (choice
  212. (const category)
  213. (const keywords))))
  214. (defcustom org-index-edit-on-yank '(yank keywords)
  215. "List of columns to edit when adding new text to yank."
  216. :group 'org-index
  217. :type '(repeat (choice
  218. (const yank)
  219. (const category)
  220. (const keywords))))
  221. (defcustom org-index-edit-on-ref '(category keywords)
  222. "List of columns to edit when adding new ref."
  223. :group 'org-index
  224. :type '(repeat (choice
  225. (const category)
  226. (const keywords))))
  227. ;; Variables to hold the configuration of the index table
  228. (defvar org-index--maxrefnum nil "Maximum number from reference table, e.g. 153.")
  229. (defvar org-index--nextref nil "Next reference, that can be used, e.g. 'R154'.")
  230. (defvar org-index--head nil "Header before number (e.g. 'R').")
  231. (defvar org-index--tail nil "Tail after number (e.g. '}' or ')'.")
  232. (defvar org-index--numcols nil "Number of columns in index table.")
  233. (defvar org-index--ref-regex nil "Regular expression to match a reference.")
  234. (defvar org-index--ref-format nil "Format, that can print a reference.")
  235. (defvar org-index--columns nil "Columns of index-table.")
  236. (defvar org-index--buffer nil "Buffer of index table.")
  237. (defvar org-index--point nil "Position at start of headline of index table.")
  238. (defvar org-index--below-hline nil "Position of first cell in first line below hline.")
  239. (defvar org-index--headings nil "Headlines of index-table as a string.")
  240. (defvar org-index--headings-visible nil "Visible part of headlines of index-table as a string.")
  241. (defvar org-index--keymap nil "Keymap for shortcuts for some commands of `org-index'. Filled and activated by `org-index-default-keybings'.")
  242. ;; Variables to hold context and state
  243. (defvar org-index--last-fingerprint nil "Fingerprint of last line created.")
  244. (defvar org-index--category-before nil "Category of node before.")
  245. (defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
  246. (defvar org-index--below-cursor nil "Word below cursor.")
  247. (defvar org-index--within-node nil "True, if we are within node of the index table.")
  248. (defvar org-index--within-occur nil "True, if we are within the occur-buffer.")
  249. (defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
  250. (defvar org-index--occur-help-text nil "Text for help in occur buffer.")
  251. (defvar org-index--occur-help-overlay nil "Overlay for help in occur buffer.")
  252. (defvar org-index--occur-stack nil "Stack with overlays for hiding lines.")
  253. (defvar org-index--occur-tail-overlay nil "Overlay to cover invisible lines.")
  254. (defvar org-index--occur-lines-collected 0 "Number of lines collected in occur buffer; helpful for tests.")
  255. (defvar org-index--last-sort nil "Last column, the index has been sorted after.")
  256. (defvar org-index--sort-timer nil "Timer to sort index in correct order.")
  257. (defvar org-index--aligned nil "Remember for this Emacs session, if table has been aligned at least once.")
  258. (defvar org-index--edit-widgets nil "List of widgets used to edit")
  259. (defvar org-index--context-index nil "Position and line used for index in edit buffer")
  260. (defvar org-index--context-occur nil "Position and line used for occur in edit buffer")
  261. (defvar org-index--context-node nil "Buffer and position for node in edit buffer")
  262. ;; static information for this program package
  263. (defconst org-index--commands '(occur add kill head ping index ref yank column edit help example sort multi-occur highlight maintain) "List of commands available.")
  264. (defconst org-index--valid-headings '(ref id created last-accessed count keywords category level yank tags) "All valid headings.")
  265. (defconst org-index--occur-buffer-name "*org-index-occur*" "Name of occur buffer.")
  266. (defconst org-index--edit-buffer-name "*org-index-edit*" "Name of edit buffer.")
  267. (defconst org-index--sort-idle-delay 300 "Delay in seconds after which buffer will sorted.")
  268. (defvar org-index-default-keybindings-list '(("a" . 'add) ("i" . 'index) ("SPC" . nil) ("o" . 'occur) ("a" . 'add) ("k" . 'kill) ("h" . 'head) ("p" . 'ping) ("." . 'ping) ("r" . 'ref) ("y" . 'yank) ("c" . 'column) ("e" . 'edit) ("?" . 'help)) "One-letter short cuts for selected subcommands of `org-index', put in effect by `org-index-default-keybindings'.")
  269. (defmacro org-index--on (column value &rest body)
  270. "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
  271. The value returned is the value of the last form in BODY or nil,
  272. if VALUE cannot be found."
  273. (declare (indent 2) (debug t))
  274. (let ((pointvar (make-symbol "point")) ; avoid clash with same-named variables in body
  275. (foundvar (make-symbol "found"))
  276. (retvar (make-symbol "ret")))
  277. `(save-current-buffer
  278. (let ((,pointvar (point))
  279. ,foundvar
  280. ,retvar)
  281. (set-buffer org-index--buffer)
  282. (setq ,foundvar (org-index--go ,column ,value))
  283. (when ,foundvar
  284. (setq ,retvar (progn ,@body)))
  285. (goto-char ,pointvar)
  286. ,retvar))))
  287. (defun org-index (&optional command search-ref arg)
  288. "Fast search index for selected org nodes and things outside of org.
  289. org-index creates and updates an index table with keywords; each line
  290. either points to a heading in org, references something outside or
  291. carries a snippet of text to yank. The index table is searched for
  292. keywords through an incremental occur; results are sorted by usage
  293. count and date, so that frequently used entries appear first among
  294. the results.
  295. References are decorated numbers (e.g. 'R237' or '--455--'); they are
  296. well suited to be used outside of org, e.g. in folder names, ticket
  297. systems or on printed documents.
  298. On first invocation org-index will help to create a dedicated node
  299. for its index table.
  300. To start building up your index, use subcommands 'add', 'ref' and
  301. 'yank' to create entries and use 'occur' to find them.
  302. This is version 5.0.2 of org-index.el.
  303. The function `org-index' is the only interactive function of this
  304. package and its main entry point; it will present you with a list
  305. of subcommands to choose from:
  306. occur: Incremental search, that shows matching lines from the
  307. index table. It is updated after every keystroke. You may
  308. enter a list of words seperated by space or comma (`,'), to
  309. select lines that contain all of the given words.
  310. add: Add the current node to your index, so that it can be
  311. found through the subcommand \"occur\". Update index,
  312. if node is already present.
  313. kill: Kill (delete) the current node from your index. Can be
  314. invoked from index, from occur or from a headline.
  315. head: Ask for a reference number and search for this heading.
  316. index: Enter index table and maybe go to a specific reference;
  317. use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
  318. ping: Echo line from index table for current node or first of
  319. its ancestors from index.
  320. ref: Create a new index line with a reference.
  321. yank: Store a new string, that can be yanked when an index row
  322. is chosen during occur.
  323. column: If within index table, read another character and jump
  324. to specified column.
  325. edit: Present current line in a seperate buffer. Can be invoked
  326. from index, from occur or from a headline.
  327. help: Show this text.
  328. example: Create a temporary index, that will not be saved, but
  329. may serve as an example.
  330. sort: Sort lines in index, in region or buffer by contained
  331. reference, or sort index by count, reference or last access.
  332. multi-occur: Apply Emacs standard `multi-occur' operation on all
  333. `org-mode' buffers to search for the given reference.
  334. highlight: Highlight or unhighlight references in active region
  335. or buffer. Call with prefix argument (`C-u') to remove
  336. highlights.
  337. maintain: Offers some choices to check, update or fix your index.
  338. If you invoke `org-index' for the first time, an assistant will be
  339. invoked, that helps you to create your own index.
  340. Invoke `org-customize' to tweak the behaviour of org-index.
  341. Call `org-index-default-keybindings' from within your init-file
  342. to establish convenient keyboard shortcuts.
  343. A numeric prefix argument is used as a reference number for
  344. commands, that need one (e.g. 'head').
  345. Use from elisp: Optional argument COMMAND is a symbol naming the
  346. command to execute. SEARCH-REF specifies a reference to search
  347. for, if needed. ARG allows passing in a prefix argument as in
  348. interactive calls."
  349. (interactive "i\ni\nP")
  350. (let (search-id ; id to search for
  351. search-fingerprint ; fingerprint to search for
  352. sort-what ; sort what ?
  353. kill-new-text ; text that will be appended to kill ring
  354. message-text) ; text that will be issued as an explanation
  355. (catch 'new-index
  356. ;;
  357. ;; Initialize and parse
  358. ;;
  359. ;; creates index table, if necessary
  360. (org-index--verify-id)
  361. ;; Get configuration of index table
  362. (org-index--parse-table)
  363. ;; store context information
  364. (org-index--retrieve-context)
  365. ;;
  366. ;; Arrange for proper sorting of index
  367. ;;
  368. ;; lets assume, that it has been sorted this way (we try hard to make sure)
  369. (unless org-index--last-sort (setq org-index--last-sort org-index-sort-by))
  370. ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
  371. (unless org-index--sort-timer
  372. (setq org-index--sort-timer
  373. (run-with-idle-timer org-index--sort-idle-delay t 'org-index--sort-silent)))
  374. ;;
  375. ;; Find out, what we are supposed to do
  376. ;;
  377. ;; Check or read command
  378. (if command
  379. (unless (memq command org-index--commands)
  380. (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
  381. command (mapconcat 'symbol-name org-index--commands ",")))
  382. (setq command (intern (org-completing-read
  383. "Please choose: "
  384. (mapcar 'symbol-name org-index--commands)))))
  385. ;;
  386. ;; Get search string, if required; process possible sources one after
  387. ;; another (lisp argument, prefix argument, user input).
  388. ;;
  389. ;; Try prefix, if no lisp argument given
  390. (if (and (not search-ref)
  391. (numberp arg))
  392. (setq search-ref (format "%s%d%s" org-index--head arg org-index--tail)))
  393. ;; These actions really need a search string and may even prompt for it
  394. (when (memq command '(index head multi-occur))
  395. ;; search from surrounding text ?
  396. (unless search-ref
  397. (if org-index--within-node
  398. (if (org-at-table-p)
  399. (setq search-ref (org-index--get-or-set-field 'ref)))
  400. (if (and org-index--below-cursor
  401. (string-match (concat "\\(" org-index--ref-regex "\\)")
  402. org-index--below-cursor))
  403. (setq search-ref (match-string 1 org-index--below-cursor)))))
  404. ;; If we still do not have a search string, ask user explicitly
  405. (unless search-ref
  406. (if (eq command 'index)
  407. (let ((r (org-index--read-search-for-index)))
  408. (setq search-ref (first r))
  409. (setq search-id (second r))
  410. (setq search-fingerprint (third r)))
  411. (setq search-ref (read-from-minibuffer "Search reference number: "))))
  412. ;; Clean up search string
  413. (when search-ref
  414. (setq search-ref (org-trim search-ref))
  415. (if (string-match "^[0-9]+$" search-ref)
  416. (setq search-ref (concat org-index--head search-ref org-index--tail)))
  417. (if (string= search-ref "") (setq search-ref nil)))
  418. (if (and (not search-ref)
  419. (not (eq command 'index)))
  420. (error "Command %s needs a reference number" command)))
  421. ;;
  422. ;; Command sort needs to know in advance, what to sort for
  423. ;;
  424. (when (eq command 'sort)
  425. (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))))
  426. ;;
  427. ;; Enter table
  428. ;;
  429. ;; Arrange for beeing able to return
  430. (when (and (memq command '(occur head index example sort maintain))
  431. (not (string= (buffer-name) org-index--occur-buffer-name)))
  432. (org-mark-ring-push))
  433. ;; These commands will leave user in index table after they are finished
  434. (when (or (memq command '(index maintain))
  435. (and (eq command 'sort)
  436. (eq sort-what 'index)))
  437. (pop-to-buffer-same-window org-index--buffer)
  438. (goto-char org-index--point)
  439. (org-index--unfold-buffer))
  440. ;;
  441. ;; Actually do, what is requested
  442. ;;
  443. (cond
  444. ((eq command 'help)
  445. ;; bring up help-buffer for this function
  446. (describe-function 'org-index))
  447. ((eq command 'multi-occur)
  448. ;; Construct list of all org-buffers
  449. (let (buff org-buffers)
  450. (dolist (buff (buffer-list))
  451. (set-buffer buff)
  452. (if (string= major-mode "org-mode")
  453. (setq org-buffers (cons buff org-buffers))))
  454. ;; Do multi-occur
  455. (multi-occur org-buffers (org-index--make-guarded-search search-ref))
  456. ;; Present results
  457. (if (get-buffer "*Occur*")
  458. (progn
  459. (setq message-text (format "multi-occur for '%s'" search-ref))
  460. (other-window 1)
  461. (toggle-truncate-lines 1))
  462. (setq message-text (format "Did not find '%s'" search-ref)))))
  463. ((eq command 'add)
  464. (let ((r (org-index--do-add-or-update (if (equal arg '(4)) t nil)
  465. (if (numberp arg) arg nil))))
  466. (setq message-text (car r))
  467. (setq kill-new-text (cdr r))))
  468. ((eq command 'kill)
  469. (setq message-text (org-index--do-kill)))
  470. ((eq command 'head)
  471. (if (and org-index--within-node
  472. (org-at-table-p))
  473. (setq search-id (org-index--get-or-set-field 'id)))
  474. (if (and (not search-id) search-ref)
  475. (setq search-id (org-index--id-from-ref search-ref)))
  476. (setq message-text
  477. (if search-id
  478. (org-index--find-id search-id)
  479. "Current line has no id")))
  480. ((eq command 'index)
  481. (goto-char org-index--below-hline)
  482. (setq message-text
  483. (if search-ref
  484. (if (org-index--go 'ref search-ref)
  485. (progn
  486. (org-index--update-current-line)
  487. (org-table-goto-column (org-index--column-num 'ref))
  488. (format "Found index line '%s'" search-ref))
  489. (format "Did not find index line with reference '%s'" search-ref))
  490. (if search-id
  491. (if (org-index--go 'id search-id)
  492. (progn
  493. (org-index--update-current-line)
  494. (org-table-goto-column (org-index--column-num 'ref))
  495. (format "Found index line '%s'" (org-index--get-or-set-field 'ref)))
  496. (format "Did not find index line with id '%s'" search-id))
  497. (if search-fingerprint
  498. (if (org-index--go 'fingerprint org-index--last-fingerprint)
  499. (progn
  500. (org-index--update-current-line)
  501. (beginning-of-line)
  502. (format "Found latest index line"))
  503. (format "Did not find index line"))
  504. ;; simply go into table
  505. "At index table"))))
  506. (recenter))
  507. ((eq command 'ping)
  508. (let ((moved-up 0) id info reached-top)
  509. (unless (string= major-mode "org-mode") (error "No node at point"))
  510. ;; take id from current node or reference
  511. (setq id (if search-ref
  512. (org-index--id-from-ref search-ref)
  513. (org-id-get)))
  514. ;; move up until we find a node in index
  515. (save-excursion
  516. (outline-back-to-heading)
  517. (while (not (or info
  518. reached-top))
  519. (if id
  520. (setq info (org-index--on 'id id
  521. (mapcar (lambda (x) (org-index--get-or-set-field x))
  522. (list 'ref 'count 'created 'last-accessed 'category 'keywords 'ref)))))
  523. (setq reached-top (= (org-outline-level) 1))
  524. (unless (or info
  525. reached-top)
  526. (outline-up-heading 1 t)
  527. (cl-incf moved-up))
  528. (setq id (org-id-get))))
  529. (if info
  530. (progn
  531. (setq message-text
  532. (apply 'format
  533. (append (list "'%s'%shas been accessed %s times between %s and %s; category is '%s', keywords are '%s'"
  534. (pop info)
  535. (if (> moved-up 0) (format " (parent node, %d level up) " moved-up) " "))
  536. info)))
  537. (setq kill-new-text (car (last info))))
  538. (setq message-text "Neither this node nor any of its parents is part of index"))))
  539. ((eq command 'occur)
  540. (set-buffer org-index--buffer)
  541. (org-index--do-occur))
  542. ((eq command 'ref)
  543. (let (args)
  544. (setq args (org-index--collect-values-from-user org-index-edit-on-ref))
  545. (setq args (plist-put args 'category "yank"))
  546. (setq args (plist-put args 'ref org-index--nextref))
  547. (apply 'org-index--do-new-line args)
  548. (setq kill-new-text org-index--nextref)
  549. (setq message-text (format "Added new row with ref '%s'" org-index--nextref))))
  550. ((eq command 'yank)
  551. (let (args)
  552. (setq args (org-index--collect-values-from-user org-index-edit-on-yank))
  553. (if (plist-get args 'yank)
  554. (plist-put args 'yank (replace-regexp-in-string "|" (regexp-quote "\\vert") (plist-get args 'yank) nil 'literal)))
  555. (setq args (plist-put args 'category "yank"))
  556. (apply 'org-index--do-new-line args)
  557. (setq message-text "Added new row with text to yank")))
  558. ((eq command 'column)
  559. (if (and org-index--within-node
  560. (org-at-table-p))
  561. (let (char col num)
  562. (setq char (read-char "Please specify, which column to go to (r=ref, k=keywords, c=category, y=yank): "))
  563. (unless (memq char (list ?r ?k ?c ?y))
  564. (error (format "Invalid char '%c', cannot goto this column" char)))
  565. (setq col (cdr (assoc char '((?r . ref) (?k . keywords) (?c . category) (?y . yank)))))
  566. (setq num (org-index--column-num col))
  567. (if num
  568. (progn
  569. (org-table-goto-column num)
  570. (setq message-text (format "At column %s" (symbol-name col))))
  571. (error (format "Column '%s' is not present" col))))
  572. (error "Need to be in index table to go to a specific column")))
  573. ((eq command 'edit)
  574. (setq message-text (org-index--do-edit)))
  575. ((eq command 'sort)
  576. (let ((sorts (list "count" "last-accessed" "mixed" "id" "ref"))
  577. sort groups-and-counts)
  578. (cond
  579. ((eq sort-what 'index)
  580. (setq sort
  581. (intern
  582. (org-icompleting-read
  583. "Please choose column to sort index table: "
  584. (cl-copy-list sorts)
  585. nil t nil nil (symbol-name org-index-sort-by))))
  586. (org-index--do-sort-index sort)
  587. (org-table-goto-column (org-index--column-num (if (eq sort 'mixed) 'last-access sort)))
  588. ;; When saving index, it should again be sorted correctly
  589. (with-current-buffer org-index--buffer
  590. (add-hook 'before-save-hook 'org-index--sort-silent t))
  591. (setq message-text
  592. (format
  593. (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
  594. (if groups-and-counts
  595. "; %d groups with equal %s and a total of %d lines have been found"
  596. ""))
  597. (symbol-name sort)
  598. org-index-sort-by
  599. org-index--sort-idle-delay
  600. (second groups-and-counts)
  601. (symbol-name sort)
  602. (third groups-and-counts))))
  603. ((memq sort-what '(region buffer))
  604. (org-index--do-sort-lines sort-what)
  605. (setq message-text (format "Sorted %s by contained references" sort-what))))))
  606. ((eq command 'highlight)
  607. (let ((where "buffer"))
  608. (save-excursion
  609. (save-restriction
  610. (when (and transient-mark-mode
  611. mark-active)
  612. (narrow-to-region (region-beginning) (region-end))
  613. (setq where "region"))
  614. (if arg
  615. (progn
  616. (unhighlight-regexp org-index--ref-regex)
  617. (setq message-text (format "Removed highlights for references in %s" where)))
  618. (highlight-regexp org-index--ref-regex 'isearch)
  619. (setq message-text (format "Highlighted references in %s" where)))))))
  620. ((eq command 'maintain)
  621. (setq message-text (org-index--do-maintain)))
  622. ((eq command 'example)
  623. (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
  624. (org-index--create-index t)))
  625. (t (error "Unknown subcommand '%s'" command)))
  626. ;; tell, what we have done and what can be yanked
  627. (if kill-new-text (setq kill-new-text
  628. (substring-no-properties kill-new-text)))
  629. (if (string= kill-new-text "") (setq kill-new-text nil))
  630. (let ((m (concat
  631. message-text
  632. (if (and message-text kill-new-text)
  633. " and r"
  634. (if kill-new-text "R" ""))
  635. (if kill-new-text (format "eady to yank '%s'." kill-new-text) (if message-text "." "")))))
  636. (unless (string= m "")
  637. (message m)
  638. (setq org-index--message-text m)))
  639. (if kill-new-text (kill-new kill-new-text)))))
  640. (defun org-index-default-keybindings (&optional prefix)
  641. "Set default keybindings for `org-index'.
  642. Invoke subcommands of org index with a single key
  643. sequence. Establish the common prefix key 'C-c i' which should be
  644. followed by the first letter of a subcommand.
  645. The ist of letters and subcommands is specified in within
  646. `org-index-default-keybindings-list'.
  647. See `org-index' for a description of all subcommands.
  648. Optional argument PREFIX specifies common prefix, defaults to 'C-c i'"
  649. (interactive)
  650. (define-prefix-command 'org-index--keymap)
  651. ;; prefix command
  652. (global-set-key (kbd (or prefix "C-c i")) 'org-index--keymap)
  653. ;; loop over subcommands
  654. (mapc
  655. (lambda (x)
  656. (define-key org-index--keymap (kbd (car x))
  657. `(lambda (arg) (interactive "P")
  658. (message nil)
  659. (org-index ,(cdr x) nil arg))))
  660. org-index-default-keybindings-list))
  661. (defun org-index-new-line (&rest keys-values)
  662. "Create a new line within the index table, returning its reference.
  663. The function takes a varying number of argument pairs; each pair
  664. is a symbol for an existing column heading followed by its value.
  665. The return value is the new reference.
  666. Example:
  667. (message \"Created reference %s\"
  668. (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
  669. Optional argument KEYS-VALUES specifies content of new line."
  670. (let ((ref (plist-get keys-values 'ref)))
  671. (org-index--verify-id)
  672. (org-index--parse-table)
  673. (if (not (memq ref '(t nil)))
  674. (error "Column 'ref' accepts only 't' or 'nil'"))
  675. (when ref
  676. (setq ref org-index--nextref)
  677. (setq keys-values (plist-put keys-values 'ref ref)))
  678. (apply 'org-index--do-new-line keys-values)
  679. ref))
  680. (defun org-index--do-edit ()
  681. "Perform command edit"
  682. (let ((maxlen 0) cols-vals buffer-keymap field-keymap keywords-pos val)
  683. (org-index--check-can-edit-or-kill "edit")
  684. ;; change to index, if whithin occur
  685. (if org-index--within-occur
  686. (let ((pos (get-text-property (point) 'org-index-lbp)))
  687. (org-index--occur-test-stale pos)
  688. (setq org-index--context-occur (cons (point) (org-index--line-in-canonical-form)))
  689. (set-buffer org-index--buffer)
  690. (goto-char pos))
  691. (setq org-index--context-occur nil))
  692. ;; change to index, if on headline
  693. (if (org-at-heading-p)
  694. (let ((id (org-id-get)))
  695. (setq org-index--context-node (cons (current-buffer) (point)))
  696. (set-buffer org-index--buffer)
  697. (unless (and id (org-index--go 'id id))
  698. (setq org-index--context-node nil)
  699. (error "This node is not in index")))
  700. (setq org-index--context-node nil))
  701. ;; retrieve current content of index line
  702. (dolist (col (mapcar 'car (reverse org-index--columns)))
  703. (if (> (length (symbol-name col)) maxlen)
  704. (setq maxlen (length (symbol-name col))))
  705. (setq val (org-index--get-or-set-field col))
  706. (if (and val (eq col 'yank)) (setq val (replace-regexp-in-string (regexp-quote "\\vert") "|" val nil 'literal)))
  707. (setq cols-vals (cons (cons col val)
  708. cols-vals)))
  709. ;; we need two different keymaps
  710. (setq buffer-keymap (make-sparse-keymap))
  711. (set-keymap-parent buffer-keymap widget-keymap)
  712. (define-key buffer-keymap (kbd "C-c C-c") 'org-index--edit-c-c-c-c)
  713. (define-key buffer-keymap (kbd "C-c C-k") 'org-index--edit-c-c-c-k)
  714. (setq field-keymap (make-sparse-keymap))
  715. (set-keymap-parent field-keymap widget-field-keymap)
  716. (define-key field-keymap (kbd "C-c C-c") 'org-index--edit-c-c-c-c)
  717. (define-key field-keymap (kbd "C-c C-k") 'org-index--edit-c-c-c-k)
  718. ;; prepare buffer
  719. (setq org-index--context-index (cons (point) (org-index--line-in-canonical-form)))
  720. (if (get-buffer org-index--edit-buffer-name) (kill-buffer org-index--edit-buffer-name))
  721. (switch-to-buffer (get-buffer-create org-index--edit-buffer-name))
  722. ;; create and fill widgets
  723. (setq org-index--edit-widgets nil)
  724. (widget-insert "Edit this line from index; type C-c C-c when done, C-c C-k to abort.\n\n")
  725. (dolist (col-val cols-vals)
  726. (if (eq (car col-val) 'keywords) (setq keywords-pos (point)))
  727. (setq org-index--edit-widgets (cons
  728. (cons (car col-val)
  729. (widget-create 'editable-field
  730. :format (format (format "%%%ds: %%%%v" maxlen) (symbol-name (car col-val)))
  731. :keymap field-keymap
  732. (or (cdr col-val) "")))
  733. org-index--edit-widgets)))
  734. (widget-setup)
  735. (goto-char keywords-pos)
  736. (beginning-of-line)
  737. (forward-char (+ maxlen 2))
  738. (use-local-map buffer-keymap)
  739. "Editing a single line from index"))
  740. (defun org-index--edit-c-c-c-c ()
  741. "Function to invoked on C-c C-c in Edit buffer."
  742. (interactive)
  743. (let ((obuf (get-buffer org-index--occur-buffer-name))
  744. val line)
  745. ;; Time might have passed
  746. (org-index--refresh-parse-table)
  747. (with-current-buffer org-index--buffer
  748. ;; check, if buffer has become stale
  749. (save-excursion
  750. (goto-char (car org-index--context-index))
  751. (unless (string= (cdr org-index--context-index)
  752. (org-index--line-in-canonical-form))
  753. (switch-to-buffer org-index--edit-buffer-name)
  754. (error "Index table has changed: Cannot find line, that this buffer is editing.")))
  755. (pop-to-buffer-same-window org-index--buffer)
  756. (goto-char (car org-index--context-index))
  757. ;; write back line to index
  758. (dolist (col-widget org-index--edit-widgets)
  759. (setq val (widget-value (cdr col-widget)))
  760. (if (eq (car col-widget) 'yank) (setq val (replace-regexp-in-string "|" (regexp-quote "\\vert") val)))
  761. (org-index--get-or-set-field (car col-widget) val))
  762. (setq line (org-index--align-and-fontify-current-line))
  763. (beginning-of-line))
  764. ;; write line to occur if appropriate
  765. (if org-index--context-occur
  766. (if obuf
  767. (if (string= (cdr org-index--context-index)
  768. (cdr org-index--context-occur))
  769. (progn
  770. (pop-to-buffer-same-window obuf)
  771. (goto-char (car org-index--context-occur))
  772. (beginning-of-line)
  773. (let ((inhibit-read-only t))
  774. (delete-region (line-beginning-position) (line-end-position))
  775. (insert line)
  776. (put-text-property (line-beginning-position) (line-end-position)
  777. 'org-index-lbp (cdr org-index--context-index))))
  778. (error "Occur buffer and index buffer do not match any longer."))
  779. (message "Occur buffer has gone, cannot switch back."))
  780. (setq org-index--context-occur nil))
  781. ;; return to node, if invoked from there
  782. (when org-index--context-node
  783. (pop-to-buffer-same-window (car org-index--context-node))
  784. (goto-char (cdr org-index--context-node)))
  785. ;; clean up
  786. (kill-buffer org-index--edit-buffer-name)
  787. (setq org-index--context-index nil)
  788. (setq org-index--edit-widgets nil)
  789. (beginning-of-line)
  790. (message "Index line has been edited.")))
  791. (defun org-index--edit-c-c-c-k ()
  792. "Function to invoked on C-c C-k in Edit buffer."
  793. (interactive)
  794. (kill-buffer org-index--edit-buffer-name)
  795. (setq org-index--context-index nil)
  796. (setq org-index--edit-widgets nil)
  797. (beginning-of-line)
  798. (message "Edit aborted."))
  799. (defun org-index--do-new-line (&rest keys-values)
  800. "Do the work for `org-index-new-line'.
  801. Optional argument KEYS-VALUES specifies content of new line."
  802. (save-excursion
  803. (org-index--retrieve-context)
  804. (with-current-buffer org-index--buffer
  805. (goto-char org-index--point)
  806. ;; check arguments early; they might come from userland
  807. (let ((kvs keys-values)
  808. k v)
  809. (while kvs
  810. (setq k (car kvs))
  811. (setq v (cadr kvs))
  812. (if (or (not (symbolp k))
  813. (and (symbolp v) (not (eq v t)) (not (eq v nil))))
  814. (error "Arguments must be alternation of key and value"))
  815. (unless (org-index--column-num k)
  816. (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
  817. (setq kvs (cddr kvs))))
  818. (let (yank)
  819. ;; create new line
  820. (org-index--create-new-line)
  821. ;; fill columns
  822. (let ((kvs keys-values)
  823. k v n)
  824. (while kvs
  825. (setq k (car kvs))
  826. (setq v (cadr kvs))
  827. (org-table-goto-column (org-index--column-num k))
  828. (insert (org-trim (or v "")))
  829. (setq kvs (cddr kvs))))
  830. ;; align and fontify line
  831. (org-index--promote-current-line)
  832. (org-index--align-and-fontify-current-line)
  833. ;; remember fingerprint to be able to return
  834. (setq org-index--last-fingerprint (org-index--get-or-set-field 'fingerprint))
  835. ;; get column to yank
  836. (setq yank (org-index--get-or-set-field org-index-yank-after-add))
  837. yank))))
  838. (defun org-index-get-line (column value)
  839. "Retrieve an existing line within the index table by ref or id.
  840. Return its contents as a property list.
  841. The function `plist-get' may be used to retrieve specific elements
  842. from the result.
  843. Example:
  844. (plist-get (org-index-get-line 'ref \"R12\") 'count)
  845. retrieves the value of the count-column for reference number 12.
  846. Argument COLUMN is a symbol, either ref or id,
  847. argument VALUE specifies the value to search for."
  848. ;; check arguments
  849. (unless (memq column '(ref id))
  850. (error "Argument column can only be 'ref' or 'id'"))
  851. (unless value
  852. (error "Need a value to search for"))
  853. (org-index--verify-id)
  854. (org-index--parse-table)
  855. (org-index--get-line column value))
  856. (defun org-index--get-line (column value)
  857. "Find a line by ID, return its contents.
  858. Argument COLUMN and VALUE specify line to get."
  859. (let (content)
  860. (org-index--on
  861. column value
  862. (mapc (lambda (x)
  863. (if (and (numberp (cdr x))
  864. (> (cdr x) 0))
  865. (setq content (cons (car x) (cons (or (org-index--get-or-set-field (car x)) "") content)))))
  866. (reverse org-index--columns)))
  867. content))
  868. (defun org-index--ref-from-id (id)
  869. "Get reference from line ID."
  870. (org-index--on 'id id (org-index--get-or-set-field 'ref)))
  871. (defun org-index--id-from-ref (ref)
  872. "Get id from line REF."
  873. (org-index--on 'ref ref (org-index--get-or-set-field 'id)))
  874. (defun org-index--get-fingerprint ()
  875. "Get fingerprint of current line."
  876. (replace-regexp-in-string
  877. "\\s " ""
  878. (mapconcat (lambda (x) (org-index--get-or-set-field x)) '(id ref yank keywords created) "")))
  879. (defun org-index--read-search-for-index ()
  880. "Special input routine for command index."
  881. ;; Accept single char commands or switch to reading a sequence of digits
  882. (let (char prompt search-ref search-id search-fingerprint)
  883. ;; start with short prompt but give more help on next iteration
  884. (setq prompt "Please specify, where to go in index (0-9.,space,backspace,return or ? for help): ")
  885. ;; read one character
  886. (while (not (memq char (append (number-sequence ?0 ?9) (list ?\d ?\b ?\r ?\j ?\s ?.))))
  887. (setq char (read-char prompt))
  888. (setq prompt "Go to index table and specific position. Digits specify a reference number to got to, <space> goes to top of index, <backspace> or <delete> to last line created and <return> or `.' to index line of current node. Please choose: "))
  889. (if (memq char (number-sequence ?0 ?9))
  890. ;; read rest of digits
  891. (setq search-ref (read-from-minibuffer "Search reference number: " (char-to-string char))))
  892. ;; decode single chars
  893. (if (memq char '(?\r ?\n ?.)) (setq search-id (org-id-get)))
  894. (if (memq char '(?\d ?\b)) (setq search-fingerprint org-index--last-fingerprint))
  895. (list search-ref search-id search-fingerprint)))
  896. (defun org-index--verify-id ()
  897. "Check, that we have a valid id."
  898. ;; Check id
  899. (unless org-index-id
  900. (let ((answer (org-completing-read "Cannot find an index (org-index-id is not set). You may:\n - read-help : to learn more about org-index\n - create-index : invoke an assistant to create an initial index\nPlease choose: " (list "read-help" "create-index") nil t nil nil "read-help")))
  901. (if (string= answer "create-index")
  902. (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
  903. (describe-function 'org-index))))
  904. ;; Find node
  905. (let (marker)
  906. (setq marker (org-id-find org-index-id 'marker))
  907. (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
  908. ; Try again with new node
  909. (setq marker (org-id-find org-index-id 'marker))
  910. (unless marker (error "Could not create node"))
  911. (setq org-index--buffer (marker-buffer marker)
  912. org-index--point (marker-position marker))
  913. (move-marker marker nil)))
  914. (defun org-index--retrieve-context ()
  915. "Collect context information before starting with command."
  916. ;; Get the content of the active region or the word under cursor
  917. (setq org-index--active-region
  918. (if (and transient-mark-mode mark-active)
  919. (buffer-substring (region-beginning) (region-end))
  920. nil))
  921. (setq org-index--below-cursor (thing-at-point 'symbol))
  922. ;; get category of current node
  923. (setq org-index--category-before
  924. (save-excursion ; workaround: org-get-category does not give category when at end of buffer
  925. (beginning-of-line)
  926. (org-get-category (point) t)))
  927. ;; Find out, if we are within index table or occur buffer
  928. (setq org-index--within-node (string= (org-id-get) org-index-id))
  929. (setq org-index--within-occur (string= (buffer-name) org-index--occur-buffer-name)))
  930. (defun org-index--parse-table ()
  931. "Parse content of index table."
  932. (let (ref-field
  933. id-field
  934. initial-point
  935. end-of-headings
  936. start-of-headings)
  937. (with-current-buffer org-index--buffer
  938. (setq org-index--maxrefnum 0)
  939. (setq initial-point (point))
  940. (org-index--go-below-hline)
  941. ;; align and fontify table once for this emacs session
  942. (unless org-index--aligned
  943. (org-table-align) ; needs to happen before fontification to be effective ?
  944. (let ((is-modified (buffer-modified-p))
  945. (below (point)))
  946. (while (org-at-table-p)
  947. (forward-line))
  948. (font-lock-fontify-region below (point))
  949. (org-index--go-below-hline)
  950. (setq org-index--aligned t)
  951. (set-buffer-modified-p is-modified)))
  952. (org-index--go-below-hline)
  953. (beginning-of-line)
  954. ;; get headings to display during occur
  955. (setq end-of-headings (point))
  956. (while (org-at-table-p) (forward-line -1))
  957. (forward-line)
  958. (setq start-of-headings (point))
  959. (setq org-index--headings-visible (substring-no-properties (org-index--copy-visible start-of-headings end-of-headings)))
  960. (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
  961. ;; count columns
  962. (org-table-goto-column 100)
  963. (setq org-index--numcols (- (org-table-current-column) 1))
  964. ;; go to top of table
  965. (while (org-at-table-p)
  966. (forward-line -1))
  967. (forward-line)
  968. ;; parse line of headings
  969. (org-index--parse-headings)
  970. ;; parse list of flags
  971. (goto-char org-index--point)
  972. ;; Retrieve any decorations around the number within the first nonempty ref-field
  973. (goto-char org-index--below-hline)
  974. (while (and (org-at-table-p)
  975. (not (setq ref-field (org-index--get-or-set-field 'ref))))
  976. (forward-line))
  977. ;; Some Checking
  978. (unless ref-field
  979. (org-index--report-index-error "Reference column is empty"))
  980. (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
  981. (org-index--report-index-error
  982. "First reference in index table ('%s') does not contain a number" ref-field))
  983. ;; These are the decorations used within the first ref of index
  984. (setq org-index--head (match-string 1 ref-field))
  985. (setq org-index--tail (match-string 3 ref-field))
  986. (setq org-index--ref-regex (concat (regexp-quote org-index--head)
  987. "\\([0-9]+\\)"
  988. (regexp-quote org-index--tail)))
  989. (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
  990. ;; check if the table still seems to be sorted mixed
  991. (goto-char org-index--below-hline)
  992. (when (eq org-index-sort-by 'mixed)
  993. (org-index--go-below-hline)
  994. (if (string< (org-index--get-or-set-field 'last-accessed)
  995. (org-index--get-mixed-time))
  996. (org-index--do-sort-index org-index-sort-by)))
  997. ;; Go through table to find maximum number and do some checking
  998. (let ((refnum 0))
  999. (while (org-at-table-p)
  1000. (setq ref-field (org-index--get-or-set-field 'ref))
  1001. (setq id-field (org-index--get-or-set-field 'id))
  1002. (if ref-field
  1003. (if (string-match org-index--ref-regex ref-field)
  1004. ;; grab number
  1005. (setq refnum (string-to-number (match-string 1 ref-field)))
  1006. (kill-whole-line)
  1007. (message "Removing line from index-table whose ref does not contain a number")))
  1008. ;; check, if higher ref
  1009. (if (> refnum org-index--maxrefnum) (setq org-index--maxrefnum refnum))
  1010. (forward-line 1)))
  1011. (setq org-index--nextref (format "%s%d%s" org-index--head (1+ org-index--maxrefnum) org-index--tail))
  1012. ;; go back to initial position
  1013. (goto-char initial-point))))
  1014. (defun org-index--refresh-parse-table ()
  1015. "Fast refresh of selected results of parsing of index table."
  1016. (setq org-index--point (marker-position (org-id-find org-index-id 'marker)))
  1017. (with-current-buffer org-index--buffer
  1018. (save-excursion
  1019. (org-index--go-below-hline))))
  1020. (defun org-index--do-maintain ()
  1021. "Choose among and perform some tasks to maintain index."
  1022. (let ((check-what) (max-mini-window-height 1.0) message-text)
  1023. (setq check-what (intern (org-completing-read "These checks and fixes are available:\n - statistics : compute statistics about index table\n - check : check ids by visiting their nodes\n - duplicates : check index for duplicate rows (ref or id)\n - clean : remove obsolete property org-index-id\n - update : update content of index lines, with an id \nPlease choose: " (list "statistics" "check" "duplicates" "clean" "update") nil t nil nil "statistics")))
  1024. (message nil)
  1025. (cond
  1026. ((eq check-what 'check)
  1027. (setq message-text (or (org-index--check-ids)
  1028. "No problems found")))
  1029. ((eq check-what 'statistics)
  1030. (setq message-text (org-index--do-statistics)))
  1031. ((eq check-what 'duplicates)
  1032. (setq message-text (org-index--find-duplicates)))
  1033. ((eq check-what 'clean)
  1034. (let ((lines 0))
  1035. (org-map-entries
  1036. (lambda ()
  1037. (when (org-entry-get (point) "org-index-ref")
  1038. (cl-incf lines)
  1039. (org-entry-delete (point) "org-index-ref")))
  1040. nil 'agenda)
  1041. (setq message-text (format "Removed property 'org-index-ref' from %d lines" lines))))
  1042. ((eq check-what 'update)
  1043. (if (y-or-n-p "Updating your index will overwrite certain columns with content from the associated heading and category. If unsure, you may try this for a single, already existing line of your index by invoking `add'. Are you SURE to proceed for ALL INDEX LINES ? ")
  1044. (setq message-text (org-index--update-all-lines))
  1045. (setq message-text "Canceled."))))
  1046. message-text))
  1047. (defun org-index--get-mixed-time ()
  1048. "Get timestamp for sorting order mixed."
  1049. (format-time-string
  1050. (org-time-stamp-format t t)
  1051. (apply 'encode-time (append '(0 0 0) (nthcdr 3 (decode-time))))))
  1052. (defun org-index--do-sort-index (sort)
  1053. "Sort index table according to SORT."
  1054. (let ((is-modified (buffer-modified-p))
  1055. top
  1056. bottom
  1057. ref-field
  1058. count-field
  1059. mixed-time)
  1060. (unless buffer-read-only
  1061. (message "Sorting index table for %s..." (symbol-name sort))
  1062. (undo-boundary)
  1063. (let ((message-log-max nil)) ; we have just issued a message, dont need those of sort-subr
  1064. ;; if needed for mixed sort
  1065. (if (eq sort 'mixed)
  1066. (setq mixed-time (org-index--get-mixed-time)))
  1067. ;; get boundaries of table
  1068. (org-index--go-below-hline)
  1069. (forward-line 0)
  1070. (setq top (point))
  1071. (while (org-at-table-p) (forward-line))
  1072. ;; kill all empty rows at bottom
  1073. (while (progn
  1074. (forward-line -1)
  1075. (org-table-goto-column 1)
  1076. (and
  1077. (not (org-index--get-or-set-field 'ref))
  1078. (not (org-index--get-or-set-field 'id))
  1079. (not (org-index--get-or-set-field 'yank))))
  1080. (org-table-kill-row))
  1081. (forward-line 1)
  1082. (setq bottom (point))
  1083. ;; sort lines
  1084. (save-restriction
  1085. (narrow-to-region top bottom)
  1086. (goto-char top)
  1087. (sort-subr t
  1088. 'forward-line
  1089. 'end-of-line
  1090. (lambda ()
  1091. (org-index--get-sort-key sort t mixed-time))
  1092. nil
  1093. 'string<)
  1094. (goto-char (point-min))
  1095. ;; restore modification state
  1096. (set-buffer-modified-p is-modified)))
  1097. (setq org-index--last-sort sort))))
  1098. (defun org-index--do-sort-lines (what)
  1099. "Sort lines in WHAT according to contained reference."
  1100. (save-restriction
  1101. (cond
  1102. ((eq what 'region)
  1103. (if (region-active-p)
  1104. (narrow-to-region (region-beginning) (region-end))
  1105. (error "No active region, cannot sort")))
  1106. ((eq what 'buffer)
  1107. (unless (y-or-n-p "Sort whole current buffer ? ")
  1108. (error "Canceled"))
  1109. (narrow-to-region (point-min) (point-max))))
  1110. (goto-char (point-min))
  1111. (sort-subr nil 'forward-line 'end-of-line
  1112. (lambda ()
  1113. (if (looking-at (concat ".*"
  1114. (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
  1115. (string-to-number (match-string 1))
  1116. 0)))))
  1117. (defun org-index--go-below-hline ()
  1118. "Move below hline in index-table."
  1119. (let ((count 0)
  1120. (errstring (format "index table within node %s" org-index-id)))
  1121. (goto-char org-index--point)
  1122. ;; go to heading of node
  1123. (while (not (org-at-heading-p)) (forward-line -1))
  1124. (forward-line 1)
  1125. ;; go to first table, but make sure we do not get into another node
  1126. (while (and (not (org-at-table-p))
  1127. (not (org-at-heading-p))
  1128. (not (eobp)))
  1129. (forward-line))
  1130. ;; check, if there really is a table
  1131. (unless (org-at-table-p)
  1132. (org-index--create-missing-index "Cannot find %s." errstring))
  1133. ;; go just after hline
  1134. (while (and (not (org-at-table-hline-p))
  1135. (org-at-table-p))
  1136. (forward-line))
  1137. (forward-line)
  1138. ;; and check
  1139. (unless (org-at-table-p)
  1140. (org-index--report-index-error "Cannot find a hline within %s" errstring))
  1141. (org-table-goto-column 1)
  1142. (setq org-index--below-hline (point))))
  1143. (defun org-index--parse-headings ()
  1144. "Parse headings of index table."
  1145. (let (field ;; field content
  1146. field-symbol ;; and as a symbol
  1147. found)
  1148. (setq org-index--columns nil)
  1149. ;; For each column
  1150. (dotimes (col org-index--numcols)
  1151. (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
  1152. (if (string= field "")
  1153. (error "Heading of column cannot be empty"))
  1154. (if (and (not (string= (substring field 0 1) "."))
  1155. (not (member (intern field) org-index--valid-headings)))
  1156. (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field))
  1157. (setq field-symbol (intern field))
  1158. ;; check if heading has already appeared
  1159. (if (assoc field-symbol org-index--columns)
  1160. (org-index--report-index-error
  1161. "'%s' appears two times as column heading" (downcase field))
  1162. ;; add it to list at front, reverse later
  1163. (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
  1164. (setq org-index--columns (reverse org-index--columns))
  1165. ;; check if all necessary headings have appeared
  1166. (mapc (lambda (head)
  1167. (unless (cdr (assoc head org-index--columns))
  1168. (org-index--report-index-error "No column has heading '%s'" head)))
  1169. org-index--valid-headings))
  1170. (defun org-index--create-missing-index (&rest reasons)
  1171. "Create a new empty index table with detailed explanation. Argument REASONS explains why."
  1172. (org-index--ask-before-create-index "Cannot find index table: "
  1173. "new permanent" "."
  1174. reasons)
  1175. (org-index--create-index))
  1176. (defun org-index--report-index-error (&rest reasons)
  1177. "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
  1178. (when org-index--buffer
  1179. (pop-to-buffer-same-window org-index--buffer)
  1180. (goto-char org-index--below-hline)
  1181. (org-reveal t))
  1182. (org-index--ask-before-create-index "The existing index contains this error: "
  1183. "temporary" ", to compare with."
  1184. reasons)
  1185. (org-index--create-index t t))
  1186. (defun org-index--ask-before-create-index (explanation type for-what reasons)
  1187. ; checkdoc-params: (explanation type for-what reasons)
  1188. "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
  1189. (let (reason prompt)
  1190. (setq reason (apply 'format reasons))
  1191. (setq prompt (concat explanation reason "\n\n"
  1192. "However, this assistant can help you to create a "
  1193. type " index with detailed comments" for-what "\n\n"
  1194. "Do you want to proceed ?"))
  1195. (unless (let ((max-mini-window-height 1.0))
  1196. (y-or-n-p prompt))
  1197. (error (concat explanation reason)))))
  1198. (defun org-index--create-index (&optional temporary compare)
  1199. "Create a new empty index table with detailed explanation.
  1200. specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
  1201. (let (buffer
  1202. title
  1203. firstref
  1204. id
  1205. with-explanation)
  1206. (if temporary
  1207. (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
  1208. (buffer-name "*org-index-example-index*"))
  1209. (setq buffer (get-buffer-create buffer-name))
  1210. (with-current-buffer buffer
  1211. ;; but it needs a file for its index to be found
  1212. (unless (string= (buffer-file-name) file-name)
  1213. (set-visited-file-name file-name))
  1214. (rename-buffer buffer-name) ; name is change by line above
  1215. (erase-buffer)
  1216. (org-mode)))
  1217. (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))))))
  1218. (setq title (read-from-minibuffer "Please enter the title of the index node: "))
  1219. (while (progn
  1220. (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 frequently within your existing notes, to avoid too many false hits when searching.\n\nPlease choose: "))
  1221. (let (desc)
  1222. (when (string-match "[[:blank:]]" firstref)
  1223. (setq desc "Contains whitespace"))
  1224. (when (string-match "[[:cntrl:]]" firstref)
  1225. (setq desc "Contains control characters"))
  1226. (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
  1227. ;; firstref not okay, report details
  1228. (setq desc
  1229. (cond ((string= firstref "") "is empty")
  1230. ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
  1231. ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
  1232. ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
  1233. )))
  1234. (if desc
  1235. (progn
  1236. (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
  1237. t)
  1238. nil))))
  1239. (setq with-explanation (y-or-n-p "Do you want an explanation within your index-table (can later be removed easily) ? "))
  1240. (with-current-buffer buffer
  1241. (goto-char (point-max))
  1242. (insert (format "* %s %s\n" firstref title))
  1243. (when with-explanation
  1244. (if temporary
  1245. (insert "
  1246. Below you find your temporary index table, which WILL NOT LAST LONGER
  1247. THAN YOUR CURRENT EMACS SESSION; please use it only for evaluation.
  1248. ")
  1249. (insert "
  1250. Below you find your initial index table, which will grow over time.
  1251. "))
  1252. (insert " You may start using it by adding some lines. Just
  1253. move to another heading within org, invoke `org-index' and
  1254. choose the command 'add'. After adding a few nodes, try the
  1255. command 'occur' to search among them.
  1256. To gain further insight you may invoke the subcommand 'help', or
  1257. (same content) read the help of `org-index'.
  1258. Within the index table below, the sequence of columns does not
  1259. matter. You may reorder them in any way you like. You may also
  1260. add your own columns, which should start with a dot
  1261. (e.g. '.my-column').
  1262. Invoke `org-customize' to tweak the behaviour of org-index
  1263. (see the group org-index).
  1264. This node needs not be a top level node; its name is completely
  1265. at your choice; it is found through its ID only.
  1266. ")
  1267. (unless temporary
  1268. (insert "
  1269. Remark: These lines of explanation can be removed at any time.
  1270. ")))
  1271. (setq id (org-id-get-create))
  1272. (insert (format "
  1273. | ref | category | keywords | tags | count | level | last-accessed | created | id | yank |
  1274. | | | | | | | | | <4> | <4> |
  1275. |-----+----------+----------+------+-------+-------+---------------+---------+-----+------|
  1276. | %s | | %s | | | | | %s | %s | |
  1277. "
  1278. firstref
  1279. title
  1280. (with-temp-buffer (org-insert-time-stamp nil nil t))
  1281. id))
  1282. ;; make sure, that node can be found
  1283. (org-id-add-location id (buffer-file-name))
  1284. (setq buffer-save-without-query t)
  1285. (basic-save-buffer)
  1286. (while (not (org-at-table-p)) (forward-line -1))
  1287. (unless buffer-read-only (org-table-align))
  1288. (while (not (org-at-heading-p)) (forward-line -1))
  1289. ;; read back some info about new index
  1290. (let ((org-index-id id))
  1291. (org-index--verify-id))
  1292. ;; remember at least for this session
  1293. (setq org-index-id id)
  1294. ;; present results to user
  1295. (if temporary
  1296. (progn
  1297. ;; Present existing and temporary index together
  1298. (when compare
  1299. (pop-to-buffer-same-window org-index--buffer)
  1300. (goto-char org-index--point)
  1301. (org-index--unfold-buffer)
  1302. (delete-other-windows)
  1303. (select-window (split-window-vertically)))
  1304. ;; show new index
  1305. (pop-to-buffer-same-window buffer)
  1306. (org-id-goto id)
  1307. (org-index--unfold-buffer)
  1308. (if compare
  1309. (progn
  1310. (message "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
  1311. (throw 'new-index nil))
  1312. (message "This is your new temporary index, use command add to populate, occur to search.")))
  1313. (progn
  1314. ;; Only show the new index
  1315. (pop-to-buffer-same-window buffer)
  1316. (delete-other-windows)
  1317. (org-id-goto id)
  1318. (org-index--unfold-buffer)
  1319. (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 ? ")
  1320. (progn
  1321. (customize-save-variable 'org-index-id id)
  1322. (message "Saved org-index-id '%s' to %s" id (or custom-file
  1323. user-init-file))
  1324. (throw 'new-index nil))
  1325. (let (sq)
  1326. (setq sq (format "(setq org-index-id \"%s\")" id))
  1327. (kill-new sq)
  1328. (message "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)
  1329. (throw 'new-index nil))))))))
  1330. (defun org-index--unfold-buffer ()
  1331. "Helper function to unfold buffer."
  1332. (org-show-context)
  1333. (org-show-subtree)
  1334. (recenter 1)
  1335. (save-excursion
  1336. (org-back-to-heading)
  1337. (forward-line) ;; on property drawer
  1338. (org-cycle)))
  1339. (defun org-index--update-line (&optional ref-or-id-or-pos)
  1340. "Update columns count and last-accessed in line REF-OR-ID-OR-POS."
  1341. (let ((newcount 0)
  1342. initial)
  1343. (with-current-buffer org-index--buffer
  1344. (unless buffer-read-only
  1345. ;; search reference or id, if given (or assume, that we are already positioned right)
  1346. (when ref-or-id-or-pos
  1347. (setq initial (point))
  1348. (goto-char org-index--below-hline)
  1349. (while (and (org-at-table-p)
  1350. (not (if (integerp ref-or-id-or-pos)
  1351. (and (>= ref-or-id-or-pos (line-beginning-position))
  1352. (< ref-or-id-or-pos (line-end-position)))
  1353. (or (string= ref-or-id-or-pos (org-index--get-or-set-field 'ref))
  1354. (string= ref-or-id-or-pos (org-index--get-or-set-field 'id))))))
  1355. (forward-line)))
  1356. (if (not (org-at-table-p))
  1357. (error "Did not find reference or id '%s'" ref-or-id-or-pos)
  1358. (org-index--update-current-line))
  1359. (if initial (goto-char initial))))))
  1360. (defun org-index--update-current-line ()
  1361. "Update current lines columns count and last-accessed."
  1362. (let (newcount (count-field (org-index--get-or-set-field 'count)))
  1363. ;; update count field only if number or empty
  1364. (when (or (not count-field)
  1365. (string-match "^[0-9]+$" count-field))
  1366. (setq newcount (+ 1 (string-to-number (or count-field "0"))))
  1367. (org-index--get-or-set-field 'count
  1368. (number-to-string newcount)))
  1369. ;; update timestamp
  1370. (org-table-goto-column (org-index--column-num 'last-accessed))
  1371. (org-table-blank-field)
  1372. (org-insert-time-stamp nil t t)
  1373. ;; move line according to new content
  1374. (org-index--promote-current-line)
  1375. (org-index--align-and-fontify-current-line)))
  1376. (defun org-index--align-and-fontify-current-line (&optional num)
  1377. "Make current line (or NUM lines) blend well among others."
  1378. (let (lines)
  1379. ;; get current content
  1380. (unless num (setq num 1))
  1381. (setq lines (delete-and-extract-region (line-beginning-position) (line-end-position num)))
  1382. ;; create minimum table with fixed-width columns to align and fontify new line
  1383. (insert (with-temp-buffer
  1384. (org-set-font-lock-defaults)
  1385. (insert org-index--headings-visible)
  1386. ;; fill columns, so that aligning cannot shrink them
  1387. (goto-char (point-min))
  1388. (search-forward "|")
  1389. (while (search-forward " " (line-end-position) t)
  1390. (replace-match "." nil t))
  1391. (goto-char (point-min))
  1392. (while (search-forward ".|." (line-end-position) t)
  1393. (replace-match " | " nil t))
  1394. (goto-char (point-min))
  1395. (while (search-forward "|." (line-end-position) t)
  1396. (replace-match "| " nil t))
  1397. (goto-char (point-max))
  1398. (insert lines)
  1399. (forward-line 0)
  1400. (let ((start (point)))
  1401. (while (re-search-forward "^\s +|-" nil t)
  1402. (replace-match "| -"))
  1403. (goto-char start))
  1404. (org-mode)
  1405. (org-table-align)
  1406. (font-lock-fontify-region (point-min) (point-max))
  1407. (goto-char (point-max))
  1408. (if (eq -1 (skip-chars-backward "\n"))
  1409. (delete-char 1))
  1410. (forward-line (- 1 num))
  1411. (buffer-substring (line-beginning-position) (line-end-position num))))
  1412. lines))
  1413. (defun org-index--promote-current-line ()
  1414. "Move current line up in table according to changed sort fields."
  1415. (let (begin end key
  1416. (to-skip 0))
  1417. (forward-line 0) ; stay at beginning of line
  1418. (setq key (org-index--get-sort-key))
  1419. (setq begin (point))
  1420. (setq end (line-beginning-position 2))
  1421. (forward-line -1)
  1422. (while (and (org-at-table-p)
  1423. (not (org-at-table-hline-p))
  1424. (string< (org-index--get-sort-key) key))
  1425. (cl-incf to-skip)
  1426. (forward-line -1))
  1427. (forward-line 1)
  1428. ;; insert line at new position
  1429. (when (> to-skip 0)
  1430. (insert (delete-and-extract-region begin end))
  1431. (forward-line -1))))
  1432. (defun org-index--get-sort-key (&optional sort with-ref mixed-time)
  1433. "Get value for sorting from column SORT, optional WITH-REF; if mixes use MIXED-TIME."
  1434. (let (ref
  1435. ref-field
  1436. key)
  1437. (unless sort (setq sort org-index--last-sort)) ; use default value
  1438. (when (or with-ref
  1439. (eq sort 'ref))
  1440. ;; get reference with leading zeroes, so it can be
  1441. ;; sorted as text
  1442. (setq ref-field (org-index--get-or-set-field 'ref))
  1443. (if ref-field
  1444. (progn
  1445. (string-match org-index--ref-regex ref-field)
  1446. (setq ref (format
  1447. "%06d"
  1448. (string-to-number
  1449. (match-string 1 ref-field)))))
  1450. (setq ref "000000")))
  1451. (setq key
  1452. (cond
  1453. ((eq sort 'count)
  1454. (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))
  1455. ((eq sort 'mixed)
  1456. (let ((last-accessed (org-index--get-or-set-field 'last-accessed)))
  1457. (unless mixed-time (setq mixed-time (org-index--get-mixed-time)))
  1458. (concat
  1459. (if (string< mixed-time last-accessed) last-accessed mixed-time)
  1460. (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))))
  1461. ((eq sort 'ref)
  1462. ref)
  1463. ((memq sort '(id last-accessed created))
  1464. (org-index--get-or-set-field sort))
  1465. (t (error "This is a bug: unmatched case '%s'" sort))))
  1466. (if with-ref (setq key (concat key ref)))
  1467. key))
  1468. (defun org-index--get-or-set-field (key &optional value)
  1469. "Retrieve field KEY from index table or set it to VALUE."
  1470. (let (field)
  1471. (save-excursion
  1472. (if (eq key 'fingerprint)
  1473. (progn
  1474. (if value (error "Internal error, pseudo-column fingerprint cannot be set"))
  1475. (setq field (org-index--get-fingerprint)))
  1476. (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value))))
  1477. (if (string= field "") (setq field nil))
  1478. (org-no-properties field))))
  1479. (defun org-index--column-num (key)
  1480. "Return number of column KEY."
  1481. (if (numberp key)
  1482. key
  1483. (cdr (assoc key org-index--columns))))
  1484. (defun org-index--make-guarded-search (ref &optional dont-quote)
  1485. "Make robust search string from REF; DONT-QUOTE it, if requested."
  1486. (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
  1487. (defun org-index--find-duplicates ()
  1488. "Find duplicate references or ids in index table."
  1489. (let (ref-duplicates id-duplicates message)
  1490. (setq ref-duplicates (org-index--find-duplicates-helper 'ref))
  1491. (setq id-duplicates (org-index--find-duplicates-helper 'id))
  1492. (goto-char org-index--below-hline)
  1493. (if (or ref-duplicates id-duplicates)
  1494. (progn
  1495. ;; show results
  1496. (pop-to-buffer-same-window
  1497. (get-buffer-create "*org-index-duplicates*"))
  1498. (when ref-duplicates
  1499. (insert "These references appear more than once:\n")
  1500. (mapc (lambda (x) (insert " " x "\n")) ref-duplicates)
  1501. (insert "\n\n"))
  1502. (when id-duplicates
  1503. (insert "These ids appear more than once:\n")
  1504. (mapc (lambda (x) (insert " " x "\n")) id-duplicates))
  1505. "Some references or ids are duplicates")
  1506. "No duplicate references or ids found")))
  1507. (defun org-index--find-duplicates-helper (column)
  1508. "Helper for `org-index--find-duplicates': Go through table and count given COLUMN."
  1509. (let (counts duplicates field found)
  1510. ;; go through table
  1511. (goto-char org-index--below-hline)
  1512. (while (org-at-table-p)
  1513. ;; get column
  1514. (setq field (org-index--get-or-set-field column))
  1515. ;; and increment
  1516. (setq found (assoc field counts))
  1517. (if found
  1518. (cl-incf (cdr found))
  1519. (setq counts (cons (cons field 1) counts)))
  1520. (forward-line))
  1521. (mapc (lambda (x) (if (and (> (cdr x) 1)
  1522. (car x))
  1523. (setq duplicates (cons (car x) duplicates)))) counts)
  1524. duplicates))
  1525. (defun org-index--do-statistics ()
  1526. "Compute statistics about index table."
  1527. (let ((total-lines 0) (total-refs 0)
  1528. ref ref-field min max message)
  1529. ;; go through table
  1530. (goto-char org-index--below-hline)
  1531. (while (org-at-table-p)
  1532. ;; get ref
  1533. (setq ref-field (org-index--get-or-set-field 'ref))
  1534. (when ref-field
  1535. (string-match org-index--ref-regex ref-field)
  1536. (setq ref (string-to-number (match-string 1 ref-field)))
  1537. ;; record min and max
  1538. (if (or (not min) (< ref min)) (setq min ref))
  1539. (if (or (not max) (> ref max)) (setq max ref))
  1540. (setq total-refs (1+ total-refs)))
  1541. ;; count
  1542. (setq total-lines (1+ total-lines))
  1543. (forward-line))
  1544. (setq message (format "%d Lines in index table. First reference is %s, last %s; %d of them are used (%d percent)"
  1545. total-lines
  1546. (format org-index--ref-format min)
  1547. (format org-index--ref-format max)
  1548. total-refs
  1549. (truncate (* 100 (/ (float total-refs) (1+ (- max min)))))))
  1550. (goto-char org-index--below-hline)
  1551. message))
  1552. (defun org-index--do-add-or-update (&optional create-ref tag-with-ref)
  1553. "For current node or current line in index, add a new line to index table or update existing."
  1554. (let* (id id-from-index ref args yank)
  1555. ;; do the same things from within index and from outside
  1556. (if org-index--within-node
  1557. (progn
  1558. (unless (org-at-table-p)
  1559. (error "Within index node but not on table"))
  1560. (setq id (org-index--get-or-set-field 'id))
  1561. (setq ref (org-index--get-or-set-field 'ref))
  1562. (setq args (org-index--collect-values-for-add-update-remote id))
  1563. (org-index--write-fields args)
  1564. (setq yank (org-index--get-or-set-field org-index-yank-after-add))
  1565. (if ref
  1566. (cons (format "Updated index line %s" ref) yank)
  1567. (cons "Updated index line" nil)))
  1568. (unless (org-at-heading-p)
  1569. (error "Not at headline"))
  1570. (setq id (org-id-get-create))
  1571. (org-index--refresh-parse-table)
  1572. (setq id-from-index (org-index--on 'id id id))
  1573. (setq ref (org-index--on 'id id (org-index--get-or-set-field 'ref)))
  1574. (if tag-with-ref
  1575. (org-toggle-tag (format "%s%d%s" org-index--head tag-with-ref org-index--tail) 'on))
  1576. (setq args (org-index--collect-values-for-add-update id))
  1577. (when (and create-ref
  1578. (not ref))
  1579. (setq ref org-index--nextref)
  1580. (setq args (plist-put args 'ref ref)))
  1581. (if id-from-index
  1582. ;; already have an id in index, find it and update fields
  1583. (let (found-and-message)
  1584. (org-index--on
  1585. 'id id
  1586. (org-index--write-fields args)
  1587. (setq yank (org-index--get-or-set-field org-index-yank-after-add)))
  1588. (if ref
  1589. (cons (format "Updated index line %s" ref) yank)
  1590. (cons "Updated index line" nil)))
  1591. ;; no id here, create new line in index
  1592. (if ref (setq ref (plist-put args 'ref org-index--nextref)))
  1593. (setq yank (apply 'org-index--do-new-line args))
  1594. (if ref
  1595. (cons
  1596. (format "Added new index line %s" ref)
  1597. (concat yank " "))
  1598. (cons
  1599. "Added new index line"
  1600. nil))))))
  1601. (defun org-index--check-ids ()
  1602. "Check, that ids really point to a node."
  1603. (let ((lines 0)
  1604. id ids marker)
  1605. (goto-char org-index--below-hline)
  1606. (catch 'problem
  1607. (while (org-at-table-p)
  1608. (when (setq id (org-index--get-or-set-field 'id))
  1609. ;; check for double ids
  1610. (when (member id ids)
  1611. (org-table-goto-column (org-index--column-num 'id))
  1612. (throw 'problem "This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
  1613. (cl-incf lines)
  1614. (setq ids (cons id ids))
  1615. ;; check, if id is valid
  1616. (setq marker (org-id-find id t))
  1617. (unless marker
  1618. (org-table-goto-column (org-index--column-num 'id))
  1619. (throw 'problem "This id cannot be found")))
  1620. (forward-line))
  1621. (goto-char org-index--below-hline)
  1622. nil)))
  1623. (defun org-index--update-all-lines ()
  1624. "Update all lines of index at once."
  1625. (let ((lines 0)
  1626. id ref kvs)
  1627. ;; check for double ids
  1628. (or
  1629. (org-index--check-ids)
  1630. (progn
  1631. (goto-char org-index--below-hline)
  1632. (while (org-at-table-p)
  1633. ;; update single line
  1634. (when (setq id (org-index--get-or-set-field 'id))
  1635. (setq ref (org-index--get-or-set-field 'ref))
  1636. (setq kvs (org-index--collect-values-for-add-update-remote id))
  1637. (org-index--write-fields kvs)
  1638. (cl-incf lines))
  1639. (forward-line))
  1640. (goto-char org-index--below-hline)
  1641. (org-table-align)
  1642. (format "Updated %d lines" lines)))))
  1643. (defun org-index--collect-values-for-add-update (id &optional silent category)
  1644. "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
  1645. (let ((args (list 'id id))
  1646. content)
  1647. (dolist (col (mapcar 'car org-index--columns))
  1648. (setq content "")
  1649. (cond
  1650. ((eq col 'keywords)
  1651. (if org-index-copy-heading-to-keywords
  1652. (setq content (nth 4 (org-heading-components))))
  1653. ;; Shift ref and timestamp ?
  1654. (if org-index-strip-ref-and-date-from-heading
  1655. (dotimes (i 2)
  1656. (if (or (string-match (concat "^\\s-*" org-index--ref-regex) content)
  1657. (string-match (concat org-ts-regexp-both) content))
  1658. (setq content (substring content (match-end 0)))))))
  1659. ((eq col 'category)
  1660. (setq content (or category org-index--category-before)))
  1661. ((eq col 'level)
  1662. (setq content (number-to-string (org-outline-level))))
  1663. ((eq col 'tags)
  1664. (setq content (org-get-tags-string))))
  1665. (unless (string= content "")
  1666. (setq args (plist-put args col content))))
  1667. (if (not silent)
  1668. (let ((args-edited (org-index--collect-values-from-user org-index-edit-on-add args)))
  1669. (setq args (append args-edited args))))
  1670. args))
  1671. (defun org-index--collect-values-for-add-update-remote (id)
  1672. "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
  1673. (let (marker point args)
  1674. (setq marker (org-id-find id t))
  1675. ;; enter buffer and collect information
  1676. (with-current-buffer (marker-buffer marker)
  1677. (setq point (point))
  1678. (goto-char marker)
  1679. (setq args (org-index--collect-values-for-add-update id t (org-get-category (point) t)))
  1680. (goto-char point))
  1681. args))
  1682. (defun org-index--collect-values-from-user (list-of-columns-to-edit &optional default-values)
  1683. "Collect values for adding a new yank-line."
  1684. (let (content args)
  1685. (dolist (col list-of-columns-to-edit)
  1686. (setq content "")
  1687. (setq content (read-from-minibuffer
  1688. (format "Enter text for column '%s': " (symbol-name col))
  1689. (plist-get col default-values)))
  1690. (unless (string= content "")
  1691. (setq args (plist-put args col content))))
  1692. args))
  1693. (defun org-index--write-fields (kvs)
  1694. "Update current line with values from KVS (keys-values)."
  1695. (while kvs
  1696. (org-index--get-or-set-field (car kvs) (org-trim (cadr kvs)))
  1697. (setq kvs (cddr kvs))))
  1698. (defun org-index--do-kill ()
  1699. "Perform command kill from within occur, index or node."
  1700. (let (id ref pos chars-deleted-index text-deleted-from pos-in-index)
  1701. (org-index--check-can-edit-or-kill "kill")
  1702. (setq pos (org-index--save-positions))
  1703. ;; Collect information: What should be deleted ?
  1704. (if (or org-index--within-occur
  1705. org-index--within-node)
  1706. (progn
  1707. (if org-index--within-node
  1708. ;; In index
  1709. (setq pos-in-index (point))
  1710. ;; In occur
  1711. (setq pos-in-index (get-text-property (point) 'org-index-lbp))
  1712. (org-index--occur-test-stale pos-in-index)
  1713. (set-buffer org-index--buffer)
  1714. (goto-char pos-in-index))
  1715. ;; In Index (maybe moved there)
  1716. (setq id (org-index--get-or-set-field 'id))
  1717. (setq ref (org-index--get-or-set-field 'ref)))
  1718. ;; At a headline
  1719. (setq id (org-entry-get (point) "ID"))
  1720. (setq ref (org-index--ref-from-id id))
  1721. (setq pos-in-index (org-index--on 'id id
  1722. (setq point-in-index (point))))
  1723. (unless pos-in-index (error "This node is not in index")))
  1724. ;; Remark: Current buffer is not certain here, but we have all the information to delete
  1725. ;; Delete from node
  1726. (when id
  1727. (let ((m (org-id-find id 'marker)))
  1728. (set-buffer (marker-buffer m))
  1729. (goto-char m)
  1730. (move-marker m nil)
  1731. (unless (string= (org-id-get) id)
  1732. (error "Could not find node with id %s" id)))
  1733. (org-index--delete-any-ref-from-tags)
  1734. (if ref (org-index--delete-ref-from-heading ref))
  1735. (setq text-deleted-from (cons "node" text-deleted-from)))
  1736. ;; Delete from index
  1737. (set-buffer org-index--buffer)
  1738. (unless pos-in-index "Internal error, pos-in-index should be defined here")
  1739. (goto-char pos-in-index)
  1740. (setq chars-deleted-index (length (delete-and-extract-region (line-beginning-position) (line-beginning-position 2))))
  1741. (setq text-deleted-from (cons "index" text-deleted-from))
  1742. ;; Delete from occur only if we started there, accept that it will be stale otherwise
  1743. (if org-index--within-occur
  1744. (let ((inhibit-read-only t))
  1745. (set-buffer org-index--occur-buffer-name)
  1746. (delete-region (line-beginning-position) (line-beginning-position 2))
  1747. ;; correct positions
  1748. (while (org-at-table-p)
  1749. (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp
  1750. (- (get-text-property (point) 'org-index-lbp) chars-deleted-index))
  1751. (forward-line))
  1752. (setq text-deleted-from (cons "occur" text-deleted-from))))
  1753. (org-index--restore-positions pos)
  1754. (concat "Deleted from: " (mapconcat 'identity (sort text-deleted-from 'string<) ","))))
  1755. (defun org-index--save-positions ()
  1756. "Save current buffer and positions in index and node; not occur."
  1757. (let (buf pn pi)
  1758. (setq buf (current-buffer))
  1759. (setq pn (point)) ; not guaranteed to be on node
  1760. (set-buffer org-index--buffer)
  1761. (setq pi (point))
  1762. (set-buffer buf)
  1763. (list buf pn pi)))
  1764. (defun org-index--restore-positions (pos)
  1765. "Restore positions as saved by `org-index--save-positions'."
  1766. (let (buf)
  1767. (setq buf (current-buffer))
  1768. (set-buffer (first pos))
  1769. (goto-char (second pos))
  1770. (set-buffer org-index--buffer)
  1771. (goto-char (third pos))
  1772. (set-buffer buf)))
  1773. (defun org-index--check-can-edit-or-kill (what)
  1774. "Check, if edit or kill can be performed for current position."
  1775. (when (not (or (org-at-heading-p)
  1776. (and (org-at-table-p)
  1777. (or org-index--within-occur
  1778. org-index--within-node))))
  1779. (if (not (org-at-table-p)) (error "Cannot %s: Not at table" what))
  1780. (if (not (org-at-heading-p)) (error "Cannot %s: Not at headline" what))
  1781. (error "Cannot %s: Neither in index nor in occur buffer" what)))
  1782. (defun org-index--delete-ref-from-heading (ref)
  1783. "Delete given REF from current heading"
  1784. (save-excursion
  1785. (end-of-line)
  1786. (let ((end (point)))
  1787. (beginning-of-line)
  1788. (when (search-forward ref end t)
  1789. (delete-char (- (length ref)))
  1790. (just-one-space)))))
  1791. (defun org-index--delete-any-ref-from-tags ()
  1792. "Delete any reference from list of tags"
  1793. (let (new-tags)
  1794. (mapc (lambda (tag)
  1795. (unless (string-match org-index--ref-regex tag)
  1796. (setq new-tags (cons tag new-tags) )))
  1797. (org-get-tags))
  1798. (org-set-tags-to new-tags)))
  1799. (defun org-index--go (&optional column value)
  1800. "Position cursor on index line where COLUMN equals VALUE.
  1801. Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
  1802. (let (found text)
  1803. (unless (eq (current-buffer) org-index--buffer)
  1804. (error "This is a bug: Not in index buffer"))
  1805. ;; loop over lines
  1806. (goto-char org-index--below-hline)
  1807. (if column
  1808. (progn
  1809. (forward-line -1)
  1810. (while (and (not found)
  1811. (forward-line)
  1812. (org-at-table-p))
  1813. (setq found (string= value (org-index--get-or-set-field column)))))
  1814. (setq found t))
  1815. ;; return value
  1816. (if found
  1817. t
  1818. (goto-char org-index--below-hline)
  1819. nil)))
  1820. (defun org-index--find-id (id &optional other)
  1821. "Perform command head: Find node with REF or ID and present it.
  1822. If OTHER in separate window."
  1823. (let (message marker)
  1824. (setq marker (org-id-find id t))
  1825. (if marker
  1826. (progn
  1827. (org-index--update-line id)
  1828. (if other
  1829. (progn
  1830. (pop-to-buffer (marker-buffer marker)))
  1831. (pop-to-buffer-same-window (marker-buffer marker)))
  1832. (goto-char marker)
  1833. (org-reveal t)
  1834. (org-show-entry)
  1835. (recenter)
  1836. (unless (string= (org-id-get) id)
  1837. (setq message "Could not go to node with id %s (narrowed ?)" id))
  1838. (setq message "Found headline"))
  1839. (setq message (format "Did not find node with %s" id)))
  1840. message))
  1841. (defun org-index--do-occur ()
  1842. "Perform command occur."
  1843. (let ((word "") ; last word to search for growing and shrinking on keystrokes
  1844. (prompt "Search for: ")
  1845. (these-commands "These commands of org-index, if invoked from the occur buffer, update it accordingly: edit, kill.")
  1846. (lines-wanted (window-body-height))
  1847. (lines-found 0) ; number of lines found
  1848. words ; list words that should match
  1849. occur-buffer
  1850. begin ; position of first line
  1851. narrow ; start of narrowed buffer
  1852. help-text ; cons with help text short and long
  1853. key-help ; for keys with special function
  1854. search-text ; description of text to search for
  1855. done ; true, if loop is done
  1856. in-c-backspace ; true, while processing C-backspace
  1857. show-headings ; true, if headings should be shown
  1858. help-overlay ; Overlay with help text
  1859. last-point ; Last position before end of search
  1860. initial-frame ; Frame when starting occur
  1861. key ; input from user in various forms
  1862. key-sequence
  1863. key-sequence-raw)
  1864. ;; make and show buffer
  1865. (if (get-buffer org-index--occur-buffer-name)
  1866. (kill-buffer org-index--occur-buffer-name))
  1867. (setq occur-buffer (make-indirect-buffer org-index--buffer org-index--occur-buffer-name))
  1868. (pop-to-buffer-same-window occur-buffer)
  1869. (setq initial-frame (selected-frame))
  1870. ;; avoid modifying direct buffer
  1871. (setq buffer-read-only t)
  1872. (toggle-truncate-lines 1)
  1873. (setq font-lock-keywords-case-fold-search t)
  1874. (setq case-fold-search t)
  1875. ;; reset stack and overlays
  1876. (setq org-index--occur-stack nil)
  1877. (setq org-index--occur-tail-overlay nil)
  1878. ;; narrow to table rows and one line before
  1879. (goto-char org-index--below-hline)
  1880. (forward-line 0)
  1881. (setq begin (point))
  1882. (forward-line -1)
  1883. (setq narrow (point))
  1884. (while (org-at-table-p)
  1885. (forward-line))
  1886. (narrow-to-region narrow (point))
  1887. (goto-char (point-min))
  1888. (forward-line)
  1889. ;; initialize help text
  1890. (setq help-text (cons
  1891. (concat
  1892. (propertize "Incremental occur" 'face 'org-todo)
  1893. (propertize "; `?' toggles help and headlines.\n" 'face 'org-agenda-dimmed-todo-face))
  1894. (concat
  1895. (propertize
  1896. (org-index--wrap
  1897. (concat
  1898. "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, <S-return> jumps to matching line in index; all other keys end search." these-commands "\n"))
  1899. 'face 'org-agenda-dimmed-todo-face)
  1900. org-index--headings)))
  1901. ;; insert overlays for help text and to cover unsearched lines
  1902. (setq help-overlay (make-overlay (point-min) begin))
  1903. (overlay-put help-overlay 'display (car help-text))
  1904. (setq org-index--occur-tail-overlay (make-overlay (point-max) (point-max)))
  1905. (overlay-put org-index--occur-tail-overlay 'invisible t)
  1906. (while (not done)
  1907. (if in-c-backspace
  1908. (setq key "<backspace>")
  1909. (setq search-text (mapconcat 'identity (reverse (cons word words)) ","))
  1910. (message "foo")
  1911. ;; read key, if selected frame has not changed
  1912. (if (eq initial-frame (selected-frame))
  1913. (progn
  1914. (setq key-sequence
  1915. (let ((echo-keystrokes 0)
  1916. (full-prompt (format "%s%s%s"
  1917. prompt
  1918. search-text
  1919. (if (string= search-text "") "" " "))))
  1920. (read-key-sequence full-prompt nil nil t t)))
  1921. (setq key (key-description key-sequence))
  1922. (setq key-sequence-raw (this-single-command-raw-keys)))
  1923. (setq done t)
  1924. (setq key-sequence nil)
  1925. (setq key nil)
  1926. (setq key-sequence-raw nil)))
  1927. (cond
  1928. ((string= key "<C-backspace>")
  1929. (setq in-c-backspace t))
  1930. ((member key (list "<backspace>" "DEL")) ; erase last char
  1931. (if (= (length word) 0)
  1932. ;; nothing more to delete from current word; try next
  1933. (progn
  1934. (setq word (car words))
  1935. (setq words (cdr words))
  1936. (setq in-c-backspace nil))
  1937. ;; unhighlight longer match
  1938. (unhighlight-regexp (regexp-quote word))
  1939. ;; some chars are left; shorten word
  1940. (setq word (substring word 0 -1))
  1941. (when (= (length word) 0) ; when nothing left, use next word from list
  1942. (setq word (car words))
  1943. (setq words (cdr words))
  1944. (setq in-c-backspace nil))
  1945. ;; free top list of overlays and remove list
  1946. (setq lines-found (or (org-index--unhide) lines-wanted))
  1947. (move-overlay org-index--occur-tail-overlay
  1948. (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
  1949. (point-max))
  1950. (point-max))
  1951. ;; highlight shorter word
  1952. (unless (= (length word) 0)
  1953. (highlight-regexp (regexp-quote word) 'isearch))
  1954. ;; make sure, point is still visible
  1955. (goto-char begin)))
  1956. ((member key (list "SPC" ",")) ; space or comma: enter an additional search word
  1957. ;; push current word and clear, no need to change display
  1958. (unless (string= word "")
  1959. (setq words (cons word words))
  1960. (setq word "")))
  1961. ((string= key "?") ; question mark: toggle display of headlines and help
  1962. (setq help-text (cons (cdr help-text) (car help-text)))
  1963. (overlay-put help-overlay 'display (car help-text)))
  1964. ((and (= (length key) 1)
  1965. (aref printable-chars (elt key 0))) ; any printable char: add to current search word
  1966. ;; unhighlight short word
  1967. (unless (= (length word) 0)
  1968. (unhighlight-regexp (regexp-quote word)))
  1969. ;; add to word
  1970. (setq word (concat word key))
  1971. ;; make overlays to hide lines, that do not match longer word any more
  1972. (goto-char begin)
  1973. (setq lines-found (org-index--hide-with-overlays (cons word words) lines-wanted))
  1974. (move-overlay org-index--occur-tail-overlay
  1975. (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
  1976. (point-max))
  1977. (point-max))
  1978. (goto-char begin)
  1979. ;; highlight longer word
  1980. (highlight-regexp (regexp-quote word) 'isearch)
  1981. ;; make sure, point is on a visible line
  1982. (line-move -1 t)
  1983. (line-move 1 t))
  1984. ;; anything else terminates loop
  1985. (t (setq done t))))
  1986. ;; put back input event, that caused the loop to end
  1987. (unless (string= key "C-g")
  1988. (setq unread-command-events (listify-key-sequence key-sequence-raw))
  1989. (message key))
  1990. ;; postprocessing
  1991. (setq last-point (point))
  1992. ;; For performance reasons do not show matching lines for rest of table. So no code here.
  1993. ;; make permanent copy
  1994. ;; copy visible lines
  1995. (let ((lines-collected 0)
  1996. keymap line all-lines all-lines-lbp header-lines lbp)
  1997. (setq cursor-type t)
  1998. (goto-char begin)
  1999. ;; collect all visible lines
  2000. (while (and (not (eobp))
  2001. (< lines-collected lines-wanted))
  2002. ;; skip over invisible lines
  2003. (while (and (invisible-p (point))
  2004. (not (eobp)))
  2005. (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
  2006. (setq lbp (line-beginning-position))
  2007. (setq line (buffer-substring-no-properties lbp (line-end-position)))
  2008. (unless (string= line "")
  2009. (cl-incf lines-collected)
  2010. (setq all-lines (cons (concat line
  2011. "\n")
  2012. all-lines))
  2013. (setq all-lines-lbp (cons lbp all-lines-lbp)))
  2014. (forward-line 1))
  2015. (kill-buffer org-index--occur-buffer-name) ; cannot keep this buffer; might become stale soon
  2016. ;; create new buffer
  2017. (setq occur-buffer (get-buffer-create org-index--occur-buffer-name))
  2018. (pop-to-buffer-same-window occur-buffer)
  2019. (insert org-index--headings)
  2020. (setq header-lines (line-number-at-pos))
  2021. ;; insert into new buffer
  2022. (save-excursion
  2023. (apply 'insert (reverse all-lines))
  2024. (if (= lines-collected lines-wanted)
  2025. (insert "\n(more lines omitted)\n")))
  2026. (setq org-index--occur-lines-collected lines-collected)
  2027. (org-mode)
  2028. (setq truncate-lines t)
  2029. (if all-lines (org-index--align-and-fontify-current-line (length all-lines)))
  2030. (font-lock-fontify-buffer)
  2031. (when all-lines-lbp
  2032. (while (not (org-at-table-p))
  2033. (forward-line -1))
  2034. (while all-lines-lbp
  2035. (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp (car all-lines-lbp))
  2036. (setq all-lines-lbp (cdr all-lines-lbp))
  2037. (forward-line -1)))
  2038. ;; prepare help text
  2039. (goto-char (point-min))
  2040. (forward-line (1- header-lines))
  2041. (setq org-index--occur-help-overlay (make-overlay (point-min) (point)))
  2042. (setq org-index--occur-help-text
  2043. (cons
  2044. (org-index--wrap
  2045. (propertize "Search is done; `?' toggles help and headlines.\n" 'face 'org-agenda-dimmed-todo-face))
  2046. (concat
  2047. (org-index--wrap
  2048. (propertize
  2049. (format
  2050. (concat "Search is done."
  2051. (if (< lines-collected lines-wanted)
  2052. " Showing all %d matches for "
  2053. " Showing one window of matches for ")
  2054. "\"" search-text
  2055. "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> jumps to matching line in index, <space> increments count." these-commands "\n")
  2056. (length all-lines))
  2057. 'face 'org-agenda-dimmed-todo-face))
  2058. org-index--headings)))
  2059. (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))
  2060. ;; highlight words
  2061. (setq case-fold-search t)
  2062. (setq font-lock-keywords-case-fold-search t)
  2063. (mapc (lambda (w) (unless (or (not w) (string= w "")) (highlight-regexp (regexp-quote w) 'isearch)))
  2064. (cons word words))
  2065. (setq buffer-read-only t)
  2066. ;; install keyboard-shortcuts
  2067. (setq keymap (make-sparse-keymap))
  2068. (set-keymap-parent keymap org-mode-map)
  2069. (mapc (lambda (x) (define-key keymap (kbd x)
  2070. (lambda () (interactive)
  2071. (message "%s" (org-index--occur-action)))))
  2072. (list "<return>" "RET"))
  2073. (define-key keymap (kbd "<tab>")
  2074. (lambda () (interactive)
  2075. (message (org-index--occur-action t))))
  2076. (define-key keymap (kbd "SPC")
  2077. (lambda () (interactive)
  2078. (org-index--refresh-parse-table)
  2079. ;; increment in index
  2080. (let ((ref (org-index--get-or-set-field 'ref))
  2081. count)
  2082. (org-index--on
  2083. 'ref ref
  2084. (setq count (+ 1 (string-to-number (org-index--get-or-set-field 'count))))
  2085. (org-index--get-or-set-field 'count (number-to-string count))
  2086. (org-index--promote-current-line)
  2087. (org-index--align-and-fontify-current-line))
  2088. ;; increment in this buffer
  2089. (let ((inhibit-read-only t))
  2090. (org-index--get-or-set-field 'count (number-to-string count)))
  2091. (message "Incremented count to %d" count))))
  2092. (define-key keymap (kbd "<S-return>")
  2093. (lambda () (interactive)
  2094. (let ((pos (get-text-property (point) 'org-index-lbp)))
  2095. (org-index--refresh-parse-table)
  2096. (org-index--occur-test-stale pos)
  2097. (pop-to-buffer org-index--buffer)
  2098. (goto-char pos)
  2099. (beginning-of-line)
  2100. (org-index--update-current-line))))
  2101. (define-key keymap (kbd "?")
  2102. (lambda () (interactive)
  2103. (org-index--refresh-parse-table)
  2104. (setq-local org-index--occur-help-text (cons (cdr org-index--occur-help-text) (car org-index--occur-help-text)))
  2105. (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))))
  2106. (use-local-map keymap))))
  2107. (defun org-index--occur-test-stale (pos)
  2108. "Test, if current line in occur buffer has become stale at POS."
  2109. (let (here there)
  2110. (org-index--refresh-parse-table)
  2111. (setq here (org-index--line-in-canonical-form))
  2112. (with-current-buffer org-index--buffer
  2113. (goto-char pos)
  2114. (setq there (org-index--line-in-canonical-form)))
  2115. (unless (string= here there)
  2116. (error "Occur buffer has become stale."))))
  2117. (defun org-index--line-in-canonical-form ()
  2118. "Return current line in its canonical form."
  2119. (org-trim (substring-no-properties (replace-regexp-in-string "\s +" " " (buffer-substring (line-beginning-position) (line-beginning-position 2))))))
  2120. (defun org-index--wrap (text)
  2121. "Wrap TEXT at fill column."
  2122. (with-temp-buffer
  2123. (insert text)
  2124. (fill-region (point-min) (point-max) nil t)
  2125. (buffer-string)))
  2126. (defun org-index--occur-action (&optional other)
  2127. "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window; or copy yank column."
  2128. (if (org-at-table-p)
  2129. (let ((id (org-index--get-or-set-field 'id))
  2130. (ref (org-index--get-or-set-field 'ref))
  2131. (yank (org-index--get-or-set-field 'yank)))
  2132. (if id
  2133. (org-index--find-id id other)
  2134. (if ref
  2135. (progn
  2136. (org-mark-ring-goto)
  2137. (format "Found reference %s" ref))
  2138. (if yank
  2139. (progn
  2140. (org-index--update-line (get-text-property (point) 'org-index-lbp))
  2141. (setq yank (replace-regexp-in-string (regexp-quote "\\vert") "|" yank nil 'literal))
  2142. (kill-new yank)
  2143. (org-mark-ring-goto)
  2144. (format "Copied '%s'" yank))
  2145. (error "Internal error, this line contains neither id, nor reference, nor text to yank")))))
  2146. (message "Not at table")))
  2147. (defun org-index--hide-with-overlays (words lines-wanted)
  2148. "Hide text that is currently visible and does not match WORDS by creating overlays; leave LINES-WANTED lines visible."
  2149. (let ((lines-found 0)
  2150. (end-of-visible (point))
  2151. overlay overlays start matched)
  2152. ;; main loop
  2153. (while (and (not (eobp))
  2154. (< lines-found lines-wanted))
  2155. ;; skip invisible lines
  2156. (while (and (not (eobp))
  2157. (and
  2158. (invisible-p (point))
  2159. (< (point) (overlay-start org-index--occur-tail-overlay))))
  2160. (goto-char (overlay-end (car (overlays-at (point))))))
  2161. ;; find stretch of lines, that are currently visible but should be invisible now
  2162. (setq matched nil)
  2163. (setq start (point))
  2164. (while (and (not (eobp))
  2165. (not
  2166. (and
  2167. (invisible-p (point))
  2168. (< (point) (overlay-start org-index--occur-tail-overlay))))
  2169. (not (and (org-index--test-words words)
  2170. (setq matched t)))) ; for its side effect
  2171. (forward-line 1))
  2172. ;; create overlay to hide this stretch
  2173. (when (< start (point)) ; avoid creating an empty overlay
  2174. (setq overlay (make-overlay start (point)))
  2175. (overlay-put overlay 'invisible t)
  2176. (setq overlays (cons overlay overlays)))
  2177. ;; skip and count line, that matched
  2178. (when matched
  2179. (forward-line 1)
  2180. (setq end-of-visible (point))
  2181. (cl-incf lines-found)))
  2182. ;; put new list on top of stack
  2183. (setq org-index--occur-stack
  2184. (cons (list (cons :overlays overlays)
  2185. (cons :end-of-visible end-of-visible)
  2186. (cons :lines lines-found))
  2187. org-index--occur-stack))
  2188. lines-found))
  2189. (defun org-index--unhide ()
  2190. "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
  2191. (when org-index--occur-stack
  2192. ;; delete overlays and make visible again
  2193. (mapc (lambda (y)
  2194. (delete-overlay y))
  2195. (cdr (assoc :overlays (car org-index--occur-stack))))
  2196. ;; remove from stack
  2197. (setq org-index--occur-stack (cdr org-index--occur-stack))
  2198. ;; return number of lines, that are now visible
  2199. (if org-index--occur-stack (cdr (assoc :lines (car org-index--occur-stack))))))
  2200. (defun org-index--test-words (words)
  2201. "Test current line for match against WORDS."
  2202. (let (line)
  2203. (setq line (downcase (buffer-substring (line-beginning-position) (line-beginning-position 2))))
  2204. (catch 'not-found
  2205. (dolist (w words)
  2206. (or (cl-search w line)
  2207. (throw 'not-found nil)))
  2208. t)))
  2209. (defun org-index--create-new-line (&optional args)
  2210. "Do the common work for `org-index-new-line' and `org-index'."
  2211. ;; insert ref or id as last or first line, depending on sort-column
  2212. (goto-char org-index--below-hline)
  2213. (if (eq org-index-sort-by 'count)
  2214. (progn
  2215. (while (org-at-table-p)
  2216. (forward-line))
  2217. (forward-line -1)
  2218. (org-table-insert-row t))
  2219. (org-table-insert-row))
  2220. ;; insert some of the standard values
  2221. (org-table-goto-column (org-index--column-num 'created))
  2222. (org-insert-time-stamp nil nil t)
  2223. (org-table-goto-column (org-index--column-num 'count))
  2224. (insert "1")
  2225. (if args (org-index--write-fields args)))
  2226. (defun org-index--sort-silent ()
  2227. "Sort index for default column to remove any effects of temporary sorting."
  2228. (save-excursion
  2229. (org-index--verify-id)
  2230. (org-index--parse-table)
  2231. (org-index--on nil nil
  2232. (org-index--do-sort-index org-index-sort-by)
  2233. (org-table-align)
  2234. (remove-hook 'before-save-hook 'org-index--sort-silent))))
  2235. (defun org-index--copy-visible (beg end)
  2236. "Copy the visible parts of the region between BEG and END without adding it to `kill-ring'; copy of `org-copy-visible'."
  2237. (let (snippets s)
  2238. (save-excursion
  2239. (save-restriction
  2240. (narrow-to-region beg end)
  2241. (setq s (goto-char (point-min)))
  2242. (while (not (= (point) (point-max)))
  2243. (goto-char (org-find-invisible))
  2244. (push (buffer-substring s (point)) snippets)
  2245. (setq s (goto-char (org-find-visible))))))
  2246. (apply 'concat (nreverse snippets))))
  2247. (provide 'org-index)
  2248. ;; Local Variables:
  2249. ;; fill-column: 75
  2250. ;; comment-column: 50
  2251. ;; End:
  2252. ;;; org-index.el ends here