org-index.el 106 KB

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