org-index.el 123 KB

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