-
Notifications
You must be signed in to change notification settings - Fork 6
/
org-fold.el
1498 lines (1361 loc) · 64.9 KB
/
org-fold.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; org-fold.el --- Folding of Org entries -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2020-2020 Free Software Foundation, Inc.
;;
;; Author: Ihor Radchenko <yantar92 at gmail dot com>
;; Keywords: folding, invisible text
;; Homepage: https://orgmode.org
;;
;; This file is part of GNU Emacs.
;;
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Commentary:
;; This file contains code handling temporary invisibility (folding
;; and unfolding) of text in org buffers.
;; The file implements the following functionality:
;; - Folding/unfolding text regions and org elements
;; - Searching and examining boundaries of folded text
;; - Revealing text around point
;; - Interactive searching in folded text (via isearch)
;; - Handling edits in folded text
;; - Killing/yanking (copying/pasting) of the folded text
;;; Folding/unfolding text regions and org elements
;; User can temporarily fold/unfold arbitrary regions or text inside
;; headlines, blocks, or drawers.
;; Internally, different types of elements are marked with different
;; folding specs (see `org-fold--spec-priority-list' for the list of available
;; specs). Overlapping folds marked with the same folding spec are
;; automatically merged, while folds with different folding specs can
;; coexist and be folded/unfolded independently.
;; By default, we define tree types of folding specs:
;; - for headlines
;; - for all kinds of blocks
;; - for drawers (including property drawers)
;; If necessary, one can add extra folding specs using
;; `org-fold-add-folding-spec'.
;; Because of details of implementation of the folding, it is not
;; recommended to set text visibility in org buffer directly by
;; setting 'invisible text property to anything other than t. While
;; this should usually work just fine, normal org folding can be
;; broken if one sets 'invisible text property to a value not listed
;; in `buffer-invisibility-spec'.
;; It is also possible to use this library if one wants to show some
;; parts of otherwise hidden text. `org-fold-add-folding-spec' has an option
;; to define a new spec, that does not hide folded text. This option,
;; for example, is used to hide some parts of org-mode links:
;; Consider the following link:
;; [[file:/path/to/file/file.ext][description]]
;; Only the word "description" is normally visible in this link.
;;
;; The way this partial visibility is achieved is combining two folding specs:
;; 1. 'org-link, which is a normal spec hiding text
;; 2. 'org-link-description, which is a "visible" folding spec
;; 'org-link-description spec is defined with higher priority (it is
;; added first) in comparison with 'org-link:
;;
;; (org-fold-add-folding-spec 'org-link-description nil t 'no-isearch-open 'append 'visible)
;; (org-fold-add-folding-spec 'org-link nil 'hide-completely 'no-isearch-open 'append nil)
;;
;; Then, the whole link is folded using 'org-link folding spec, but
;; the visible part is additionally folded using
;; 'org-link-description:
;;
;; <begin fold: 'org-link>[[file:/path/to/file/file.ext][<begin fold: 'org-link-description>description<end fold: 'org-link-description>]]<end fold: 'org-link>
;;
;; Because 'org-link-description is visible folding spec and has
;; higher priority than 'org-link, it suppresses all the
;; lower-priority specs and thus reveal the description part of the
;; link.
;;
;; Note that the above call to `org-fold-add-folding-spec' used 'append
;; argument, so that default outline/drawer/block folding is ensured
;; to be prioritised over the link description.
;;; Searching and examining boundaries of folded text
;; It is possible to examine folding specs (there may be several) of
;; text at point or search for regions with the same folding spec.
;; If one wants to search invisible text without using functions
;; defined below, it is important to keep in mind that 'invisible text
;; property in org buffers may have multiple possible values (not just nil
;; and t). Hence, (next-single-char-property-change pos 'invisible) is
;; not guarantied to return the boundary of invisible/visible text.
;;; Revealing text around point
;; In addition to unfolding individual org elements, it is possible to
;; unfold meaningful headline structure around point using
;; `org-fold-show-context' and `org-fold-reveal'. There are several possible variants
;; of structure to be revealed. See `org-fold-show-context-detail' for the
;; details.
;;; Handling edits inside invisible text
;; Accidental user edits inside invisible text may easily mess up org
;; documents. Here, we provide a framework to catch such edits and
;; throw error if necessary. This framework is used, for example, by
;; `org-self-insert-command' and `org-delete-backward-char', See
;; `org-fold-catch-invisible-edits' for available customisation.
;; Some edits inside folded text are not accidental and done by
;; various Org functions. Setting scheduled time, deadlines,
;; properties, etc often involve adding or changing text insided
;; folded headlines or drawers. Normally, such edits do not reveal
;; the folded text. However, the edited text is revealed when
;; document structure is disturbed by edits. See more details in
;; `org-fold--fix-folded-region'.
;;; Code:
(require 'org-macs)
(defvar org-inlinetask-min-level)
(declare-function isearch-filter-visible "isearch" (beg end))
(declare-function org-element-type "org-element" (element))
(declare-function org-element-property "org-element" (property element))
;;; Customization
(defgroup org-fold-reveal-location nil
"Options about how to make context of a location visible."
:tag "Org Reveal Location"
:group 'org-structure)
(defcustom org-fold-show-context-detail '((agenda . local)
(bookmark-jump . lineage)
(isearch . lineage)
(default . ancestors))
"Alist between context and visibility span when revealing a location.
\\<org-mode-map>Some actions may move point into invisible
locations. As a consequence, Org always exposes a neighborhood
around point. How much is shown depends on the initial action,
or context. Valid contexts are
agenda when exposing an entry from the agenda
org-goto when using the command `org-goto' (`\\[org-goto]')
occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
tags-tree when constructing a sparse tree based on tags matches
link-search when exposing search matches associated with a link
mark-goto when exposing the jump goal of a mark
bookmark-jump when exposing a bookmark location
isearch when exiting from an incremental search
default default for all contexts not set explicitly
Allowed visibility spans are
minimal show current headline; if point is not on headline,
also show entry
local show current headline, entry and next headline
ancestors show current headline and its direct ancestors; if
point is not on headline, also show entry
lineage show current headline, its direct ancestors and all
their children; if point is not on headline, also show
entry and first child
tree show current headline, its direct ancestors and all
their children; if point is not on headline, also show
entry and all children
canonical show current headline, its direct ancestors along with
their entries and children; if point is not located on
the headline, also show current entry and all children
As special cases, a nil or t value means show all contexts in
`minimal' or `canonical' view, respectively.
Some views can make displayed information very compact, but also
make it harder to edit the location of the match. In such
a case, use the command `org-fold-reveal' (`\\[org-fold-reveal]') to show
more context."
:group 'org-fold-reveal-location
:version "26.1"
:package-version '(Org . "9.0")
:type '(choice
(const :tag "Canonical" t)
(const :tag "Minimal" nil)
(repeat :greedy t :tag "Individual contexts"
(cons
(choice :tag "Context"
(const agenda)
(const org-goto)
(const occur-tree)
(const tags-tree)
(const link-search)
(const mark-goto)
(const bookmark-jump)
(const isearch)
(const default))
(choice :tag "Detail level"
(const minimal)
(const local)
(const ancestors)
(const lineage)
(const tree)
(const canonical))))))
(defvar org-fold-reveal-start-hook nil
"Hook run before revealing a location.")
(defcustom org-fold-catch-invisible-edits 'smart
"Check if in invisible region before inserting or deleting a character.
Valid values are:
nil Do not check, so just do invisible edits.
error Throw an error and do nothing.
show Make point visible, and do the requested edit.
show-and-error Make point visible, then throw an error and abort the edit.
smart Make point visible, and do insertion/deletion if it is
adjacent to visible text and the change feels predictable.
Never delete a previously invisible character or add in the
middle or right after an invisible region. Basically, this
allows insertion and backward-delete right before ellipses.
FIXME: maybe in this case we should not even show?"
:group 'org-edit-structure
:version "24.1"
:type '(choice
(const :tag "Do not check" nil)
(const :tag "Throw error when trying to edit" error)
(const :tag "Unhide, but do not do the edit" show-and-error)
(const :tag "Show invisible part and do the edit" show)
(const :tag "Be smart and do the right thing" smart)))
;;; Core functionality
;;;; Buffer-local folding specs
(defvar-local org-fold--spec-priority-list '(org-fold-outline
org-fold-drawer
org-fold-block)
"Priority of folding specs.
If a region has multiple folding specs at the same time, only the
first property from this list will be considered.")
(defvar-local org-fold--spec-with-ellipsis '(org-fold-outline
org-fold-drawer
org-fold-block)
"A list of folding specs, which should be indicated by `org-ellipsis'.")
(defvar-local org-fold--isearch-specs '(org-fold-block
org-fold-drawer
org-fold-outline)
"List of text invisibility specs to be searched by isearch.
By default ([2020-05-09 Sat]), isearch does not search in hidden text,
which was made invisible using text properties. Isearch will be forced
to search in hidden text with any of the listed 'invisible property value.")
(defsubst org-fold-get-folding-spec-for-element (type)
"Return name of folding spec for element TYPE."
(pcase type
(`headline 'org-fold-outline)
(`inlinetask 'org-fold-outline)
(`plain-list 'org-fold-outline)
(`block 'org-fold-block)
(`center-block 'org-fold-block)
(`comment-block 'org-fold-block)
(`dynamic-block 'org-fold-block)
(`example-block 'org-fold-block)
(`export-block 'org-fold-block)
(`quote-block 'org-fold-block)
(`special-block 'org-fold-block)
(`src-block 'org-fold-block)
(`verse-block 'org-fold-block)
(`drawer 'org-fold-drawer)
(`property-drawer 'org-fold-drawer)
(_ nil)))
(defun org-fold-get-folding-spec-from-folding-prop (folding-prop)
"Return folding spec symbol used for folding property with name FOLDING-PROP."
(catch :exit
(dolist (spec org-fold--spec-priority-list)
(when (string-match-p (symbol-name spec)
(symbol-name folding-prop))
(throw :exit spec)))))
(defvar org-fold--property-symbol-cache (make-hash-table :test 'equal)
"Saved values of folding properties for (buffer . spec) conses.")
;; This is the core function used to fold text in org buffers. We use
;; text properties to hide folded text, however 'invisible property is
;; not directly used. Instead, we define unique text property (folding
;; property) for every possible folding spec and add the resulting
;; text properties into `char-property-alias-alist', so that
;; 'invisible text property is automatically defined if any of the
;; folding properties is non-nil.
;; This approach lets us maintain multiple folds for the same text
;; region - poor man's overlays (but much faster).
;; Additionally, folding properties are ensured to be unique for
;; different buffers (especially for indirect buffers). This is done
;; to allow different folding states in indirect org buffers.
;; If one changes folding state in a fresh indirect buffer, all the
;; folding properties carried from the base buffer are updated to
;; become unique in the new indirect buffer.
(defun org-fold--property-symbol-get-create (spec &optional buffer return-only)
"Return a unique symbol suitable as folding text property.
Return value is unique for folding SPEC in BUFFER.
If the buffer already have buffer-local setup in `char-property-alias-alist'
and the setup appears to be created for different buffer,
copy the old invisibility state into new buffer-local text properties,
unless RETURN-ONLY is non-nil."
(org-fold--check-spec spec)
(let* ((buf (or buffer (current-buffer))))
;; Create unique property symbol for SPEC in BUFFER
(let ((local-prop (or (gethash (cons buf spec) org-fold--property-symbol-cache)
(puthash (cons buf spec)
(intern (format "org-fold--spec-%s-%S"
(symbol-name spec)
;; (sxhash buf) appears to be not constant over time.
;; Using buffer-name is safe, since the only place where
;; buffer-local text property actually matters is an indirect
;; buffer, where the name cannot be same anyway.
(sxhash (buffer-name buf))))
org-fold--property-symbol-cache))))
(prog1
local-prop
(unless return-only
(with-current-buffer buf
;; Update folding properties carried over from other
;; buffer (implying that current buffer is indirect
;; buffer). Normally, `char-property-alias-alist' in new
;; indirect buffer is a copy of the same variable from
;; the base buffer. Then, `char-property-alias-alist'
;; would contain folding properties, which are not
;; matching the generated `local-prop'.
(unless (member local-prop (cdr (assq 'invisible char-property-alias-alist)))
;; Copy all the old folding properties to preserve the folding state
(dolist (old-prop (cdr (assq 'invisible char-property-alias-alist)))
(org-with-wide-buffer
(let* ((pos (point-min))
;; We know that folding properties have
;; folding spec in their name. Extract that
;; spec.
(spec (org-fold-get-folding-spec-from-folding-prop old-prop))
;; Generate new buffer-unique folding property
(new-prop (org-fold--property-symbol-get-create spec nil 'return-only)))
;; Copy the visibility state for `spec' from `old-prop' to `new-prop'
(while (< pos (point-max))
(let ((val (get-text-property pos old-prop)))
(when val
(put-text-property pos (next-single-char-property-change pos old-prop) new-prop val)))
(setq pos (next-single-char-property-change pos old-prop)))
;; Make sure that folding property is non-stiky
(setq-local text-property-default-nonsticky (delq (cons old-prop t) text-property-default-nonsticky)))))
;; Make sure that folding property is non-stiky
(mapcar (lambda (spec)
(setq-local text-property-default-nonsticky (append (list (cons (org-fold--property-symbol-get-create spec nil 'return-only) t))
text-property-default-nonsticky)))
org-fold--spec-priority-list)
;; Update `char-property-alias-alist' with folding
;; properties unique for the current buffer.
(setq-local char-property-alias-alist
(cons (cons 'invisible
(mapcar (lambda (spec)
(org-fold--property-symbol-get-create spec nil 'return-only))
org-fold--spec-priority-list))
(remove (assq 'invisible char-property-alias-alist)
char-property-alias-alist))))))))))
;;; API
;;;; Modifying folding specs
(defun org-fold-folding-spec-p (spec)
"Check if SPEC is a registered folding spec."
(and spec (memq spec org-fold--spec-priority-list)))
(defun org-fold-add-folding-spec (spec &optional buffer no-ellipsis-p no-isearch-open-p append visible)
"Add a new folding SPEC in BUFFER.
If VISIBLE is non-nil, visibility of text folded using SPEC will be
controlled by `buffer-invisibility-spec'. The folded text will have
'invisible property set to SPEC (with lowest possible priority).
SPEC must be a symbol. BUFFER can be a buffer to set SPEC in, nil to
set SPEC in current buffer, or 'all to set SPEC in all open `org-mode'
buffers and all future org buffers. Non-nil optional argument
NO-ELLIPSIS-P means that folded text will not be indicated by
`org-ellipsis'. Non-nil optional argument NO-ISEARCH-OPEN-P means
that folded text cannot be searched by isearch. By default, the added
SPEC will have highest priority among the previously defined specs.
When optional APPEND argument is non-nil, SPEC will have the lowest
priority instead. If SPEC was already defined earlier, it will be
redefined according to provided optional arguments."
(when (eq spec 'all) (user-error "Folding spec name 'all is not allowed"))
(when (eq buffer 'all)
(mapc (lambda (buf)
(org-fold-add-folding-spec spec buf no-ellipsis-p no-isearch-open-p append visible))
(org-buffer-list))
(setq-default org-fold--spec-priority-list (delq spec org-fold--spec-priority-list))
(add-to-list 'org-fold--spec-priority-list spec append)
(setq-default org-fold--spec-priority-list org-fold--spec-priority-list)
(when no-ellipsis-p (setq-default org-fold--spec-with-ellipsis (delq spec org-fold--spec-with-ellipsis)))
(unless no-ellipsis-p
(add-to-list 'org-fold--spec-with-ellipsis spec)
(setq-default org-fold--spec-with-ellipsis org-fold--spec-with-ellipsis))
(when no-isearch-open-p (setq-default org-fold--isearch-specs (delq spec org-fold--isearch-specs)))
(unless no-isearch-open-p
(add-to-list 'org-fold--isearch-specs spec)
(setq-default org-fold--isearch-specs org-fold--isearch-specs)))
(let ((buffer (or buffer (current-buffer))))
(with-current-buffer buffer
(remove-from-invisibility-spec (cons spec t))
(remove-from-invisibility-spec spec)
(remove-from-invisibility-spec (list spec))
(unless (or visible
(member (cons spec (not no-ellipsis-p)) buffer-invisibility-spec))
(add-to-invisibility-spec (cons spec (not no-ellipsis-p))))
(setq org-fold--spec-priority-list (delq spec org-fold--spec-priority-list))
(add-to-list 'org-fold--spec-priority-list spec append)
(when no-ellipsis-p (setq org-fold--spec-with-ellipsis (delq spec org-fold--spec-with-ellipsis)))
(unless no-ellipsis-p (add-to-list 'org-fold--spec-with-ellipsis spec))
(when no-isearch-open-p (setq org-fold--isearch-specs (delq spec org-fold--isearch-specs)))
(unless no-isearch-open-p (add-to-list 'org-fold--isearch-specs spec)))))
(defun org-fold-remove-folding-spec (spec &optional buffer)
"Remove a folding SPEC in BUFFER.
SPEC must be a symbol.
BUFFER can be a buffer to remove SPEC in, nil to remove SPEC in current buffer,
or 'all to remove SPEC in all open `org-mode' buffers and all future org buffers."
(org-fold--check-spec spec)
(when (eq buffer 'all)
(mapc (lambda (buf)
(org-fold-remove-folding-spec spec buf))
(org-buffer-list))
(setq-default org-fold--spec-priority-list (delq spec org-fold--spec-priority-list))
(setq-default org-fold--spec-with-ellipsis (delq spec org-fold--spec-with-ellipsis))
(setq-default org-fold--isearch-specs (delq spec org-fold--isearch-specs)))
(let ((buffer (or buffer (current-buffer))))
(with-current-buffer buffer
(remove-from-invisibility-spec (cons spec t))
(remove-from-invisibility-spec spec)
(remove-from-invisibility-spec (list spec))
(setq org-fold--spec-priority-list (delq spec org-fold--spec-priority-list))
(setq org-fold--spec-with-ellipsis (delq spec org-fold--spec-with-ellipsis))
(setq org-fold--isearch-specs (delq spec org-fold--isearch-specs)))))
(defun org-fold-initialize ()
"Setup org-fold in current buffer."
(dolist (spec org-fold--spec-priority-list)
(org-fold-add-folding-spec spec nil (not (memq spec org-fold--spec-with-ellipsis)) (not (memq spec org-fold--isearch-specs))))
(add-hook 'after-change-functions 'org-fold--fix-folded-region nil 'local)
;; Setup killing text
(setq-local filter-buffer-substring-function #'org-fold--buffer-substring-filter)
;; Make isearch reveal context
(setq-local outline-isearch-open-invisible-function
(lambda (&rest _) (org-fold-show-context 'isearch)))
(require 'isearch)
(if (boundp 'isearch-opened-regions)
;; Use new implementation of isearch allowing to search inside text
;; hidden via text properties.
(org-fold--isearch-setup 'text-properties)
(org-fold--isearch-setup 'overlays)))
;;;; Searching and examining folded text
(defun org-fold-folded-p (&optional pos spec-or-element)
"Non-nil if the character after POS is folded.
If POS is nil, use `point' instead.
If SPEC-OR-ELEMENT is a folding spec, only check the given folding spec.
If SPEC-OR-ELEMENT is a foldable element (see
`org-fold-get-folding-spec-for-element'), only check folding spec for
the given element. Note that multiple elements may have same folding
specs."
(org-fold-get-folding-spec (or (org-fold-get-folding-spec spec-or-element) spec-or-element) pos))
(defun org-fold-get-folding-spec (&optional spec-or-element pom)
"Get folding state at `point' or POM.
Return nil if there is no folding at point or POM.
If SPEC-OR-ELEMENT is nil, return a folding spec with highest priority
among present at `point' or POM.
If SPEC-OR-ELEMENT is 'all, return the list of all present folding
specs.
If SPEC-OR-ELEMENT is a valid folding spec, return the corresponding
folding spec (if the text is folded using that spec).
If SPEC-OR-ELEMENT is a foldable org element (see
`org-fold-get-folding-spec-for-element'), act as if the element's
folding spec was used as an argument. Note that multiple elements may
have same folding specs."
(let ((spec (or (org-fold-get-folding-spec-for-element spec-or-element)
spec-or-element)))
(when (and spec (not (eq spec 'all))) (org-fold--check-spec spec))
(org-with-point-at (or pom (point))
(if (and spec (not (eq spec 'all)))
(get-char-property (point) (org-fold--property-symbol-get-create spec nil t))
(let ((result))
(dolist (spec org-fold--spec-priority-list)
(let ((val (get-char-property (point) (org-fold--property-symbol-get-create spec nil t))))
(when val
(push val result))))
(if (eq spec 'all)
result
(car (last result))))))))
(defun org-fold-get-folding-specs-in-region (beg end)
"Get all folding specs in region from BEG to END."
(let ((pos beg)
all-specs)
(while (< pos end)
(setq all-specs (append all-specs (org-fold-get-folding-spec nil pos)))
(setq pos (org-fold-next-folding-state-change nil pos end)))
(unless (listp all-specs) (setq all-specs (list all-specs)))
(delete-dups all-specs)))
(defun org-fold-get-region-at-point (&optional spec pom)
"Return region folded using SPEC at POM.
If SPEC is nil, return the largest possible folded region.
The return value is a cons of beginning and the end of the region.
Return nil when no fold is present at point of POM."
(when spec (org-fold--check-spec spec))
(org-with-point-at (or pom (point))
(if spec
(org-find-text-property-region (point) (org-fold--property-symbol-get-create spec nil t))
(let ((region (cons (point) (point))))
(dolist (spec (org-fold-get-folding-spec 'all))
(let ((local-region (org-fold-get-region-at-point spec)))
(when (< (car local-region) (car region))
(setcar region (car local-region)))
(when (> (cdr local-region) (cdr region))
(setcdr region (cdr local-region)))))
(unless (eq (car region) (cdr region)) region)))))
;; FIXME: Optimize performance
(defun org-fold-next-visibility-change (&optional pos limit ignore-hidden-p previous-p)
"Return next point from POS up to LIMIT where text becomes visible/invisible.
By default, text hidden by any means (i.e. not only by folding, but
also via fontification) will be considered.
If IGNORE-HIDDEN-P is non-nil, consider only folded text.
If PREVIOUS-P is non-nil, search backwards."
(let* ((pos (or pos (point)))
(invisible-p (if ignore-hidden-p
#'org-fold-folded-p
#'invisible-p))
(invisible-initially? (funcall invisible-p pos))
(limit (or limit (if previous-p
(point-min)
(point-max))))
(cmp (if previous-p #'> #'<))
(next-change (if previous-p
(if ignore-hidden-p
(lambda (p) (org-fold-previous-folding-state-change (org-fold-get-folding-spec nil p) p limit))
(lambda (p) (max limit (1- (previous-single-char-property-change p 'invisible nil limit)))))
(if ignore-hidden-p
(lambda (p) (org-fold-next-folding-state-change (org-fold-get-folding-spec nil p) p limit))
(lambda (p) (next-single-char-property-change p 'invisible nil limit)))))
(next pos))
(while (and (funcall cmp next limit)
(not (xor invisible-initially? (funcall invisible-p next))))
(setq next (funcall next-change next)))
next))
(defun org-fold-previous-visibility-change (&optional pos limit ignore-hidden-p)
"Call `org-fold-next-visibility-change' searching backwards."
(org-fold-next-visibility-change pos limit ignore-hidden-p 'previous))
(defun org-fold-next-folding-state-change (&optional spec-or-element pos limit previous-p)
"Return next point where folding state changes relative to POS up to LIMIT.
If SPEC-OR-ELEMENT is nil, return next point where _any_ single folding
type changes.
For example, (org-fold-next-folding-state-change nil) with point
somewhere in the below structure will return the nearest <...> point.
* Headline <begin outline fold>
:PROPERTIES:<begin drawer fold>
:ID: test
:END:<end drawer fold>
Fusce suscipit, wisi nec facilisis facilisis, est dui fermentum leo, quis tempor ligula erat quis odio.
** Another headline
:DRAWER:<begin drawer fold>
:END:<end drawer fold>
** Yet another headline
<end of outline fold>
If SPEC-OR-ELEMENT is a folding spec symbol, only consider that folded spec.
If SPEC-OR-ELEMENT is a foldable element, consider that element's
folding spec (see `org-fold-get-folding-spec-for-element'). Note that
multiple elements may have the same folding spec.
If SPEC-OR-ELEMENT is a list, only consider changes of folding states
from the list.
Search backwards when PREVIOUS-P is non-nil."
(when (and spec-or-element (symbolp spec-or-element))
(setq spec-or-element (list spec-or-element)))
(when spec-or-element
(setq spec-or-element
(mapcar (lambda (spec-or-element)
(or (org-fold-get-folding-spec-for-element spec-or-element)
spec-or-element))
spec-or-element))
(mapc #'org-fold--check-spec spec-or-element))
(unless spec-or-element
(setq spec-or-element org-fold--spec-priority-list))
(let* ((pos (or pos (point)))
(props (mapcar (lambda (el) (org-fold--property-symbol-get-create el nil t))
spec-or-element))
(cmp (if previous-p
#'max
#'min))
(next-change (if previous-p
(lambda (prop) (max (or limit (point-min)) (previous-single-char-property-change pos prop nil (or limit (point-min)))))
(lambda (prop) (next-single-char-property-change pos prop nil (or limit (point-max)))))))
(apply cmp (mapcar next-change props))))
(defun org-fold-previous-folding-state-change (&optional spec-or-element pos limit)
"Call `org-fold-next-folding-state-change' searching backwards."
(org-fold-next-folding-state-change spec-or-element pos limit 'previous))
(defun org-fold-search-forward (spec &optional limit)
"Search next region folded via folding SPEC up to LIMIT.
Move point right after the end of the region, to LIMIT, or
`point-max'. The `match-data' will contain the region."
(org-fold--check-spec spec)
(let ((prop-symbol (org-fold--property-symbol-get-create spec nil t)))
(goto-char (or (next-single-char-property-change (point) prop-symbol nil limit) limit (point-max)))
(when (and (< (point) (or limit (point-max)))
(not (org-fold-get-folding-spec spec)))
(goto-char (next-single-char-property-change (point) prop-symbol nil limit)))
(when (org-fold-get-folding-spec spec)
(let ((region (org-fold-get-region-at-point spec)))
(when (< (cdr region) (or limit (point-max)))
(goto-char (1+ (cdr region)))
(set-match-data (list (set-marker (make-marker) (car region) (current-buffer))
(set-marker (make-marker) (cdr region) (current-buffer)))))))))
;;;; Changing visibility (regions, blocks, drawers, headlines)
;;;;; Region visibility
;; This is the core function performing actual folding/unfolding. The
;; folding state is stored in text property (folding property)
;; returned by `org-fold--property-symbol-get-create'. The value of the
;; folding property is folding spec symbol.
(defun org-fold-region (from to flag &optional spec-or-element)
"Hide or show lines from FROM to TO, according to FLAG.
SPEC-OR-ELEMENT is the folding spec or foldable element, as a symbol.
If SPEC-OR-ELEMENT is omitted and FLAG is nil, unfold everything in the region."
(let ((spec (or (org-fold-get-folding-spec-for-element spec-or-element)
spec-or-element)))
(when spec (org-fold--check-spec spec))
(with-silent-modifications
(org-with-wide-buffer
(if flag
(if (not spec)
(error "Calling `org-fold-region' with missing SPEC")
(put-text-property from to
(org-fold--property-symbol-get-create spec)
spec)
(put-text-property from to
'isearch-open-invisible
#'org-fold--isearch-show)
(put-text-property from to
'isearch-open-invisible-temporary
#'org-fold--isearch-show-temporary))
(if (not spec)
(dolist (spec org-fold--spec-priority-list)
(remove-text-properties from to
(list (org-fold--property-symbol-get-create spec) nil)))
(remove-text-properties from to
(list (org-fold--property-symbol-get-create spec) nil))))))))
(defun org-fold-show-all (&optional types)
"Show all contents in the visible part of the buffer.
By default, the function expands headings, blocks and drawers.
When optional argument TYPES is a list of symbols among `blocks',
`drawers' and `headings', to only expand one specific type."
(interactive)
(dolist (type (or types '(blocks drawers headings)))
(org-fold-region (point-min) (point-max) nil
(pcase type
(`blocks 'block)
(`drawers 'drawer)
(`headings 'headline)
(_ (error "Invalid type: %S" type))))))
(defun org-fold-flag-above-first-heading (&optional arg)
"Hide from bob up to the first heading.
Move point to the beginning of first heading or end of buffer."
(goto-char (point-min))
(unless (org-at-heading-p)
(outline-next-heading))
(unless (bobp)
(org-fold-region 1 (1- (point)) (not arg) 'headline)))
;;;;; Heading visibility
(defun org-fold-heading (flag &optional entry)
"Fold/unfold the current heading. FLAG non-nil means make invisible.
When ENTRY is non-nil, show the entire entry."
(save-excursion
(org-back-to-heading t)
;; Check if we should show the entire entry
(if (not entry)
(org-fold-region
(line-end-position 0) (line-end-position) flag 'headline)
(org-fold-show-entry)
(save-excursion
;; FIXME: potentially catches inlinetasks
(and (outline-next-heading)
(org-fold-heading nil))))))
(defun org-fold-hide-entry ()
"Hide the body directly following this heading."
(interactive)
(save-excursion
(org-back-to-heading-or-point-min t)
(when (org-at-heading-p) (forward-line))
(unless (eobp) ; Current headline is empty and ends at the end of buffer.
(org-fold-region
(line-end-position 0)
(save-excursion
(if (re-search-forward
(concat "[\r\n]" (org-get-limited-outline-regexp)) nil t)
(line-end-position 0)
(point-max)))
t
'headline))))
(defun org-fold-subtree (flag)
(save-excursion
(org-back-to-heading t)
(org-fold-region (line-end-position)
(progn (org-end-of-subtree t) (point))
flag
'headline)))
(defun org-fold-hide-subtree ()
"Hide everything after this heading at deeper levels."
(interactive)
(org-fold-subtree t))
(defun org-fold-hide-sublevels (levels)
"Hide everything but the top LEVELS levels of headers, in whole buffer.
This also unhides the top heading-less body, if any.
Interactively, the prefix argument supplies the value of LEVELS.
When invoked without a prefix argument, LEVELS defaults to the level
of the current heading, or to 1 if the current line is not a heading."
(interactive (list
(cond
(current-prefix-arg (prefix-numeric-value current-prefix-arg))
((save-excursion (beginning-of-line)
(looking-at outline-regexp))
(funcall outline-level))
(t 1))))
(if (< levels 1)
(error "Must keep at least one level of headers"))
(save-excursion
(let* ((beg (progn
(goto-char (point-min))
;; Skip the prelude, if any.
(unless (org-at-heading-p) (outline-next-heading))
(point)))
(end (progn
(goto-char (point-max))
;; Keep empty last line, if available.
(max (point-min) (if (bolp) (1- (point)) (point))))))
(if (< end beg)
(setq beg (prog1 end (setq end beg))))
;; First hide everything.
(org-fold-region beg end t 'headline)
;; Then unhide the top level headers.
(org-map-region
(lambda ()
(when (<= (funcall outline-level) levels)
(org-fold-heading nil)))
beg end)
;; Finally unhide any trailing newline.
(goto-char (point-max))
(if (and (bolp) (not (bobp)) (outline-invisible-p (1- (point))))
(org-fold-region (max (point-min) (1- (point))) (point) nil)))))
(defun org-fold-show-entry ()
"Show the body directly following its heading.
Show the heading too, if it is currently invisible."
(interactive)
(save-excursion
(org-back-to-heading-or-point-min t)
(org-fold-region
(line-end-position 0)
(save-excursion
(if (re-search-forward
(concat "[\r\n]\\(" (org-get-limited-outline-regexp) "\\)") nil t)
(match-beginning 1)
(point-max)))
nil
'headline)
(org-cycle-hide-drawers 'children)))
;; FIXME: defalias instead?
(defun org-fold-show-hidden-entry ()
"Show an entry where even the heading is hidden."
(save-excursion
(org-fold-show-entry)))
(defun org-fold-show-siblings ()
"Show all siblings of the current headline."
(save-excursion
(while (org-goto-sibling) (org-fold-heading nil)))
(save-excursion
(while (org-goto-sibling 'previous)
(org-fold-heading nil))))
(defun org-fold-show-children (&optional level)
"Show all direct subheadings of this heading.
Prefix arg LEVEL is how many levels below the current level
should be shown. Default is enough to cause the following
heading to appear."
(interactive "p")
(unless (org-before-first-heading-p)
(save-excursion
(org-with-limited-levels (org-back-to-heading t))
(let* ((current-level (funcall outline-level))
(max-level (org-get-valid-level
current-level
(if level (prefix-numeric-value level) 1)))
(end (save-excursion (org-end-of-subtree t t)))
(regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
(past-first-child nil)
;; Make sure to skip inlinetasks.
(re (format regexp-fmt
current-level
(cond
((not (featurep 'org-inlinetask)) "")
(org-odd-levels-only (- (* 2 org-inlinetask-min-level)
3))
(t (1- org-inlinetask-min-level))))))
;; Display parent heading.
(org-fold-heading nil)
(forward-line)
;; Display children. First child may be deeper than expected
;; MAX-LEVEL. Since we want to display it anyway, adjust
;; MAX-LEVEL accordingly.
(while (re-search-forward re end t)
(unless past-first-child
(setq re (format regexp-fmt
current-level
(max (funcall outline-level) max-level)))
(setq past-first-child t))
(org-fold-heading nil))))))
(defun org-fold-show-subtree ()
"Show everything after this heading at deeper levels."
(interactive)
(org-fold-region
(point) (save-excursion (org-end-of-subtree t t)) nil 'headline))
(defun org-fold-show-branches ()
"Show all subheadings of this heading, but not their bodies."
(interactive)
(org-fold-show-children 1000))
(defun org-fold-show-branches-buffer ()
"Show all branches in the buffer."
(org-fold-flag-above-first-heading)
(org-fold-hide-sublevels 1)
(unless (eobp)
(org-fold-show-branches)
(while (outline-get-next-sibling)
(org-fold-show-branches)))
(goto-char (point-min)))
;;;;; Blocks and drawers visibility
(defun org-fold--hide-wrapper-toggle (element category force no-error)
"Toggle visibility for ELEMENT.
ELEMENT is a block or drawer type parsed element. CATEGORY is
either `block' or `drawer'. When FORCE is `off', show the block
or drawer. If it is non-nil, hide it unconditionally. Throw an
error when not at a block or drawer, unless NO-ERROR is non-nil.
Return a non-nil value when toggling is successful."
(let ((type (org-element-type element)))
(cond
((memq type
(pcase category
(`drawer '(drawer property-drawer))
(`block '(center-block
comment-block dynamic-block example-block export-block
quote-block special-block src-block verse-block))
(_ (error "Unknown category: %S" category))))
(let* ((post (org-element-property :post-affiliated element))
(start (save-excursion
(goto-char post)
(line-end-position)))
(end (save-excursion
(goto-char (org-element-property :end element))
(skip-chars-backward " \t\n")
(line-end-position))))
;; Do nothing when not before or at the block opening line or
;; at the block closing line.
(unless (let ((eol (line-end-position)))
(and (> eol start) (/= eol end)))
(let* ((spec (cond ((eq category 'block) (org-fold-get-folding-spec-for-element 'block))
((eq category 'drawer) (org-fold-get-folding-spec-for-element 'drawer))
(t (org-fold-get-folding-spec-for-element 'headline))))
(flag
(cond ((eq force 'off) nil)
(force t)
((org-fold-folded-p start) nil)
(t t))))
(org-fold-region start end flag spec))
;; When the block is hidden away, make sure point is left in
;; a visible part of the buffer.
(when (invisible-p (max (1- (point)) (point-min)))
(goto-char post))
;; Signal success.
t)))
(no-error nil)
(t
(user-error (if (eq category 'drawer)
"Not at a drawer"
"Not at a block"))))))
(defun org-fold-hide-block-toggle (&optional force no-error element)
"Toggle the visibility of the current block.
When optional argument FORCE is `off', make block visible. If it
is non-nil, hide it unconditionally. Throw an error when not at
a block, unless NO-ERROR is non-nil. When optional argument
ELEMENT is provided, consider it instead of the current block.
Return a non-nil value when toggling is successful."
(interactive)
(org-fold--hide-wrapper-toggle
(or element (org-element-at-point)) 'block force no-error))
(defun org-fold-hide-drawer-toggle (&optional force no-error element)
"Toggle the visibility of the current drawer.
When optional argument FORCE is `off', make drawer visible. If
it is non-nil, hide it unconditionally. Throw an error when not
at a drawer, unless NO-ERROR is non-nil. When optional argument
ELEMENT is provided, consider it instead of the current drawer.
Return a non-nil value when toggling is successful."
(interactive)
(org-fold--hide-wrapper-toggle
(or element (org-element-at-point)) 'drawer force no-error))
(defun org-fold-hide-block-all ()
"Fold all blocks in the current buffer."
(interactive)
(org-fold-show-all '(blocks))
(org-block-map 'org-fold-hide-block-toggle))
(defun org-fold-hide-drawer-all ()
"Fold all visible drawers in the current buffer or narrow."
(save-excursion
(goto-char (point-min))
(while (re-search-forward org-drawer-regexp nil t)
;; Skip drawers in folded headings
(when (org-fold-folded-p) (goto-char (org-fold-next-visibility-change nil nil 'ignore-hidden)))
(let* ((drawer (org-element-at-point))
(type (org-element-type drawer)))
(when (memq type '(drawer property-drawer))
;; We are sure regular drawers are unfolded because of
;; `org-show-all' call above. However, property drawers may
;; be folded, or in a folded headline. In that case, do not
;; re-hide it.
(unless (and (eq type 'property-drawer)
(org-fold-folded-p))
(org-fold-hide-drawer-toggle t nil drawer))
;; Make sure to skip drawer entirely or we might flag it
;; another time when matching its ending line with
;; `org-drawer-regexp'.
(goto-char (org-element-property :end drawer)))))))
;;;;; Reveal point location