org-index.el 119 KB

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