org-index.el 114 KB

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