org-fold-core.el 76 KB

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