org-index.el 124 KB

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