org-index.el 110 KB

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