org-index.el 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412
  1. ;;; org-index.el --- A personal index for org and beyond
  2. ;; Copyright (C) 2011-2015 Free Software Foundation, Inc.
  3. ;; Author: Marc Ihm <org-index@2484.de>
  4. ;; Version: 4.1.0
  5. ;; Keywords: outlines index
  6. ;; This file is not part of GNU Emacs.
  7. ;;; License:
  8. ;; This program is free software; you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation; either version 3, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  20. ;;; Commentary:
  21. ;; Purpose:
  22. ;;
  23. ;; Fast search for selected org headings and things outside of org.
  24. ;;
  25. ;; This package creates and updates an index table of headings or
  26. ;; keywords, references and ids, where each line points to a heading
  27. ;; within org or references something outside. This table is sorted by
  28. ;; usage count, so that frequently used lines appear among the first
  29. ;; results.
  30. ;;
  31. ;; References are essentially small numbers (e.g. 'R237' or '--455--'), as
  32. ;; created by this package; they are well suited to be used outside of
  33. ;; org, e.g. in folder names, issue trackers or on printed documents.
  34. ;;
  35. ;; On first invocation org-index will guide you to create a dedicated node
  36. ;; for its index table and its configuration flags.
  37. ;;
  38. ;; For basic usage, subcommands 'add' and 'occur' are most important.
  39. ;;
  40. ;;
  41. ;; Setup:
  42. ;;
  43. ;; - Add these lines to your .emacs:
  44. ;;
  45. ;; (require 'org-index)
  46. ;; (org-index-default-keybindings) ; optional
  47. ;;
  48. ;; - Restart your Emacs to make these lines effective.
  49. ;;
  50. ;; - Invoke `org-index', which will assist in creating your index
  51. ;; table. The variable org-index-id will be persisted within your
  52. ;; customization file (typically .emacs).
  53. ;;
  54. ;;
  55. ;; Further reading:
  56. ;;
  57. ;; See the documentation of `org-index', which can also be read
  58. ;; by invoking `org-index' and choosing the help-command.
  59. ;;
  60. ;;
  61. ;; Updates:
  62. ;;
  63. ;; The latest tested version of this file can always be found at:
  64. ;;
  65. ;; http://orgmode.org/w/org-mode.git?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
  66. ;;; Change Log:
  67. ;; [2015-02-26 Th] Version 4.0.0 and 4.1.0:
  68. ;; - Removed command "leave"; rather go back with org-mark-ring-goto
  69. ;; - Property "org-index-ref" is no longer used or needed
  70. ;; - Renamed column "link" to "id"
  71. ;; - Added maintainance options to find duplicate rows, to check ids,
  72. ;; update index or remove property org-index-ref from nodes
  73. ;; - New command point
  74. ;; - Shortened versin history
  75. ;;
  76. ;; [2014-12-07 Sa] to [2015-01-31 Sa] Version 3.0.0 to 3.2.0:
  77. ;; - Complete sorting of index only occurs in idle-timer
  78. ;; - New command "maintain" with some subcommands
  79. ;; - Rewrote command "occur" with overlays in an indirect buffer
  80. ;; - introduced variable org-index-version
  81. ;; - Command "add" updates index, if node is already present
  82. ;; - New commands "add" and "delete" to easily add and remove
  83. ;; the current node to or from your index.
  84. ;; - New command "example" to create an example index.
  85. ;; - Moved flags to a list within the same node as the index table;
  86. ;; this breaks compatibility to prior versions of the package.
  87. ;; - Several new flags that are explained within index node.
  88. ;; - Removed commands "reuse", "missing", "put", "goto",
  89. ;; "update", "link", "fill", "unhighlight"
  90. ;; - New function `org-index-default-keybindings'
  91. ;;
  92. ;; [2012-12-07 Fr] to [2014-04-26 Sa] Version 2.0.0 to 2.4.3:
  93. ;; - New functions org-index-new-line and org-index-get-line
  94. ;; offer access to org-index from other lisp programs
  95. ;; - Regression tests with ert
  96. ;; - Renamed from "org-favtable" to "org-index"
  97. ;; - Added an assistant to set up the index table
  98. ;; - occur is now incremental, searching as you type
  99. ;; - Integrated with org-mark-ring-goto
  100. ;; - Added full support for ids
  101. ;; - Renamed the package from "org-reftable" to "org-favtable"
  102. ;; - Additional columns are required (e.g. "link"). Error messages will
  103. ;; guide you
  104. ;; - Ask user explicitly, which command to invoke
  105. ;; - Renamed the package from "org-refer-by-number" to "org-reftable"
  106. ;;
  107. ;; [2011-12-10 Sa] to [2012-09-22 Sa] Version Version 1.2.0 to 1.5.0:
  108. ;; - New command "sort" to sort a buffer or region by reference number
  109. ;; - New commands "highlight" and "unhighlight" to mark references
  110. ;; - New command "head" to find a headline with a reference number
  111. ;; - New commands occur and multi-occur
  112. ;; - Started this Change Log
  113. ;;; Code:
  114. (require 'org-table)
  115. (require 'cl)
  116. (defcustom org-index-id nil
  117. "Id of the Org-mode node, which contains the index table."
  118. :group 'org
  119. :group 'org-index)
  120. ;; Version of this package
  121. (defvar org-index-version "4.1.0" "Version of `org-index', format is major.minor.bugfix, where \"major\" is a change in index-table and \"minor\" are new features.")
  122. ;; Variables to hold the configuration of the index table
  123. (defvar org-index--maxref nil "Maximum number from reference table (e.g. \"153\").")
  124. (defvar org-index--head nil "Any header before number (e.g. \"R\").")
  125. (defvar org-index--tail nil "Tail after number (e.g. \"}\" or \")\".")
  126. (defvar org-index--numcols nil "Number of columns in index table.")
  127. (defvar org-index--ref-regex nil "Regular expression to match a reference.")
  128. (defvar org-index--ref-format nil "Format, that can print a reference.")
  129. (defvar org-index--columns nil "Columns of index-table.")
  130. (defvar org-index--special-columns nil "Columns with flags, that may appear only once.")
  131. (defvar org-index--flagged-columns nil "Columns with flags, that may appear multiple times.")
  132. (defvar org-index--buffer nil "Buffer of index table.")
  133. (defvar org-index--point nil "Position at start of headline of index table.")
  134. (defvar org-index--below-hline nil "Position of first cell in first line below hline.")
  135. (defvar org-index--headings nil "Headlines of index-table as a string.")
  136. (defvar org-index-map nil "Keymap for shortcuts for some commands of `org-index'. Can be activated and filled by org-index-default-keybings.")
  137. ;; Variables to hold context and state
  138. (defvar org-index--last-ref nil "Last reference created or visited.")
  139. (defvar org-index--category-before nil "Category of node before.")
  140. (defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
  141. (defvar org-index--below-cursor nil "Word below cursor.")
  142. (defvar org-index--within-node nil "True, if we are within node of the index table.")
  143. (defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
  144. (defvar org-index--occur-help-text nil "Text for help in occur buffer.")
  145. (defvar org-index--occur-help-overlay nil "Overlay for help in occur buffer.")
  146. (defvar org-index--occur-stack nil "Stack with overlays for hiding lines.")
  147. (defvar org-index--occur-tail-overlay nil "Overlay to cover invisible lines.")
  148. (defvar org-index--last-sort nil "Last column, the index has been sorted after.")
  149. (defvar org-index--sort-timer nil "Timer to sort index in correct order.")
  150. (defvar org-index--aligned nil "Remember for this Emacs session, if table has been aligned at least once.")
  151. ;; static information for this program package
  152. (defconst org-index--commands '(occur add delete head point enter ref help example sort multi-occur highlight maintain) "List of commands available.")
  153. (defconst org-index--required-flags '(sort) "Flags that are required.")
  154. (defconst org-index--single-flags '(sort point-on-add yank-after-add get-category-on-add get-heading-on-add shift-ref-and-date-on-add) "Flags, that may only appear once; these can appear as special-columns.")
  155. (defconst org-index--multiple-flags '(edit-on-add) "Flags, that might appear multiple times.")
  156. (defconst org-index--all-flags (append org-index--single-flags org-index--multiple-flags) "All flags.")
  157. (defconst org-index--required-headings '(ref id created last-accessed count) "All required headings.")
  158. (defconst org-index--valid-headings (append org-index--required-headings '(keywords category)) "All valid headings.")
  159. (defconst org-index--occur-buffer-name "*org-index-occur*" "Name of occur buffer.")
  160. (defconst org-index--sort-idle-delay 300 "Delay in seconds after which buffer will sorted.")
  161. (defconst org-index--sample-flags
  162. "
  163. - columns-and-flags :: associate columns of index table with flags. Do not remove.
  164. - ref
  165. - yank-after-add
  166. - category
  167. - get-category-on-add
  168. - edit-on-add
  169. - keywords
  170. - get-heading-on-add
  171. - edit-on-add
  172. - point-on-add
  173. - count
  174. - sort
  175. - last-accessed
  176. - created
  177. - id
  178. - all-columns-explained :: All columns of the index table and their meaning.
  179. - ref :: The reference number; will be generated automatically.
  180. - id :: id of the node, that this line represents
  181. - created :: When has this entry been created ?
  182. - last-accessed :: When has this entry been accessed last ?
  183. - count :: How many times has this entry been picked ?
  184. - keywords :: (optional) Suggested column to keep a list of keywords,
  185. which may match your input during occur.
  186. - category :: (optional) Suggested column to get category of node.
  187. - Any name starting with a dot (`.') :: No predefined meaning,
  188. depends on its flags.
  189. - all-flags-explained :: All flags, that can be associated with columns.
  190. - sort :: Sort whole table according to this column.
  191. - yank-after-add :: This column will be yanked after picking this line during
  192. occur.
  193. - edit-on-add :: This field will be presented for editing, when adding
  194. a new line to your index.
  195. - point-on-add :: Point will land here, when adding a new line, e.g. with
  196. command ref.
  197. - get-category-on-add :: This column will receive the nodes category
  198. during command add.
  199. - get-heading-on-add :: This column will receive the nodes heading
  200. during add.
  201. - shift-ref-and-date-on-add :: Remove leading reference and timestamp on add."
  202. "A sample string of flags.")
  203. (defmacro org-index--on (column value &rest body)
  204. "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
  205. The value returned is the value of the last form in BODY or nil,
  206. if VALUE cannot be found."
  207. (declare (indent 2) (debug t))
  208. (let ((pointvar (make-symbol "point")) ; avoid clash with same-named variables in body
  209. (foundvar (make-symbol "found"))
  210. (retvar (make-symbol "ret")))
  211. `(save-current-buffer
  212. (set-buffer org-index--buffer)
  213. (setq ,pointvar (point))
  214. (setq ,foundvar nil)
  215. (setq ,retvar nil)
  216. (setq ,foundvar (org-index--go ,column ,value))
  217. (when ,foundvar
  218. (setq ,retvar (progn ,@body)))
  219. (goto-char ,pointvar)
  220. ,retvar)))
  221. (defun org-index (&optional command search-ref arg)
  222. "Fast search for selected org headings and things outside of org.
  223. This package creates and updates an index table of headings or
  224. keywords, references and ids, where each line points to a heading
  225. within org or references something outside. This table is sorted by
  226. usage count, so that frequently used lines appear among the first
  227. results.
  228. References are essentially small numbers (e.g. 'R237' or '--455--'), as
  229. created by this package; they are well suited to be used outside of
  230. org, e.g. in folder names, issue trackers or on printed documents.
  231. On first invocation `org-index' will guide you to create a dedicated node
  232. for its index table and its configuration flags.
  233. For basic usage, subcommands 'add' and 'occur' are most important.
  234. This is version 4.1.0 of org-index.el.
  235. \\<org-mode-map>
  236. The function `org-index' operates on a dedicated table, the index
  237. table, which lives within its own Org-mode node. The table and
  238. its containing node will be created, when you first invoke
  239. `org-index'. The node also contains a commented list, describing
  240. the columns of the index table and their associated flags. The
  241. node is found through its id, which is stored within the variable
  242. `org-index-id'.
  243. The function `org-index' is the only interactive function of this
  244. package and its main entry point; it will present you with a list
  245. of subcommands to choose from:
  246. occur: Incremental search, that shows matching lines from the
  247. index table. It is updated after every keystroke. You may
  248. enter a list of words seperated by space or comma (`,'), to
  249. select lines that contain all of the given words.
  250. add: Add the current node to your index, so that it can be
  251. found through the subcommand \"occur\". Update index,
  252. if node has already been present.
  253. delete: Delete the current node from your index.
  254. head: Ask for a reference number and search for this heading.
  255. enter: Enter index table and maybe go to a specific reference;
  256. use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
  257. point: Echo information from index table for node at point.
  258. ref: Create a new reference.
  259. help: Show this text.
  260. example: Create a temporary index, that will not be saved, but
  261. may serve as an example.
  262. sort: Sort lines in index, in region or buffer by contained
  263. reference, or sort index by count, reference or last access.
  264. multi-occur: Apply Emacs standard `multi-occur' operation on all
  265. `org-mode' buffers to search for the given reference.
  266. highlight: Highlight or unhiglight references in active region or buffer.
  267. Call with prefix argument (`C-u') to remove highlights.
  268. maintain: Offers some choices to check, update or fix your index.
  269. If you invoke `org-index' for the first time, an assistant will be
  270. invoked, that helps you to create your own, commented index.
  271. Use `org-index-default-keybindings' to establish convenient
  272. keyboard shortcuts.
  273. See the commented list of flags within your index node for ways to
  274. modify the behaviour of org-index.
  275. Optional arguments for use from elisp: COMMAND is a symbol naming
  276. the command to execute. SEARCH-REF specifies a reference to
  277. search for, if needed. ARG allows passing in a prefix argument
  278. as in interactive calls."
  279. (interactive "P")
  280. (let (search-id ; id to search for
  281. sort-what ; sort what ?
  282. kill-new-text ; text that will be appended to kill ring
  283. message-text) ; text that will be issued as an explanation
  284. ;;
  285. ;; Initialize and parse
  286. ;;
  287. ;; creates index table, if necessary
  288. (org-index--verify-id)
  289. ;; Get configuration of index table
  290. (org-index--parse-table)
  291. ;; store context information
  292. (org-index--retrieve-context)
  293. ;;
  294. ;; Arrange for proper sorting of index
  295. ;;
  296. ;; lets assume, that it has been sorted this way (we try hard to make sure)
  297. (unless org-index--last-sort (setq org-index--last-sort (org-index--special-column 'sort)))
  298. ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
  299. (unless org-index--sort-timer
  300. (setq org-index--sort-timer
  301. (run-with-idle-timer org-index--sort-idle-delay t 'org-index--sort-silent)))
  302. ;;
  303. ;; Find out, what we are supposed to do
  304. ;;
  305. (when (equal command '(4))
  306. (setq arg command)
  307. (setq command nil))
  308. (if command
  309. (unless (memq command org-index--commands)
  310. (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
  311. command (mapconcat 'symbol-name org-index--commands ",")))
  312. (setq command (intern (org-completing-read
  313. "Please choose: "
  314. (mapcar 'symbol-name org-index--commands)))))
  315. ;;
  316. ;; Get search string, if required
  317. ;;
  318. ;; These actions need a search string:
  319. (when (memq command '(enter head multi-occur))
  320. ;; search from surrounding text ?
  321. (unless search-ref
  322. (if org-index--within-node
  323. (if (org-at-table-p)
  324. (setq search-ref (org-index--get-or-set-field 'ref)))
  325. (if (and org-index--below-cursor
  326. (string-match (concat "\\(" org-index--ref-regex "\\)")
  327. org-index--below-cursor))
  328. (setq search-ref (match-string 1 org-index--below-cursor)))))
  329. ;; If we still do not have a search string, ask user explicitly
  330. (unless search-ref
  331. (if (eq command 'enter)
  332. (let ((r (org-index--read-search-for-enter)))
  333. (setq search-ref (car r))
  334. (setq search-id (cdr r)))
  335. (setq search-ref (read-from-minibuffer "Search reference number: "))))
  336. ;; Clean up search string
  337. (when search-ref
  338. (setq search-ref (org-trim search-ref))
  339. (if (string-match "^[0-9]+$" search-ref)
  340. (setq search-ref (concat org-index--head search-ref org-index--tail)))
  341. (if (string= search-ref "") (setq search-ref nil)))
  342. (if (and (not search-ref)
  343. (not (eq command 'enter)))
  344. (error "Command %s needs a reference number" command)))
  345. ;;
  346. ;; Command sort needs to know in advance, what to sort for
  347. ;;
  348. (when (eq command 'sort)
  349. (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))))
  350. ;;
  351. ;; Enter table
  352. ;;
  353. ;; These commands will leave user in index table after they are finished
  354. (when (or (memq command '(enter ref maintain))
  355. (and (eq command 'sort)
  356. (eq sort-what 'index)))
  357. ;; Support orgmode-standard of going back (buffer and position)
  358. (org-mark-ring-push)
  359. (pop-to-buffer-same-window org-index--buffer)
  360. (goto-char org-index--point)
  361. (org-index--unfold-buffer))
  362. ;;
  363. ;; Actually do, what is requested
  364. ;;
  365. (cond
  366. ((eq command 'help)
  367. ;; bring up help-buffer for this function
  368. (describe-function 'org-index))
  369. ((eq command 'multi-occur)
  370. ;; Construct list of all org-buffers
  371. (let (buff org-buffers)
  372. (dolist (buff (buffer-list))
  373. (set-buffer buff)
  374. (if (string= major-mode "org-mode")
  375. (setq org-buffers (cons buff org-buffers))))
  376. ;; Do multi-occur
  377. (multi-occur org-buffers (org-index--make-guarded-search search-ref))
  378. ;; Present results
  379. (if (get-buffer "*Occur*")
  380. (progn
  381. (setq message-text (format "multi-occur for '%s'" search-ref))
  382. (other-window 1)
  383. (toggle-truncate-lines 1))
  384. (setq message-text (format "Did not find '%s'" search-ref)))))
  385. ((eq command 'add)
  386. (let ((r (org-index--do-add-or-update)))
  387. (setq message-text (car r))
  388. (setq kill-new-text (cdr r))))
  389. ((eq command 'delete)
  390. (setq message-text (org-index--do-delete)))
  391. ((eq command 'head)
  392. (if (and org-index--within-node
  393. (org-at-table-p))
  394. (setq search-id (org-index--get-or-set-field 'id)))
  395. (setq message-text
  396. (if search-id
  397. (org-index--do-head search-ref search-id)
  398. (message "Current line has no id."))))
  399. ((eq command 'enter)
  400. (goto-char org-index--below-hline)
  401. (setq message-text
  402. (if search-ref
  403. (if (org-index--go 'ref search-ref)
  404. (progn
  405. (org-index--update-current-line)
  406. (org-table-goto-column (org-index--column-num 'ref))
  407. (format "Found index line '%s'" search-ref))
  408. (format "Did not find index line with reference '%s'" search-ref))
  409. (if search-id
  410. (if (org-index--go 'id search-id)
  411. (progn
  412. (org-index--update-current-line)
  413. (org-table-goto-column (org-index--column-num 'ref))
  414. (format "Found index line '%s'" (org-index--get-or-set-field 'ref)))
  415. (format "Did not find index line with id '%s'" search-id))
  416. ;; simply go into table
  417. (setq message-text "At index table"))))
  418. (recenter))
  419. ((eq command 'point)
  420. (let (id info)
  421. (setq id (org-id-get))
  422. (if id
  423. (setq info (org-index--on 'id id
  424. (mapcar (lambda (x) (org-index--get-or-set-field x))
  425. (list 'created 'count 'last-accessed 'ref)))))
  426. (if info
  427. (progn
  428. (setq message-text (apply 'format (cons "Created %s, %s times accessed, last %s" info)))
  429. (setq kill-new-text (car (last info))))
  430. (setq message-text "This node is not part of index"))))
  431. ((eq command 'occur)
  432. (set-buffer org-index--buffer)
  433. (org-index--do-occur))
  434. ((eq command 'ref)
  435. (let (new)
  436. ;; add a new row
  437. (setq new (org-index--create-new-line))
  438. ;; fill special columns with standard values
  439. (org-table-goto-column (org-index--column-num 'ref))
  440. (insert new)
  441. (setq org-index--last-ref new)
  442. ;; goto point-field or first empty one or first field
  443. (if (org-index--special-column 'point-on-add)
  444. (org-table-goto-column (org-index--column-num (org-index--special-column 'point-on-add)))
  445. (unless (catch 'empty
  446. (dotimes (col org-index--numcols)
  447. (org-table-goto-column (+ col 1))
  448. (if (string= (org-trim (org-table-get-field)) "")
  449. (throw 'empty t))))
  450. ;; none found, goto first
  451. (org-table-goto-column 1)))
  452. (if org-index--active-region (setq kill-new-text org-index--active-region))
  453. (setq message-text (format "Adding a new row with ref '%s'" new))))
  454. ((eq command 'sort)
  455. (let ((columns (list "ref" "count" "created" "last-accessed" "id"))
  456. sort groups-and-counts)
  457. (cond
  458. ((eq sort-what 'index)
  459. (setq sort
  460. (intern
  461. (org-icompleting-read
  462. "Please choose column to sort index table: "
  463. (append (copy-list columns) (list "group-by"))
  464. nil t nil nil (symbol-name (org-index--special-column 'sort)))))
  465. (when (eq sort 'group-by)
  466. (setq sort
  467. (intern
  468. (org-icompleting-read
  469. "Please choose column to group index table by: "
  470. columns
  471. nil t nil nil (symbol-name (org-index--special-column 'sort)))))
  472. (setq groups-and-counts (org-index--collect-sort-groups sort)))
  473. (org-index--do-sort-index sort (first groups-and-counts))
  474. (org-table-goto-column (org-index--column-num sort))
  475. ;; When saving index, it should again be sorted correctly
  476. (with-current-buffer org-index--buffer
  477. (add-hook 'before-save-hook 'org-index--sort-silent t))
  478. (setq message-text
  479. (format
  480. (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
  481. (if groups-and-counts
  482. "; %d groups with equal %s and a total of %d lines have been found"
  483. ""))
  484. (symbol-name sort)
  485. (org-index--special-column 'sort)
  486. org-index--sort-idle-delay
  487. (second groups-and-counts)
  488. (symbol-name sort)
  489. (third groups-and-counts))))
  490. ((memq sort-what '(region buffer))
  491. (org-index--do-sort-lines sort-what)
  492. (setq message-text (format "Sorted %s by contained references" sort-what))))))
  493. ((eq command 'highlight)
  494. (let ((where "buffer"))
  495. (save-excursion
  496. (save-restriction
  497. (when (and transient-mark-mode
  498. mark-active)
  499. (narrow-to-region (region-beginning) (region-end))
  500. (setq where "region"))
  501. (if arg
  502. (progn
  503. (unhighlight-regexp org-index--ref-regex)
  504. (setq message-text (format "Removed highlights for references in %s" where)))
  505. (highlight-regexp org-index--ref-regex 'isearch)
  506. (setq message-text (format "Highlighted references in %s" where)))))))
  507. ((eq command 'maintain)
  508. (setq message-text (org-index--do-maintain)))
  509. ((eq command 'example)
  510. (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
  511. (org-index--create-index t)))
  512. (t (error "Unknown subcommand '%s'" command)))
  513. ;; tell, what we have done and what can be yanked
  514. (if kill-new-text (setq kill-new-text
  515. (substring-no-properties kill-new-text)))
  516. (if (string= kill-new-text "") (setq kill-new-text nil))
  517. (let ((m (concat
  518. message-text
  519. (if (and message-text kill-new-text)
  520. " and r"
  521. (if kill-new-text "R" ""))
  522. (if kill-new-text (format "eady to yank '%s'." kill-new-text) (if message-text "." "")))))
  523. (unless (string= m "")
  524. (message m)
  525. (setq org-index--message-text m)))
  526. (if kill-new-text (kill-new kill-new-text))))
  527. (defun org-index-default-keybindings ()
  528. "Set default keybindings for `org-index'.
  529. Establish the common prefix key `C-c i' Which is followed by the
  530. first letter of selected subcommands:
  531. key binding
  532. --- -------
  533. i show complete list of commands
  534. o subcommand occur
  535. a add
  536. d delete
  537. h head
  538. e enter
  539. p or . point
  540. r ref
  541. ? help
  542. See `org-index' for a description of all subcommands."
  543. (interactive)
  544. (define-prefix-command 'org-index-map)
  545. (global-set-key (kbd "C-c i") 'org-index-map)
  546. (define-key org-index-map (kbd "i") (lambda (arg) (interactive "P") (message nil) (org-index nil nil arg)))
  547. (define-key org-index-map (kbd "o") (lambda (arg) (interactive "P") (message nil) (org-index 'occur nil arg)))
  548. (define-key org-index-map (kbd "a") (lambda (arg) (interactive "P") (message nil) (org-index 'add nil arg)))
  549. (define-key org-index-map (kbd "d") (lambda (arg) (interactive "P") (message nil) (org-index 'delete nil arg)))
  550. (define-key org-index-map (kbd "h") (lambda (arg) (interactive "P") (message nil) (org-index 'head nil arg)))
  551. (define-key org-index-map (kbd "e") (lambda (arg) (interactive "P") (message nil) (org-index 'enter nil arg)))
  552. (define-key org-index-map (kbd "p") (lambda (arg) (interactive "P") (message nil) (org-index 'point nil arg)))
  553. (define-key org-index-map (kbd ".") (lambda (arg) (interactive "P") (message nil) (org-index 'point nil arg)))
  554. (define-key org-index-map (kbd "?") (lambda (arg) (interactive "P") (message nil) (org-index 'help nil arg))))
  555. (defun org-index-new-line (&rest keys-values)
  556. "Create a new line within the index table, returning its reference.
  557. The function takes a varying number of argument pairs; each pair
  558. is a symbol for an existing column heading followed by its value.
  559. The return value is the new reference.
  560. Example:
  561. (message \"Created reference %s\"
  562. (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
  563. Optional argument KEYS-VALUES specifies content of new line."
  564. (org-index--verify-id)
  565. (org-index--parse-table)
  566. (car (apply 'org-index--do-new-line keys-values)))
  567. (defun org-index--do-new-line (&rest keys-values)
  568. "Do the work for `org-index-new-line'.
  569. Optional argument KEYS-VALUES specifies content of new line."
  570. (save-excursion
  571. (org-index--retrieve-context)
  572. (with-current-buffer org-index--buffer
  573. (goto-char org-index--point)
  574. ;; check arguments early; they might come from lisp-user
  575. (let ((kvs keys-values)
  576. k v)
  577. (while kvs
  578. (setq k (car kvs))
  579. (setq v (cadr kvs))
  580. (if (eq k 'ref)
  581. (unless (memq v '(t nil))
  582. (error "Column 'ref' accepts only \"t\" or \"nil\""))
  583. (if (or (not (symbolp k))
  584. (and (symbolp v) (not (eq v t)) (not (eq v nil))))
  585. (error "Arguments must be alternation of key and value")))
  586. (unless (org-index--column-num k)
  587. (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
  588. (setq kvs (cddr kvs))))
  589. (let (ref yank)
  590. ;; create new line
  591. (setq ref (org-index--create-new-line))
  592. (plist-put keys-values 'ref ref)
  593. ;; fill columns
  594. (let ((kvs keys-values)
  595. k v n)
  596. (while kvs
  597. (setq k (car kvs))
  598. (setq v (cadr kvs))
  599. (org-table-goto-column (org-index--column-num k))
  600. (insert (org-trim v))
  601. (setq kvs (cddr kvs))))
  602. ;; align table and fontify line
  603. (org-table-align)
  604. (setq org-index--aligned t)
  605. (font-lock-fontify-region (line-beginning-position) (line-end-position))
  606. ;; get column to yank
  607. (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add)))
  608. (cons ref yank)))))
  609. (defun org-index-get-line (column value)
  610. "Retrieve an existing line within the index table by ref or id.
  611. Return its contents as a property list.
  612. The function `plist-get' may be used to retrieve specific elements
  613. from the result.
  614. Example:
  615. (plist-get (org-index-get-line 'ref \"R12\") 'count)
  616. retrieves the value of the count-column for reference number 12.
  617. Argument COLUMN is a symbol, either ref or id,
  618. argument VALUE specifies the value to search for."
  619. ;; check arguments
  620. (unless (memq column '(ref id))
  621. (error "Argument column can only be 'ref' or 'id'"))
  622. (unless value
  623. (error "Need a value to search for"))
  624. (org-index--verify-id)
  625. (org-index--parse-table)
  626. (org-index--get-line column value))
  627. (defun org-index--get-line (column value)
  628. "Find a line by ID, return its contents.
  629. Argument COLUMN and VALUE specify line to get."
  630. (let (content)
  631. (org-index--on
  632. column value
  633. (mapc (lambda (x)
  634. (if (and (numberp (cdr x))
  635. (> (cdr x) 0))
  636. (setq content (cons (car x) (cons (or (org-index--get-or-set-field (car x)) "") content)))))
  637. (reverse org-index--columns)))
  638. content))
  639. (defun org-index--delete-line (id)
  640. "Delete a line specified by ID."
  641. (let (content)
  642. (org-index--on
  643. 'id id
  644. (let ((start (line-beginning-position)))
  645. (beginning-of-line)
  646. (forward-line)
  647. (delete-region start (point))
  648. t))))
  649. (defun org-index--ref-from-id (id)
  650. "Get reference from line ID."
  651. (org-index--on 'id id (org-index--get-or-set-field 'ref)))
  652. (defun org-index--id-from-ref (ref)
  653. "Get id from line REF."
  654. (org-index--on 'ref ref (org-index--get-or-set-field 'id)))
  655. (defun org-index--read-search-for-enter ()
  656. "Special input routine for command enter."
  657. ;; Accept single char commands or switch to reading a sequence of digits
  658. (let (char prompt search-ref search-id)
  659. ;; start with short prompt but give more help on next iteration
  660. (setq prompt "Please specify, where to go in index (0-9.,space,backspace,return or ? for help): ")
  661. ;; read one character
  662. (while (not (memq char (append (number-sequence ?0 ?9) (list ?\d ?\b ?\r ?\j ?\s ?.))))
  663. (setq char (read-char prompt))
  664. (setq prompt "Go to index table and specific position. Digits specify a reference number to got to, <space> goes to top of index, <backspace> or <delete> to last line created and <return> or `.' to index line of current node. Please choose: "))
  665. (if (memq char (number-sequence ?0 ?9))
  666. ;; read rest of digits
  667. (setq search-ref (read-from-minibuffer "Search reference number: " (char-to-string char))))
  668. ;; decode single chars
  669. (if (memq char '(?\r ?\n ?.)) (setq search-id (org-id-get)))
  670. (if (memq char '(?\d ?\b)) (setq search-ref (number-to-string org-index--maxref)))
  671. (cons search-ref search-id)))
  672. (defun org-index--verify-id ()
  673. "Check, that we have a valid id."
  674. ;; Check id
  675. (unless org-index-id
  676. (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")))
  677. (if (string= "create-index" answer)
  678. (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
  679. (describe-function 'org-index))))
  680. ;; Find node
  681. (let (marker)
  682. (setq marker (org-id-find org-index-id 'marker))
  683. (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
  684. ; Try again with new node
  685. (setq marker (org-id-find org-index-id 'marker))
  686. (unless marker (error "Could not create node"))
  687. (setq org-index--buffer (marker-buffer marker)
  688. org-index--point (marker-position marker))
  689. (move-marker marker nil)))
  690. (defun org-index--retrieve-context ()
  691. "Collect context information before starting with command."
  692. ;; Get the content of the active region or the word under cursor
  693. (setq org-index--active-region
  694. (if (and transient-mark-mode mark-active)
  695. (buffer-substring (region-beginning) (region-end))
  696. nil))
  697. (setq org-index--below-cursor (thing-at-point 'symbol))
  698. ;; get category of current node
  699. (setq org-index--category-before
  700. (save-excursion ; workaround: org-get-category does not give category when at end of buffer
  701. (beginning-of-line)
  702. (org-get-category)))
  703. ;; Find out, if we are within index table or not
  704. (setq org-index--within-node (string= (org-id-get) org-index-id)))
  705. (defun org-index--parse-table ()
  706. "Parse content of index table."
  707. (let (ref-field
  708. id-field
  709. initial-point
  710. end-of-headings
  711. start-of-headings)
  712. (with-current-buffer org-index--buffer
  713. (setq org-index--maxref 0)
  714. (setq initial-point (point))
  715. (org-index--go-below-hline)
  716. ;; align and fontify table once for this emacs session
  717. (unless org-index--aligned
  718. (org-table-align) ; needs to happen before fontification to be effective ?
  719. (let ((is-modified (buffer-modified-p))
  720. (below (point)))
  721. (while (org-at-table-p)
  722. (forward-line))
  723. (font-lock-fontify-region below (point))
  724. (org-index--go-below-hline)
  725. (setq org-index--aligned t)
  726. (set-buffer-modified-p is-modified)))
  727. (org-index--go-below-hline)
  728. (setq org-index--below-hline (point-marker))
  729. (beginning-of-line)
  730. ;; get headings to display during occur
  731. (setq end-of-headings (point))
  732. (while (org-at-table-p) (forward-line -1))
  733. (forward-line)
  734. (setq start-of-headings (point))
  735. (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
  736. ;; count columns
  737. (org-table-goto-column 100)
  738. (setq org-index--numcols (- (org-table-current-column) 1))
  739. ;; go to top of table
  740. (while (org-at-table-p)
  741. (forward-line -1))
  742. (forward-line)
  743. ;; parse line of headings
  744. (org-index--parse-headings)
  745. ;; parse list of flags
  746. (goto-char org-index--point)
  747. (org-index--parse-flags)
  748. ;; Retrieve any decorations around the number within the first nonempty ref-field
  749. (goto-char org-index--below-hline)
  750. (while (and (org-at-table-p)
  751. (not (setq ref-field (org-index--get-or-set-field 'ref))))
  752. (forward-line))
  753. ;; Some Checking
  754. (unless ref-field
  755. (org-index--report-index-error "Reference column is empty"))
  756. (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
  757. (org-index--report-index-error
  758. "First reference in index table ('%s') does not contain a number" ref-field))
  759. ;; These are the decorations used within the first ref of index
  760. (setq org-index--head (match-string 1 ref-field))
  761. (setq org-index--tail (match-string 3 ref-field))
  762. (setq org-index--ref-regex (concat (regexp-quote org-index--head)
  763. "\\([0-9]+\\)"
  764. (regexp-quote org-index--tail)))
  765. (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
  766. ;; Go through table to find maximum number and do some checking
  767. (let ((ref 0))
  768. (while (org-at-table-p)
  769. (setq ref-field (org-index--get-or-set-field 'ref))
  770. (setq id-field (org-index--get-or-set-field 'id))
  771. (when (and (not ref-field)
  772. (not id-field))
  773. (kill-whole-line)
  774. (message "Removing line from index-table with both ref and id empty"))
  775. (if ref-field
  776. (if (string-match org-index--ref-regex ref-field)
  777. ;; grab number
  778. (setq ref (string-to-number (match-string 1 ref-field)))
  779. (kill-whole-line)
  780. (message "Removing line from index-table whose ref does not contain a number")))
  781. ;; check, if higher ref
  782. (if (> ref org-index--maxref) (setq org-index--maxref ref))
  783. (forward-line 1)))
  784. ;; go back to initial position
  785. (goto-char initial-point))))
  786. (defun org-index--do-maintain ()
  787. "Choose among and perform some tasks to maintain index."
  788. (let ((check-what) (max-mini-window-height 1.0) message-text)
  789. (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 (any column)\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")))
  790. (message nil)
  791. (cond
  792. ((eq check-what 'check)
  793. (setq message-text (or (org-index--check-ids)
  794. "No problems found")))
  795. ((eq check-what 'statistics)
  796. (setq message-text (org-index--do-statistics)))
  797. ((eq check-what 'duplicates)
  798. (setq message-text "Finding duplcates can be done by sorting your index appropriately: Choose 'group-by' and select a column; rows will then be sorted together, if they have the same value within the coosen column."))
  799. ((eq check-what 'clean)
  800. (let ((lines 0))
  801. (org-map-entries
  802. (lambda ()
  803. (when (org-entry-get (point) "org-index-ref")
  804. (incf lines)
  805. (org-entry-delete (point) "org-index-ref")))
  806. nil 'agenda)
  807. (setq message-text (format "Removed property 'org-index-ref' from %d lines" lines))))
  808. ((eq check-what 'update)
  809. (if (and (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 doing `add' from within your index. Are you sure to proceed for ALL index lines ? ")
  810. (or (not (or (org-index--flag-p 'edit-on-add (org-index--special-column 'get-heading-on-add))
  811. (org-index--flag-p 'edit-on-add (org-index--special-column 'get-category-on-add))))
  812. (y-or-n-p "If you did any editing of keyowrds or category while adding lines to your index before, these edits will now get lost. Do you still want to proceed ? ")))
  813. (setq message-text (org-index--update-all-lines))
  814. (setq message-text "Canceled."))))
  815. message-text))
  816. (defun org-index--do-sort-index (sort &optional groups)
  817. "Sort index table according to SORT, optinally with GROUPS."
  818. (let ((is-modified (buffer-modified-p))
  819. top
  820. bottom
  821. ref-field
  822. count-field)
  823. (unless buffer-read-only
  824. (message "Sorting table for %s..." (symbol-name sort))
  825. (undo-boundary)
  826. (let ((message-log-max nil)) ; we have just issued a message, dont need those of sort-subr
  827. ;; get boundaries of table
  828. (goto-char org-index--below-hline)
  829. (forward-line 0)
  830. (setq top (point))
  831. (while (org-at-table-p) (forward-line))
  832. ;; kill all empty rows at bottom
  833. (while (progn
  834. (forward-line -1)
  835. (org-table-goto-column 1)
  836. (and
  837. (not (org-index--get-or-set-field 'ref))
  838. (not (org-index--get-or-set-field 'id))))
  839. (org-table-kill-row))
  840. (forward-line 1)
  841. (setq bottom (point))
  842. ;; sort lines
  843. (save-restriction
  844. (narrow-to-region top bottom)
  845. (goto-char top)
  846. (sort-subr t
  847. 'forward-line
  848. 'end-of-line
  849. (lambda ()
  850. (concat
  851. (if groups
  852. (format "%06d-" (cdr (assoc (org-index--get-or-set-field sort) groups)))
  853. "")
  854. (org-index--get-sort-key sort t)))
  855. nil
  856. 'string<)
  857. (goto-char (point-min))
  858. ;; restore modification state
  859. (set-buffer-modified-p is-modified)))
  860. (setq org-index--last-sort sort))))
  861. (defun org-index--collect-sort-groups (sort)
  862. "Collect groups to SORT for."
  863. (let ((count-groups 0) (count-lines 0)
  864. groups key key-value)
  865. (org-index--on
  866. nil nil
  867. (while (org-at-table-p)
  868. (setq key (org-index--get-or-set-field sort))
  869. (setq key-value (assoc key groups))
  870. (if key-value
  871. (progn
  872. (incf (cdr key-value)))
  873. (setq groups (cons (cons key 1) groups)))
  874. (forward-line)))
  875. (mapc (lambda (x) (when (> (cdr x) 1)
  876. (incf count-groups)
  877. (incf count-lines (cdr x))))
  878. groups)
  879. (list groups count-groups count-lines)))
  880. (defun org-index--do-sort-lines (what)
  881. "Sort lines in WHAT according to contained reference."
  882. (save-restriction
  883. (cond
  884. ((eq what 'region)
  885. (if (region-active-p)
  886. (narrow-to-region (region-beginning) (region-end))
  887. (error "No active region, cannot sort")))
  888. ((eq what 'buffer)
  889. (unless (y-or-n-p "Sort whole current buffer ? ")
  890. (error "Canceled"))
  891. (narrow-to-region (point-min) (point-max))))
  892. (goto-char (point-min))
  893. (sort-subr nil 'forward-line 'end-of-line
  894. (lambda ()
  895. (if (looking-at (concat ".*"
  896. (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
  897. (string-to-number (match-string 1))
  898. 0)))))
  899. (defun org-index--go-below-hline ()
  900. "Move below hline in index-table."
  901. (let ((count 0)
  902. (errstring (format "index table within node %s" org-index-id)))
  903. (goto-char org-index--point)
  904. ;; go to heading of node
  905. (while (not (org-at-heading-p)) (forward-line -1))
  906. (forward-line 1)
  907. ;; go to first table, but make sure we do not get into another node
  908. (while (and (not (org-at-table-p))
  909. (not (org-at-heading-p))
  910. (not (eobp)))
  911. (forward-line))
  912. ;; check, if there really is a table
  913. (unless (org-at-table-p)
  914. (org-index--create-missing-index "Cannot find %s." errstring))
  915. ;; go just after hline
  916. (while (and (not (org-at-table-hline-p))
  917. (org-at-table-p))
  918. (forward-line))
  919. (forward-line)
  920. ;; and check
  921. (unless (org-at-table-p)
  922. (org-index--report-index-error "Cannot find a hline within %s" errstring))
  923. (org-table-goto-column 1)))
  924. (defun org-index--parse-headings ()
  925. "Parse headings of index table."
  926. (let (field ;; field content
  927. field-symbol ;; and as a symbol
  928. found)
  929. (setq org-index--columns nil)
  930. ;; For each column
  931. (dotimes (col org-index--numcols)
  932. (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
  933. (if (string= field "")
  934. (error "Heading of column cannot be empty"))
  935. (if (and (not (string= (substring field 0 1) "."))
  936. (not (member (intern field) org-index--valid-headings)))
  937. (if (string= field "link")
  938. ;; Ask user to migrate his index to new version (since [2015-02-11 Mi])
  939. (progn
  940. ;; pop to index buffer
  941. (pop-to-buffer-same-window org-index--buffer)
  942. (goto-char org-index--below-hline)
  943. (org-reveal t)
  944. ;; go to column
  945. (while (org-at-table-p)
  946. (forward-line -1))
  947. (forward-line)
  948. (org-table-goto-column (+ 1 col))
  949. (error "Column 'link' should be named 'id' with recent versions of org-index,\nplease adjust your table (cursor is already positioned right)"))
  950. (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field)))
  951. (setq field-symbol (intern field))
  952. ;; check if heading has already appeared
  953. (if (assoc field-symbol org-index--columns)
  954. (org-index--report-index-error
  955. "'%s' appears two times as column heading" (downcase field))
  956. ;; add it to list at front, reverse later
  957. (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
  958. (setq org-index--columns (reverse org-index--columns))
  959. ;; check if all necessary headings have appeared
  960. (mapc (lambda (head)
  961. (unless (cdr (assoc head org-index--columns))
  962. (org-index--report-index-error "No column has heading '%s'" head)))
  963. org-index--required-headings))
  964. (defun org-index--parse-flags ()
  965. "Parse list of flags in index table."
  966. (let (parent parent-is-comment child)
  967. ;; reset configuration variables
  968. (setq org-index--special-columns nil)
  969. (setq org-index--flagged-columns nil)
  970. (org-index--goto-list "columns-and-flags" t)
  971. (forward-line 1)
  972. ;; outer loop over columns
  973. (while (and (setq parent (org-index--parse-list-item))
  974. parent
  975. (> (cdr (assoc :indent parent)) 0))
  976. (setq parent-is-comment (member (cdr (assoc :text parent)) '("all-columns-explained" "all-flags-explained")))
  977. ;; check, that we have a valid heading
  978. (unless (or parent-is-comment
  979. (assoc (cdr (assoc :sym parent)) org-index--columns))
  980. (when (string= "link" (cdr (assoc :text parent)))
  981. (pop-to-buffer-same-window org-index--buffer)
  982. (org-reveal t)
  983. (error "Flag 'link' should be named 'id' with recent versions of org-index,\nplease adjust this flag (cursor is already positioned right)"))
  984. (org-index--report-index-error "'%s' appears within flags, but not as a index column. " (cdr (assoc :text parent))))
  985. ;; inner loop over children
  986. (while (and (forward-line 1)
  987. (setq child (org-index--parse-list-item))
  988. child
  989. (> (cdr (assoc :indent child))
  990. (cdr (assoc :indent parent))))
  991. (unless parent-is-comment
  992. ;; check, that we have a valid flag
  993. (unless (memq (cdr (assoc :sym child)) org-index--all-flags)
  994. (org-index--report-index-error "'%s' is not a valid flag" (cdr (assoc :text child))))
  995. ;; process flag with respect to current index-column
  996. (if (memq (cdr (assoc :sym child)) org-index--single-flags)
  997. ;; Check, that none of org-index--single-flags appears twice
  998. (if (assoc (cdr (assoc :sym child)) org-index--special-columns)
  999. (org-index--report-index-error
  1000. "More than one column is marked with flag '%s'" (cdr (assoc :text child)))
  1001. ;; add it to list
  1002. (setq org-index--special-columns (cons (cons (cdr (assoc :sym child)) (cdr (assoc :sym parent)))
  1003. org-index--special-columns))))
  1004. ;; all flags are stored in org-index--flagged-columns
  1005. (let ((l (assoc (cdr (assoc :sym child)) org-index--flagged-columns))) ;; list of flag and columns, that carry this flag
  1006. (unless l
  1007. ;; no list of columns with this flag is present, create one
  1008. (setq org-index--flagged-columns
  1009. (cons (cons (cdr (assoc :sym child)) nil)
  1010. org-index--flagged-columns))
  1011. (setq l (car org-index--flagged-columns)))
  1012. ;; prepend this column to list of columns with this flag
  1013. (setcdr l (cons (cdr (assoc :sym parent)) (cdr l)))))))
  1014. ;; check, that all needed flags have been specified
  1015. (mapc (lambda (x)
  1016. (unless (assoc x org-index--special-columns)
  1017. (org-index--report-index-error "Required flag '%s' does not appear" (substring (symbol-name x) 1))))
  1018. org-index--required-flags)))
  1019. (defun org-index--goto-list (name &optional required non-top)
  1020. "Goto list NAME (maybe NON-TOP Level) in index node, err if REQUIRED list is not present."
  1021. (goto-char org-index--point)
  1022. ;; go to heading of node
  1023. (while (not (org-at-heading-p)) (forward-line -1))
  1024. (forward-line 1)
  1025. ;; go to named list
  1026. (while (and (not (let ((item (org-index--parse-list-item)))
  1027. (if item
  1028. (and (or non-top (= (cdr (assoc :indent item)) 0)) ;; accept only toplevel ?
  1029. (string= (cdr (assoc :text item)) name)) ;; with requested name
  1030. nil)))
  1031. (not (org-at-table-p))
  1032. (not (org-at-heading-p))
  1033. (not (eobp)))
  1034. (forward-line 1))
  1035. (if (org-at-item-p)
  1036. t
  1037. (if required
  1038. (org-index--report-index-error "Could not find required list '%s'" name)
  1039. nil)))
  1040. (defun org-index--parse-list-item ()
  1041. "Parse a list item into an assoc array (indent, checkbox, text, value)."
  1042. ;; matche full list-item, maybe with checkbox and double-colon
  1043. (if (looking-at org-list-full-item-re)
  1044. ;; retrieve interesting parts of list item from match data
  1045. (let (indent checkbox text value next-line)
  1046. (setq indent
  1047. (- (save-excursion (goto-char (match-beginning 1)) (current-column)) ; first column
  1048. (save-match-data (org-current-level)) ; indent-level
  1049. 1))
  1050. (setq checkbox (match-string 3))
  1051. (setq text (match-string 4))
  1052. (set (if text 'value 'text) (buffer-substring (match-end 0) (line-end-position))) ; regexp did not capture this
  1053. ;; peek ahead, if item continues on next line
  1054. (forward-line 1)
  1055. (if (looking-at org-list-full-item-re)
  1056. (forward-line -1) ; already at next item; go back
  1057. (setq next-line (buffer-substring (line-beginning-position) (line-end-position))))
  1058. ;; clean up strings
  1059. (mapc (lambda (x)
  1060. (if (stringp (symbol-value x))
  1061. (set x (org-trim (substring-no-properties (symbol-value x))))))
  1062. '(text value next-line))
  1063. (if next-line (setq text (concat text " " next-line))) ; append next line if
  1064. (list (cons :indent indent) (cons :text text) (cons :value value) (cons :sym (intern text))))
  1065. nil))
  1066. (defun org-index--create-missing-index (&rest reasons)
  1067. "Create a new empty index table with detailed explanation. Argument REASONS explains why."
  1068. (org-index--ask-before-create-index "Cannot find your index table: "
  1069. "new permanent" "."
  1070. reasons)
  1071. (org-index--create-index))
  1072. (defun org-index--report-index-error (&rest reasons)
  1073. "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
  1074. (when org-index--buffer
  1075. (pop-to-buffer-same-window org-index--buffer)
  1076. (goto-char org-index--below-hline)
  1077. (org-reveal t))
  1078. (org-index--ask-before-create-index "The existing index contains this error: "
  1079. "temporary" ", to compare with."
  1080. reasons)
  1081. (org-index--create-index t t))
  1082. (defun org-index--ask-before-create-index (explanation type for-what reasons)
  1083. ; checkdoc-params: (explanation type for-what reasons)
  1084. "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
  1085. (let (reason prompt)
  1086. (setq reason (apply 'format reasons))
  1087. (setq prompt (concat explanation reason "\n\n"
  1088. "However, this assistant can help you to create a "
  1089. type " index with detailed comments" for-what "\n\n"
  1090. "Do you want to proceed ?"))
  1091. (unless (let ((max-mini-window-height 1.0))
  1092. (y-or-n-p prompt))
  1093. (error (concat explanation reason)))))
  1094. (defun org-index--create-index (&optional temporary compare)
  1095. "Create a new empty index table with detailed explanation.
  1096. specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
  1097. (let (buffer
  1098. title
  1099. firstref
  1100. id)
  1101. (if temporary
  1102. (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
  1103. (buffer-name "*org-index-example-index*"))
  1104. (setq buffer (get-buffer-create buffer-name))
  1105. (with-current-buffer buffer
  1106. ;; but it needs a file for its index to be found
  1107. (unless (string= (buffer-file-name) file-name)
  1108. (set-visited-file-name file-name))
  1109. (rename-buffer buffer-name) ; name is change by line above
  1110. (erase-buffer)
  1111. (org-mode)))
  1112. (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))))))
  1113. (setq title (read-from-minibuffer "Please enter the title of the index node: "))
  1114. (while (progn
  1115. (setq firstref (read-from-minibuffer "Please enter your first reference-number. This is a number preceeded by some non-digit chars and optionally followed by some more non-digit 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 to frequently within your existing notes, to avoid too many false hits when searching.\n\nPlease choose: "))
  1116. (let (desc)
  1117. (when (string-match "[[:blank:]]" firstref)
  1118. (setq desc "Contains whitespace"))
  1119. (when (string-match "[[:cntrl:]]" firstref)
  1120. (setq desc "Contains control characters"))
  1121. (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
  1122. ;; firstref not okay, report details
  1123. (setq desc
  1124. (cond ((string= firstref "") "is empty")
  1125. ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
  1126. ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
  1127. ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
  1128. )))
  1129. (if desc
  1130. (progn
  1131. (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
  1132. t)
  1133. nil))))
  1134. (with-current-buffer buffer
  1135. (goto-char (point-max))
  1136. (insert (format "* %s %s\n" firstref title))
  1137. (if temporary
  1138. (insert "
  1139. Below you find your temporary index table, which will not last longer
  1140. than your current emacs session.
  1141. ")
  1142. (insert "
  1143. Below you find your initial index table, which will grow over time.
  1144. "))
  1145. (insert "
  1146. You may start using it by adding some lines. Just move to
  1147. another heading, invoke `org-index' and choose the command
  1148. \"add\". After adding a few nodes, try the command \"occur\"
  1149. to search among them.
  1150. To gain further insight you may invoke the subcommand \"help\", or
  1151. read the description of `org-index'.
  1152. Within the index table below, dhe sequence of columns does not
  1153. matter. You may reorder them any way you like. Columns are
  1154. found by their heading. You may also add your own columns.
  1155. Following these explanations there is the item-list
  1156. `columns-and-flags', which influences the behaviour of
  1157. `org-index'. See the explanations which are part of this list.
  1158. This node needs not be a top level node; its name is completely
  1159. at your choice; it is found through its ID only.
  1160. Remark: These lines of explanation can be removed at any time.
  1161. ")
  1162. (setq id (org-id-get-create))
  1163. (insert (format "
  1164. %s
  1165. | ref | category | keywords | count | last-accessed | created | id |
  1166. | | | | | | | <4> |
  1167. |-----+-----------+----------+-------+---------------+---------+------|
  1168. | %s | | %s | | | %s | %s |
  1169. "
  1170. org-index--sample-flags
  1171. firstref
  1172. "This node"
  1173. (with-temp-buffer (org-insert-time-stamp nil nil t))
  1174. id))
  1175. ;; make sure, that node can be found
  1176. (org-id-add-location id (buffer-file-name))
  1177. (setq buffer-save-without-query t)
  1178. (basic-save-buffer)
  1179. (while (not (org-at-table-p)) (forward-line -1))
  1180. (unless buffer-read-only (org-table-align))
  1181. (while (not (org-at-heading-p)) (forward-line -1))
  1182. ;; read back some info about new index
  1183. (let ((org-index-id id))
  1184. (org-index--verify-id))
  1185. ;; remember at least for this session
  1186. (setq org-index-id id)
  1187. ;; present results to user
  1188. (if temporary
  1189. (progn
  1190. ;; Present existing and temporary index together
  1191. (when compare
  1192. (pop-to-buffer-same-window org-index--buffer)
  1193. (goto-char org-index--point)
  1194. (org-index--unfold-buffer)
  1195. (delete-other-windows)
  1196. (select-window (split-window-vertically)))
  1197. ;; show new index
  1198. (pop-to-buffer-same-window buffer)
  1199. (org-id-goto id)
  1200. (org-index--unfold-buffer)
  1201. (if compare
  1202. (error "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
  1203. (message "This is your new temporary index.")))
  1204. (progn
  1205. ;; Only show the new index
  1206. (pop-to-buffer-same-window buffer)
  1207. (delete-other-windows)
  1208. (org-id-goto id)
  1209. (org-index--unfold-buffer)
  1210. (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 ? ")
  1211. (progn
  1212. (customize-save-variable 'org-index-id id)
  1213. (error "Saved org-index-id '%s' to %s" id (or custom-file
  1214. user-init-file)))
  1215. (let (sq)
  1216. (setq sq (format "(setq org-index-id \"%s\")" id))
  1217. (kill-new sq)
  1218. (error "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))))))))
  1219. (defun org-index--unfold-buffer ()
  1220. "Helper function to unfold buffer."
  1221. (org-show-context)
  1222. (org-show-subtree)
  1223. (recenter 1)
  1224. (save-excursion
  1225. (org-back-to-heading)
  1226. (forward-line) ;; on property drawer
  1227. (org-cycle)
  1228. (org-index--goto-list "columns-and-flags")
  1229. (org-cycle)))
  1230. (defun org-index--update-line (&optional ref-or-id)
  1231. "Update columns count and last-accessed in line REF-OR-ID."
  1232. (let ((newcount 0)
  1233. initial)
  1234. (with-current-buffer org-index--buffer
  1235. (unless buffer-read-only
  1236. ;; search reference or id, if given (or assume, that we are already positioned right)
  1237. (when ref-or-id
  1238. (setq initial (point))
  1239. (goto-char org-index--below-hline)
  1240. (while (and (org-at-table-p)
  1241. (not (or (string= ref-or-id (org-index--get-or-set-field 'ref))
  1242. (string= ref-or-id (org-index--get-or-set-field 'id)))))
  1243. (forward-line)))
  1244. (if (not (org-at-table-p))
  1245. (error "Did not find reference or id '%s'" ref-or-id)
  1246. (org-index--update-current-line))
  1247. (if initial (goto-char initial))))))
  1248. (defun org-index--update-current-line ()
  1249. "Update current lines columns count and last-accessed."
  1250. (let (newcount (count-field (org-index--get-or-set-field 'count)))
  1251. ;; update count field only if number or empty
  1252. (when (or (not count-field)
  1253. (string-match "^[0-9]+$" count-field))
  1254. (setq newcount (+ 1 (string-to-number (or count-field "0"))))
  1255. (org-index--get-or-set-field 'count
  1256. (number-to-string newcount)))
  1257. ;; update timestamp
  1258. (org-table-goto-column (org-index--column-num 'last-accessed))
  1259. (org-table-blank-field)
  1260. (org-insert-time-stamp nil t t)
  1261. ;; move line according to new content
  1262. (org-index--promote-current-line)))
  1263. (defun org-index--promote-current-line ()
  1264. "Move current line up in table according to changed sort fields."
  1265. (let (begin end key
  1266. (to-skip 0))
  1267. (forward-line 0) ; stay at beginning of line
  1268. (setq key (org-index--get-sort-key))
  1269. (setq begin (point))
  1270. (setq end (line-beginning-position 2))
  1271. (forward-line -1)
  1272. (while (and (org-at-table-p)
  1273. (not (org-at-table-hline-p))
  1274. (string< (org-index--get-sort-key) key))
  1275. (incf to-skip)
  1276. (forward-line -1))
  1277. (forward-line 1)
  1278. ;; insert line at new position
  1279. (when (> to-skip 0)
  1280. (insert (delete-and-extract-region begin end))
  1281. (forward-line -1))))
  1282. (defun org-index--get-sort-key (&optional sort with-ref)
  1283. "Get value for sorting from column SORT, optional WITH-REF."
  1284. (let (ref
  1285. ref-field
  1286. key)
  1287. (unless sort (setq sort org-index--last-sort)) ; use default value
  1288. (when (or with-ref
  1289. (eq sort 'ref))
  1290. ;; get reference with leading zeroes, so it can be
  1291. ;; sorted as text
  1292. (setq ref-field (org-index--get-or-set-field 'ref))
  1293. (string-match org-index--ref-regex ref-field)
  1294. (setq ref (format
  1295. "%06d"
  1296. (string-to-number
  1297. (or (match-string 1 ref-field)
  1298. "0")))))
  1299. (setq key
  1300. (cond
  1301. ((eq sort 'count)
  1302. (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))
  1303. ((eq sort 'ref)
  1304. ref)
  1305. ((eq sort 'id)
  1306. (org-index--get-or-set-field sort))
  1307. ((eq sort 'last-accessed)
  1308. (org-index--get-or-set-field sort))
  1309. ((eq sort 'created)
  1310. (org-index--get-or-set-field sort))
  1311. (t (error "This is a bug: unmatched case '%s'" sort))))
  1312. (if with-ref (setq key (concat key ref)))
  1313. key))
  1314. (defun org-index--get-or-set-field (key &optional value)
  1315. "Retrieve field KEY from index table or set it to VALUE."
  1316. (let (field)
  1317. (save-excursion
  1318. (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value)))
  1319. (if (string= field "") (setq field nil))
  1320. (org-no-properties field))))
  1321. (defun org-index--column-num (key)
  1322. "Return number of column KEY."
  1323. (if (numberp key)
  1324. key
  1325. (cdr (assoc key org-index--columns))))
  1326. (defun org-index--special-column (key)
  1327. "Return column (not a number) for special column KEY."
  1328. (cdr (assoc key org-index--special-columns)))
  1329. (defun org-index--flag-p (flag column)
  1330. "Check if COLUMN has FLAG set."
  1331. (unless (memq flag org-index--all-flags)
  1332. (error (format "Internal error: unknown flag %s" (symbol-name flag))))
  1333. (memq column (assoc flag org-index--flagged-columns)))
  1334. (defun org-index--make-guarded-search (ref &optional dont-quote)
  1335. "Make robust search string from REF; DONT-QUOTE it, if requested."
  1336. (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
  1337. (defun org-index--do-statistics ()
  1338. "Compute statistics about index table."
  1339. (let ((total 0)
  1340. ref-field ref min max message)
  1341. ;; go through table and remove all refs, that we see
  1342. (goto-char org-index--below-hline)
  1343. (while (org-at-table-p)
  1344. ;; get ref-field and number
  1345. (setq ref-field (org-index--get-or-set-field 'ref))
  1346. (if (and ref-field
  1347. (string-match org-index--ref-regex ref-field))
  1348. (setq ref (string-to-number (match-string 1 ref-field))))
  1349. ;; record min and max
  1350. (if (or (not min) (< ref min)) (setq min ref))
  1351. (if (or (not max) (> ref max)) (setq max ref))
  1352. ;; count
  1353. (setq total (1+ total))
  1354. (forward-line))
  1355. (setq message (format "First reference is %s, last %s; %d values in between, %d of them are used (%d percent)"
  1356. (format org-index--ref-format min)
  1357. (format org-index--ref-format max)
  1358. (1+ (- max min))
  1359. total
  1360. (truncate (* 100 (/ (float total) (1+ (- max min)))))
  1361. ))
  1362. (goto-char org-index--below-hline)
  1363. message))
  1364. (defun org-index--do-add-or-update ()
  1365. "For current node or current line in index, add a new line to index table or update existing."
  1366. (let* (id ref args yank ref-and-yank)
  1367. ;; do the same things from within index and from outside
  1368. (if org-index--within-node
  1369. (progn
  1370. (unless (org-at-table-p)
  1371. (error "Within index node but not on table"))
  1372. (setq id (org-index--get-or-set-field 'id))
  1373. (setq ref (org-index--get-or-set-field 'ref))
  1374. (setq args (org-index--collect-values-for-add-update-remote id))
  1375. (org-index--write-fields-for-add-update args)
  1376. (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add)))
  1377. (cons (format "Updated index line %s" ref) yank))
  1378. (unless (org-at-heading-p)
  1379. (error "Not at headline"))
  1380. (setq id (org-id-get-create))
  1381. (setq ref (org-index--on 'id id (org-index--get-or-set-field 'ref)))
  1382. (setq args (org-index--collect-values-for-add-update id ref))
  1383. (if ref
  1384. ;; already have a ref, find it in index and update fields
  1385. (let ((kvs args)
  1386. found-and-message)
  1387. (org-index--on
  1388. 'ref ref
  1389. (org-index--write-fields-for-add-update args)
  1390. (setq yank (org-index--get-or-set-field (org-index--special-column 'yank-after-add))))
  1391. (cons (format "Updated index line %s" ref) yank))
  1392. ;; no ref here, create new line in index
  1393. (setq ref-and-yank (apply 'org-index--do-new-line args))
  1394. (cons (format "Added index line %s" (car ref-and-yank)) (cdr ref-and-yank))))))
  1395. (defun org-index--check-ids ()
  1396. "Check, that ids really point to a node."
  1397. (let ((lines 0)
  1398. id ids marker)
  1399. (goto-char org-index--below-hline)
  1400. (catch 'problem
  1401. (while (org-at-table-p)
  1402. (when (setq id (org-index--get-or-set-field 'id))
  1403. ;; check for double ids
  1404. (when (member id ids)
  1405. (org-table-goto-column (org-index--column-num 'id))
  1406. (throw 'problem "This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
  1407. (incf lines)
  1408. (setq ids (cons id ids))
  1409. ;; check, if id is valid
  1410. (setq marker (org-id-find id t))
  1411. (unless marker
  1412. (org-table-goto-column (org-index--column-num 'id))
  1413. (throw 'problem "This id cannot be found")))
  1414. (forward-line))
  1415. (goto-char org-index--below-hline)
  1416. nil)))
  1417. (defun org-index--update-all-lines ()
  1418. "Update all lines of index at once."
  1419. (let ((lines 0)
  1420. id ref kvs)
  1421. ;; check for double ids
  1422. (or
  1423. (org-index--check-ids)
  1424. (progn
  1425. (goto-char org-index--below-hline)
  1426. (while (org-at-table-p)
  1427. ;; update single line
  1428. (when (setq id (org-index--get-or-set-field 'id))
  1429. (setq ref (org-index--get-or-set-field 'ref))
  1430. (setq kvs (org-index--collect-values-for-add-update-remote id))
  1431. (org-index--write-fields-for-add-update kvs)
  1432. (incf lines))
  1433. (forward-line))
  1434. (goto-char org-index--below-hline)
  1435. (org-table-align)
  1436. (format "Update %d lines." lines)))))
  1437. (defun org-index--collect-values-for-add-update (id &optional silent category)
  1438. "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
  1439. (let ((args (list 'ref t 'id id))
  1440. content)
  1441. (dolist (col-num org-index--columns)
  1442. (setq content "")
  1443. ;; copy heading ?
  1444. (if (org-index--flag-p 'get-heading-on-add (car col-num))
  1445. (setq content (nth 4 (org-heading-components))))
  1446. ;; copy category ?
  1447. (if (org-index--flag-p 'get-category-on-add (car col-num))
  1448. (setq content (or category org-index--category-before)))
  1449. ;; Shift ref and timestamp ?
  1450. (if (org-index--flag-p 'shift-ref-and-date-on-add (car col-num))
  1451. (dotimes (i 2)
  1452. (if (or (string-match (concat "^\\s-*" org-index--ref-regex) content)
  1453. (string-match (concat org-ts-regexp-both) content))
  1454. (setq content (substring content (match-end 0))))))
  1455. (if (and (not silent) ; do not edit, if heading has already been added
  1456. (org-index--flag-p 'edit-on-add (car col-num)))
  1457. (setq content (read-from-minibuffer
  1458. (format "Edit text for column '%s': " (symbol-name (car col-num)))
  1459. content)))
  1460. (if (not (string= content ""))
  1461. (setq args (append (list (car col-num) content) args))))
  1462. args))
  1463. (defun org-index--collect-values-for-add-update-remote (id)
  1464. "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
  1465. (let (marker point args)
  1466. (setq marker (org-id-find id t))
  1467. ;; enter buffer and collect information
  1468. (with-current-buffer (marker-buffer marker)
  1469. (setq point (point))
  1470. (goto-char marker)
  1471. (setq args (org-index--collect-values-for-add-update id t (org-get-category)))
  1472. (goto-char point))
  1473. args))
  1474. (defun org-index--write-fields-for-add-update (kvs)
  1475. "Update current line with values from KVS (keys-values)."
  1476. (while kvs
  1477. (unless (eq (car kvs) 'ref)
  1478. (org-index--get-or-set-field (car kvs) (org-trim (cadr kvs))))
  1479. (setq kvs (cddr kvs))))
  1480. (defun org-index--do-delete ()
  1481. "Perform command delete."
  1482. (unless (org-at-heading-p)
  1483. (error "Not at headline"))
  1484. (let* ((id (org-entry-get (point) "ID"))
  1485. (ref (org-index--ref-from-id id)))
  1486. ;; maybe delete from heading
  1487. (if ref
  1488. (save-excursion
  1489. (end-of-line)
  1490. (let ((end (point)))
  1491. (beginning-of-line)
  1492. (when (search-forward ref end t)
  1493. (delete-char (- (length ref)))
  1494. (just-one-space)))))
  1495. ;; delete from index table
  1496. (if (org-index--delete-line id)
  1497. (format "Deleted index line %s" ref)
  1498. (format "Did not find id %s in index" id))))
  1499. (defun org-index--go (&optional column value)
  1500. "Position cursor on index line where COLUMN equals VALUE.
  1501. Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
  1502. (let (found text)
  1503. (unless (eq (current-buffer) org-index--buffer)
  1504. (error "This is a bug: Not in index buffer"))
  1505. ;; loop over lines
  1506. (goto-char org-index--below-hline)
  1507. (if column
  1508. (progn
  1509. (forward-line -1)
  1510. (while (and (not found)
  1511. (forward-line)
  1512. (org-at-table-p))
  1513. (setq found (string= value (org-index--get-or-set-field column)))))
  1514. (setq found t))
  1515. ;; return value
  1516. (if found
  1517. t
  1518. (goto-char org-index--below-hline)
  1519. nil)))
  1520. (defun org-index--do-head (ref id &optional other)
  1521. "Perform command head: Find node with REF or ID and present it.
  1522. If OTHER in separate window."
  1523. (setq org-index--last-ref ref)
  1524. (let (message marker)
  1525. (setq marker (org-id-find id t))
  1526. (if marker
  1527. (progn
  1528. (org-index--update-line id)
  1529. (let (cb)
  1530. (if other
  1531. (progn
  1532. (setq cb (current-buffer))
  1533. (pop-to-buffer (marker-buffer marker)))
  1534. (pop-to-buffer-same-window (marker-buffer marker)))
  1535. (goto-char marker)
  1536. (org-reveal t)
  1537. (org-show-entry)
  1538. (recenter))
  1539. (setq message (format "Found headline %s" ref)))
  1540. (setq message (format "Did not find headline %s" ref)))))
  1541. (defun org-index--do-occur ()
  1542. "Perform command occur."
  1543. (let ((word "") ; last word to search for growing and shrinking on keystrokes
  1544. (prompt "Search for: ")
  1545. (lines-wanted (window-body-height))
  1546. (lines-found 0) ; number of lines found
  1547. words ; list words that should match
  1548. occur-buffer
  1549. begin ; position of first line
  1550. narrow ; start of narrowed buffer
  1551. help-text ; cons with help text short and long
  1552. key-help ; for keys with special function
  1553. search-text ; description of text to search for
  1554. done ; true, if loop is done
  1555. in-c-backspace ; true, while processing C-backspace
  1556. show-headings ; true, if headings should be shown
  1557. help-overlay ; Overlay with help text
  1558. last-point ; Last position before end of search
  1559. key ; input from user
  1560. key-sequence) ; as a sequence
  1561. ;; make and show buffer
  1562. (if (get-buffer org-index--occur-buffer-name)
  1563. (kill-buffer org-index--occur-buffer-name))
  1564. (setq occur-buffer (make-indirect-buffer org-index--buffer org-index--occur-buffer-name))
  1565. (pop-to-buffer-same-window occur-buffer)
  1566. ;; avoid modifying direct buffer
  1567. (setq buffer-read-only t)
  1568. (toggle-truncate-lines 1)
  1569. (setq font-lock-keywords-case-fold-search t)
  1570. (setq case-fold-search t)
  1571. ;; reset stack and overlays
  1572. (setq org-index--occur-stack nil)
  1573. (setq org-index--occur-tail-overlay nil)
  1574. ;; narrow to table rows and one line before
  1575. (goto-char (marker-position org-index--below-hline))
  1576. (forward-line 0)
  1577. (setq begin (point))
  1578. (forward-line -1)
  1579. (setq narrow (point))
  1580. (while (org-at-table-p)
  1581. (forward-line))
  1582. (narrow-to-region narrow (point))
  1583. (goto-char (point-min))
  1584. (forward-line)
  1585. ;; initialize help text
  1586. (setq help-text (cons
  1587. "Incremental occur; `?' toggles help and headlines.\n"
  1588. (concat
  1589. (org-index--wrap
  1590. (concat
  1591. "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; all other keys end search.\n"))
  1592. org-index--headings)))
  1593. ;; insert overlays for help text and to cover unsearched lines
  1594. (setq help-overlay (make-overlay (point-min) begin))
  1595. (overlay-put help-overlay 'display (car help-text))
  1596. (overlay-put help-overlay 'face 'org-agenda-dimmed-todo-face)
  1597. (setq org-index--occur-tail-overlay (make-overlay (point-max) (point-max)))
  1598. (overlay-put org-index--occur-tail-overlay 'invisible t)
  1599. (while (not done)
  1600. (if in-c-backspace
  1601. (setq key "<backspace>")
  1602. (setq search-text (mapconcat 'identity (reverse (cons word words)) ","))
  1603. ;; read key
  1604. (setq key-sequence
  1605. (vector (read-key
  1606. (format "%s%s%s"
  1607. prompt
  1608. search-text
  1609. (if (string= search-text "") "" " ")))))
  1610. (setq key (key-description key-sequence)))
  1611. (cond
  1612. ((string= key "<C-backspace>")
  1613. (setq in-c-backspace t))
  1614. ((member key (list "<backspace>" "DEL")) ; erase last char
  1615. (if (= (length word) 0)
  1616. ;; nothing more to delete from current word; try next
  1617. (progn
  1618. (setq word (car words))
  1619. (setq words (cdr words))
  1620. (setq in-c-backspace nil))
  1621. ;; unhighlight longer match
  1622. (unhighlight-regexp (regexp-quote word))
  1623. ;; some chars are left; shorten word
  1624. (setq word (substring word 0 -1))
  1625. (when (= (length word) 0) ; when nothing left, use next word from list
  1626. (setq word (car words))
  1627. (setq words (cdr words))
  1628. (setq in-c-backspace nil))
  1629. ;; free top list of overlays and remove list
  1630. (setq lines-found (or (org-index--unhide) lines-wanted))
  1631. (move-overlay org-index--occur-tail-overlay
  1632. (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
  1633. (point-max))
  1634. (point-max))
  1635. ;; highlight shorter word
  1636. (unless (= (length word) 0)
  1637. (highlight-regexp (regexp-quote word) 'isearch))
  1638. ;; make sure, point is still visible
  1639. (goto-char begin)))
  1640. ((member key (list "SPC" ",")) ; space or comma: enter an additional search word
  1641. ;; push current word and clear, no need to change display
  1642. (setq words (cons word words))
  1643. (setq word ""))
  1644. ((string= key "?") ; question mark: toggle display of headlines and help
  1645. (setq help-text (cons (cdr help-text) (car help-text)))
  1646. (overlay-put help-overlay 'display (car help-text)))
  1647. ((and (= (length key) 1)
  1648. (aref printable-chars (elt key 0))) ; any printable char: add to current search word
  1649. ;; unhighlight short word
  1650. (unless (= (length word) 0)
  1651. (unhighlight-regexp (regexp-quote word)))
  1652. ;; add to word
  1653. (setq word (concat word key))
  1654. ;; make overlays to hide lines, that do not match longer word any more
  1655. (goto-char begin)
  1656. (setq lines-found (org-index--hide-with-overlays (cons word words) lines-wanted))
  1657. (move-overlay org-index--occur-tail-overlay
  1658. (if org-index--occur-stack (cdr (assoc :end-of-visible (car org-index--occur-stack)))
  1659. (point-max))
  1660. (point-max))
  1661. (goto-char begin)
  1662. ;; highlight longer word
  1663. (highlight-regexp (regexp-quote word) 'isearch)
  1664. ;; make sure, point is on a visible line
  1665. (line-move -1 t)
  1666. (line-move 1 t))
  1667. ;; anything else terminates loop
  1668. (t (setq done t))))
  1669. ;; put back input event, that caused the loop to end
  1670. (unless (string= key "C-g")
  1671. (setq unread-command-events (listify-key-sequence key-sequence))
  1672. (message key))
  1673. ;; postprocessing
  1674. (setq last-point (point))
  1675. ;; For performance reasons do not show matching lines for rest of table. So no code here.
  1676. ;; make permanent copy
  1677. ;; copy visible lines
  1678. (let ((lines-collected 0)
  1679. keymap line all-lines end-of-head)
  1680. (setq cursor-type t)
  1681. (goto-char begin)
  1682. ;; collect all visible lines
  1683. (while (and (not (eobp))
  1684. (< lines-collected lines-wanted))
  1685. ;; skip over invisible lines
  1686. (while (and (invisible-p (point))
  1687. (not (eobp)))
  1688. (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
  1689. (setq line (buffer-substring (line-beginning-position) (line-end-position)))
  1690. (unless (string= line "")
  1691. (incf lines-collected)
  1692. (setq all-lines (cons (concat line
  1693. "\n")
  1694. all-lines)))
  1695. (forward-line 1))
  1696. (kill-buffer org-index--occur-buffer-name) ; cannot keep this buffer; might become stale soon
  1697. ;; create new buffer
  1698. (setq occur-buffer (get-buffer-create org-index--occur-buffer-name))
  1699. (pop-to-buffer-same-window occur-buffer)
  1700. (insert org-index--headings)
  1701. (setq end-of-head (point))
  1702. ;; insert into new buffer
  1703. (save-excursion
  1704. (apply 'insert (reverse all-lines))
  1705. (if (= lines-collected lines-wanted)
  1706. (insert "\n(more lines omitted)\n")))
  1707. (org-mode)
  1708. (setq truncate-lines t)
  1709. (if (org-at-table-p) (org-table-align))
  1710. (font-lock-fontify-buffer)
  1711. ;; prepare help text
  1712. (setq org-index--occur-help-overlay (make-overlay (point-min) end-of-head))
  1713. (setq org-index--occur-help-text
  1714. (cons
  1715. (org-index--wrap
  1716. (concat "Search is done; `?' toggles help and headlines.\n"))
  1717. (concat
  1718. (org-index--wrap (format (concat "Search is done. "
  1719. (if (< lines-collected lines-wanted)
  1720. " Showing all %d matches for "
  1721. " Showing one window of matches for ")
  1722. "\"" search-text
  1723. "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> to matching line in index, <space> increments count.\n" )
  1724. (length all-lines)))
  1725. org-index--headings)))
  1726. (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))
  1727. (overlay-put org-index--occur-help-overlay 'face 'org-agenda-dimmed-todo-face)
  1728. ;; highlight words
  1729. (setq case-fold-search t)
  1730. (setq font-lock-keywords-case-fold-search t)
  1731. (mapc (lambda (w) (unless (or (not w) (string= w "")) (highlight-regexp (regexp-quote w) 'isearch)))
  1732. (cons word words))
  1733. (setq buffer-read-only t)
  1734. ;; install keyboard-shortcuts
  1735. (setq keymap (make-sparse-keymap))
  1736. (set-keymap-parent keymap org-mode-map)
  1737. (mapc (lambda (x) (define-key keymap (kbd x)
  1738. (lambda () (interactive)
  1739. (message "%s" (org-index--occur-to-head)))))
  1740. (list "<return>" "RET"))
  1741. (define-key keymap (kbd "<tab>")
  1742. (lambda () (interactive)
  1743. (message (org-index--occur-to-head t))))
  1744. (define-key keymap (kbd "SPC")
  1745. (lambda () (interactive)
  1746. ;; increment in index
  1747. (let ((ref (org-index--get-or-set-field 'ref))
  1748. count)
  1749. (org-index--on
  1750. 'ref ref
  1751. (setq count (+ 1 (string-to-number (org-index--get-or-set-field 'count))))
  1752. (org-index--get-or-set-field 'count (number-to-string count))
  1753. (org-index--promote-current-line))
  1754. ;; increment in this buffer
  1755. (let ((inhibit-read-only t))
  1756. (org-index--get-or-set-field 'count (number-to-string count)))
  1757. (message "Incremented count to %d" count))))
  1758. (define-key keymap (kbd "<S-return>")
  1759. (lambda () (interactive)
  1760. (org-index 'enter (org-index--get-or-set-field 'ref))))
  1761. (define-key keymap (kbd "?")
  1762. (lambda () (interactive)
  1763. (setq-local org-index--occur-help-text (cons (cdr org-index--occur-help-text) (car org-index--occur-help-text)))
  1764. (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))))
  1765. (use-local-map keymap))))
  1766. (defun org-index--wrap (text)
  1767. "Wrap TEXT at fill column."
  1768. (with-temp-buffer
  1769. (insert text)
  1770. (fill-region (point-min) (point-max) nil t)
  1771. (buffer-string)))
  1772. (defun org-index--occur-to-head (&optional other)
  1773. "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window."
  1774. (let ((ref (org-index--get-or-set-field 'ref))
  1775. (id (org-index--get-or-set-field 'id)))
  1776. (org-mark-ring-push)
  1777. (if id
  1778. (org-index--do-head ref id other)
  1779. (message "Current line has no id."))))
  1780. (defun org-index--hide-with-overlays (words lines-wanted)
  1781. "Hide text that is currently visible and does not match WORDS by creating overlays; leave LINES-WANTED lines visible."
  1782. (let ((lines-found 0)
  1783. (end-of-visible (point))
  1784. overlay overlays start matched)
  1785. ;; main loop
  1786. (while (and (not (eobp))
  1787. (< lines-found lines-wanted))
  1788. ;; skip invisible lines
  1789. (while (and (not (eobp))
  1790. (and
  1791. (invisible-p (point))
  1792. (< (point) (overlay-start org-index--occur-tail-overlay))))
  1793. (goto-char (overlay-end (car (overlays-at (point))))))
  1794. ;; find stretch of lines, that are currently visible but should be invisible now
  1795. (setq matched nil)
  1796. (setq start (point))
  1797. (while (and (not (eobp))
  1798. (not
  1799. (and
  1800. (invisible-p (point))
  1801. (< (point) (overlay-start org-index--occur-tail-overlay))))
  1802. (not (and (org-index--test-words words)
  1803. (setq matched t)))) ; for its side effect
  1804. (forward-line 1))
  1805. ;; create overlay to hide this stretch
  1806. (when (< start (point)) ; avoid creating an empty overlay
  1807. (setq overlay (make-overlay start (point)))
  1808. (overlay-put overlay 'invisible t)
  1809. (setq overlays (cons overlay overlays)))
  1810. ;; skip and count line, that matched
  1811. (when matched
  1812. (forward-line 1)
  1813. (setq end-of-visible (point))
  1814. (incf lines-found)))
  1815. ;; put new list on top of stack
  1816. (setq org-index--occur-stack
  1817. (cons (list (cons :overlays overlays)
  1818. (cons :end-of-visible end-of-visible)
  1819. (cons :lines lines-found))
  1820. org-index--occur-stack))
  1821. lines-found))
  1822. (defun org-index--unhide ()
  1823. "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
  1824. (when org-index--occur-stack
  1825. ;; delete overlays and make visible again
  1826. (mapc (lambda (y)
  1827. (delete-overlay y))
  1828. (cdr (assoc :overlays (car org-index--occur-stack))))
  1829. ;; remove from stack
  1830. (setq org-index--occur-stack (cdr org-index--occur-stack))
  1831. ;; return number of lines, that are now visible
  1832. (if org-index--occur-stack (cdr (assoc :lines (car org-index--occur-stack))))))
  1833. (defun org-index--test-words (words)
  1834. "Test current line for match against WORDS."
  1835. (let (line)
  1836. (setq line (downcase (buffer-substring (line-beginning-position) (line-beginning-position 2))))
  1837. (catch 'not-found
  1838. (dolist (w words)
  1839. (or (search w line)
  1840. (throw 'not-found nil)))
  1841. t)))
  1842. (defun org-index--create-new-line ()
  1843. "Do the common work for `org-index-new-line' and `org-index'."
  1844. (let (new)
  1845. ;; construct new reference
  1846. (unless new
  1847. (setq new (format "%s%d%s" org-index--head (1+ org-index--maxref) org-index--tail)))
  1848. ;; insert ref or id as last or first line, depending on sort-column
  1849. (goto-char org-index--below-hline)
  1850. (if (eq (org-index--special-column 'sort) 'count)
  1851. (progn
  1852. (while (org-at-table-p)
  1853. (forward-line))
  1854. (forward-line -1)
  1855. (org-table-insert-row t))
  1856. (org-table-insert-row))
  1857. ;; insert some of the standard values
  1858. (org-table-goto-column (org-index--column-num 'created))
  1859. (org-insert-time-stamp nil nil t)
  1860. (org-table-goto-column (org-index--column-num 'count))
  1861. (insert "1")
  1862. new))
  1863. (defun org-index--sort-silent ()
  1864. "Sort index for default column to remove any effects of temporary sorting."
  1865. (save-excursion
  1866. (org-index--verify-id)
  1867. (org-index--parse-table)
  1868. (org-index--on nil nil
  1869. (org-index--do-sort-index (org-index--special-column 'sort))
  1870. (org-table-align)
  1871. (remove-hook 'before-save-hook 'org-index--sort-silent))))
  1872. (provide 'org-index)
  1873. ;; Local Variables:
  1874. ;; fill-column: 75
  1875. ;; comment-column: 50
  1876. ;; lexical-binding: t
  1877. ;; End:
  1878. ;;; org-index.el ends here