org-fold-core.el 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. ;;; org-fold-core.el --- Folding buffer text -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2020-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Ihor Radchenko <yantar92 at gmail dot com>
  6. ;; Keywords: folding, invisible text
  7. ;; Homepage: https://orgmode.org
  8. ;;
  9. ;; This file is part of GNU Emacs.
  10. ;;
  11. ;; GNU Emacs is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation, either version 3 of the License, or
  14. ;; (at your option) any later version.
  15. ;; GNU Emacs is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  21. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  22. ;;
  23. ;;; Commentary:
  24. ;; This file contains library to control temporary invisibility
  25. ;; (folding and unfolding) of text in buffers.
  26. ;; The file implements the following functionality:
  27. ;;
  28. ;; - Folding/unfolding regions of text
  29. ;; - Searching and examining boundaries of folded text
  30. ;; - Interactive searching in folded text (via isearch)
  31. ;; - Handling edits in folded text
  32. ;; - Killing/yanking (copying/pasting) of the folded text
  33. ;; - Fontification of the folded text
  34. ;; To setup folding in an arbitrary buffer, one must call
  35. ;; `org-fold-core-initialize', optionally providing the list of folding specs to be
  36. ;; used in the buffer. The specs can be added, removed, or
  37. ;; re-configured later. Read below for more details.
  38. ;;; Folding/unfolding regions of text
  39. ;; User can temporarily hide/reveal (fold/unfold) arbitrary regions or
  40. ;; text. The folds can be nested.
  41. ;; Internally, nested folds are marked with different folding specs
  42. ;; Overlapping folds marked with the same folding spec are
  43. ;; automatically merged, while folds with different folding specs can
  44. ;; coexist and be folded/unfolded independently.
  45. ;; When multiple folding specs are applied to the same region of text,
  46. ;; text visibility is decided according to the folding spec with
  47. ;; topmost priority.
  48. ;; By default, we define two types of folding specs:
  49. ;; - 'org-fold-visible :: the folded text is not hidden
  50. ;; - 'org-fold-hidden :: the folded text is completely hidden
  51. ;;
  52. ;; The 'org-fold-visible spec has highest priority allowing parts of
  53. ;; text folded with 'org-fold-hidden to be shown unconditionally.
  54. ;; Consider the following Org mode link:
  55. ;; [[file:/path/to/file/file.ext][description]]
  56. ;; Only the word "description" is normally visible in this link.
  57. ;;
  58. ;; The way this partial visibility is achieved is combining the two
  59. ;; folding specs. The whole link is folded using 'org-fold-hidden
  60. ;; folding spec, but the visible part is additionally folded using
  61. ;; 'org-fold-visible:
  62. ;;
  63. ;; <begin org-fold-hidden>[[file:/path/to/file/file.ext][<begin org-fold-visible>description<end org-fold-visible>]]<end org-fold-hidden>
  64. ;;
  65. ;; Because 'org-fold-visible has higher priority than
  66. ;; 'org-fold-hidden, it suppresses the 'org-fold-hidden effect and
  67. ;; thus reveals the description part of the link.
  68. ;; Similar to 'org-fold-visible, display of any arbitrary folding spec
  69. ;; can be configured using folding spec properties. In particular,
  70. ;; `:visible' folding spec proprety controls whether the folded text
  71. ;; is visible or not. If the `:visible' folding spec property is nil,
  72. ;; folded text is hidden or displayed as a constant string (ellipsis)
  73. ;; according to the value of `:ellipsis' folding spec property. See
  74. ;; docstring of `org-fold-core--specs' for the description of all the available
  75. ;; folding spec properties.
  76. ;; Folding spec properties of any valid folding spec can be changed
  77. ;; any time using `org-fold-core-set-folding-spec-property'.
  78. ;; If necessary, one can add or remove folding specs using
  79. ;; `org-fold-core-add-folding-spec' and `org-fold-core-remove-folding-spec'.
  80. ;; If a buffer initialised with `org-fold-core-initialize' is cloned into indirect
  81. ;; buffers, it's folding state is copied to that indirect buffer.
  82. ;; The folding states are independent.
  83. ;; When working with indirect buffers that are handled by this
  84. ;; library, one has to keep in mind that folding state is preserved on
  85. ;; copy when using non-interactive functions. Moreover, the folding
  86. ;; states of all the indirect buffers will be copied together.
  87. ;;
  88. ;; Example of the implications:
  89. ;; Consider a base buffer and indirect buffer with the following state:
  90. ;; ----- base buffer --------
  91. ;; * Heading<begin fold>
  92. ;; Some text folded in the base buffer, but unfolded in the indirect buffer<end fold>
  93. ;; * Other heading
  94. ;; Heading unfolded in both the buffers.
  95. ;; ---------------------------
  96. ;; ------ indirect buffer ----
  97. ;; * Heading
  98. ;; Some text folded in the base buffer, but unfolded in the indirect buffer
  99. ;; * Other heading
  100. ;; Heading unfolded in both the buffers.
  101. ;; ----------------------------
  102. ;; If some Elisp code copies the whole "Heading" from the indirect
  103. ;; buffer with `buffer-substring' or match data and inserts it into
  104. ;; the base buffer, the inserted heading will be folded since the
  105. ;; internal setting for the folding state is shared between the base
  106. ;; and indirect buffers. It's just that the indirect buffer ignores
  107. ;; the base buffer folding settings. However, as soon as the text is
  108. ;; copied back to the base buffer, the folding state will become
  109. ;; respected again.
  110. ;; If the described situation is undesired, Elisp code can use
  111. ;; `filter-buffer-substring' instead of `buffer-substring'. All the
  112. ;; folding states that do not belong to the currently active buffer
  113. ;; will be cleared in the copied text then. See
  114. ;; `org-fold-core--buffer-substring-filter' for more details.
  115. ;; Because of details of implementation of the folding, it is also not
  116. ;; recommended to set text visibility in buffer directly by setting
  117. ;; `invisible' text property to anything other than t. While this
  118. ;; should usually work just fine, normal folding can be broken if one
  119. ;; sets `invisible' text property to a value not listed in
  120. ;; `buffer-invisibility-spec'.
  121. ;;; Searching and examining boundaries of folded text
  122. ;; It is possible to examine folding specs (there may be several) of
  123. ;; text at point or search for regions with the same folding spec.
  124. ;; See functions defined under ";;;; Searching and examining folded
  125. ;; text" below for details.
  126. ;; All the folding specs can be specified by symbol representing their
  127. ;; name. However, this is not always convenient, especially if the
  128. ;; same spec can be used for fold different syntaxical structures.
  129. ;; Any folding spec can be additionally referenced by a symbol listed
  130. ;; in the spec's `:alias' folding spec property. For example, Org
  131. ;; mode's `org-fold-outline' folding spec can be referened as any
  132. ;; symbol from the following list: '(headline heading outline
  133. ;; inlinetask plain-list) The list is the value of the spec's `:alias'
  134. ;; property.
  135. ;; Most of the functions defined below that require a folding spec
  136. ;; symbol as their argument, can also accept any symbol from the
  137. ;; `:alias' spec property to reference that folding spec.
  138. ;; If one wants to search invisible text without using the provided
  139. ;; functions, it is important to keep in mind that 'invisible text
  140. ;; property may have multiple possible values (not just nil and
  141. ;; t). Hence, (next-single-char-property-change pos 'invisible) is not
  142. ;; guarantied to return the boundary of invisible/visible text.
  143. ;;; Interactive searching inside folded text (via isearch)
  144. ;; The library provides a way to control if the folded text can be
  145. ;; searchable using isearch. If the text is searchable, it is also
  146. ;; possible to control to unfold it temporarily during interactive
  147. ;; isearch session.
  148. ;; The isearch behaviour is controlled on per-folding-spec basis by
  149. ;; setting `isearch-open' and `isearch-ignore' folding spec
  150. ;; properties. The the docstring of `org-fold-core--specs' for more details.
  151. ;;; Handling edits inside folded text
  152. ;; The visibility of the text inserted in front, rear, or in the
  153. ;; middle of a folded region is managed according to `:front-sticky'
  154. ;; and `:rear-sticky' folding properties of the corresponding folding
  155. ;; spec. The rules are the same with stickyness of text properties in
  156. ;; Elisp.
  157. ;; If a text being inserted into the buffer is already folded and
  158. ;; invisible (before applying the stickyness rules), then it is
  159. ;; revealed. This behaviour can be changed by wrapping the insertion
  160. ;; code into `org-fold-core-ignore-modifications' macro. The macro will disable
  161. ;; all the processing related to buffer modifications.
  162. ;; The library also provides a way to unfold the text after some
  163. ;; destructive changes breaking syntaxical structure of the buffer.
  164. ;; For example, Org mode automatically reveals folded drawers when the
  165. ;; drawer becomes syntaxically incorrect:
  166. ;; ------- before modification -------
  167. ;; :DRAWER:<begin fold>
  168. ;; Some folded text inside drawer
  169. ;; :END:<end fold>
  170. ;; -----------------------------------
  171. ;; If the ":END:" is edited, drawer syntax is not correct anymore and
  172. ;; the folded text is automatically unfolded.
  173. ;; ------- after modification --------
  174. ;; :DRAWER:
  175. ;; Some folded text inside drawer
  176. ;; :EN:
  177. ;; -----------------------------------
  178. ;; The described automatic unfolding is controlled by `:fragile'
  179. ;; folding spec property. It's value can be a function checking if
  180. ;; changes inside (or around) the fold should drigger the unfold. By
  181. ;; default, only changes that directly involve folded regions will
  182. ;; trigger the check. In addition, `org-fold-core-extend-changed-region-functions'
  183. ;; can be set to extend the checks to all folded regions intersecting
  184. ;; with the region returned by the functions listed in the variable.
  185. ;; The fragility checks can be bypassed if the code doing
  186. ;; modifications is wrapped into `org-fold-core-ignore-fragility-checks' macro.
  187. ;;; Fontification of the folded text
  188. ;; When working with huge buffers, `font-lock' may take a lot of time
  189. ;; to fontify all the buffer text during startup. This library
  190. ;; provides a way to delay fontification of initially folded text to
  191. ;; the time when the text is unfolded. The fontification is
  192. ;; controlled on per-folding-spec basis according to `:font-lock-skip'
  193. ;; folding spec property.
  194. ;; This library replaces `font-lock-fontify-region-function' to implement the
  195. ;; delayed fontification. However, it only does so when
  196. ;; `font-lock-fontify-region-function' is not modified at the initialisation
  197. ;; time. If one needs to use both delayed fontification and custom
  198. ;; `font-lock-fontify-region-function', it is recommended to consult the
  199. ;; source code of `org-fold-core-fontify-region'.
  200. ;;; Performance considerations
  201. ;; This library is using text properties to hide text. Text
  202. ;; properties are much faster than overlays, that could be used for
  203. ;; the same purpose. Overlays are implemented with O(n) complexity in
  204. ;; Emacs (as for 2021-03-11). It means that any attempt to move
  205. ;; through hidden text in a file with many invisible overlays will
  206. ;; require time scaling with the number of folded regions (the problem
  207. ;; Overlays note of the manual warns about). For curious, historical
  208. ;; reasons why overlays are not efficient can be found in
  209. ;; https://www.jwz.org/doc/lemacs.html.
  210. ;; Despite using text properties, the performance is still limited by
  211. ;; Emacs display engine. For example, >7Mb of text hidden within
  212. ;; visible part of a buffer may cause noticeable lags (which is still
  213. ;; orders of magnitude better in comparison with overlays). If the
  214. ;; performance issues become critical while using this library, it is
  215. ;; recommended to minimise the number of folding specs used in the
  216. ;; same buffer at a time.
  217. ;; Alternatively, the library provides `org-fold-core--optimise-for-huge-buffers'
  218. ;; for additional speedup. This can be used as a file-local variable
  219. ;; in huge buffers. The variable can be set to enable various levels
  220. ;; of extra optimisation. See the docstring for detailed information.
  221. ;; It is worth noting that when using `org-fold-core--optimise-for-huge-buffers'
  222. ;; with `grab-invisible' option, folded regions copied to other
  223. ;; buffers (including buffers that do not use this library) will
  224. ;; remain invisible. org-fold-core provides functions to work around
  225. ;; this issue: `org-fold-core-remove-optimisation' and `org-fold-core-update-optimisation', but
  226. ;; it is unlikely that a random external package will use them.
  227. ;; Another possible bottleneck is the fragility check after the change
  228. ;; related to the folded text. The functions used in `:fragile'
  229. ;; folding properties must be optimised. Also,
  230. ;; `org-fold-core-ignore-fragility-checks' or even `org-fold-core-ignore-modifications' may be
  231. ;; used when appropriate in the performance-critical code. When
  232. ;; inserting text from within `org-fold-core-ignore-modifications' macro, it is
  233. ;; recommended to use `insert-and-inherit' instead of `insert' and
  234. ;; `insert-before-markers-and-inherit' instead of
  235. ;; `insert-before-markers' to avoid revealing inserted text in the
  236. ;; middle of a folded region.
  237. ;; Performance of isearch is currently limited by Emacs isearch
  238. ;; implementation. For now, Emacs isearch only supports searching
  239. ;; through text hidden using overlays. This library handles isearch
  240. ;; by converting folds with matching text to overlays, which may
  241. ;; affect performance in case of large number of matches. In the
  242. ;; future, Emacs will hopefully accept the relevant patch allowing
  243. ;; isearch to work with text hidden via text properties, but the
  244. ;; performance hit has to be accepted meanwhile.
  245. ;;; Code:
  246. (require 'org-macs)
  247. (require 'org-compat)
  248. (declare-function isearch-filter-visible "isearch" (beg end))
  249. ;;; Customization
  250. (defcustom org-fold-core-style 'text-properties
  251. "Internal implementation detail used to hide folded text.
  252. Can be either `text-properties' or `overlays'.
  253. The former is faster on large files, while the latter is generally
  254. less error-prone."
  255. :group 'org
  256. :package-version '(Org . "9.6")
  257. :type '(choice
  258. (const :tag "Overlays" 'overlays)
  259. (const :tag "Text properties" 'text-properties)))
  260. (defcustom org-fold-core-first-unfold-functions nil
  261. "Functions executed after first unfolding during fontification.
  262. Each function is exectured with two arguments: begin and end points of
  263. the unfolded region."
  264. :group 'org
  265. :package-version '(Org . "9.6")
  266. :type 'hook)
  267. (defvar-local org-fold-core-isearch-open-function #'org-fold-core--isearch-reveal
  268. "Function used to reveal hidden text found by isearch.
  269. The function is called with a single argument - point where text is to
  270. be revealed.")
  271. (defvar-local org-fold-core--optimise-for-huge-buffers nil
  272. "Non-nil turns on extra speedup on huge buffers (Mbs of folded text).
  273. This setting is risky and may cause various artefacts and degraded
  274. functionality, especially when using external packages. It is
  275. recommended to enable it on per-buffer basis as file-local variable.
  276. When set to non-nil, must be a list containing one or multiple the
  277. following symbols:
  278. - `grab-invisible': Use `invisible' text property to hide text. This
  279. will reduce the load on Emacs display engine and one may use it if
  280. moving point across folded regions becomes slow. However, as a side
  281. effect, some external packages extracting i.e. headlings from folded
  282. parts of buffer may keep the text invisible.
  283. - `ignore-fragility-checks': Do not try to detect when user edits
  284. break structure of the folded elements. This will speed up
  285. modifying the folded regions at the cost that some higher-level
  286. functions relying on this package might not be able to unfold the
  287. edited text. For example, removed leading stars from a folded
  288. headline in Org mode will break visibility cycling since Org mode
  289. will not be avare that the following folded text belonged to
  290. headline.
  291. - `ignore-modification-checks': Do not try to detect insertions in the
  292. middle of the folded regions. This will speed up non-interactive
  293. edits of the folded regions. However, text inserted in the middle
  294. of the folded regions may become visible for some external packages
  295. inserting text using `insert' instead of `insert-and-inherit' (the
  296. latter is rarely used in practice).
  297. - `ignore-indirect': Do not decouple folding state in the indirect
  298. buffers. This can speed up Emacs display engine (and thus motion of
  299. point), especially when large number of indirect buffers is being
  300. used.
  301. - `merge-folds': Do not distinguish between different types of folding
  302. specs. This is the most aggressive optimisation with unforseen and
  303. potentially drastic effects.")
  304. (put 'org-fold-core--optimise-for-huge-buffers 'safe-local-variable 'listp)
  305. ;;; Core functionality
  306. ;;;; Folding specs
  307. (defvar-local org-fold-core--specs '((org-fold-visible
  308. (:visible . t)
  309. (:alias . (visible)))
  310. (org-fold-hidden
  311. (:ellipsis . "...")
  312. (:isearch-open . t)
  313. (:alias . (hidden))))
  314. "Folding specs defined in current buffer.
  315. Each spec is a list (SPEC-SYMBOL SPEC-PROPERTIES).
  316. SPEC-SYMBOL is the symbol respresenting the folding spec.
  317. SPEC-PROPERTIES is an alist defining folding spec properties.
  318. If a text region is folded using multiple specs, only the folding spec
  319. listed earlier is used.
  320. The following properties are known:
  321. - :ellipsis :: must be nil or string to show when text is folded
  322. using this spec.
  323. - :global :: non-nil means that folding state will be preserved
  324. when copying folded text between buffers.
  325. - :isearch-ignore :: non-nil means that folded text is not searchable
  326. using isearch.
  327. - :isearch-open :: non-nil means that isearch can reveal text hidden
  328. using this spec. This property does nothing
  329. when 'isearch-ignore property is non-nil.
  330. - :front-sticky :: non-nil means that text prepended to the folded text
  331. is automatically folded.
  332. - :rear-sticky :: non-nil means that text appended to the folded text
  333. is folded.
  334. - :visible :: non-nil means that folding spec visibility is not
  335. managed. Instead, visibility settings in
  336. `buffer-invisibility-spec' will be used as is.
  337. Note that changing this property from nil to t may
  338. clear the setting in `buffer-invisibility-spec'.
  339. - :alias :: a list of aliases for the SPEC-SYMBOL.
  340. - :font-lock-skip :: Suppress font-locking in folded text.
  341. - :fragile :: Must be a function accepting two arguments.
  342. Non-nil means that changes in region may cause
  343. the region to be revealed. The region is
  344. revealed after changes if the function returns
  345. non-nil.
  346. The function called after changes are made with
  347. two arguments: cons (beg . end) representing the
  348. folded region and spec symbol.")
  349. (defvar-local org-fold-core--spec-symbols nil
  350. "Alist holding buffer spec symbols and aliases.
  351. This variable is defined to reduce load on Emacs garbage collector
  352. reducing the number of transiently allocated variables.")
  353. (defvar-local org-fold-core--spec-list nil
  354. "List holding buffer spec symbols, but not aliases.
  355. This variable is defined to reduce load on Emacs garbage collector
  356. reducing the number of transiently allocated variables.")
  357. (defvar-local org-fold-core-extend-changed-region-functions nil
  358. "Special hook run just before handling changes in buffer.
  359. This is used to account changes outside folded regions that still
  360. affect the folded region visibility. For example, removing all stars
  361. at the beginning of a folded Org mode heading should trigger the
  362. folded text to be revealed. Each function is called with two
  363. arguments: beginning and the end of the changed region.")
  364. ;;; Utility functions
  365. (defsubst org-fold-core-folding-spec-list (&optional buffer)
  366. "Return list of all the folding spec symbols in BUFFER."
  367. (or (buffer-local-value 'org-fold-core--spec-list (or buffer (current-buffer)))
  368. (with-current-buffer (or buffer (current-buffer))
  369. (setq org-fold-core--spec-list (mapcar #'car org-fold-core--specs)))))
  370. (defun org-fold-core-get-folding-spec-from-alias (spec-or-alias)
  371. "Return the folding spec symbol for SPEC-OR-ALIAS.
  372. Return nil when there is no matching folding spec."
  373. (when spec-or-alias
  374. (unless org-fold-core--spec-symbols
  375. (dolist (spec (org-fold-core-folding-spec-list))
  376. (push (cons spec spec) org-fold-core--spec-symbols)
  377. (dolist (alias (assq :alias (assq spec org-fold-core--specs)))
  378. (push (cons alias spec) org-fold-core--spec-symbols))))
  379. (alist-get spec-or-alias org-fold-core--spec-symbols)))
  380. (defsubst org-fold-core-folding-spec-p (spec-or-alias)
  381. "Check if SPEC-OR-ALIAS is a registered folding spec."
  382. (org-fold-core-get-folding-spec-from-alias spec-or-alias))
  383. (defsubst org-fold-core--check-spec (spec-or-alias)
  384. "Throw an error if SPEC-OR-ALIAS is not in `org-fold-core--spec-priority-list'."
  385. (unless (org-fold-core-folding-spec-p spec-or-alias)
  386. (error "%s is not a valid folding spec" spec-or-alias)))
  387. (defsubst org-fold-core-get-folding-spec-property (spec-or-alias property)
  388. "Get PROPERTY of a folding SPEC-OR-ALIAS.
  389. Possible properties can be found in `org-fold-core--specs' docstring."
  390. (org-fold-core--check-spec spec-or-alias)
  391. (if (and (memql 'ignore-indirect org-fold-core--optimise-for-huge-buffers)
  392. (eq property :global))
  393. t
  394. (if (and (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
  395. (eq property :visible))
  396. nil
  397. (cdr (assq property (assq (org-fold-core-get-folding-spec-from-alias spec-or-alias) org-fold-core--specs))))))
  398. (defconst org-fold-core--spec-property-prefix "org-fold--spec-"
  399. "Prefix used to create property symbol.")
  400. (defsubst org-fold-core-get-folding-property-symbol (spec &optional buffer global)
  401. "Get folding text property using to store SPEC in current buffer or BUFFER.
  402. If GLOBAL is non-nil, do not make the property unique in the BUFFER."
  403. (if (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
  404. (intern (format "%s-global" org-fold-core--spec-property-prefix))
  405. (intern (format (concat org-fold-core--spec-property-prefix "%s-%S")
  406. (symbol-name spec)
  407. ;; (sxhash buf) appears to be not constant over time.
  408. ;; Using buffer-name is safe, since the only place where
  409. ;; buffer-local text property actually matters is an indirect
  410. ;; buffer, where the name cannot be same anyway.
  411. (if global 'global
  412. (sxhash (buffer-name (or buffer (current-buffer)))))))))
  413. (defsubst org-fold-core-get-folding-spec-from-folding-prop (folding-prop)
  414. "Return folding spec symbol used for folding property with name FOLDING-PROP."
  415. (catch :exit
  416. (dolist (spec (org-fold-core-folding-spec-list))
  417. ;; We know that folding properties have
  418. ;; folding spec in their name.
  419. (when (string-match-p (symbol-name spec)
  420. (symbol-name folding-prop))
  421. (throw :exit spec)))))
  422. (defvar org-fold-core--property-symbol-cache (make-hash-table :test 'equal)
  423. "Saved values of folding properties for (buffer . spec) conses.")
  424. (defvar-local org-fold-core--indirect-buffers nil
  425. "List of indirect buffers created from current buffer.
  426. The first element of the list is always the current buffer.
  427. This variable is needed to work around Emacs bug#46982, while Emacs
  428. does not provide a way `after-change-functions' in any other buffer
  429. than the buffer where the change was actually made.")
  430. (defmacro org-fold-core-cycle-over-indirect-buffers (&rest body)
  431. "Execute BODY in current buffer and all its indirect buffers.
  432. Also, make sure that folding properties from killed buffers are not
  433. hanging around."
  434. (declare (debug (form body)) (indent 1))
  435. `(let (buffers dead-properties)
  436. (if (and (not (buffer-base-buffer))
  437. (not (eq (current-buffer) (car org-fold-core--indirect-buffers))))
  438. ;; We are in base buffer with `org-fold-core--indirect-buffers' value from
  439. ;; different buffer. This can happen, for example, when
  440. ;; org-capture copies local variables into *Capture* buffer.
  441. (setq buffers (list (current-buffer)))
  442. (dolist (buf (cons (or (buffer-base-buffer) (current-buffer))
  443. (buffer-local-value 'org-fold-core--indirect-buffers (or (buffer-base-buffer) (current-buffer)))))
  444. (if (buffer-live-p buf)
  445. (push buf buffers)
  446. (dolist (spec (org-fold-core-folding-spec-list))
  447. (when (and (not (org-fold-core-get-folding-spec-property spec :global))
  448. (gethash (cons buf spec) org-fold-core--property-symbol-cache))
  449. ;; Make sure that dead-properties variable can be passed
  450. ;; as argument to `remove-text-properties'.
  451. (push t dead-properties)
  452. (push (gethash (cons buf spec) org-fold-core--property-symbol-cache)
  453. dead-properties))))))
  454. (dolist (buf buffers)
  455. (with-current-buffer buf
  456. (with-silent-modifications
  457. (save-restriction
  458. (widen)
  459. (remove-text-properties
  460. (point-min) (point-max)
  461. dead-properties)))
  462. ,@body))))
  463. ;; This is the core function used to fold text in buffers. We use
  464. ;; text properties to hide folded text, however 'invisible property is
  465. ;; not directly used (unless risky `org-fold-core--optimise-for-huge-buffers' is
  466. ;; enabled). Instead, we define unique text property (folding
  467. ;; property) for every possible folding spec and add the resulting
  468. ;; text properties into `char-property-alias-alist', so that
  469. ;; 'invisible text property is automatically defined if any of the
  470. ;; folding properties is non-nil. This approach lets us maintain
  471. ;; multiple folds for the same text region - poor man's overlays (but
  472. ;; much faster). Additionally, folding properties are ensured to be
  473. ;; unique for different buffers (especially for indirect
  474. ;; buffers). This is done to allow different folding states in
  475. ;; indirect buffers.
  476. (defun org-fold-core--property-symbol-get-create (spec &optional buffer return-only)
  477. "Return a unique symbol suitable as folding text property.
  478. Return value is unique for folding SPEC in BUFFER.
  479. If the buffer already have buffer-local setup in `char-property-alias-alist'
  480. and the setup appears to be created for different buffer,
  481. copy the old invisibility state into new buffer-local text properties,
  482. unless RETURN-ONLY is non-nil."
  483. (if (eq org-fold-core-style 'overlays)
  484. (org-fold-core-get-folding-property-symbol spec nil 'global)
  485. (let* ((buf (or buffer (current-buffer))))
  486. ;; Create unique property symbol for SPEC in BUFFER
  487. (let ((local-prop (or (gethash (cons buf spec) org-fold-core--property-symbol-cache)
  488. (puthash (cons buf spec)
  489. (org-fold-core-get-folding-property-symbol
  490. spec buf
  491. (org-fold-core-get-folding-spec-property spec :global))
  492. org-fold-core--property-symbol-cache))))
  493. (prog1
  494. local-prop
  495. (unless return-only
  496. (with-current-buffer buf
  497. ;; Update folding properties carried over from other
  498. ;; buffer (implying that current buffer is indirect
  499. ;; buffer). Normally, `char-property-alias-alist' in new
  500. ;; indirect buffer is a copy of the same variable from
  501. ;; the base buffer. Then, `char-property-alias-alist'
  502. ;; would contain folding properties, which are not
  503. ;; matching the generated `local-prop'.
  504. (unless (member local-prop (cdr (assq 'invisible char-property-alias-alist)))
  505. ;; Add current buffer to the list of indirect buffers in the base buffer.
  506. (when (buffer-base-buffer)
  507. (with-current-buffer (buffer-base-buffer)
  508. (setq-local org-fold-core--indirect-buffers
  509. (let (bufs)
  510. (org-fold-core-cycle-over-indirect-buffers
  511. (push (current-buffer) bufs))
  512. (push buf bufs)
  513. (delete-dups bufs)))))
  514. ;; Copy all the old folding properties to preserve the folding state
  515. (with-silent-modifications
  516. (dolist (old-prop (cdr (assq 'invisible char-property-alias-alist)))
  517. (org-with-wide-buffer
  518. (let* ((pos (point-min))
  519. (spec (org-fold-core-get-folding-spec-from-folding-prop old-prop))
  520. ;; Generate new buffer-unique folding property
  521. (new-prop (when spec (org-fold-core--property-symbol-get-create spec nil 'return-only))))
  522. ;; Copy the visibility state for `spec' from `old-prop' to `new-prop'
  523. (unless (eq old-prop new-prop)
  524. (while (< pos (point-max))
  525. (let ((val (get-text-property pos old-prop))
  526. (next (next-single-char-property-change pos old-prop)))
  527. (when val
  528. (put-text-property pos next new-prop val))
  529. (setq pos next)))))))
  530. ;; Update `char-property-alias-alist' with folding
  531. ;; properties unique for the current buffer.
  532. (setq-local char-property-alias-alist
  533. (cons (cons 'invisible
  534. (mapcar (lambda (spec)
  535. (org-fold-core--property-symbol-get-create spec nil 'return-only))
  536. (org-fold-core-folding-spec-list)))
  537. (remove (assq 'invisible char-property-alias-alist)
  538. char-property-alias-alist)))
  539. ;; Set folding property stickyness according to
  540. ;; their `:font-sticky' and `:rear-sticky'
  541. ;; parameters.
  542. (let (full-prop-list)
  543. (org-fold-core-cycle-over-indirect-buffers
  544. (setq full-prop-list
  545. (append full-prop-list
  546. (delq nil
  547. (mapcar (lambda (spec)
  548. (cond
  549. ((org-fold-core-get-folding-spec-property spec :front-sticky)
  550. (cons (org-fold-core--property-symbol-get-create spec nil 'return-only)
  551. nil))
  552. ((org-fold-core-get-folding-spec-property spec :rear-sticky)
  553. nil)
  554. (t
  555. (cons (org-fold-core--property-symbol-get-create spec nil 'return-only)
  556. t))))
  557. (org-fold-core-folding-spec-list))))))
  558. (org-fold-core-cycle-over-indirect-buffers
  559. (setq-local text-property-default-nonsticky
  560. (delete-dups (append
  561. text-property-default-nonsticky
  562. full-prop-list))))))))))))))
  563. (defun org-fold-core-decouple-indirect-buffer-folds ()
  564. "Copy and decouple folding state in a newly created indirect buffer.
  565. This function is mostly indented to be used in `clone-indirect-buffer-hook'."
  566. (when (and (buffer-base-buffer)
  567. (eq org-fold-core-style 'text-properties))
  568. (org-fold-core--property-symbol-get-create (car (org-fold-core-folding-spec-list)))))
  569. ;;; API
  570. ;;;; Modifying folding specs
  571. (defun org-fold-core-set-folding-spec-property (spec property value &optional force)
  572. "Set PROPERTY of a folding SPEC to VALUE.
  573. Possible properties and values can be found in `org-fold-core--specs' docstring.
  574. Do not check previous value when FORCE is non-nil."
  575. (pcase property
  576. (:ellipsis
  577. (unless (and (not force) (equal value (org-fold-core-get-folding-spec-property spec :ellipsis)))
  578. (remove-from-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis)))
  579. (unless (org-fold-core-get-folding-spec-property spec :visible)
  580. (add-to-invisibility-spec (cons spec value)))))
  581. (:visible
  582. (unless (or (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
  583. (and (not force) (equal value (org-fold-core-get-folding-spec-property spec :visible))))
  584. (if value
  585. (remove-from-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis)))
  586. (add-to-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis))))))
  587. (:alias
  588. ;; Clear symbol cache.
  589. (setq org-fold-core--spec-symbols nil))
  590. (:isearch-open nil)
  591. (:isearch-ignore nil)
  592. (:front-sticky nil)
  593. (:rear-sticky nil)
  594. (_ nil))
  595. (setf (cdr (assq property (assq spec org-fold-core--specs))) value))
  596. (defun org-fold-core-add-folding-spec (spec &optional properties buffer append)
  597. "Add a new folding SPEC with PROPERTIES in BUFFER.
  598. SPEC must be a symbol. BUFFER can be a buffer to set SPEC in or nil to
  599. set SPEC in current buffer.
  600. By default, the added SPEC will have highest priority among the
  601. previously defined specs. When optional APPEND argument is non-nil,
  602. SPEC will have the lowest priority instead. If SPEC was already
  603. defined earlier, it will be redefined according to provided optional
  604. arguments.
  605. `
  606. The folding spec properties will be set to PROPERTIES (see
  607. `org-fold-core--specs' for details)."
  608. (when (eq spec 'all) (error "Cannot use reserved folding spec symbol 'all"))
  609. (with-current-buffer (or buffer (current-buffer))
  610. ;; Clear the cache.
  611. (setq org-fold-core--spec-list nil
  612. org-fold-core--spec-symbols nil)
  613. (let* ((full-properties (mapcar (lambda (prop) (cons prop (cdr (assq prop properties))))
  614. '( :visible :ellipsis :isearch-ignore
  615. :global :isearch-open :front-sticky
  616. :rear-sticky :fragile :alias
  617. :font-lock-skip)))
  618. (full-spec (cons spec full-properties)))
  619. (add-to-list 'org-fold-core--specs full-spec append)
  620. (mapc (lambda (prop-cons) (org-fold-core-set-folding-spec-property spec (car prop-cons) (cdr prop-cons) 'force)) full-properties)
  621. ;; Update buffer inivisibility specs.
  622. (org-fold-core--property-symbol-get-create spec))))
  623. (defun org-fold-core-remove-folding-spec (spec &optional buffer)
  624. "Remove a folding SPEC in BUFFER.
  625. SPEC must be a symbol.
  626. BUFFER can be a buffer to remove SPEC in, nil to remove SPEC in current
  627. buffer, or 'all to remove SPEC in all open `org-mode' buffers and all
  628. future org buffers."
  629. (org-fold-core--check-spec spec)
  630. (when (eq buffer 'all)
  631. (setq-default org-fold-core--specs (delete (cdr (assq spec org-fold-core--specs)) org-fold-core--specs))
  632. (mapc (lambda (buf)
  633. (org-fold-core-remove-folding-spec spec buf))
  634. (buffer-list)))
  635. (let ((buffer (or buffer (current-buffer))))
  636. (with-current-buffer buffer
  637. ;; Clear the cache.
  638. (setq org-fold-core--spec-list nil
  639. org-fold-core--spec-symbols nil)
  640. (org-fold-core-set-folding-spec-property spec :visible t)
  641. (setq org-fold-core--specs (delete (cdr (assq spec org-fold-core--specs)) org-fold-core--specs)))))
  642. (defun org-fold-core-initialize (&optional specs)
  643. "Setup folding in current buffer using SPECS as value of `org-fold-core--specs'."
  644. ;; Preserve the priorities.
  645. (when specs (setq specs (nreverse specs)))
  646. (unless specs (setq specs org-fold-core--specs))
  647. (setq org-fold-core--specs nil
  648. org-fold-core--spec-list nil
  649. org-fold-core--spec-symbols nil)
  650. (dolist (spec specs)
  651. (org-fold-core-add-folding-spec (car spec) (cdr spec)))
  652. (add-hook 'after-change-functions 'org-fold-core--fix-folded-region nil 'local)
  653. (add-hook 'clone-indirect-buffer-hook #'org-fold-core-decouple-indirect-buffer-folds nil 'local)
  654. ;; Optimise buffer fontification to not fontify folded text.
  655. (when (eq font-lock-fontify-region-function #'font-lock-default-fontify-region)
  656. (setq-local font-lock-fontify-region-function 'org-fold-core-fontify-region)
  657. (add-to-list 'font-lock-extra-managed-props 'org-fold-core-fontified))
  658. ;; Setup killing text
  659. (setq-local filter-buffer-substring-function #'org-fold-core--buffer-substring-filter)
  660. (if (and (boundp 'isearch-opened-regions)
  661. (eq org-fold-core-style 'text-properties))
  662. ;; Use new implementation of isearch allowing to search inside text
  663. ;; hidden via text properties.
  664. (org-fold-core--isearch-setup 'text-properties)
  665. (org-fold-core--isearch-setup 'overlays)))
  666. ;;;; Searching and examining folded text
  667. (defsubst org-fold-core-folded-p (&optional pos spec-or-alias)
  668. "Non-nil if the character after POS is folded.
  669. If POS is nil, use `point' instead.
  670. If SPEC-OR-ALIAS is a folding spec, only check the given folding spec."
  671. (org-fold-core-get-folding-spec spec-or-alias pos))
  672. (defun org-fold-core-region-folded-p (beg end &optional spec-or-alias)
  673. "Non-nil if the region between BEG and END is folded.
  674. If SPEC-OR-ALIAS is a folding spec, only check the given folding spec."
  675. (org-with-point-at beg
  676. (catch :visible
  677. (while (< (point) end)
  678. (unless (org-fold-core-get-folding-spec spec-or-alias) (throw :visible nil))
  679. (goto-char (org-fold-core-next-folding-state-change spec-or-alias nil end)))
  680. t)))
  681. (defun org-fold-core-get-folding-spec (&optional spec-or-alias pom)
  682. "Get folding state at `point' or POM.
  683. Return nil if there is no folding at point or POM.
  684. If SPEC-OR-ALIAS is nil, return a folding spec with highest priority
  685. among present at `point' or POM.
  686. If SPEC-OR-ALIAS is 'all, return the list of all present folding
  687. specs.
  688. If SPEC-OR-ALIAS is a valid folding spec or a spec alias, return the
  689. corresponding folding spec (if the text is folded using that spec)."
  690. (let ((spec (if (eq spec-or-alias 'all)
  691. 'all
  692. (org-fold-core-get-folding-spec-from-alias spec-or-alias))))
  693. (when (and spec (not (eq spec 'all))) (org-fold-core--check-spec spec))
  694. (org-with-point-at pom
  695. (cond
  696. ((eq spec 'all)
  697. (let ((result))
  698. (dolist (spec (org-fold-core-folding-spec-list))
  699. (let ((val (get-char-property (point) (org-fold-core--property-symbol-get-create spec nil t))))
  700. (when val (push val result))))
  701. (reverse result)))
  702. ((null spec)
  703. (let ((result (get-char-property (point) 'invisible)))
  704. (when (org-fold-core-folding-spec-p result) result)))
  705. (t (get-char-property (point) (org-fold-core--property-symbol-get-create spec nil t)))))))
  706. (defun org-fold-core-get-folding-specs-in-region (beg end)
  707. "Get all folding specs in region from BEG to END."
  708. (let ((pos beg)
  709. all-specs)
  710. (while (< pos end)
  711. (setq all-specs (append all-specs (org-fold-core-get-folding-spec nil pos)))
  712. (setq pos (org-fold-core-next-folding-state-change nil pos end)))
  713. (unless (listp all-specs) (setq all-specs (list all-specs)))
  714. (delete-dups all-specs)))
  715. (defun org-fold-core-get-region-at-point (&optional spec-or-alias pom)
  716. "Return region folded using SPEC-OR-ALIAS at POM.
  717. If SPEC is nil, return the largest possible folded region.
  718. The return value is a cons of beginning and the end of the region.
  719. Return nil when no fold is present at point of POM."
  720. (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
  721. (org-with-point-at (or pom (point))
  722. (if spec
  723. (if (eq org-fold-core-style 'text-properties)
  724. (org-find-text-property-region (point) (org-fold-core--property-symbol-get-create spec nil t))
  725. (let ((ov (cdr (get-char-property-and-overlay (point) (org-fold-core--property-symbol-get-create spec nil t)))))
  726. (when ov (cons (overlay-start ov) (overlay-end ov)))))
  727. (let ((region (cons (point) (point))))
  728. (dolist (spec (org-fold-core-get-folding-spec 'all))
  729. (let ((local-region (org-fold-core-get-region-at-point spec)))
  730. (when (< (car local-region) (car region))
  731. (setcar region (car local-region)))
  732. (when (> (cdr local-region) (cdr region))
  733. (setcdr region (cdr local-region)))))
  734. (unless (eq (car region) (cdr region)) region))))))
  735. (defun org-fold-core-next-visibility-change (&optional pos limit ignore-hidden-p previous-p)
  736. "Return next point from POS up to LIMIT where text becomes visible/invisible.
  737. By default, text hidden by any means (i.e. not only by folding, but
  738. also via fontification) will be considered.
  739. If IGNORE-HIDDEN-P is non-nil, consider only folded text.
  740. If PREVIOUS-P is non-nil, search backwards."
  741. (let* ((pos (or pos (point)))
  742. (invisible-p (if ignore-hidden-p
  743. #'org-fold-core-folded-p
  744. #'invisible-p))
  745. (invisible-initially? (funcall invisible-p pos))
  746. (limit (or limit (if previous-p
  747. (point-min)
  748. (point-max))))
  749. (cmp (if previous-p #'> #'<))
  750. (next-change (if previous-p
  751. (if ignore-hidden-p
  752. (lambda (p) (org-fold-core-previous-folding-state-change (org-fold-core-get-folding-spec nil p) p limit))
  753. (lambda (p) (max limit (1- (previous-single-char-property-change p 'invisible nil limit)))))
  754. (if ignore-hidden-p
  755. (lambda (p) (org-fold-core-next-folding-state-change (org-fold-core-get-folding-spec nil p) p limit))
  756. (lambda (p) (next-single-char-property-change p 'invisible nil limit)))))
  757. (next pos))
  758. (while (and (funcall cmp next limit)
  759. (not (org-xor invisible-initially? (funcall invisible-p next))))
  760. (setq next (funcall next-change next)))
  761. next))
  762. (defun org-fold-core-previous-visibility-change (&optional pos limit ignore-hidden-p)
  763. "Call `org-fold-core-next-visibility-change' searching backwards."
  764. (org-fold-core-next-visibility-change pos limit ignore-hidden-p 'previous))
  765. (defun org-fold-core-next-folding-state-change (&optional spec-or-alias pos limit previous-p)
  766. "Return point after POS where folding state changes up to LIMIT.
  767. If SPEC-OR-ALIAS is nil, return next point where _any_ single folding
  768. spec changes.
  769. For example, (org-fold-core-next-folding-state-change nil) with point
  770. somewhere in the below structure will return the nearest <...> point.
  771. * Headline <begin outline fold>
  772. :PROPERTIES:<begin drawer fold>
  773. :ID: test
  774. :END:<end drawer fold>
  775. Fusce suscipit, wisi nec facilisis facilisis, est dui fermentum leo,
  776. quis tempor ligula erat quis odio.
  777. ** Another headline
  778. :DRAWER:<begin drawer fold>
  779. :END:<end drawer fold>
  780. ** Yet another headline
  781. <end of outline fold>
  782. If SPEC-OR-ALIAS is a folding spec symbol, only consider that folding
  783. spec.
  784. If SPEC-OR-ALIAS is a list, only consider changes of folding specs
  785. from the list.
  786. Search backwards when PREVIOUS-P is non-nil."
  787. (when (and spec-or-alias (symbolp spec-or-alias))
  788. (setq spec-or-alias (list spec-or-alias)))
  789. (when spec-or-alias
  790. (setq spec-or-alias
  791. (mapcar (lambda (spec-or-alias)
  792. (or (org-fold-core-get-folding-spec-from-alias spec-or-alias)
  793. spec-or-alias))
  794. spec-or-alias))
  795. (mapc #'org-fold-core--check-spec spec-or-alias))
  796. (unless spec-or-alias
  797. (setq spec-or-alias (org-fold-core-folding-spec-list)))
  798. (setq pos (or pos (point)))
  799. (apply (if previous-p
  800. #'max
  801. #'min)
  802. (mapcar (if previous-p
  803. (lambda (prop) (max (or limit (point-min)) (previous-single-property-change pos prop nil (or limit (point-min)))))
  804. (lambda (prop) (next-single-property-change pos prop nil (or limit (point-max)))))
  805. (mapcar (lambda (el) (org-fold-core--property-symbol-get-create el nil t))
  806. spec-or-alias))))
  807. (defun org-fold-core-previous-folding-state-change (&optional spec-or-alias pos limit)
  808. "Call `org-fold-core-next-folding-state-change' searching backwards."
  809. (org-fold-core-next-folding-state-change spec-or-alias pos limit 'previous))
  810. (defun org-fold-core-search-forward (spec-or-alias &optional limit)
  811. "Search next region folded via folding SPEC-OR-ALIAS up to LIMIT.
  812. Move point right after the end of the region, to LIMIT, or
  813. `point-max'. The `match-data' will contain the region."
  814. (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
  815. (let ((prop-symbol (org-fold-core--property-symbol-get-create spec nil t)))
  816. (goto-char (or (next-single-char-property-change (point) prop-symbol nil limit) limit (point-max)))
  817. (when (and (< (point) (or limit (point-max)))
  818. (not (org-fold-core-get-folding-spec spec)))
  819. (goto-char (next-single-char-property-change (point) prop-symbol nil limit)))
  820. (when (org-fold-core-get-folding-spec spec)
  821. (let ((region (org-fold-core-get-region-at-point spec)))
  822. (when (< (cdr region) (or limit (point-max)))
  823. (goto-char (1+ (cdr region)))
  824. (set-match-data (list (set-marker (make-marker) (car region) (current-buffer))
  825. (set-marker (make-marker) (cdr region) (current-buffer))))))))))
  826. ;;;; Changing visibility
  827. ;;;;; Region visibility
  828. (defvar org-fold-core--fontifying nil
  829. "Flag used to avoid font-lock recursion.")
  830. ;; This is the core function performing actual folding/unfolding. The
  831. ;; folding state is stored in text property (folding property)
  832. ;; returned by `org-fold-core--property-symbol-get-create'. The value of the
  833. ;; folding property is folding spec symbol.
  834. (defun org-fold-core-region (from to flag &optional spec-or-alias)
  835. "Hide or show lines from FROM to TO, according to FLAG.
  836. SPEC-OR-ALIAS is the folding spec or foldable element, as a symbol.
  837. If SPEC-OR-ALIAS is omitted and FLAG is nil, unfold everything in the region."
  838. (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
  839. (when spec (org-fold-core--check-spec spec))
  840. (with-silent-modifications
  841. (org-with-wide-buffer
  842. (when (eq org-fold-core-style 'overlays) (remove-overlays from to 'invisible spec))
  843. (if flag
  844. (if (not spec)
  845. (error "Calling `org-fold-core-region' with missing SPEC")
  846. (if (eq org-fold-core-style 'overlays)
  847. ;; Use `front-advance' since text right before to the beginning of
  848. ;; the overlay belongs to the visible line than to the contents.
  849. (let ((o (make-overlay from to nil
  850. (org-fold-core-get-folding-spec-property spec :front-sticky)
  851. (org-fold-core-get-folding-spec-property spec :rear-sticky))))
  852. (overlay-put o 'evaporate t)
  853. (overlay-put o (org-fold-core--property-symbol-get-create spec) spec)
  854. (overlay-put o 'invisible spec)
  855. (overlay-put o 'isearch-open-invisible #'org-fold-core--isearch-show)
  856. (overlay-put o 'isearch-open-invisible-temporary #'org-fold-core--isearch-show-temporary))
  857. (put-text-property from to (org-fold-core--property-symbol-get-create spec) spec)
  858. (put-text-property from to 'isearch-open-invisible #'org-fold-core--isearch-show)
  859. (put-text-property from to 'isearch-open-invisible-temporary #'org-fold-core--isearch-show-temporary)
  860. (when (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  861. ;; If the SPEC has highest priority, assign it directly
  862. ;; to 'invisible property as well. This is done to speed
  863. ;; up Emacs redisplay on huge (Mbs) folded regions where
  864. ;; we don't even want Emacs to spend time cycling over
  865. ;; `char-property-alias-alist'.
  866. (when (eq spec (caar org-fold-core--specs)) (put-text-property from to 'invisible spec)))))
  867. (if (not spec)
  868. (mapc (lambda (spec) (org-fold-core-region from to nil spec)) (org-fold-core-folding-spec-list))
  869. (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  870. (eq org-fold-core-style 'text-properties))
  871. (when (eq spec (caar org-fold-core--specs))
  872. (let ((pos from))
  873. (while (< pos to)
  874. (if (eq spec (get-text-property pos 'invisible))
  875. (let ((next (org-fold-core-next-folding-state-change spec pos to)))
  876. (remove-text-properties pos next '(invisible t))
  877. (setq pos next))
  878. (setq pos (next-single-char-property-change pos 'invisible nil to)))))))
  879. (when (eq org-fold-core-style 'text-properties)
  880. (remove-text-properties from to (list (org-fold-core--property-symbol-get-create spec) nil)))
  881. ;; Fontify unfolded text.
  882. (unless (or (not font-lock-mode)
  883. org-fold-core--fontifying
  884. (not (org-fold-core-get-folding-spec-property spec :font-lock-skip))
  885. (not (text-property-not-all from to 'org-fold-core-fontified t)))
  886. (let ((org-fold-core--fontifying t))
  887. (if jit-lock-mode
  888. (jit-lock-refontify from to)
  889. (save-match-data (font-lock-fontify-region from to)))))))))))
  890. ;;; Make isearch search in some text hidden via text propertoes
  891. (defvar org-fold-core--isearch-overlays nil
  892. "List of overlays temporarily created during isearch.
  893. This is used to allow searching in regions hidden via text properties.
  894. As for [2020-05-09 Sat], Isearch only has special handling of hidden overlays.
  895. Any text hidden via text properties is not revealed even if `search-invisible'
  896. is set to 't.")
  897. (defvar-local org-fold-core--isearch-local-regions (make-hash-table :test 'equal)
  898. "Hash table storing temporarily shown folds from isearch matches.")
  899. (defun org-fold-core--isearch-setup (type)
  900. "Initialize isearch in org buffer.
  901. TYPE can be either `text-properties' or `overlays'."
  902. (pcase type
  903. (`text-properties
  904. (setq-local search-invisible 'open-all)
  905. (add-hook 'isearch-mode-end-hook #'org-fold-core--clear-isearch-state nil 'local)
  906. (add-hook 'isearch-mode-hook #'org-fold-core--clear-isearch-state nil 'local)
  907. (setq-local isearch-filter-predicate #'org-fold-core--isearch-filter-predicate-text-properties))
  908. (`overlays
  909. (when (eq org-fold-core-style 'text-properties)
  910. (setq-local isearch-filter-predicate #'org-fold-core--isearch-filter-predicate-overlays)
  911. (add-hook 'isearch-mode-end-hook #'org-fold-core--clear-isearch-overlays nil 'local)))
  912. (_ (error "%s: Unknown type of setup for `org-fold-core--isearch-setup'" type))))
  913. (defun org-fold-core--isearch-reveal (pos)
  914. "Default function used to reveal hidden text at POS for isearch."
  915. (let ((region (org-fold-core-get-region-at-point pos)))
  916. (org-fold-core-region (car region) (cdr region) nil)))
  917. (defun org-fold-core--isearch-filter-predicate-text-properties (beg end)
  918. "Make sure that folded text is searchable when user whant so.
  919. This function is intended to be used as `isearch-filter-predicate'."
  920. (and
  921. ;; Check folding specs that cannot be searched
  922. (not (memq nil (mapcar (lambda (spec) (not (org-fold-core-get-folding-spec-property spec :isearch-ignore)))
  923. (org-fold-core-get-folding-specs-in-region beg end))))
  924. ;; Check 'invisible properties that are not folding specs.
  925. (or (eq search-invisible t) ; User wants to search anyway, allow it.
  926. (let ((pos beg)
  927. unknown-invisible-property)
  928. (while (and (< pos end)
  929. (not unknown-invisible-property))
  930. (when (and (get-text-property pos 'invisible)
  931. (not (org-fold-core-folding-spec-p (get-text-property pos 'invisible))))
  932. (setq unknown-invisible-property t))
  933. (setq pos (next-single-char-property-change pos 'invisible)))
  934. (not unknown-invisible-property)))
  935. (or (and (eq search-invisible t)
  936. ;; FIXME: this opens regions permanenly for now.
  937. ;; I also tried to force search-invisible 'open-all around
  938. ;; `isearch-range-invisible', but that somehow causes
  939. ;; infinite loop in `isearch-lazy-highlight'.
  940. (prog1 t
  941. ;; We still need to reveal the folded location
  942. (org-fold-core--isearch-show-temporary (cons beg end) nil)))
  943. (not (isearch-range-invisible beg end)))))
  944. (defun org-fold-core--clear-isearch-state ()
  945. "Clear `org-fold-core--isearch-local-regions'."
  946. (clrhash org-fold-core--isearch-local-regions))
  947. (defun org-fold-core--isearch-show (region)
  948. "Reveal text in REGION found by isearch."
  949. (org-with-point-at (car region)
  950. (while (< (point) (cdr region))
  951. (funcall org-fold-core-isearch-open-function (car region))
  952. (goto-char (org-fold-core-next-visibility-change (point) (cdr region) 'ignore-hidden)))))
  953. (defun org-fold-core--isearch-show-temporary (region hide-p)
  954. "Temporarily reveal text in REGION.
  955. Hide text instead if HIDE-P is non-nil."
  956. (if (not hide-p)
  957. (let ((pos (car region)))
  958. (while (< pos (cdr region))
  959. (let ((spec-no-open
  960. (catch :found
  961. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  962. (unless (org-fold-core-get-folding-spec-property spec :isearch-open)
  963. (throw :found spec))))))
  964. (if spec-no-open
  965. ;; Skip regions folded with folding specs that cannot be opened.
  966. (setq pos (org-fold-core-next-folding-state-change spec-no-open pos (cdr region)))
  967. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  968. (push (cons spec (org-fold-core-get-region-at-point spec pos)) (gethash region org-fold-core--isearch-local-regions)))
  969. (org-fold-core--isearch-show region)
  970. (setq pos (org-fold-core-next-folding-state-change nil pos (cdr region)))))))
  971. (mapc (lambda (val) (org-fold-core-region (cadr val) (cddr val) t (car val))) (gethash region org-fold-core--isearch-local-regions))
  972. (remhash region org-fold-core--isearch-local-regions)))
  973. (defvar-local org-fold-core--isearch-special-specs nil
  974. "List of specs that can break visibility state when converted to overlays.
  975. This is a hack, but I do not see a better way around until isearch
  976. gets support of text properties.")
  977. (defun org-fold-core--create-isearch-overlays (beg end)
  978. "Replace text property invisibility spec by overlays between BEG and END.
  979. All the searcheable folded regions will be changed to use overlays
  980. instead of text properties. The created overlays will be stored in
  981. `org-fold-core--isearch-overlays'."
  982. (let ((pos beg))
  983. (while (< pos end)
  984. ;; We need loop below to make sure that we clean all invisible
  985. ;; properties, which may be nested.
  986. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  987. (unless (org-fold-core-get-folding-spec-property spec :isearch-ignore)
  988. (let* ((region (org-fold-core-get-region-at-point spec pos)))
  989. (when (memq spec org-fold-core--isearch-special-specs)
  990. (setq pos (min pos (car region)))
  991. (setq end (max end (cdr region))))
  992. ;; Changing text properties is considered buffer modification.
  993. ;; We do not want it here.
  994. (with-silent-modifications
  995. (org-fold-core-region (car region) (cdr region) nil spec)
  996. ;; The overlay is modelled after `outline-flag-region'
  997. ;; [2020-05-09 Sat] overlay for 'outline blocks.
  998. (let ((o (make-overlay (car region) (cdr region) nil 'front-advance)))
  999. (overlay-put o 'evaporate t)
  1000. (overlay-put o 'invisible spec)
  1001. (overlay-put o 'org-invisible spec)
  1002. ;; Make sure that overlays are applied in the same order
  1003. ;; with the folding specs.
  1004. ;; Note: `memq` returns cdr with car equal to the first
  1005. ;; found matching element.
  1006. (overlay-put o 'priority (length (memq spec (org-fold-core-folding-spec-list))))
  1007. ;; `delete-overlay' here means that spec information will be lost
  1008. ;; for the region. The region will remain visible.
  1009. (if (org-fold-core-get-folding-spec-property spec :isearch-open)
  1010. (overlay-put o 'isearch-open-invisible #'delete-overlay)
  1011. (overlay-put o 'isearch-open-invisible #'ignore)
  1012. (overlay-put o 'isearch-open-invisible-temporary #'ignore))
  1013. (push o org-fold-core--isearch-overlays))))))
  1014. (setq pos (org-fold-core-next-folding-state-change nil pos end)))))
  1015. (defun org-fold-core--isearch-filter-predicate-overlays (beg end)
  1016. "Return non-nil if text between BEG and END is deemed visible by isearch.
  1017. This function is intended to be used as `isearch-filter-predicate'."
  1018. (org-fold-core--create-isearch-overlays beg end) ;; trick isearch by creating overlays in place of invisible text
  1019. (isearch-filter-visible beg end))
  1020. (defun org-fold-core--clear-isearch-overlay (ov)
  1021. "Convert OV region back into using text properties."
  1022. (let ((spec (if isearch-mode-end-hook-quit
  1023. ;; Restore all folds.
  1024. (overlay-get ov 'org-invisible)
  1025. ;; Leave opened folds open.
  1026. (overlay-get ov 'invisible))))
  1027. ;; Ignore deleted overlays.
  1028. (when (and spec
  1029. (overlay-buffer ov))
  1030. ;; Changing text properties is considered buffer modification.
  1031. ;; We do not want it here.
  1032. (with-silent-modifications
  1033. (when (<= (overlay-end ov) (point-max))
  1034. (org-fold-core-region (overlay-start ov) (overlay-end ov) t spec)))))
  1035. (when (member ov isearch-opened-overlays)
  1036. (setq isearch-opened-overlays (delete ov isearch-opened-overlays)))
  1037. (delete-overlay ov))
  1038. (defun org-fold-core--clear-isearch-overlays ()
  1039. "Convert overlays from `org-fold-core--isearch-overlays' back to text properties."
  1040. (when org-fold-core--isearch-overlays
  1041. (mapc #'org-fold-core--clear-isearch-overlay org-fold-core--isearch-overlays)
  1042. (setq org-fold-core--isearch-overlays nil)))
  1043. ;;; Handling changes in folded elements
  1044. (defvar org-fold-core--ignore-modifications nil
  1045. "Non-nil: skip processing modifications in `org-fold-core--fix-folded-region'.")
  1046. (defvar org-fold-core--ignore-fragility-checks nil
  1047. "Non-nil: skip fragility checks in `org-fold-core--fix-folded-region'.")
  1048. (defmacro org-fold-core-ignore-modifications (&rest body)
  1049. "Run BODY ignoring buffer modifications in `org-fold-core--fix-folded-region'."
  1050. (declare (debug (form body)) (indent 1))
  1051. `(let ((org-fold-core--ignore-modifications t))
  1052. (unwind-protect (progn ,@body)
  1053. (setq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick)))))
  1054. (defmacro org-fold-core-ignore-fragility-checks (&rest body)
  1055. "Run BODY skipping :fragility checks in `org-fold-core--fix-folded-region'."
  1056. (declare (debug (form body)) (indent 1))
  1057. `(let ((org-fold-core--ignore-fragility-checks t))
  1058. (progn ,@body)))
  1059. (defvar-local org-fold-core--last-buffer-chars-modified-tick nil
  1060. "Variable storing the last return value of `buffer-chars-modified-tick'.")
  1061. (defun org-fold-core--fix-folded-region (from to _)
  1062. "Process modifications in folded elements within FROM . TO region.
  1063. This function intended to be used as one of `after-change-functions'.
  1064. This function does nothing if text the only modification was changing
  1065. text properties (for the sake of reducing overheads).
  1066. If a text was inserted into invisible region, hide the inserted text.
  1067. If a text was inserted in front/back of the region, hide it according
  1068. to :font-sticky/:rear-sticky folding spec property.
  1069. If the folded region is folded with a spec with non-nil :fragile
  1070. property, unfold the region if the :fragile function returns non-nil."
  1071. ;; If no insertions or deletions in buffer, skip all the checks.
  1072. (unless (or (eq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick))
  1073. org-fold-core--ignore-modifications
  1074. (memql 'ignore-modification-checks org-fold-core--optimise-for-huge-buffers))
  1075. ;; Store the new buffer modification state.
  1076. (setq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick))
  1077. (save-match-data
  1078. ;; Handle changes in all the indirect buffers and in the base
  1079. ;; buffer. Work around Emacs bug#46982.
  1080. (when (eq org-fold-core-style 'text-properties)
  1081. (org-fold-core-cycle-over-indirect-buffers
  1082. ;; Re-hide text inserted in the middle/font/back of a folded
  1083. ;; region.
  1084. (unless (equal from to) ; Ignore deletions.
  1085. (dolist (spec (org-fold-core-folding-spec-list))
  1086. ;; Reveal fully invisible text inserted in the middle
  1087. ;; of visible portion of the buffer. This is needed,
  1088. ;; for example, when there was a deletion in a folded
  1089. ;; heading, the heading was unfolded, end `undo' was
  1090. ;; called. The `undo' would insert the folded text.
  1091. (when (and (or (eq from (point-min))
  1092. (not (org-fold-core-folded-p (1- from) spec)))
  1093. (or (eq to (point-max))
  1094. (not (org-fold-core-folded-p to spec)))
  1095. (org-fold-core-region-folded-p from to spec))
  1096. (org-fold-core-region from to nil spec))
  1097. ;; Look around and fold the new text if the nearby folds are
  1098. ;; sticky.
  1099. (unless (org-fold-core-region-folded-p from to spec)
  1100. (let ((spec-to (org-fold-core-get-folding-spec spec (min to (1- (point-max)))))
  1101. (spec-from (org-fold-core-get-folding-spec spec (max (point-min) (1- from)))))
  1102. ;; Reveal folds around undoed deletion.
  1103. (when undo-in-progress
  1104. (let ((lregion (org-fold-core-get-region-at-point spec (max (point-min) (1- from))))
  1105. (rregion (org-fold-core-get-region-at-point spec (min to (1- (point-max))))))
  1106. (if (and lregion rregion)
  1107. (org-fold-core-region (car lregion) (cdr rregion) nil spec)
  1108. (when lregion
  1109. (org-fold-core-region (car lregion) (cdr lregion) nil spec))
  1110. (when rregion
  1111. (org-fold-core-region (car rregion) (cdr rregion) nil spec)))))
  1112. ;; Hide text inserted in the middle of a fold.
  1113. (when (and (or spec-from (eq from (point-min)))
  1114. (or spec-to (eq to (point-max)))
  1115. (or spec-from spec-to)
  1116. (eq spec-to spec-from)
  1117. (or (org-fold-core-get-folding-spec-property spec :front-sticky)
  1118. (org-fold-core-get-folding-spec-property spec :rear-sticky)))
  1119. (unless (and (eq from (point-min)) (eq to (point-max))) ; Buffer content replaced.
  1120. (org-fold-core-region from to t (or spec-from spec-to))))
  1121. ;; Hide text inserted at the end of a fold.
  1122. (when (and spec-from (org-fold-core-get-folding-spec-property spec-from :rear-sticky))
  1123. (org-fold-core-region from to t spec-from))
  1124. ;; Hide text inserted in front of a fold.
  1125. (when (and spec-to
  1126. (not (eq to (point-max))) ; Text inserted at the end of buffer is not prepended anywhere.
  1127. (org-fold-core-get-folding-spec-property spec-to :front-sticky))
  1128. (org-fold-core-region from to t spec-to))))))))
  1129. ;; Process all the folded text between `from' and `to'. Do it
  1130. ;; only in current buffer to avoid verifying semantic structure
  1131. ;; multiple times in indirect buffers that have exactly same
  1132. ;; text anyway.
  1133. (unless (or org-fold-core--ignore-fragility-checks
  1134. (memql 'ignore-fragility-checks org-fold-core--optimise-for-huge-buffers))
  1135. (dolist (func org-fold-core-extend-changed-region-functions)
  1136. (let ((new-region (funcall func from to)))
  1137. (setq from (car new-region))
  1138. (setq to (cdr new-region))))
  1139. (dolist (spec (org-fold-core-folding-spec-list))
  1140. ;; No action is needed when :fragile is nil for the spec.
  1141. (when (org-fold-core-get-folding-spec-property spec :fragile)
  1142. (org-with-wide-buffer
  1143. ;; Expand the considered region to include partially present fold.
  1144. ;; Note: It is important to do this inside loop over all
  1145. ;; specs. Otherwise, the region may be expanded to huge
  1146. ;; outline fold, potentially involving majority of the
  1147. ;; buffer. That would cause the below code to loop over
  1148. ;; almost all the folds in buffer, which would be too slow.
  1149. (let ((local-from from)
  1150. (local-to to)
  1151. (region-from (org-fold-core-get-region-at-point spec (max (point-min) (1- from))))
  1152. (region-to (org-fold-core-get-region-at-point spec (min to (1- (point-max))))))
  1153. (when region-from (setq local-from (car region-from)))
  1154. (when region-to (setq local-to (cdr region-to)))
  1155. (let ((pos local-from))
  1156. ;; Move to the first hidden region.
  1157. (unless (org-fold-core-get-folding-spec spec pos)
  1158. (setq pos (org-fold-core-next-folding-state-change spec pos local-to)))
  1159. ;; Cycle over all the folds.
  1160. (while (< pos local-to)
  1161. (save-match-data ; we should not clobber match-data in after-change-functions
  1162. (let ((fold-begin (and (org-fold-core-get-folding-spec spec pos)
  1163. pos))
  1164. (fold-end (org-fold-core-next-folding-state-change spec pos local-to)))
  1165. (when (and fold-begin fold-end)
  1166. (when (save-excursion
  1167. (funcall (org-fold-core-get-folding-spec-property spec :fragile)
  1168. (cons fold-begin fold-end)
  1169. spec))
  1170. ;; Reveal completely, not just from the SPEC.
  1171. (org-fold-core-region fold-begin fold-end nil)))))
  1172. ;; Move to next fold.
  1173. (setq pos (org-fold-core-next-folding-state-change spec pos local-to))))))))))))
  1174. ;;; Hanlding killing/yanking of folded text
  1175. ;; Backward compatibility with Emacs 24.
  1176. (defun org-fold-core--seq-partition (list n)
  1177. "Return list of elements of LIST grouped into sub-sequences of length N.
  1178. The last list may contain less than N elements. If N is a
  1179. negative integer or 0, nil is returned."
  1180. (if (fboundp 'seq-partition)
  1181. (seq-partition list n)
  1182. (unless (< n 1)
  1183. (let ((result '()))
  1184. (while list
  1185. (let (part)
  1186. (dotimes (_ n)
  1187. (when list (push (car list) part)))
  1188. (push part result))
  1189. (dotimes (_ n)
  1190. (setq list (cdr list))))
  1191. (nreverse result)))))
  1192. ;; By default, all the text properties of the killed text are
  1193. ;; preserved, including the folding text properties. This can be
  1194. ;; awkward when we copy a text from an indirect buffer to another
  1195. ;; indirect buffer (or the base buffer). The copied text might be
  1196. ;; visible in the source buffer, but might disappear if we yank it in
  1197. ;; another buffer. This happens in the following situation:
  1198. ;; ---- base buffer ----
  1199. ;; * Headline<begin fold>
  1200. ;; Some text hidden in the base buffer, but revealed in the indirect
  1201. ;; buffer.<end fold>
  1202. ;; * Another headline
  1203. ;;
  1204. ;; ---- end of base buffer ----
  1205. ;; ---- indirect buffer ----
  1206. ;; * Headline
  1207. ;; Some text hidden in the base buffer, but revealed in the indirect
  1208. ;; buffer.
  1209. ;; * Another headline
  1210. ;;
  1211. ;; ---- end of indirect buffer ----
  1212. ;; If we copy the text under "Headline" from the indirect buffer and
  1213. ;; insert it under "Another headline" in the base buffer, the inserted
  1214. ;; text will be hidden since it's folding text properties are copyed.
  1215. ;; Basically, the copied text would have two sets of folding text
  1216. ;; properties: (1) Properties for base buffer telling that the text is
  1217. ;; hidden; (2) Properties for the indirect buffer telling that the
  1218. ;; text is visible. The first set of the text properties in inactive
  1219. ;; in the indirect buffer, but will become active once we yank the
  1220. ;; text back into the base buffer.
  1221. ;;
  1222. ;; To avoid the above situation, we simply clear all the properties,
  1223. ;; unrealated to current buffer when a text is copied.
  1224. ;; FIXME: Ideally, we may want to carry the folding state of copied
  1225. ;; text between buffer (probably via user customisation).
  1226. (defun org-fold-core--buffer-substring-filter (beg end &optional delete)
  1227. "Clear folding state in killed text.
  1228. This function is intended to be used as `filter-buffer-substring-function'.
  1229. The arguments and return value are as specified for `filter-buffer-substring'."
  1230. (let ((return-string (buffer-substring--filter beg end delete))
  1231. ;; The list will be used as an argument to `remove-text-properties'.
  1232. props-list)
  1233. ;; There is no easy way to examine all the text properties of a
  1234. ;; string, so we utilise the fact that printed string
  1235. ;; representation lists all its properties.
  1236. ;; Loop over the elements of string representation.
  1237. (unless (or (string= "" return-string)
  1238. (<= end beg)
  1239. (eq org-fold-core-style 'overlays))
  1240. ;; Collect all the text properties the string is completely
  1241. ;; hidden with.
  1242. (dolist (spec (org-fold-core-folding-spec-list))
  1243. (when (and (org-fold-core-region-folded-p beg end spec)
  1244. (org-region-invisible-p beg end))
  1245. (push (org-fold-core--property-symbol-get-create spec nil t) props-list)))
  1246. (dolist (plist
  1247. (if (fboundp 'object-intervals)
  1248. (object-intervals return-string)
  1249. ;; Backward compatibility with Emacs <28.
  1250. ;; FIXME: Is there any better way to do it?
  1251. ;; Yes, it is a hack.
  1252. ;; The below gives us string representation as a list.
  1253. ;; Note that we need to remove unreadable values, like markers (#<...>).
  1254. (org-fold-core--seq-partition
  1255. (cdr (let ((data (read (replace-regexp-in-string
  1256. "^#(" "("
  1257. (replace-regexp-in-string
  1258. " #(" " ("
  1259. (replace-regexp-in-string
  1260. "#<[^>]+>" "dummy"
  1261. ;; Get text representation of the string object.
  1262. ;; Make sure to print everything (see `prin1' docstring).
  1263. ;; `prin1' is used to print "%S" format.
  1264. (let (print-level print-length)
  1265. (format "%S" return-string))))))))
  1266. (if (listp data) data (list data))))
  1267. 3)))
  1268. (let* ((start (car plist))
  1269. (fin (cadr plist))
  1270. (plist (car (cddr plist))))
  1271. ;; Only lists contain text properties.
  1272. (when (listp plist)
  1273. ;; Collect all the relevant text properties.
  1274. (while plist
  1275. (let* ((prop (car plist))
  1276. (prop-name (symbol-name prop)))
  1277. ;; Reveal hard-hidden text. See
  1278. ;; `org-fold-core--optimise-for-huge-buffers'.
  1279. (when (and (eq prop 'invisible)
  1280. (member (cadr plist) (org-fold-core-folding-spec-list)))
  1281. (remove-text-properties start fin '(invisible t) return-string))
  1282. ;; We do not care about values now.
  1283. (setq plist (cddr plist))
  1284. (when (string-match-p org-fold-core--spec-property-prefix prop-name)
  1285. ;; Leave folding specs from current buffer. See
  1286. ;; comments in `org-fold-core--property-symbol-get-create' to
  1287. ;; understand why it works.
  1288. (unless (member prop (cdr (assq 'invisible char-property-alias-alist)))
  1289. (push prop props-list))))))))
  1290. (remove-text-properties 0 (length return-string) props-list return-string))
  1291. return-string))
  1292. ;;; Do not fontify folded text until needed.
  1293. (defvar org-fold-core--force-fontification nil
  1294. "Let-bind this variable to t in order to force fontification in
  1295. folded regions.")
  1296. (defun org-fold-core-fontify-region (beg end loudly &optional force)
  1297. "Run `font-lock-default-fontify-region' in visible regions."
  1298. (with-silent-modifications
  1299. (let* ((pos beg) next font-lock-return-value
  1300. (force (or force org-fold-core--force-fontification))
  1301. (org-fold-core--fontifying t)
  1302. (skip-specs
  1303. (unless force
  1304. (let (result)
  1305. (dolist (spec (org-fold-core-folding-spec-list))
  1306. (when (and (not (org-fold-core-get-folding-spec-property spec :visible))
  1307. (org-fold-core-get-folding-spec-property spec :font-lock-skip))
  1308. (push spec result)))
  1309. result))))
  1310. ;; Move POS to first visible point within BEG..END.
  1311. (unless force
  1312. (while (and (catch :found
  1313. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  1314. (when (org-fold-core-get-folding-spec-property spec :font-lock-skip)
  1315. (throw :found spec))))
  1316. (< pos end))
  1317. (setq pos (org-fold-core-next-folding-state-change nil pos end))))
  1318. (when force (setq pos beg next end))
  1319. (while (< pos end)
  1320. (unless force
  1321. (setq next (org-fold-core-next-folding-state-change skip-specs pos end))
  1322. ;; Move to the end of the region to be fontified.
  1323. (while (and (not (catch :found
  1324. (dolist (spec (org-fold-core-get-folding-spec 'all next))
  1325. (when (org-fold-core-get-folding-spec-property spec :font-lock-skip)
  1326. (throw :found spec)))))
  1327. (< next end))
  1328. (setq next (org-fold-core-next-folding-state-change nil next end))))
  1329. (save-excursion
  1330. ;; Keep track of the actually fontified region.
  1331. (pcase (font-lock-default-fontify-region pos next loudly)
  1332. (`(jit-lock-bounds ,beg . ,end)
  1333. (pcase font-lock-return-value
  1334. (`(jit-lock-bounds ,oldbeg . ,oldend)
  1335. (setq font-lock-return-value
  1336. `(jit-lock-bounds
  1337. ,(min oldbeg beg)
  1338. ,(max oldend end))))
  1339. (value (setq font-lock-return-value value)))))
  1340. (save-match-data
  1341. ;; Only run within regions that are not yet touched by
  1342. ;; fontification.
  1343. (let ((r next) (c pos) nxt)
  1344. (when (get-text-property c 'org-fold-core-fontified)
  1345. (setq c (next-single-property-change c 'org-fold-core-fontified)))
  1346. (setq nxt (next-single-property-change c 'org-fold-core-fontified nil r))
  1347. (while (< c r)
  1348. (run-hook-with-args 'org-fold-core-first-unfold-functions c nxt)
  1349. (setq c (next-single-property-change nxt 'org-fold-core-fontified nil r))
  1350. (setq nxt (next-single-property-change c 'org-fold-core-fontified nil r))))))
  1351. (put-text-property pos next 'org-fold-core-fontified t)
  1352. (put-text-property pos next 'fontified t)
  1353. (setq pos next))
  1354. (or font-lock-return-value `(jit-lock-bounds ,beg . ,end)))))
  1355. (defun org-fold-core-update-optimisation (beg end)
  1356. "Update huge buffer optimisation between BEG and END.
  1357. See `org-fold-core--optimise-for-huge-buffers'."
  1358. (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  1359. (eq org-fold-core-style 'text-properties))
  1360. (let ((pos beg))
  1361. (while (< pos end)
  1362. (when (and (org-fold-core-folded-p pos (caar org-fold-core--specs))
  1363. (not (eq (caar org-fold-core--specs) (get-text-property pos 'invisible))))
  1364. (put-text-property pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end)
  1365. 'invisible (caar org-fold-core--specs)))
  1366. (setq pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end))))))
  1367. (defun org-fold-core-remove-optimisation (beg end)
  1368. "Remove huge buffer optimisation between BEG and END.
  1369. See `org-fold-core--optimise-for-huge-buffers'."
  1370. (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  1371. (eq org-fold-core-style 'text-properties))
  1372. (let ((pos beg))
  1373. (while (< pos end)
  1374. (if (and (org-fold-core-folded-p pos (caar org-fold-core--specs))
  1375. (eq (caar org-fold-core--specs) (get-text-property pos 'invisible)))
  1376. (remove-text-properties pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end)
  1377. '(invisible t)))
  1378. (setq pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end))))))
  1379. (provide 'org-fold-core)
  1380. ;;; org-fold-core.el ends here