org-fold-core.el 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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. (defvar-local org-fold-core-isearch-open-function #'org-fold-core--isearch-reveal
  261. "Function used to reveal hidden text found by isearch.
  262. The function is called with a single argument - point where text is to
  263. be revealed.")
  264. (defvar-local org-fold-core--optimise-for-huge-buffers nil
  265. "Non-nil turns on extra speedup on huge buffers (Mbs of folded text).
  266. This setting is risky and may cause various artefacts and degraded
  267. functionality, especially when using external packages. It is
  268. recommended to enable it on per-buffer basis as file-local variable.
  269. When set to non-nil, must be a list containing one or multiple the
  270. following symbols:
  271. - `grab-invisible': Use `invisible' text property to hide text. This
  272. will reduce the load on Emacs display engine and one may use it if
  273. moving point across folded regions becomes slow. However, as a side
  274. effect, some external packages extracting i.e. headlings from folded
  275. parts of buffer may keep the text invisible.
  276. - `ignore-fragility-checks': Do not try to detect when user edits
  277. break structure of the folded elements. This will speed up
  278. modifying the folded regions at the cost that some higher-level
  279. functions relying on this package might not be able to unfold the
  280. edited text. For example, removed leading stars from a folded
  281. headline in Org mode will break visibility cycling since Org mode
  282. will not be avare that the following folded text belonged to
  283. headline.
  284. - `ignore-modification-checks': Do not try to detect insertions in the
  285. middle of the folded regions. This will speed up non-interactive
  286. edits of the folded regions. However, text inserted in the middle
  287. of the folded regions may become visible for some external packages
  288. inserting text using `insert' instead of `insert-and-inherit' (the
  289. latter is rarely used in practice).
  290. - `ignore-indirect': Do not decouple folding state in the indirect
  291. buffers. This can speed up Emacs display engine (and thus motion of
  292. point), especially when large number of indirect buffers is being
  293. used.
  294. - `merge-folds': Do not distinguish between different types of folding
  295. specs. This is the most aggressive optimisation with unforseen and
  296. potentially drastic effects.")
  297. (put 'org-fold-core--optimise-for-huge-buffers 'safe-local-variable 'listp)
  298. ;;; Core functionality
  299. ;;;; Folding specs
  300. (defvar-local org-fold-core--specs '((org-fold-visible
  301. (:visible . t)
  302. (:alias . (visible)))
  303. (org-fold-hidden
  304. (:ellipsis . "...")
  305. (:isearch-open . t)
  306. (:alias . (hidden))))
  307. "Folding specs defined in current buffer.
  308. Each spec is a list (SPEC-SYMBOL SPEC-PROPERTIES).
  309. SPEC-SYMBOL is the symbol respresenting the folding spec.
  310. SPEC-PROPERTIES is an alist defining folding spec properties.
  311. If a text region is folded using multiple specs, only the folding spec
  312. listed earlier is used.
  313. The following properties are known:
  314. - :ellipsis :: must be nil or string to show when text is folded
  315. using this spec.
  316. - :global :: non-nil means that folding state will be preserved
  317. when copying folded text between buffers.
  318. - :isearch-ignore :: non-nil means that folded text is not searchable
  319. using isearch.
  320. - :isearch-open :: non-nil means that isearch can reveal text hidden
  321. using this spec. This property does nothing
  322. when \\='isearch-ignore property is non-nil.
  323. - :front-sticky :: non-nil means that text prepended to the folded text
  324. is automatically folded.
  325. - :rear-sticky :: non-nil means that text appended to the folded text
  326. is folded.
  327. - :visible :: non-nil means that folding spec visibility is not
  328. managed. Instead, visibility settings in
  329. `buffer-invisibility-spec' will be used as is.
  330. Note that changing this property from nil to t may
  331. clear the setting in `buffer-invisibility-spec'.
  332. - :alias :: a list of aliases for the SPEC-SYMBOL.
  333. - :font-lock-skip :: Suppress font-locking in folded text.
  334. - :fragile :: Must be a function accepting two arguments.
  335. Non-nil means that changes in region may cause
  336. the region to be revealed. The region is
  337. revealed after changes if the function returns
  338. non-nil.
  339. The function called after changes are made with
  340. two arguments: cons (beg . end) representing the
  341. folded region and spec symbol.")
  342. (defvar-local org-fold-core--spec-symbols nil
  343. "Alist holding buffer spec symbols and aliases.
  344. This variable is defined to reduce load on Emacs garbage collector
  345. reducing the number of transiently allocated variables.")
  346. (defvar-local org-fold-core--spec-list nil
  347. "List holding buffer spec symbols, but not aliases.
  348. This variable is defined to reduce load on Emacs garbage collector
  349. reducing the number of transiently allocated variables.")
  350. (defvar-local org-fold-core-extend-changed-region-functions nil
  351. "Special hook run just before handling changes in buffer.
  352. This is used to account changes outside folded regions that still
  353. affect the folded region visibility. For example, removing all stars
  354. at the beginning of a folded Org mode heading should trigger the
  355. folded text to be revealed. Each function is called with two
  356. arguments: beginning and the end of the changed region.")
  357. ;;; Utility functions
  358. (defsubst org-fold-core-folding-spec-list (&optional buffer)
  359. "Return list of all the folding spec symbols in BUFFER."
  360. (or (buffer-local-value 'org-fold-core--spec-list (or buffer (current-buffer)))
  361. (with-current-buffer (or buffer (current-buffer))
  362. (setq org-fold-core--spec-list (mapcar #'car org-fold-core--specs)))))
  363. (defun org-fold-core-get-folding-spec-from-alias (spec-or-alias)
  364. "Return the folding spec symbol for SPEC-OR-ALIAS.
  365. Return nil when there is no matching folding spec."
  366. (when spec-or-alias
  367. (unless org-fold-core--spec-symbols
  368. (dolist (spec (org-fold-core-folding-spec-list))
  369. (push (cons spec spec) org-fold-core--spec-symbols)
  370. (dolist (alias (assq :alias (assq spec org-fold-core--specs)))
  371. (push (cons alias spec) org-fold-core--spec-symbols))))
  372. (alist-get spec-or-alias org-fold-core--spec-symbols)))
  373. (defsubst org-fold-core-folding-spec-p (spec-or-alias)
  374. "Check if SPEC-OR-ALIAS is a registered folding spec."
  375. (org-fold-core-get-folding-spec-from-alias spec-or-alias))
  376. (defsubst org-fold-core--check-spec (spec-or-alias)
  377. "Throw an error if SPEC-OR-ALIAS is not in `org-fold-core--spec-priority-list'."
  378. (unless (org-fold-core-folding-spec-p spec-or-alias)
  379. (error "%s is not a valid folding spec" spec-or-alias)))
  380. (defsubst org-fold-core-get-folding-spec-property (spec-or-alias property)
  381. "Get PROPERTY of a folding SPEC-OR-ALIAS.
  382. Possible properties can be found in `org-fold-core--specs' docstring."
  383. (org-fold-core--check-spec spec-or-alias)
  384. (if (and (memql 'ignore-indirect org-fold-core--optimise-for-huge-buffers)
  385. (eq property :global))
  386. t
  387. (if (and (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
  388. (eq property :visible))
  389. nil
  390. (cdr (assq property (assq (org-fold-core-get-folding-spec-from-alias spec-or-alias) org-fold-core--specs))))))
  391. (defconst org-fold-core--spec-property-prefix "org-fold--spec-"
  392. "Prefix used to create property symbol.")
  393. (defsubst org-fold-core-get-folding-property-symbol (spec &optional buffer global)
  394. "Get folding text property using to store SPEC in current buffer or BUFFER.
  395. If GLOBAL is non-nil, do not make the property unique in the BUFFER."
  396. (if (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
  397. (intern (format "%s-global" org-fold-core--spec-property-prefix))
  398. (intern (format (concat org-fold-core--spec-property-prefix "%s-%S")
  399. (symbol-name spec)
  400. ;; (sxhash buf) appears to be not constant over time.
  401. ;; Using buffer-name is safe, since the only place where
  402. ;; buffer-local text property actually matters is an indirect
  403. ;; buffer, where the name cannot be same anyway.
  404. (if global 'global
  405. (sxhash (buffer-name (or buffer (current-buffer)))))))))
  406. (defsubst org-fold-core-get-folding-spec-from-folding-prop (folding-prop)
  407. "Return folding spec symbol used for folding property with name FOLDING-PROP."
  408. (catch :exit
  409. (dolist (spec (org-fold-core-folding-spec-list))
  410. ;; We know that folding properties have
  411. ;; folding spec in their name.
  412. (when (string-match-p (symbol-name spec)
  413. (symbol-name folding-prop))
  414. (throw :exit spec)))))
  415. (defvar org-fold-core--property-symbol-cache (make-hash-table :test 'equal)
  416. "Saved values of folding properties for (buffer . spec) conses.")
  417. (defvar-local org-fold-core--indirect-buffers nil
  418. "List of indirect buffers created from current buffer.
  419. The first element of the list is always the current buffer.
  420. This variable is needed to work around Emacs bug#46982, while Emacs
  421. does not provide a way `after-change-functions' in any other buffer
  422. than the buffer where the change was actually made.")
  423. (defmacro org-fold-core-cycle-over-indirect-buffers (&rest body)
  424. "Execute BODY in current buffer and all its indirect buffers.
  425. Also, make sure that folding properties from killed buffers are not
  426. hanging around."
  427. (declare (debug (form body)) (indent 0))
  428. `(let (buffers dead-properties)
  429. (if (and (not (buffer-base-buffer))
  430. (not (eq (current-buffer) (car org-fold-core--indirect-buffers))))
  431. ;; We are in base buffer with `org-fold-core--indirect-buffers' value from
  432. ;; different buffer. This can happen, for example, when
  433. ;; org-capture copies local variables into *Capture* buffer.
  434. (setq buffers (list (current-buffer)))
  435. (dolist (buf (cons (or (buffer-base-buffer) (current-buffer))
  436. (buffer-local-value 'org-fold-core--indirect-buffers (or (buffer-base-buffer) (current-buffer)))))
  437. (if (buffer-live-p buf)
  438. (push buf buffers)
  439. (dolist (spec (org-fold-core-folding-spec-list))
  440. (when (and (not (org-fold-core-get-folding-spec-property spec :global))
  441. (gethash (cons buf spec) org-fold-core--property-symbol-cache))
  442. ;; Make sure that dead-properties variable can be passed
  443. ;; as argument to `remove-text-properties'.
  444. (push t dead-properties)
  445. (push (gethash (cons buf spec) org-fold-core--property-symbol-cache)
  446. dead-properties))))))
  447. (dolist (buf buffers)
  448. (with-current-buffer buf
  449. (with-silent-modifications
  450. (save-restriction
  451. (widen)
  452. (remove-text-properties
  453. (point-min) (point-max)
  454. dead-properties)))
  455. ,@body))))
  456. ;; This is the core function used to fold text in buffers. We use
  457. ;; text properties to hide folded text, however 'invisible property is
  458. ;; not directly used (unless risky `org-fold-core--optimise-for-huge-buffers' is
  459. ;; enabled). Instead, we define unique text property (folding
  460. ;; property) for every possible folding spec and add the resulting
  461. ;; text properties into `char-property-alias-alist', so that
  462. ;; 'invisible text property is automatically defined if any of the
  463. ;; folding properties is non-nil. This approach lets us maintain
  464. ;; multiple folds for the same text region - poor man's overlays (but
  465. ;; much faster). Additionally, folding properties are ensured to be
  466. ;; unique for different buffers (especially for indirect
  467. ;; buffers). This is done to allow different folding states in
  468. ;; indirect buffers.
  469. (defun org-fold-core--property-symbol-get-create (spec &optional buffer return-only)
  470. "Return a unique symbol suitable as folding text property.
  471. Return value is unique for folding SPEC in BUFFER.
  472. If the buffer already have buffer-local setup in `char-property-alias-alist'
  473. and the setup appears to be created for different buffer,
  474. copy the old invisibility state into new buffer-local text properties,
  475. unless RETURN-ONLY is non-nil."
  476. (if (eq org-fold-core-style 'overlays)
  477. (org-fold-core-get-folding-property-symbol spec nil 'global)
  478. (let* ((buf (or buffer (current-buffer))))
  479. ;; Create unique property symbol for SPEC in BUFFER
  480. (let ((local-prop (or (gethash (cons buf spec) org-fold-core--property-symbol-cache)
  481. (puthash (cons buf spec)
  482. (org-fold-core-get-folding-property-symbol
  483. spec buf
  484. (org-fold-core-get-folding-spec-property spec :global))
  485. org-fold-core--property-symbol-cache))))
  486. (prog1
  487. local-prop
  488. (unless return-only
  489. (with-current-buffer buf
  490. ;; Update folding properties carried over from other
  491. ;; buffer (implying that current buffer is indirect
  492. ;; buffer). Normally, `char-property-alias-alist' in new
  493. ;; indirect buffer is a copy of the same variable from
  494. ;; the base buffer. Then, `char-property-alias-alist'
  495. ;; would contain folding properties, which are not
  496. ;; matching the generated `local-prop'.
  497. (unless (member local-prop (cdr (assq 'invisible char-property-alias-alist)))
  498. ;; Add current buffer to the list of indirect buffers in the base buffer.
  499. (when (buffer-base-buffer)
  500. (with-current-buffer (buffer-base-buffer)
  501. (setq-local org-fold-core--indirect-buffers
  502. (let (bufs)
  503. (org-fold-core-cycle-over-indirect-buffers
  504. (push (current-buffer) bufs))
  505. (push buf bufs)
  506. (delete-dups bufs)))))
  507. ;; Copy all the old folding properties to preserve the folding state
  508. (with-silent-modifications
  509. (dolist (old-prop (cdr (assq 'invisible char-property-alias-alist)))
  510. (org-with-wide-buffer
  511. (let* ((pos (point-min))
  512. (spec (org-fold-core-get-folding-spec-from-folding-prop old-prop))
  513. ;; Generate new buffer-unique folding property
  514. (new-prop (when spec (org-fold-core--property-symbol-get-create spec nil 'return-only))))
  515. ;; Copy the visibility state for `spec' from `old-prop' to `new-prop'
  516. (unless (eq old-prop new-prop)
  517. (while (< pos (point-max))
  518. (let ((val (get-text-property pos old-prop))
  519. (next (next-single-char-property-change pos old-prop)))
  520. (when val
  521. (put-text-property pos next new-prop val))
  522. (setq pos next)))))))
  523. ;; Update `char-property-alias-alist' with folding
  524. ;; properties unique for the current buffer.
  525. (setq-local char-property-alias-alist
  526. (cons (cons 'invisible
  527. (mapcar (lambda (spec)
  528. (org-fold-core--property-symbol-get-create spec nil 'return-only))
  529. (org-fold-core-folding-spec-list)))
  530. (remove (assq 'invisible char-property-alias-alist)
  531. char-property-alias-alist)))
  532. ;; Set folding property stickyness according to
  533. ;; their `:font-sticky' and `:rear-sticky'
  534. ;; parameters.
  535. (let (full-prop-list)
  536. (org-fold-core-cycle-over-indirect-buffers
  537. (setq full-prop-list
  538. (append full-prop-list
  539. (delq nil
  540. (mapcar (lambda (spec)
  541. (cond
  542. ((org-fold-core-get-folding-spec-property spec :front-sticky)
  543. (cons (org-fold-core--property-symbol-get-create spec nil 'return-only)
  544. nil))
  545. ((org-fold-core-get-folding-spec-property spec :rear-sticky)
  546. nil)
  547. (t
  548. (cons (org-fold-core--property-symbol-get-create spec nil 'return-only)
  549. t))))
  550. (org-fold-core-folding-spec-list))))))
  551. (org-fold-core-cycle-over-indirect-buffers
  552. (setq-local text-property-default-nonsticky
  553. (delete-dups (append
  554. text-property-default-nonsticky
  555. full-prop-list))))))))))))))
  556. (defun org-fold-core-decouple-indirect-buffer-folds ()
  557. "Copy and decouple folding state in a newly created indirect buffer.
  558. This function is mostly indented to be used in `clone-indirect-buffer-hook'."
  559. (when (and (buffer-base-buffer)
  560. (eq org-fold-core-style 'text-properties))
  561. (org-fold-core--property-symbol-get-create (car (org-fold-core-folding-spec-list)))))
  562. ;;; API
  563. ;;;; Modifying folding specs
  564. (defun org-fold-core-set-folding-spec-property (spec property value &optional force)
  565. "Set PROPERTY of a folding SPEC to VALUE.
  566. Possible properties and values can be found in `org-fold-core--specs' docstring.
  567. Do not check previous value when FORCE is non-nil."
  568. (pcase property
  569. (:ellipsis
  570. (unless (and (not force) (equal value (org-fold-core-get-folding-spec-property spec :ellipsis)))
  571. (remove-from-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis)))
  572. (unless (org-fold-core-get-folding-spec-property spec :visible)
  573. (add-to-invisibility-spec (cons spec value)))))
  574. (:visible
  575. (unless (or (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
  576. (and (not force) (equal value (org-fold-core-get-folding-spec-property spec :visible))))
  577. (if value
  578. (remove-from-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis)))
  579. (add-to-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis))))))
  580. (:alias
  581. ;; Clear symbol cache.
  582. (setq org-fold-core--spec-symbols nil))
  583. (:isearch-open nil)
  584. (:isearch-ignore nil)
  585. (:front-sticky nil)
  586. (:rear-sticky nil)
  587. (_ nil))
  588. (setf (cdr (assq property (assq spec org-fold-core--specs))) value))
  589. (defun org-fold-core-add-folding-spec (spec &optional properties buffer append)
  590. "Add a new folding SPEC with PROPERTIES in BUFFER.
  591. SPEC must be a symbol. BUFFER can be a buffer to set SPEC in or nil to
  592. set SPEC in current buffer.
  593. By default, the added SPEC will have highest priority among the
  594. previously defined specs. When optional APPEND argument is non-nil,
  595. SPEC will have the lowest priority instead. If SPEC was already
  596. defined earlier, it will be redefined according to provided optional
  597. arguments.
  598. `
  599. The folding spec properties will be set to PROPERTIES (see
  600. `org-fold-core--specs' for details)."
  601. (when (eq spec 'all) (error "Cannot use reserved folding spec symbol 'all"))
  602. (with-current-buffer (or buffer (current-buffer))
  603. ;; Clear the cache.
  604. (setq org-fold-core--spec-list nil
  605. org-fold-core--spec-symbols nil)
  606. (let* ((full-properties (mapcar (lambda (prop) (cons prop (cdr (assq prop properties))))
  607. '( :visible :ellipsis :isearch-ignore
  608. :global :isearch-open :front-sticky
  609. :rear-sticky :fragile :alias
  610. :font-lock-skip)))
  611. (full-spec (cons spec full-properties)))
  612. (add-to-list 'org-fold-core--specs full-spec append)
  613. (mapc (lambda (prop-cons) (org-fold-core-set-folding-spec-property spec (car prop-cons) (cdr prop-cons) 'force)) full-properties)
  614. ;; Update buffer inivisibility specs.
  615. (org-fold-core--property-symbol-get-create spec))))
  616. (defun org-fold-core-remove-folding-spec (spec &optional buffer)
  617. "Remove a folding SPEC in BUFFER.
  618. SPEC must be a symbol.
  619. BUFFER can be a buffer to remove SPEC in, nil to remove SPEC in current
  620. buffer, or \\='all to remove SPEC in all open `org-mode' buffers and all
  621. future org buffers."
  622. (org-fold-core--check-spec spec)
  623. (when (eq buffer 'all)
  624. (setq-default org-fold-core--specs (delete (cdr (assq spec org-fold-core--specs)) org-fold-core--specs))
  625. (mapc (lambda (buf)
  626. (org-fold-core-remove-folding-spec spec buf))
  627. (buffer-list)))
  628. (let ((buffer (or buffer (current-buffer))))
  629. (with-current-buffer buffer
  630. ;; Clear the cache.
  631. (setq org-fold-core--spec-list nil
  632. org-fold-core--spec-symbols nil)
  633. (org-fold-core-set-folding-spec-property spec :visible t)
  634. (setq org-fold-core--specs (delete (cdr (assq spec org-fold-core--specs)) org-fold-core--specs)))))
  635. (defun org-fold-core-initialize (&optional specs)
  636. "Setup folding in current buffer using SPECS as value of `org-fold-core--specs'."
  637. ;; Preserve the priorities.
  638. (when specs (setq specs (nreverse specs)))
  639. (unless specs (setq specs org-fold-core--specs))
  640. (setq org-fold-core--specs nil
  641. org-fold-core--spec-list nil
  642. org-fold-core--spec-symbols nil)
  643. (dolist (spec specs)
  644. (org-fold-core-add-folding-spec (car spec) (cdr spec)))
  645. (add-hook 'after-change-functions 'org-fold-core--fix-folded-region nil 'local)
  646. (add-hook 'clone-indirect-buffer-hook #'org-fold-core-decouple-indirect-buffer-folds nil 'local)
  647. ;; Optimise buffer fontification to not fontify folded text.
  648. (when (eq font-lock-fontify-region-function #'font-lock-default-fontify-region)
  649. (setq-local font-lock-fontify-region-function 'org-fold-core-fontify-region))
  650. ;; Setup killing text
  651. (setq-local filter-buffer-substring-function #'org-fold-core--buffer-substring-filter)
  652. (if (and (boundp 'isearch-opened-regions)
  653. (eq org-fold-core-style 'text-properties))
  654. ;; Use new implementation of isearch allowing to search inside text
  655. ;; hidden via text properties.
  656. (org-fold-core--isearch-setup 'text-properties)
  657. (org-fold-core--isearch-setup 'overlays)))
  658. ;;;; Searching and examining folded text
  659. (defsubst org-fold-core-folded-p (&optional pos spec-or-alias)
  660. "Non-nil if the character after POS is folded.
  661. If POS is nil, use `point' instead.
  662. If SPEC-OR-ALIAS is a folding spec or a list, only check the given
  663. folding spec or the listed specs."
  664. (if (and spec-or-alias (listp spec-or-alias))
  665. (catch :found
  666. (dolist (spec spec-or-alias)
  667. (let ((val (org-fold-core-get-folding-spec spec pos)))
  668. (when val (throw :found val)))))
  669. (org-fold-core-get-folding-spec spec-or-alias pos)))
  670. (defun org-fold-core-region-folded-p (beg end &optional spec-or-alias)
  671. "Non-nil if the region between BEG and END is folded.
  672. If SPEC-OR-ALIAS is a folding spec, only check the given folding spec."
  673. (org-with-point-at beg
  674. (catch :visible
  675. (while (< (point) end)
  676. (unless (org-fold-core-get-folding-spec spec-or-alias) (throw :visible nil))
  677. (goto-char (org-fold-core-next-folding-state-change spec-or-alias nil end)))
  678. t)))
  679. (defun org-fold-core-get-folding-spec (&optional spec-or-alias pom)
  680. "Get folding state at `point' or POM.
  681. Return nil if there is no folding at point or POM.
  682. If SPEC-OR-ALIAS is nil, return a folding spec with highest priority
  683. among present at `point' or POM.
  684. If SPEC-OR-ALIAS is \\='all, return the list of all present folding
  685. specs.
  686. If SPEC-OR-ALIAS is a valid folding spec or a spec alias, return the
  687. corresponding folding spec (if the text is folded using that spec)."
  688. (let ((spec (if (eq spec-or-alias 'all)
  689. 'all
  690. (org-fold-core-get-folding-spec-from-alias spec-or-alias))))
  691. (when (and spec (not (eq spec 'all))) (org-fold-core--check-spec spec))
  692. (org-with-point-at pom
  693. (cond
  694. ((eq spec 'all)
  695. (let ((result))
  696. (dolist (spec (org-fold-core-folding-spec-list))
  697. (let ((val (get-char-property (point) (org-fold-core--property-symbol-get-create spec nil t))))
  698. (when val (push val result))))
  699. (reverse result)))
  700. ((null spec)
  701. (let ((result (get-char-property (point) 'invisible)))
  702. (when (org-fold-core-folding-spec-p result) result)))
  703. (t (get-char-property (point) (org-fold-core--property-symbol-get-create spec nil t)))))))
  704. (defun org-fold-core-get-folding-specs-in-region (beg end)
  705. "Get all folding specs in region from BEG to END."
  706. (let ((pos beg)
  707. all-specs)
  708. (while (< pos end)
  709. (setq all-specs (append all-specs (org-fold-core-get-folding-spec nil pos)))
  710. (setq pos (org-fold-core-next-folding-state-change nil pos end)))
  711. (unless (listp all-specs) (setq all-specs (list all-specs)))
  712. (delete-dups all-specs)))
  713. (defun org-fold-core-get-region-at-point (&optional spec-or-alias pom)
  714. "Return region folded using SPEC-OR-ALIAS at POM.
  715. If SPEC is nil, return the largest possible folded region.
  716. The return value is a cons of beginning and the end of the region.
  717. Return nil when no fold is present at point of POM."
  718. (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
  719. (org-with-point-at (or pom (point))
  720. (if spec
  721. (if (eq org-fold-core-style 'text-properties)
  722. (org-find-text-property-region (point) (org-fold-core--property-symbol-get-create spec nil t))
  723. (let ((ov (cdr (get-char-property-and-overlay (point) (org-fold-core--property-symbol-get-create spec nil t)))))
  724. (when ov (cons (overlay-start ov) (overlay-end ov)))))
  725. (let ((region (cons (point) (point))))
  726. (dolist (spec (org-fold-core-get-folding-spec 'all))
  727. (let ((local-region (org-fold-core-get-region-at-point spec)))
  728. (when (< (car local-region) (car region))
  729. (setcar region (car local-region)))
  730. (when (> (cdr local-region) (cdr region))
  731. (setcdr region (cdr local-region)))))
  732. (unless (eq (car region) (cdr region)) region))))))
  733. (defun org-fold-core-next-visibility-change (&optional pos limit ignore-hidden-p previous-p)
  734. "Return next point from POS up to LIMIT where text becomes visible/invisible.
  735. By default, text hidden by any means (i.e. not only by folding, but
  736. also via fontification) will be considered.
  737. If IGNORE-HIDDEN-P is non-nil, consider only folded text.
  738. If PREVIOUS-P is non-nil, search backwards."
  739. (let* ((pos (or pos (point)))
  740. (invisible-p (if ignore-hidden-p
  741. #'org-fold-core-folded-p
  742. #'invisible-p))
  743. (invisible-initially? (funcall invisible-p pos))
  744. (limit (or limit (if previous-p
  745. (point-min)
  746. (point-max))))
  747. (cmp (if previous-p #'> #'<))
  748. (next-change (if previous-p
  749. (if ignore-hidden-p
  750. (lambda (p) (org-fold-core-previous-folding-state-change (org-fold-core-get-folding-spec nil p) p limit))
  751. (lambda (p) (max limit (1- (previous-single-char-property-change p 'invisible nil limit)))))
  752. (if ignore-hidden-p
  753. (lambda (p) (org-fold-core-next-folding-state-change (org-fold-core-get-folding-spec nil p) p limit))
  754. (lambda (p) (next-single-char-property-change p 'invisible nil limit)))))
  755. (next pos))
  756. (while (and (funcall cmp next limit)
  757. (not (org-xor invisible-initially? (funcall invisible-p next))))
  758. (setq next (funcall next-change next)))
  759. next))
  760. (defun org-fold-core-previous-visibility-change (&optional pos limit ignore-hidden-p)
  761. "Call `org-fold-core-next-visibility-change' searching backwards."
  762. (org-fold-core-next-visibility-change pos limit ignore-hidden-p 'previous))
  763. (defun org-fold-core-next-folding-state-change (&optional spec-or-alias pos limit previous-p)
  764. "Return point after POS where folding state changes up to LIMIT.
  765. If SPEC-OR-ALIAS is nil, return next point where _any_ single folding
  766. spec changes.
  767. For example, (org-fold-core-next-folding-state-change nil) with point
  768. somewhere in the below structure will return the nearest <...> point.
  769. * Headline <begin outline fold>
  770. :PROPERTIES:<begin drawer fold>
  771. :ID: test
  772. :END:<end drawer fold>
  773. Fusce suscipit, wisi nec facilisis facilisis, est dui fermentum leo,
  774. quis tempor ligula erat quis odio.
  775. ** Another headline
  776. :DRAWER:<begin drawer fold>
  777. :END:<end drawer fold>
  778. ** Yet another headline
  779. <end of outline fold>
  780. If SPEC-OR-ALIAS is a folding spec symbol, only consider that folding
  781. spec.
  782. If SPEC-OR-ALIAS is a list, only consider changes of folding specs
  783. from the list.
  784. Search backwards when PREVIOUS-P is non-nil."
  785. (when (and spec-or-alias (symbolp spec-or-alias))
  786. (setq spec-or-alias (list spec-or-alias)))
  787. (when spec-or-alias
  788. (setq spec-or-alias
  789. (mapcar (lambda (spec-or-alias)
  790. (or (org-fold-core-get-folding-spec-from-alias spec-or-alias)
  791. spec-or-alias))
  792. spec-or-alias))
  793. (mapc #'org-fold-core--check-spec spec-or-alias))
  794. (unless spec-or-alias
  795. (setq spec-or-alias (org-fold-core-folding-spec-list)))
  796. (setq pos (or pos (point)))
  797. (apply (if previous-p
  798. #'max
  799. #'min)
  800. (mapcar (if previous-p
  801. (lambda (prop) (max (or limit (point-min)) (previous-single-property-change pos prop nil (or limit (point-min)))))
  802. (lambda (prop) (next-single-property-change pos prop nil (or limit (point-max)))))
  803. (mapcar (lambda (el) (org-fold-core--property-symbol-get-create el nil t))
  804. spec-or-alias))))
  805. (defun org-fold-core-previous-folding-state-change (&optional spec-or-alias pos limit)
  806. "Call `org-fold-core-next-folding-state-change' searching backwards."
  807. (org-fold-core-next-folding-state-change spec-or-alias pos limit 'previous))
  808. (defun org-fold-core-search-forward (spec-or-alias &optional limit)
  809. "Search next region folded via folding SPEC-OR-ALIAS up to LIMIT.
  810. Move point right after the end of the region, to LIMIT, or
  811. `point-max'. The `match-data' will contain the region."
  812. (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
  813. (let ((prop-symbol (org-fold-core--property-symbol-get-create spec nil t)))
  814. (goto-char (or (next-single-char-property-change (point) prop-symbol nil limit) limit (point-max)))
  815. (when (and (< (point) (or limit (point-max)))
  816. (not (org-fold-core-get-folding-spec spec)))
  817. (goto-char (next-single-char-property-change (point) prop-symbol nil limit)))
  818. (when (org-fold-core-get-folding-spec spec)
  819. (let ((region (org-fold-core-get-region-at-point spec)))
  820. (when (< (cdr region) (or limit (point-max)))
  821. (goto-char (1+ (cdr region)))
  822. (set-match-data (list (set-marker (make-marker) (car region) (current-buffer))
  823. (set-marker (make-marker) (cdr region) (current-buffer))))))))))
  824. ;;;; Changing visibility
  825. ;;;;; Region visibility
  826. (defvar org-fold-core--fontifying nil
  827. "Flag used to avoid font-lock recursion.")
  828. ;; This is the core function performing actual folding/unfolding. The
  829. ;; folding state is stored in text property (folding property)
  830. ;; returned by `org-fold-core--property-symbol-get-create'. The value of the
  831. ;; folding property is folding spec symbol.
  832. (defun org-fold-core-region (from to flag &optional spec-or-alias)
  833. "Hide or show lines from FROM to TO, according to FLAG.
  834. SPEC-OR-ALIAS is the folding spec or foldable element, as a symbol.
  835. If SPEC-OR-ALIAS is omitted and FLAG is nil, unfold everything in the region."
  836. (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
  837. (when spec (org-fold-core--check-spec spec))
  838. (with-silent-modifications
  839. (org-with-wide-buffer
  840. (when (eq org-fold-core-style 'overlays) (remove-overlays from to 'invisible spec))
  841. (if flag
  842. (if (not spec)
  843. (error "Calling `org-fold-core-region' with missing SPEC")
  844. (if (eq org-fold-core-style 'overlays)
  845. ;; Use `front-advance' since text right before to the beginning of
  846. ;; the overlay belongs to the visible line than to the contents.
  847. (let ((o (make-overlay from to nil
  848. (org-fold-core-get-folding-spec-property spec :front-sticky)
  849. (org-fold-core-get-folding-spec-property spec :rear-sticky))))
  850. (overlay-put o 'evaporate t)
  851. (overlay-put o (org-fold-core--property-symbol-get-create spec) spec)
  852. (overlay-put o 'invisible spec)
  853. (overlay-put o 'isearch-open-invisible #'org-fold-core--isearch-show)
  854. (overlay-put o 'isearch-open-invisible-temporary #'org-fold-core--isearch-show-temporary))
  855. (put-text-property from to (org-fold-core--property-symbol-get-create spec) spec)
  856. (put-text-property from to 'isearch-open-invisible #'org-fold-core--isearch-show)
  857. (put-text-property from to 'isearch-open-invisible-temporary #'org-fold-core--isearch-show-temporary)
  858. (when (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  859. ;; If the SPEC has highest priority, assign it directly
  860. ;; to 'invisible property as well. This is done to speed
  861. ;; up Emacs redisplay on huge (Mbs) folded regions where
  862. ;; we don't even want Emacs to spend time cycling over
  863. ;; `char-property-alias-alist'.
  864. (when (eq spec (caar org-fold-core--specs)) (put-text-property from to 'invisible spec)))))
  865. (if (not spec)
  866. (mapc (lambda (spec) (org-fold-core-region from to nil spec)) (org-fold-core-folding-spec-list))
  867. (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  868. (eq org-fold-core-style 'text-properties))
  869. (when (eq spec (caar org-fold-core--specs))
  870. (let ((pos from))
  871. (while (< pos to)
  872. (if (eq spec (get-text-property pos 'invisible))
  873. (let ((next (org-fold-core-next-folding-state-change spec pos to)))
  874. (remove-text-properties pos next '(invisible t))
  875. (setq pos next))
  876. (setq pos (next-single-char-property-change pos 'invisible nil to)))))))
  877. (when (eq org-fold-core-style 'text-properties)
  878. (remove-text-properties from to (list (org-fold-core--property-symbol-get-create spec) nil)))
  879. ;; Fontify unfolded text.
  880. (unless (or (not font-lock-mode)
  881. org-fold-core--fontifying
  882. (not (org-fold-core-get-folding-spec-property spec :font-lock-skip)))
  883. (let ((org-fold-core--fontifying t))
  884. (if jit-lock-mode
  885. (jit-lock-refontify from to)
  886. (save-match-data (font-lock-fontify-region from to)))))))))))
  887. ;;; Make isearch search in some text hidden via text propertoes
  888. (defvar org-fold-core--isearch-overlays nil
  889. "List of overlays temporarily created during isearch.
  890. This is used to allow searching in regions hidden via text properties.
  891. As for [2020-05-09 Sat], Isearch only has special handling of hidden overlays.
  892. Any text hidden via text properties is not revealed even if `search-invisible'
  893. is set to `t'.")
  894. (defvar-local org-fold-core--isearch-local-regions (make-hash-table :test 'equal)
  895. "Hash table storing temporarily shown folds from isearch matches.")
  896. (defun org-fold-core--isearch-setup (type)
  897. "Initialize isearch in org buffer.
  898. TYPE can be either `text-properties' or `overlays'."
  899. (pcase type
  900. (`text-properties
  901. (setq-local search-invisible 'open-all)
  902. (add-hook 'isearch-mode-end-hook #'org-fold-core--clear-isearch-state nil 'local)
  903. (add-hook 'isearch-mode-hook #'org-fold-core--clear-isearch-state nil 'local)
  904. (setq-local isearch-filter-predicate #'org-fold-core--isearch-filter-predicate-text-properties))
  905. (`overlays
  906. (when (eq org-fold-core-style 'text-properties)
  907. (setq-local isearch-filter-predicate #'org-fold-core--isearch-filter-predicate-overlays)
  908. (add-hook 'isearch-mode-end-hook #'org-fold-core--clear-isearch-overlays nil 'local)))
  909. (_ (error "%s: Unknown type of setup for `org-fold-core--isearch-setup'" type))))
  910. (defun org-fold-core--isearch-reveal (pos)
  911. "Default function used to reveal hidden text at POS for isearch."
  912. (let ((region (org-fold-core-get-region-at-point pos)))
  913. (org-fold-core-region (car region) (cdr region) nil)))
  914. (defun org-fold-core--isearch-filter-predicate-text-properties (beg end)
  915. "Make sure that folded text is searchable when user whant so.
  916. This function is intended to be used as `isearch-filter-predicate'."
  917. (and
  918. ;; Check folding specs that cannot be searched
  919. (not (memq nil (mapcar (lambda (spec) (not (org-fold-core-get-folding-spec-property spec :isearch-ignore)))
  920. (org-fold-core-get-folding-specs-in-region beg end))))
  921. ;; Check 'invisible properties that are not folding specs.
  922. (or (eq search-invisible t) ; User wants to search anyway, allow it.
  923. (let ((pos beg)
  924. unknown-invisible-property)
  925. (while (and (< pos end)
  926. (not unknown-invisible-property))
  927. (when (and (get-text-property pos 'invisible)
  928. (not (org-fold-core-folding-spec-p (get-text-property pos 'invisible))))
  929. (setq unknown-invisible-property t))
  930. (setq pos (next-single-char-property-change pos 'invisible)))
  931. (not unknown-invisible-property)))
  932. (or (and (eq search-invisible t)
  933. ;; FIXME: this opens regions permanenly for now.
  934. ;; I also tried to force search-invisible 'open-all around
  935. ;; `isearch-range-invisible', but that somehow causes
  936. ;; infinite loop in `isearch-lazy-highlight'.
  937. (prog1 t
  938. ;; We still need to reveal the folded location
  939. (org-fold-core--isearch-show-temporary (cons beg end) nil)))
  940. (not (isearch-range-invisible beg end)))))
  941. (defun org-fold-core--clear-isearch-state ()
  942. "Clear `org-fold-core--isearch-local-regions'."
  943. (clrhash org-fold-core--isearch-local-regions))
  944. (defun org-fold-core--isearch-show (region)
  945. "Reveal text in REGION found by isearch."
  946. (org-with-point-at (car region)
  947. (while (< (point) (cdr region))
  948. (funcall org-fold-core-isearch-open-function (car region))
  949. (goto-char (org-fold-core-next-visibility-change (point) (cdr region) 'ignore-hidden)))))
  950. (defun org-fold-core--isearch-show-temporary (region hide-p)
  951. "Temporarily reveal text in REGION.
  952. Hide text instead if HIDE-P is non-nil."
  953. (if (not hide-p)
  954. (let ((pos (car region)))
  955. (while (< pos (cdr region))
  956. (let ((spec-no-open
  957. (catch :found
  958. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  959. (unless (org-fold-core-get-folding-spec-property spec :isearch-open)
  960. (throw :found spec))))))
  961. (if spec-no-open
  962. ;; Skip regions folded with folding specs that cannot be opened.
  963. (setq pos (org-fold-core-next-folding-state-change spec-no-open pos (cdr region)))
  964. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  965. (push (cons spec (org-fold-core-get-region-at-point spec pos)) (gethash region org-fold-core--isearch-local-regions)))
  966. (org-fold-core--isearch-show region)
  967. (setq pos (org-fold-core-next-folding-state-change nil pos (cdr region)))))))
  968. (mapc (lambda (val) (org-fold-core-region (cadr val) (cddr val) t (car val))) (gethash region org-fold-core--isearch-local-regions))
  969. (remhash region org-fold-core--isearch-local-regions)))
  970. (defvar-local org-fold-core--isearch-special-specs nil
  971. "List of specs that can break visibility state when converted to overlays.
  972. This is a hack, but I do not see a better way around until isearch
  973. gets support of text properties.")
  974. (defun org-fold-core--create-isearch-overlays (beg end)
  975. "Replace text property invisibility spec by overlays between BEG and END.
  976. All the searcheable folded regions will be changed to use overlays
  977. instead of text properties. The created overlays will be stored in
  978. `org-fold-core--isearch-overlays'."
  979. (let ((pos beg))
  980. (while (< pos end)
  981. ;; We need loop below to make sure that we clean all invisible
  982. ;; properties, which may be nested.
  983. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  984. (unless (org-fold-core-get-folding-spec-property spec :isearch-ignore)
  985. (let* ((region (org-fold-core-get-region-at-point spec pos)))
  986. (when (memq spec org-fold-core--isearch-special-specs)
  987. (setq pos (min pos (car region)))
  988. (setq end (max end (cdr region))))
  989. ;; Changing text properties is considered buffer modification.
  990. ;; We do not want it here.
  991. (with-silent-modifications
  992. (org-fold-core-region (car region) (cdr region) nil spec)
  993. ;; The overlay is modelled after `outline-flag-region'
  994. ;; [2020-05-09 Sat] overlay for 'outline blocks.
  995. (let ((o (make-overlay (car region) (cdr region) nil 'front-advance)))
  996. (overlay-put o 'evaporate t)
  997. (overlay-put o 'invisible spec)
  998. (overlay-put o 'org-invisible spec)
  999. ;; Make sure that overlays are applied in the same order
  1000. ;; with the folding specs.
  1001. ;; Note: `memq` returns cdr with car equal to the first
  1002. ;; found matching element.
  1003. (overlay-put o 'priority (length (memq spec (org-fold-core-folding-spec-list))))
  1004. ;; `delete-overlay' here means that spec information will be lost
  1005. ;; for the region. The region will remain visible.
  1006. (if (org-fold-core-get-folding-spec-property spec :isearch-open)
  1007. (overlay-put o 'isearch-open-invisible #'delete-overlay)
  1008. (overlay-put o 'isearch-open-invisible #'ignore)
  1009. (overlay-put o 'isearch-open-invisible-temporary #'ignore))
  1010. (push o org-fold-core--isearch-overlays))))))
  1011. (setq pos (org-fold-core-next-folding-state-change nil pos end)))))
  1012. (defun org-fold-core--isearch-filter-predicate-overlays (beg end)
  1013. "Return non-nil if text between BEG and END is deemed visible by isearch.
  1014. This function is intended to be used as `isearch-filter-predicate'."
  1015. (org-fold-core--create-isearch-overlays beg end) ;; trick isearch by creating overlays in place of invisible text
  1016. (isearch-filter-visible beg end))
  1017. (defun org-fold-core--clear-isearch-overlay (ov)
  1018. "Convert OV region back into using text properties."
  1019. (let ((spec (if isearch-mode-end-hook-quit
  1020. ;; Restore all folds.
  1021. (overlay-get ov 'org-invisible)
  1022. ;; Leave opened folds open.
  1023. (overlay-get ov 'invisible))))
  1024. ;; Ignore deleted overlays.
  1025. (when (and spec
  1026. (overlay-buffer ov))
  1027. ;; Changing text properties is considered buffer modification.
  1028. ;; We do not want it here.
  1029. (with-silent-modifications
  1030. (when (<= (overlay-end ov) (point-max))
  1031. (org-fold-core-region (overlay-start ov) (overlay-end ov) t spec)))))
  1032. (when (member ov isearch-opened-overlays)
  1033. (setq isearch-opened-overlays (delete ov isearch-opened-overlays)))
  1034. (delete-overlay ov))
  1035. (defun org-fold-core--clear-isearch-overlays ()
  1036. "Convert overlays from `org-fold-core--isearch-overlays' back to text properties."
  1037. (when org-fold-core--isearch-overlays
  1038. (mapc #'org-fold-core--clear-isearch-overlay org-fold-core--isearch-overlays)
  1039. (setq org-fold-core--isearch-overlays nil)))
  1040. ;;; Handling changes in folded elements
  1041. (defvar org-fold-core--ignore-modifications nil
  1042. "Non-nil: skip processing modifications in `org-fold-core--fix-folded-region'.")
  1043. (defvar org-fold-core--ignore-fragility-checks nil
  1044. "Non-nil: skip fragility checks in `org-fold-core--fix-folded-region'.")
  1045. (defmacro org-fold-core-ignore-modifications (&rest body)
  1046. "Run BODY ignoring buffer modifications in `org-fold-core--fix-folded-region'."
  1047. (declare (debug (form body)) (indent 0))
  1048. `(let ((org-fold-core--ignore-modifications t))
  1049. (unwind-protect (progn ,@body)
  1050. (setq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick)))))
  1051. (defmacro org-fold-core-ignore-fragility-checks (&rest body)
  1052. "Run BODY skipping :fragility checks in `org-fold-core--fix-folded-region'."
  1053. (declare (debug (form body)) (indent 0))
  1054. `(let ((org-fold-core--ignore-fragility-checks t))
  1055. (progn ,@body)))
  1056. (defvar-local org-fold-core--last-buffer-chars-modified-tick nil
  1057. "Variable storing the last return value of `buffer-chars-modified-tick'.")
  1058. (defun org-fold-core--fix-folded-region (from to _)
  1059. "Process modifications in folded elements within FROM . TO region.
  1060. This function intended to be used as one of `after-change-functions'.
  1061. This function does nothing if text the only modification was changing
  1062. text properties (for the sake of reducing overheads).
  1063. If a text was inserted into invisible region, hide the inserted text.
  1064. If a text was inserted in front/back of the region, hide it according
  1065. to :font-sticky/:rear-sticky folding spec property.
  1066. If the folded region is folded with a spec with non-nil :fragile
  1067. property, unfold the region if the :fragile function returns non-nil."
  1068. ;; If no insertions or deletions in buffer, skip all the checks.
  1069. (unless (or (eq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick))
  1070. org-fold-core--ignore-modifications
  1071. (memql 'ignore-modification-checks org-fold-core--optimise-for-huge-buffers))
  1072. ;; Store the new buffer modification state.
  1073. (setq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick))
  1074. (save-match-data
  1075. ;; Handle changes in all the indirect buffers and in the base
  1076. ;; buffer. Work around Emacs bug#46982.
  1077. (when (eq org-fold-core-style 'text-properties)
  1078. (org-fold-core-cycle-over-indirect-buffers
  1079. ;; Re-hide text inserted in the middle/font/back of a folded
  1080. ;; region.
  1081. (unless (equal from to) ; Ignore deletions.
  1082. (dolist (spec (org-fold-core-folding-spec-list))
  1083. ;; Reveal fully invisible text inserted in the middle
  1084. ;; of visible portion of the buffer. This is needed,
  1085. ;; for example, when there was a deletion in a folded
  1086. ;; heading, the heading was unfolded, end `undo' was
  1087. ;; called. The `undo' would insert the folded text.
  1088. (when (and (or (eq from (point-min))
  1089. (not (org-fold-core-folded-p (1- from) spec)))
  1090. (or (eq to (point-max))
  1091. (not (org-fold-core-folded-p to spec)))
  1092. (org-fold-core-region-folded-p from to spec))
  1093. (org-fold-core-region from to nil spec))
  1094. ;; Look around and fold the new text if the nearby folds are
  1095. ;; sticky.
  1096. (unless (org-fold-core-region-folded-p from to spec)
  1097. (let ((spec-to (org-fold-core-get-folding-spec spec (min to (1- (point-max)))))
  1098. (spec-from (org-fold-core-get-folding-spec spec (max (point-min) (1- from)))))
  1099. ;; Reveal folds around undoed deletion.
  1100. (when undo-in-progress
  1101. (let ((lregion (org-fold-core-get-region-at-point spec (max (point-min) (1- from))))
  1102. (rregion (org-fold-core-get-region-at-point spec (min to (1- (point-max))))))
  1103. (if (and lregion rregion)
  1104. (org-fold-core-region (car lregion) (cdr rregion) nil spec)
  1105. (when lregion
  1106. (org-fold-core-region (car lregion) (cdr lregion) nil spec))
  1107. (when rregion
  1108. (org-fold-core-region (car rregion) (cdr rregion) nil spec)))))
  1109. ;; Hide text inserted in the middle of a fold.
  1110. (when (and (or spec-from (eq from (point-min)))
  1111. (or spec-to (eq to (point-max)))
  1112. (or spec-from spec-to)
  1113. (eq spec-to spec-from)
  1114. (or (org-fold-core-get-folding-spec-property spec :front-sticky)
  1115. (org-fold-core-get-folding-spec-property spec :rear-sticky)))
  1116. (unless (and (eq from (point-min)) (eq to (point-max))) ; Buffer content replaced.
  1117. (org-fold-core-region from to t (or spec-from spec-to))))
  1118. ;; Hide text inserted at the end of a fold.
  1119. (when (and spec-from (org-fold-core-get-folding-spec-property spec-from :rear-sticky))
  1120. (org-fold-core-region from to t spec-from))
  1121. ;; Hide text inserted in front of a fold.
  1122. (when (and spec-to
  1123. (not (eq to (point-max))) ; Text inserted at the end of buffer is not prepended anywhere.
  1124. (org-fold-core-get-folding-spec-property spec-to :front-sticky))
  1125. (org-fold-core-region from to t spec-to))))))))
  1126. ;; Process all the folded text between `from' and `to'. Do it
  1127. ;; only in current buffer to avoid verifying semantic structure
  1128. ;; multiple times in indirect buffers that have exactly same
  1129. ;; text anyway.
  1130. (unless (or org-fold-core--ignore-fragility-checks
  1131. (memql 'ignore-fragility-checks org-fold-core--optimise-for-huge-buffers))
  1132. (dolist (func org-fold-core-extend-changed-region-functions)
  1133. (let ((new-region (funcall func from to)))
  1134. (setq from (car new-region))
  1135. (setq to (cdr new-region))))
  1136. (dolist (spec (org-fold-core-folding-spec-list))
  1137. ;; No action is needed when :fragile is nil for the spec.
  1138. (when (org-fold-core-get-folding-spec-property spec :fragile)
  1139. (org-with-wide-buffer
  1140. ;; Expand the considered region to include partially present fold.
  1141. ;; Note: It is important to do this inside loop over all
  1142. ;; specs. Otherwise, the region may be expanded to huge
  1143. ;; outline fold, potentially involving majority of the
  1144. ;; buffer. That would cause the below code to loop over
  1145. ;; almost all the folds in buffer, which would be too slow.
  1146. (let ((local-from from)
  1147. (local-to to)
  1148. (region-from (org-fold-core-get-region-at-point spec (max (point-min) (1- from))))
  1149. (region-to (org-fold-core-get-region-at-point spec (min to (1- (point-max))))))
  1150. (when region-from (setq local-from (car region-from)))
  1151. (when region-to (setq local-to (cdr region-to)))
  1152. (let ((pos local-from))
  1153. ;; Move to the first hidden region.
  1154. (unless (org-fold-core-get-folding-spec spec pos)
  1155. (setq pos (org-fold-core-next-folding-state-change spec pos local-to)))
  1156. ;; Cycle over all the folds.
  1157. (while (< pos local-to)
  1158. (save-match-data ; we should not clobber match-data in after-change-functions
  1159. (let ((fold-begin (and (org-fold-core-get-folding-spec spec pos)
  1160. pos))
  1161. (fold-end (org-fold-core-next-folding-state-change spec pos local-to)))
  1162. (when (and fold-begin fold-end)
  1163. (when (save-excursion
  1164. (funcall (org-fold-core-get-folding-spec-property spec :fragile)
  1165. (cons fold-begin fold-end)
  1166. spec))
  1167. ;; Reveal completely, not just from the SPEC.
  1168. (org-fold-core-region fold-begin fold-end nil)))))
  1169. ;; Move to next fold.
  1170. (setq pos (org-fold-core-next-folding-state-change spec pos local-to))))))))))))
  1171. ;;; Hanlding killing/yanking of folded text
  1172. ;; Backward compatibility with Emacs 24.
  1173. (defun org-fold-core--seq-partition (list n)
  1174. "Return list of elements of LIST grouped into sub-sequences of length N.
  1175. The last list may contain less than N elements. If N is a
  1176. negative integer or 0, nil is returned."
  1177. (if (fboundp 'seq-partition)
  1178. (seq-partition list n)
  1179. (unless (< n 1)
  1180. (let ((result '()))
  1181. (while list
  1182. (let (part)
  1183. (dotimes (_ n)
  1184. (when list (push (car list) part)))
  1185. (push part result))
  1186. (dotimes (_ n)
  1187. (setq list (cdr list))))
  1188. (nreverse result)))))
  1189. ;; By default, all the text properties of the killed text are
  1190. ;; preserved, including the folding text properties. This can be
  1191. ;; awkward when we copy a text from an indirect buffer to another
  1192. ;; indirect buffer (or the base buffer). The copied text might be
  1193. ;; visible in the source buffer, but might disappear if we yank it in
  1194. ;; another buffer. This happens in the following situation:
  1195. ;; ---- base buffer ----
  1196. ;; * Headline<begin fold>
  1197. ;; Some text hidden in the base buffer, but revealed in the indirect
  1198. ;; buffer.<end fold>
  1199. ;; * Another headline
  1200. ;;
  1201. ;; ---- end of base buffer ----
  1202. ;; ---- indirect buffer ----
  1203. ;; * Headline
  1204. ;; Some text hidden in the base buffer, but revealed in the indirect
  1205. ;; buffer.
  1206. ;; * Another headline
  1207. ;;
  1208. ;; ---- end of indirect buffer ----
  1209. ;; If we copy the text under "Headline" from the indirect buffer and
  1210. ;; insert it under "Another headline" in the base buffer, the inserted
  1211. ;; text will be hidden since it's folding text properties are copyed.
  1212. ;; Basically, the copied text would have two sets of folding text
  1213. ;; properties: (1) Properties for base buffer telling that the text is
  1214. ;; hidden; (2) Properties for the indirect buffer telling that the
  1215. ;; text is visible. The first set of the text properties in inactive
  1216. ;; in the indirect buffer, but will become active once we yank the
  1217. ;; text back into the base buffer.
  1218. ;;
  1219. ;; To avoid the above situation, we simply clear all the properties,
  1220. ;; unrealated to current buffer when a text is copied.
  1221. ;; FIXME: Ideally, we may want to carry the folding state of copied
  1222. ;; text between buffer (probably via user customisation).
  1223. (defun org-fold-core--buffer-substring-filter (beg end &optional delete)
  1224. "Clear folding state in killed text.
  1225. This function is intended to be used as `filter-buffer-substring-function'.
  1226. The arguments and return value are as specified for `filter-buffer-substring'."
  1227. (let ((return-string (buffer-substring--filter beg end delete))
  1228. ;; The list will be used as an argument to `remove-text-properties'.
  1229. props-list)
  1230. ;; There is no easy way to examine all the text properties of a
  1231. ;; string, so we utilise the fact that printed string
  1232. ;; representation lists all its properties.
  1233. ;; Loop over the elements of string representation.
  1234. (unless (or (string= "" return-string)
  1235. (<= end beg)
  1236. (eq org-fold-core-style 'overlays))
  1237. ;; Collect all the text properties the string is completely
  1238. ;; hidden with.
  1239. (dolist (spec (org-fold-core-folding-spec-list))
  1240. (when (and (org-fold-core-region-folded-p beg end spec)
  1241. (org-region-invisible-p beg end))
  1242. (push (org-fold-core--property-symbol-get-create spec nil t) props-list)))
  1243. (dolist (plist
  1244. (if (fboundp 'object-intervals)
  1245. (object-intervals return-string)
  1246. ;; Backward compatibility with Emacs <28.
  1247. ;; FIXME: Is there any better way to do it?
  1248. ;; Yes, it is a hack.
  1249. ;; The below gives us string representation as a list.
  1250. ;; Note that we need to remove unreadable values, like markers (#<...>).
  1251. (org-fold-core--seq-partition
  1252. (cdr (let ((data (read (replace-regexp-in-string
  1253. "^#(" "("
  1254. (replace-regexp-in-string
  1255. " #(" " ("
  1256. (replace-regexp-in-string
  1257. "#<[^>]+>" "dummy"
  1258. ;; Get text representation of the string object.
  1259. ;; Make sure to print everything (see `prin1' docstring).
  1260. ;; `prin1' is used to print "%S" format.
  1261. (let (print-level print-length)
  1262. (format "%S" return-string))))))))
  1263. (if (listp data) data (list data))))
  1264. 3)))
  1265. (let* ((start (car plist))
  1266. (fin (cadr plist))
  1267. (plist (car (cddr plist))))
  1268. ;; Only lists contain text properties.
  1269. (when (listp plist)
  1270. ;; Collect all the relevant text properties.
  1271. (while plist
  1272. (let* ((prop (car plist))
  1273. (prop-name (symbol-name prop)))
  1274. ;; Reveal hard-hidden text. See
  1275. ;; `org-fold-core--optimise-for-huge-buffers'.
  1276. (when (and (eq prop 'invisible)
  1277. (member (cadr plist) (org-fold-core-folding-spec-list)))
  1278. (remove-text-properties start fin '(invisible t) return-string))
  1279. ;; We do not care about values now.
  1280. (setq plist (cddr plist))
  1281. (when (string-match-p org-fold-core--spec-property-prefix prop-name)
  1282. ;; Leave folding specs from current buffer. See
  1283. ;; comments in `org-fold-core--property-symbol-get-create' to
  1284. ;; understand why it works.
  1285. (unless (member prop (cdr (assq 'invisible char-property-alias-alist)))
  1286. (push prop props-list))))))))
  1287. (remove-text-properties 0 (length return-string) props-list return-string))
  1288. return-string))
  1289. ;;; Do not fontify folded text until needed.
  1290. (defvar org-fold-core--force-fontification nil
  1291. "Let-bind this variable to t in order to force fontification in
  1292. folded regions.")
  1293. (defun org-fold-core-fontify-region (beg end loudly &optional force)
  1294. "Run `font-lock-default-fontify-region' in visible regions."
  1295. (with-silent-modifications
  1296. (let* ((pos beg) next font-lock-return-value
  1297. (force (or force org-fold-core--force-fontification))
  1298. (org-fold-core--fontifying t)
  1299. (skip-specs
  1300. (unless force
  1301. (let (result)
  1302. (dolist (spec (org-fold-core-folding-spec-list))
  1303. (when (and (not (org-fold-core-get-folding-spec-property spec :visible))
  1304. (org-fold-core-get-folding-spec-property spec :font-lock-skip))
  1305. (push spec result)))
  1306. result))))
  1307. ;; Move POS to first visible point within BEG..END.
  1308. (unless force
  1309. (while (and (catch :found
  1310. (dolist (spec (org-fold-core-get-folding-spec 'all pos))
  1311. (when (org-fold-core-get-folding-spec-property spec :font-lock-skip)
  1312. (throw :found spec))))
  1313. (< pos end))
  1314. (setq pos (org-fold-core-next-folding-state-change nil pos end))))
  1315. (when force (setq pos beg next end))
  1316. (while (< pos end)
  1317. (unless force
  1318. (setq next (org-fold-core-next-folding-state-change skip-specs pos end))
  1319. ;; Move to the end of the region to be fontified.
  1320. (while (and (not (catch :found
  1321. (dolist (spec (org-fold-core-get-folding-spec 'all next))
  1322. (when (org-fold-core-get-folding-spec-property spec :font-lock-skip)
  1323. (throw :found spec)))))
  1324. (< next end))
  1325. (setq next (org-fold-core-next-folding-state-change nil next end))))
  1326. (save-excursion
  1327. ;; Keep track of the actually fontified region.
  1328. (pcase (font-lock-default-fontify-region pos next loudly)
  1329. (`(jit-lock-bounds ,beg . ,end)
  1330. (pcase font-lock-return-value
  1331. (`(jit-lock-bounds ,oldbeg . ,oldend)
  1332. (setq font-lock-return-value
  1333. `(jit-lock-bounds
  1334. ,(min oldbeg beg)
  1335. ,(max oldend end))))
  1336. (value (setq font-lock-return-value value))))))
  1337. (put-text-property pos next 'fontified t)
  1338. (setq pos next))
  1339. (or font-lock-return-value `(jit-lock-bounds ,beg . ,end)))))
  1340. (defun org-fold-core-update-optimisation (beg end)
  1341. "Update huge buffer optimisation between BEG and END.
  1342. See `org-fold-core--optimise-for-huge-buffers'."
  1343. (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  1344. (eq org-fold-core-style 'text-properties))
  1345. (let ((pos beg))
  1346. (while (< pos end)
  1347. (when (and (org-fold-core-folded-p pos (caar org-fold-core--specs))
  1348. (not (eq (caar org-fold-core--specs) (get-text-property pos 'invisible))))
  1349. (put-text-property pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end)
  1350. 'invisible (caar org-fold-core--specs)))
  1351. (setq pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end))))))
  1352. (defun org-fold-core-remove-optimisation (beg end)
  1353. "Remove huge buffer optimisation between BEG and END.
  1354. See `org-fold-core--optimise-for-huge-buffers'."
  1355. (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
  1356. (eq org-fold-core-style 'text-properties))
  1357. (let ((pos beg))
  1358. (while (< pos end)
  1359. (if (and (org-fold-core-folded-p pos (caar org-fold-core--specs))
  1360. (eq (caar org-fold-core--specs) (get-text-property pos 'invisible)))
  1361. (remove-text-properties pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end)
  1362. '(invisible t)))
  1363. (setq pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end))))))
  1364. (provide 'org-fold-core)
  1365. ;;; org-fold-core.el ends here