org-index.el 110 KB

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