org-index.el 116 KB

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