org-index.el 126 KB

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