org-fold-core.el 76 KB

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