-
Notifications
You must be signed in to change notification settings - Fork 47
/
org-transclusion.el
1856 lines (1651 loc) · 77 KB
/
org-transclusion.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-transclusion.el --- Transclude text content via links -*- lexical-binding: t; -*-
;; Copyright (C) 2021-2024 Free Software Foundation, Inc.
;; This program 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.
;; This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
;; Author: Noboru Ota <[email protected]>
;; Created: 10 October 2020
;; Last modified: 20 May 2024
;; URL: https://github.com/nobiot/org-transclusion
;; Keywords: org-mode, transclusion, writing
;; Version: 1.4.0
;; Package-Requires: ((emacs "27.1") (org "9.4"))
;; This file is not part of GNU Emacs.
;;; Commentary:
;; This library is an attempt to enable transclusion with Org Mode.
;; Transclusion is the ability to include content from one file into
;; another by reference.
;;; Code:
;;;; Requirements
(require 'org)
(require 'org-element)
(require 'org-id)
(require 'text-clone)
(require 'text-property-search)
(require 'seq)
;;;; Customization
(defgroup org-transclusion nil
"Insert text contents by way of link references."
:group 'org
:prefix "org-transclusion-"
:link '(url-link :tag "Github" "https://github.com/nobiot/org-transclusion")
:package-version '("Org-transclusion" . "1.0.0"))
(defun org-transclusion-set-extensions (var value)
"Set VAR to VALUE and `org-transclusion-load-extensions-maybe'.
Intended for :set property for `customize'."
(set var value)
(when (featurep 'org-transclusion)
(org-transclusion-load-extensions-maybe 'force)))
(defcustom org-transclusion-extensions
'(org-transclusion-src-lines org-transclusion-font-lock)
"Extensions to be loaded with org-transclusion.el."
:set #'org-transclusion-set-extensions
:type
'(set :greedy t
(const :tag "src-lines: Add :src and :lines for non-Org files"
org-transclusion-src-lines)
(const :tag "font-lock: Add font-lock for Org-transclusion"
org-transclusion-font-lock)
(const :tag "indent-mode: Support org-indent-mode"
org-transclusion-indent-mode)
(const :tag "html: Transclude HTML converted to Org with Pandoc"
org-transclusion-html)
(repeat :tag "Other packages" :inline t (symbol :tag "Package"))))
(defcustom org-transclusion-add-all-on-activate t
"Define whether to add all the transclusions on activation.
When non-nil, automatically add all on `org-transclusion-activate'."
:type 'boolean)
(defcustom org-transclusion-exclude-elements (list 'property-drawer)
"Define the Org elements that are excluded from transcluded copies.
It is a list of elements to be filtered out.
Refer to variable `org-element-all-elements' for names of elements accepted."
:type '(repeat symbol))
(defcustom org-transclusion-include-first-section t
"Define whether or not transclusion for Org files includes \"first section\".
If t, the section before the first headline is
transcluded. Default is t."
:type 'boolean)
(defcustom org-transclusion-open-source-display-action-list '(nil . nil)
"Action list used to open source buffer to display.
See `display-buffer' for example options."
:type display-buffer--action-custom-type
:risky t)
(defcustom org-transclusion-mode-lighter
" OT"
"Mode-line indicator for minor-mode variable `org-transclusion-mode'."
:type '(choice (const :tag "No lighter" "") string)
:safe 'stringp)
(defcustom org-transclusion-after-add-functions nil
"Functions to be called after a transclusion content has been added.
The hook runs after the content and the read-only text property
have been added so it is not supposed to manipulate the content
but to add further text properties. For example, it is used by
the `org-transclusion-indent-mode' extension to support
`org-indent-mode'. The functions are called with arguments beg
and end, pointing to the beginning and end of the transcluded
content."
:type '(repeat function))
;;;; Faces
(defface org-transclusion-source-fringe
'((((class color) (min-colors 88) (background light)))
(((class color) (min-colors 88) (background dark)))
(t ))
"Face for source region's fringe being transcluded in another buffer.")
(defface org-transclusion-source
'((((class color) (min-colors 88) (background light)))
(((class color) (min-colors 88) (background dark)))
(t ))
"Face for source region being transcluded in another buffer.
The default is no color specification (transparent).")
(defface org-transclusion-source-edit
'((((class color) (min-colors 88) (background light))
:background "#fff3da" :extend t)
(((class color) (min-colors 88) (background dark))
:background "#221000" :extend t)
(t
:background "chocolate4" :extend t))
"Face for element in the source being edited by another buffer.")
(defface org-transclusion-fringe
'((((class color) (min-colors 88) (background light)))
(((class color) (min-colors 88) (background dark)))
(t ))
"Face for transcluded region's fringe in the transcluding buffer.")
(defface org-transclusion
'((((class color) (min-colors 88) (background light)))
(((class color) (min-colors 88) (background dark)))
(t ))
"Face for transcluded region in the transcluding buffer.
The default is no color specification (transparent).")
(defface org-transclusion-edit
'((((class color) (min-colors 88) (background light))
:background "#ebf6fa" :extend t)
(((class color) (min-colors 88) (background dark))
:background "#041529" :extend t)
(t
:background "forest green" :extend t))
"Face for element in the transcluding buffer in the edit mode.")
;;;; Variables
(defvar org-transclusion-extensions-loaded nil
"Have the extensions been loaded already?")
(defvar-local org-transclusion-remember-point nil
"This variable is used to remember the current just before `save-buffer'.
It is meant to be used to remember and return to the current
point after `before-save-hook' and `after-save-hook' pair;
`org-transclusion-before-save-buffer' and
`org-transclusion-after-save-buffer' use this variable.")
(defvar-local org-transclusion-remember-transclusions nil
"Remember the active transclusions before `save-buffer'.
It is meant to be used to keep the file the current buffer is
visiting clear of the transcluded text content. Instead of
blindly deactivate and activate all transclusions with t flag,
this variable is meant to provide mechanism to
deactivate/activate only the transclusions currently used to copy
a text content.
`org-transclusion-before-save-buffer' and
`org-transclusion-after-save-buffer' use this variable.")
(defvar-local org-transclusion-remember-window-config nil
"Remember window config (the arrangement of windows) for the current buffer.
This is for live-sync. Analogous to
`org-edit-src-code'.")
(defvar org-transclusion-add-functions
'(org-transclusion-add-org-id
org-transclusion-add-org-file
org-transclusion-add-other-file)
"Define a list of functions to get a payload for transclusion.
These function take two arguments: Org link and keyword plist,
and return a payload. The payload is defined as a property list
that consists of the following properties:
- :tc-type
- :src-buf
- :src-beg
- :src-end
- :src-content
Otherwise, the payload may be a named or lambda function which
will be called with the following arguments:
- \\+`link'
- \\+`keyword-plist'
- \\+`copy'
In order for the transclusion to be inserted into the buffer, the
payload function should generate a payload plist, then call
`org-transclusion-add-payload', passing in the payload as well as
the \\+`link', \\+`keyword-plist', and \\+`copy' arguments.")
(defvar org-transclusion-keyword-value-functions
'(org-transclusion-keyword-value-link
org-transclusion-keyword-value-level
org-transclusion-keyword-value-disable-auto
org-transclusion-keyword-value-only-contents
org-transclusion-keyword-value-exclude-elements
org-transclusion-keyword-value-expand-links
org-transclusion-keyword-current-indentation)
"Define a list of functions used to parse a #+transclude keyword.
These functions take a single argument, the whole keyword value
as a string. Each function retrieves a property with using a
regexp from the string.")
(defvar org-transclusion-keyword-plist-to-string-functions '())
(defvar org-transclusion-content-format-functions
'(org-transclusion-content-format-org
org-transclusion-content-format))
(defvar org-transclusion-open-source-marker-functions
'(org-transclusion-open-source-marker))
(defvar org-transclusion-live-sync-buffers-functions
'(org-transclusion-live-sync-buffers-org
org-transclusion-live-sync-buffers-others-default))
(defvar org-transclusion-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map org-mode-map)
(define-key map (kbd "e") #'org-transclusion-live-sync-start)
(define-key map (kbd "g") #'org-transclusion-refresh)
(define-key map (kbd "d") #'org-transclusion-remove)
(define-key map (kbd "C-d") #'org-transclusion-detach)
(define-key map (kbd "P") #'org-transclusion-promote-subtree)
(define-key map (kbd "D") #'org-transclusion-demote-subtree)
(define-key map (kbd "o") #'org-transclusion-open-source)
(define-key map (kbd "O") #'org-transclusion-move-to-source)
map)
"It is the local-map used within a transclusion.
As the transcluded text content is read-only, these keybindings
are meant to be a sort of contextual menu to trigger different
functions on the transclusion.")
(defvar org-transclusion-live-sync-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map org-mode-map)
(define-key map (kbd "C-c C-c") #'org-transclusion-live-sync-exit)
(define-key map (kbd "C-y") #'org-transclusion-live-sync-paste)
map)
"It is the local-map used within the live-sync overlay.
It inherits `org-mode-map' and adds a couple of org-transclusion
specific keybindings; namely:
- `org-transclusion-live-sync-paste'
- `org-transclusion-live-sync-exit'")
(defvar org-transclusion-yank-excluded-properties
'(org-transclusion-type org-transclusion-beg-mkr
org-transclusion-end-mkr org-transclusion-pair
org-transclusion-orig-keyword wrap-prefix line-prefix
:parent front-sticky rear-nonsticky))
(defvar org-transclusion-yank-remember-user-excluded-props '())
(define-fringe-bitmap 'org-transclusion-fringe-bitmap
[#b11000000
#b11000000
#b11000000
#b11000000
#b11000000
#b11000000
#b11000000
#b11000000]
nil nil '(center t))
;;;; Macro
;;;; Defining macros before they are used in the rest of package
;;;; Flycheck warns with "macro X defined too late"
(defmacro org-transclusion-with-inhibit-read-only (&rest body)
"Run BODY with `'inhibit-read-only` t.
This macro is used instead of `with-silent-modifications' because
Org mode's caching relies upon modification hooks to function."
(declare (debug t) (indent 0))
(let ((modified (make-symbol "modified")))
`(let* ((,modified (buffer-modified-p))
(inhibit-read-only t))
(unwind-protect
(progn
,@body)
(unless ,modified
(restore-buffer-modified-p nil))))))
;;;; Commands
;;;###autoload
(define-minor-mode org-transclusion-mode
"Toggle Org-transclusion minor mode."
:init-value nil
:lighter org-transclusion-mode-lighter
:global nil
:keymap (let ((map (make-sparse-keymap)))
map)
(cond
(org-transclusion-mode
(org-transclusion-activate)
(when org-transclusion-add-all-on-activate
(org-transclusion-add-all)))
(t (org-transclusion-deactivate))))
;;;###autoload
(defun org-transclusion-activate ()
"Activate Org-transclusion hooks and other setups in the current buffer.
This function does not add transclusions; it merely sets up hooks
and variables."
(interactive)
(add-hook 'before-save-hook #'org-transclusion-before-save-buffer nil t)
(add-hook 'after-save-hook #'org-transclusion-after-save-buffer nil t)
(add-hook 'kill-buffer-hook #'org-transclusion-before-kill nil t)
(add-hook 'kill-emacs-hook #'org-transclusion-before-kill nil t)
(add-hook (if (version< org-version "9.6")
'org-export-before-processing-hook
'org-export-before-processing-functions)
#'org-transclusion-inhibit-read-only nil t)
(org-transclusion-yank-excluded-properties-set)
(org-transclusion-load-extensions-maybe))
(defun org-transclusion-deactivate ()
"Deactivate Org-transclusion hooks and other setups in the current buffer.
This function also removes all the transclusions in the current buffer."
(interactive)
(org-transclusion-remove-all)
(remove-hook 'before-save-hook #'org-transclusion-before-save-buffer t)
(remove-hook 'after-save-hook #'org-transclusion-after-save-buffer t)
(remove-hook 'kill-buffer-hook #'org-transclusion-before-kill t)
(remove-hook 'kill-emacs-hook #'org-transclusion-before-kill t)
(remove-hook (if (version< org-version "9.6")
'org-export-before-processing-hook
'org-export-before-processing-functions)
#'org-transclusion-inhibit-read-only t)
(org-transclusion-yank-excluded-properties-remove))
;;;###autoload
(defun org-transclusion-make-from-link (&optional arg)
"Make a transclusion keyword from a link at point.
The resultant transclusion keyword will be placed in the first
next empty line. If there is no empty line until the bottom of
the buffer, this function adds a new empty line.
When minor-mode `org-transclusion-mode' is active, this function
automatically transcludes the text content; when it is inactive,
it simply adds the \"#+transclude\" keyword before the link and
inserts the whole line.
If you pass a `universal-argument', this function reverses this:
if the mode is active, the keyword gets inserted; if the mode is
inactive, the transclusion gets added.
You can pass a prefix argument (ARG) with using
`digit-argument' (e.g. C-1 or C-2; or \\[universal-argument] 3,
so on) or `universal-argument' (\\[universal-argument]).
If you pass a positive number 1-9 with `digit-argument', this
function automatically puts the :level property to the resultant
transclusion keyword."
(interactive "P")
(let* ((context (org-element-lineage
(org-element-context)'(link) t))
(auto-transclude-p (if (or (not arg) (numberp arg))
org-transclusion-mode
;; if `universal-argument' is passed,
;; reverse nil/t when
(not org-transclusion-mode))))
(let* ((contents-beg (org-element-property :contents-begin context))
(contents-end (org-element-property :contents-end context))
(contents (and contents-beg
(buffer-substring-no-properties contents-beg
contents-end)))
(link (org-element-link-interpreter context contents)))
(save-excursion
(org-transclusion-search-or-add-next-empty-line)
(insert (format "#+transclude: %s\n" link))
(forward-line -1)
(when (and (numberp arg)
(> arg 0)
(<= arg 9))
(end-of-line)
(insert (format " :level %d" arg)))
(when auto-transclude-p (org-transclusion-add))))))
;;;###autoload
(defun org-transclusion-add (&optional copy)
"Transclude text content for the #+transclude at point.
When minor-mode `org-transclusion-mode' is inactive in the
current buffer, this function toggles it on.
With using `universal-argument' (\\[universal-argument]) or
non-nil COPY argument, you can copy the transcluded content into
the buffer instead of transclusion.
Examples of acceptable formats are as below:
- \"#+transclude: [[file:path/file.org::search-option][desc]]:level n\"
- \"#+transclude: [[id:uuid]] :level n :only-contents\"
The file path or id in the transclude keyword value are
translated to the normal Org Mode link format such as
[[file:path/tofile.org::*Heading]] or [[id:uuid]] to copy a piece
of text from the link target.
TODO: id:uuid without brackets [[]] is a valid link within Org
Mode. This is not supported yet.
A transcluded text region is read-only. You can use a variety of
commands on the transcluded region at point. Refer to the
commands below. You can customize the keymap with
using `org-transclusion-map'.
For example, `org-transclusion-live-sync-start' lets you edit the
part of the text at point. This edit mode is analogous to Occur
Edit for Occur Mode.
TODO: that for transclusions of Org elements/buffer, live-sync
does not support all the elements.
\\{org-transclusion-map}"
(interactive "P")
(when (progn (org-transclusion-fix-common-misspelling)
(org-transclusion-check-add))
;; Turn on the minor mode to load extensions before staring to add.
(unless org-transclusion-mode
(let ((org-transclusion-add-all-on-activate nil))
(org-transclusion-mode +1)))
(let* ((keyword-plist (org-transclusion-keyword-string-to-plist))
(link (org-transclusion-wrap-path-to-link
(plist-get keyword-plist :link)))
(payload (run-hook-with-args-until-success
'org-transclusion-add-functions link keyword-plist)))
(if (functionp payload)
;; Allow for asynchronous transclusion
(funcall payload link keyword-plist copy)
(org-transclusion-add-payload payload link keyword-plist copy)))))
(defun org-transclusion-add-payload (payload link keyword-plist copy)
"Insert transcluded content with error handling.
PAYLOAD should be a plist according to the description in
`org-transclusion-add-functions'. LINK should be an org-element
context object for the link. KEYWORD-PLIST should contain the
\"#+transclude:\" keywords for the transclusion at point. With
non-nil COPY, copy the transcluded content into the buffer.
This function is intended to be called from within
`org-transclusion-add' as well as payload functions returned by
hooks in `org-transclusion-add-functions'."
(let ((tc-type (plist-get payload :tc-type))
(src-buf (plist-get payload :src-buf))
(src-beg (plist-get payload :src-beg))
(src-end (plist-get payload :src-end))
(src-content (plist-get payload :src-content)))
(if (or (string= src-content "")
(eq src-content nil))
;; Keep going with program when no content `org-transclusion-add-all'
;; should move to the next transclusion
(prog1 nil
(message
"No content found with \"%s\". Check the link at point %d, line %d"
(org-element-property :raw-link link) (point) (org-current-line)))
(let ((beg (line-beginning-position))
(end))
(org-transclusion-with-inhibit-read-only
(when (save-excursion
(end-of-line) (insert-char ?\n)
(org-transclusion-content-insert
keyword-plist tc-type src-content
src-buf src-beg src-end copy)
(unless (eobp) (delete-char 1))
(setq end (point))
t)
;; `org-transclusion-keyword-remove' checks element at point is a
;; keyword or not
(org-transclusion-keyword-remove)))
(run-hook-with-args 'org-transclusion-after-add-functions beg end))
t)))
;;;###autoload
(defun org-transclusion-add-all (&optional narrowed)
"Add all active transclusions in the current buffer.
By default, this function temporarily widens the narrowed region
you are in and works on the entire buffer. Note that this
behavior is important for `org-transclusion-after-save-buffer' in
order to clear the underlying file of all the transcluded text.
For interactive use, you can pass NARROWED with using
`universal-argument' (\\[universal-argument]) to get this
function to work only on the narrowed region you are in, leaving
the rest of the buffer unchanged."
(interactive "P")
(save-restriction
(let ((marker (move-marker (make-marker) (point))))
(unless narrowed (widen))
(goto-char (point-min))
(let ((regexp "^[ \t]*#\\+TRANSCLUDE:"))
(while (re-search-forward regexp nil t)
;; Don't transclude if within a transclusion to avoid infinite
;; recursion
(unless (or (org-transclusion-within-transclusion-p)
(plist-get (org-transclusion-keyword-string-to-plist)
:disable-auto))
;; Demoted-errors so that one error does not stop the whole process
(with-demoted-errors
"Not transcluded. Continue to next: %S"
(when (org-transclusion-add)
(message "Transcluded at point %d, line %d"
(point) (org-current-line)))))))
(goto-char marker)
(move-marker marker nil) ; point nowhere for GC
t)))
(defun org-transclusion-remove ()
"Remove transcluded text at point.
When success, return the beginning point of the keyword re-inserted."
(interactive)
(if-let* ((beg (marker-position
(get-char-property (point) 'org-transclusion-beg-mkr)))
(end (marker-position
(get-char-property (point) 'org-transclusion-end-mkr)))
(keyword-plist (get-char-property (point)
'org-transclusion-orig-keyword))
(indent (plist-get keyword-plist :current-indentation))
(keyword (org-transclusion-keyword-plist-to-string keyword-plist))
(tc-pair-ov (get-char-property (point) 'org-transclusion-pair)))
(progn
;; Need to retain the markers of the other adjacent transclusions
;; if any. If their positions differ after insert, move them back
;; beg or end
(let ((mkr-at-beg
;; Check the points to look at exist in buffer. Then look for
;; adjacent transclusions' markers if any.
(when (>= (1- beg)(point-min))
(get-text-property (1- beg) 'org-transclusion-end-mkr))))
;; If within live-sync, exit. It's not absolutely
;; required. delete-region below will evaporate the live-sync
;; overlay, and text-clone's post-command correctly handles the
;; overlay on the source.
(when (org-transclusion-within-live-sync-p)
(org-transclusion-live-sync-exit))
(delete-overlay tc-pair-ov)
(org-transclusion-with-inhibit-read-only
(save-excursion
(delete-region beg end)
(when (> indent 0) (indent-to indent))
(insert-before-markers keyword))
;; Move markers of adjacent transclusions if any to their original
;; positions. Some markers move if two transclusions are placed
;; without any blank lines, and either of beg and end markers will
;; inevitably have the same position (location "between" lines)
(when mkr-at-beg (move-marker mkr-at-beg beg))
;; Go back to the beginning of the inserted keyword line
(goto-char beg))
(move-marker (make-marker) beg)))
(message "Nothing done. No transclusion exists here.") nil))
(defun org-transclusion-detach ()
"Make the transcluded region normal copied text content."
(interactive)
;; Make sure the transclusion is removed first so that undo can be used
;; to go back to the #+transclusion before detach.
(org-transclusion-refresh 'detach))
(defun org-transclusion-remove-all (&optional narrowed)
"Remove all transcluded text regions in the current buffer.
Return the list of points for the transclusion keywords
re-inserted. It is assumed that the list is ordered in
descending order from the bottom of the buffer to the top. The
list is intended to be used in
`org-transclusion-before-save-buffer'.
By default, this function temporarily widens the narrowed region
you are in and works on the entire buffer. Note that this
behavior is important for `org-transclusion-before-save-buffer'
and `org-transclusion-before-kill' to clear the underlying file
of all the transcluded text.
For interactive use, you can pass NARROWED with using
`universal-argument' (\\[universal-argument]) to get this
function to work only on the narrowed region you are in, leaving
the rest of the buffer unchanged."
(interactive "P")
(save-restriction
(let ((current-marker (move-marker (make-marker) (point)))
match removed-marker list)
(unless narrowed (widen))
(goto-char (point-min))
(while (setq match (text-property-search-forward 'org-transclusion-type))
(goto-char (prop-match-beginning match))
(setq removed-marker (org-transclusion-remove))
(when removed-marker (push removed-marker list)))
(goto-char current-marker)
(move-marker current-marker nil) ; point nowhere for GC
list)))
(defun org-transclusion-refresh (&optional detach)
"Refresh the transcluded text at point.
With using `universal-argument' (\\[universal-argument]), you can
pass DETACH, which copies the source instead of transclusion.
TODO: Support asynchronous transclusions (set point correctly)."
(interactive "P")
(when (org-transclusion-within-transclusion-p)
(let ((pos (point)))
(org-transclusion-remove)
(org-transclusion-add detach)
(goto-char pos))
t))
(defun org-transclusion-promote-subtree ()
"Promote transcluded subtree at point."
(interactive)
(org-transclusion-promote-or-demote-subtree))
(defun org-transclusion-demote-subtree ()
"Demote transcluded subtree at point."
(interactive)
(org-transclusion-promote-or-demote-subtree 'demote))
(defun org-transclusion-open-source (&optional arg)
"Open the source buffer of transclusion at point.
When ARG is non-nil (e.g. \\[universal-argument]), the point will
remain in the source buffer for further editing.
TODO: Support asynchronous transclusions when source buffer
doesn't exist."
(interactive "P")
(unless (overlay-buffer (get-text-property (point) 'org-transclusion-pair))
(org-transclusion-refresh))
(let* ((type (get-text-property (point) 'org-transclusion-type))
;; Temporary marker to be discarded at the end of this function
(src-mkr (run-hook-with-args-until-success
'org-transclusion-open-source-marker-functions type))
(src-buf (marker-buffer src-mkr))
(buf (current-buffer))
(pos (point)))
(if (not src-buf)
(user-error
(format "No paired source buffer found here: at %d" (point)))
(unwind-protect
(progn
(when (display-buffer
src-buf
org-transclusion-open-source-display-action-list)
(pop-to-buffer src-buf)
(goto-char src-mkr)
(recenter-top-bottom)))
(unless arg
(progn (pop-to-buffer buf)
(goto-char pos)))))
(move-marker src-mkr nil))) ; point nowhere for GC
(defun org-transclusion-move-to-source ()
"Open the source buffer and move point to it.
It's a function only to enable a keymap to call
`org-transclusion-open-source' with an argument."
(interactive)
(org-transclusion-open-source t))
(defun org-transclusion-live-sync-start ()
"Start live-sync edit on the transclusion at point.
While live-sync is on, before- and after-save-hooks to remove/add
transclusions are also temporarily disabled. This prevents
auto-save from getting in the way of live-sync.
For transclusions of Org elements or a buffer, live-sync works
only on the following elements: center-block, drawer,
dynamic-block, latex-environment, paragraph, plain-list,
quote-block, special-block table, and verse-block.
It is known that live-sync does not work for the other Org
elements: comment-block, export-block, example-block,
fixed-width, keyword, src-block, and property-drawer.
`org-transclusion-live-sync-map' inherits `org-mode-map' and adds
a couple of org-transclusion specific keybindings; namely:
- `org-transclusion-live-sync-paste'
- `org-transclusion-live-sync-exit'
\\{org-transclusion-live-sync-map}
TODO: Support asynchronous transclusions."
(interactive)
(if (not (org-transclusion-within-transclusion-p))
(progn (message (format "Nothing done. Not a translusion at %d" (point)))
nil)
;; Delete the other live-sync and refresh its transclusion
;; There should be only one pair of transclusion-source in live-sync
(when-let* ((deleted-live-sync-ovs (text-clone-delete-overlays))
(deleted-tc-ov (cadr deleted-live-sync-ovs)))
(org-transclusion-live-sync-refresh-after-exit deleted-tc-ov))
(org-transclusion-refresh)
(let* ((remember-pos (point))
(ovs (org-transclusion-live-sync-buffers))
(src-ov (car ovs))
(tc-ov (cdr ovs))
(tc-beg (overlay-start tc-ov))
(tc-end (overlay-end tc-ov)))
;; Check the length of both overlays
;; if different, abort live-sync
(if (not (= (- (overlay-end tc-ov) (overlay-start tc-ov))
(- (overlay-end src-ov) (overlay-start src-ov))))
(progn
(user-error
(concat
"No live-sync can be started. "
"Lengths of transclusion and source are not identical"
(format " - tc: [%s] src: [%s]"
(- (overlay-end tc-ov) (overlay-start tc-ov))
(- (overlay-end src-ov) (overlay-start src-ov)))))
nil) ; return nil
(org-transclusion-live-sync-modify-overlays
(text-clone-set-overlays src-ov tc-ov))
(org-transclusion-live-sync-display-buffer (overlay-buffer src-ov))
(goto-char remember-pos)
(remove-hook 'before-save-hook #'org-transclusion-before-save-buffer t)
(remove-hook 'after-save-hook #'org-transclusion-after-save-buffer t)
(with-silent-modifications
(remove-text-properties (1- tc-beg) tc-end '(read-only)))
t))))
(defun org-transclusion-live-sync-exit ()
"Exit live-sync at point.
It attempts to re-arrange the windows for the current buffer to
the state before live-sync started."
(interactive)
(if (not (org-transclusion-within-live-sync-p))
(user-error "Not within a transclusion in live-sync")
(text-clone-delete-overlays)
;; Re-activate hooks inactive during live-sync
(org-transclusion-activate)
(org-transclusion-refresh)
(when org-transclusion-remember-window-config
(unwind-protect
(set-window-configuration org-transclusion-remember-window-config)
(progn
(setq org-transclusion-remember-window-config nil))))))
(defun org-transclusion-live-sync-paste ()
"Paste text content from `kill-ring' and inherit the text props.
This is meant to be used within live-sync overlay as part of
`org-transclusion-live-sync-map'"
(interactive)
(insert-and-inherit (current-kill 0)))
;;;;---------------------------------------------------------------------------
;;;; Private Functions
;;;; Functions for Activate / Deactivate / save-buffer hooks
(defun org-transclusion-before-save-buffer ()
"Remove transclusions in `before-save-hook'.
This function is meant to clear the file clear of the
transclusions. It also remembers the current point for
`org-transclusion-after-save-buffer' to move it back."
(setq org-transclusion-remember-point (point))
(setq org-transclusion-remember-transclusions
(org-transclusion-remove-all)))
(defun org-transclusion-after-save-buffer ()
"Add transclusions back as they were `before-save-buffer'.
This function relies on `org-transclusion-remember-transclusions'
set in `before-save-hook'. It also move the point back to
`org-transclusion-remember-point'."
(unwind-protect
(progn
;; Assume the list is in descending order.
;; pop and do from the bottom of buffer
(let ((do-length (length org-transclusion-remember-transclusions))
(do-count 0))
(dolist (p org-transclusion-remember-transclusions)
(save-excursion
(goto-char p)
(org-transclusion-add)
(move-marker p nil)
(setq do-count (1+ do-count))
(when (> do-count do-length)
(error
"org-transclusion: Aborting. You may be in an infinite loop"))))
;; After save and adding all transclusions, the modified flag should
;; be set to nil.
(restore-buffer-modified-p nil)
(when org-transclusion-remember-point
(goto-char org-transclusion-remember-point))))
(progn
(setq org-transclusion-remember-point nil)
(setq org-transclusion-remember-transclusions nil))))
(defun org-transclusion-before-kill ()
"Remove transclusions before `kill-buffer' or `kill-emacs'.
Intended to be used with `kill-buffer-hook' and `kill-emacs-hook'
to clear the file of the transcluded text regions. This function
also flags the buffer modified and `save-buffer'. Calling the
second `org-transclusion-remove-all' ensures the clearing process
to occur. This is required because during live-sync, some hooks
that manage the clearing process are temporarily turned
off (removed)."
;; Remove transclusions first. To deal with an edge case where transclusions
;; were added for a capture buffer -- e.g. `org-capture' or `org-roam-catpure'
;; --, check is done for `buffer-file-name' to see if there is a file visited
;; by the buffer. If a "temp" buffer, there is no file being visited.
(when (and (org-transclusion-remove-all)
(buffer-file-name))
(org-transclusion-remove-all)))
;;;;---------------------------------------------------------------------------
;;;; Functions for Transclude Keyword
(defun org-transclusion-keyword-string-to-plist ()
"Return the \"#+transclude:\" keyword's values if any at point."
(save-excursion
(beginning-of-line)
(let ((plist))
(when (string= "TRANSCLUDE"
(org-element-property :key (org-element-at-point)))
;; #+transclude: keyword exists.
;; Further checking the value
(when-let ((str (org-element-property :value (org-element-at-point))))
(dolist (fn org-transclusion-keyword-value-functions) plist
(setq plist (append plist (funcall fn str)))))
plist))))
(defun org-transclusion-keyword-value-link (string)
"It is a utility function used converting a keyword STRING to plist.
It is meant to be used by
`org-transclusion-get-string-to-plist'. It needs to be set in
`org-transclusion-keyword-value-functions'."
(if (string-match "\\(\\[\\[.+?\\]\\]\\)" string)
(list :link (org-strip-quotes (match-string 0 string)))
;; link mandatory
(user-error "Error. Link in #+transclude is mandatory at %d" (point))
nil))
(defun org-transclusion-keyword-value-disable-auto (string)
"It is a utility function used converting a keyword STRING to plist.
It is meant to be used by `org-transclusion-get-string-to-plist'.
It needs to be set in
`org-transclusion-keyword-value-functions'."
(when (string-match ":disable-auto" string)
(list :disable-auto
(org-strip-quotes (match-string 0 string)))))
(defun org-transclusion-keyword-value-level (string)
"It is a utility function used converting a keyword STRING to plist.
It is meant to be used by `org-transclusion-get-string-to-plist'.
It needs to be set in
`org-transclusion-keyword-value-functions'."
(when (string-match ":level *\\([1-9]\\)" string)
(list :level
(string-to-number (org-strip-quotes (match-string 1 string))))))
(defun org-transclusion-keyword-value-only-contents (string)
"It is a utility function used converting a keyword STRING to plist.
It is meant to be used by `org-transclusion-get-string-to-plist'.
It needs to be set in
`org-transclusion-keyword-value-functions'."
(when (string-match ":only-contents?" string)
(list :only-contents
(org-strip-quotes (match-string 0 string)))))
(defun org-transclusion-keyword-value-exclude-elements (string)
"It is a utility function used converting a keyword STRING to plist.
It is meant to be used by `org-transclusion-get-string-to-plist'.
It needs to be set in
`org-transclusion-get-keyword-values-hook'.
Double quotations are mandatory."
(when (string-match ":exclude-elements +\"\\(.*\\)\"" string)
(list :exclude-elements
(org-trim (org-strip-quotes (match-string 1 string))))))
(defun org-transclusion-keyword-current-indentation (_)
"It is a utility function used converting a keyword STRING to plist.
It is meant to be used by `org-transclusion-get-string-to-plist'.
It needs to be set in
`org-transclusion-keyword-value-functions'."
(list :current-indentation (current-indentation)))
(defun org-transclusion-keyword-value-expand-links (string)
"It is a utility function used converting a keyword STRING to plist.
It is meant to be used by `org-transclusion-get-string-to-plist'.
It needs to be set in
`org-transclusion-keyword-value-functions'."
(when (string-match ":expand-links" string)
(list :expand-links
(org-strip-quotes (match-string 0 string)))))
(defun org-transclusion-keyword-remove ()
"Remove the keyword element at point.
Returns t if successful. It checks if the element at point is a
keyword. If not, returns nil."
(let* ((elm (org-element-at-point))
;; Ignore and keep affiliated keywords before #+transclusion
;; Fix issue #115
(beg (org-element-property :post-affiliated elm))
(end (org-element-property :end elm))
(post-blank (org-element-property :post-blank elm)))
(when (string= "keyword" (org-element-type elm))
(delete-region beg (- end post-blank))
t)))
(defun org-transclusion-keyword-plist-to-string (plist)
"Convert a keyword PLIST to a string."
(let (;;(active-p (plist-get plist :active-p))
(link (plist-get plist :link))
(level (plist-get plist :level))
(disable-auto (plist-get plist :disable-auto))
(only-contents (plist-get plist :only-contents))
(exclude-elements (plist-get plist :exclude-elements))
(expand-links (plist-get plist :expand-links))
(custom-properties-string nil))
(setq custom-properties-string
(dolist (fn org-transclusion-keyword-plist-to-string-functions
custom-properties-string)
(let ((str (funcall fn plist)))
(when (and str (not (string-empty-p str)))
(setq custom-properties-string
(concat custom-properties-string " " str ))))))
(concat "#+transclude: "
link
(when level (format " :level %d" level))
(when disable-auto (format " :disable-auto"))
(when only-contents (format " :only-contents"))
(when exclude-elements (format " :exclude-elements \"%s\""
exclude-elements))
(when expand-links (format " :expand-links"))
custom-properties-string
"\n")))
(defun org-transclusion-keyword-plist-to-exclude-elements (plist)
"Return list of symbols from PLIST when applicable.
If PLIST does not have :exclude-elements, return nil.
This function also attempts to remove empty string that gets
inserted when more than one space is inserted between symbols."
(let ((str (plist-get plist :exclude-elements)))
(when str
(let ((list (split-string str " "))
elements)
(dolist (s list elements)
(unless (string= s "")
(when (memq (intern s) org-element-all-elements)
(push (intern s) elements))))))))
;;-----------------------------------------------------------------------------
;;;; Add-at-point functions
(defun org-transclusion-add-org-id (link plist)
"Return a list for Org-ID LINK object and PLIST.
Return nil if not found."
(when (string= "id" (org-element-property :type link))
;; when type is id, the value of path is the id
(let* ((id (org-element-property :path link))
(mkr (ignore-errors (org-id-find id t)))
(payload '(:tc-type "org-id")))
(if mkr
(append payload (org-transclusion-content-org-marker mkr plist))
(message
"No transclusion done for this ID. Ensure it works at point %d, line %d"
(point) (org-current-line))
nil))))
(defun org-transclusion-add-org-file (link plist)
"Return a list for Org file LINK object and PLIST.
Return nil if not found."
(and (string= "file" (org-element-property :type link))
(org-transclusion-org-file-p (org-element-property :path link))
(append '(:tc-type "org-link")
(org-transclusion-content-org-link link plist))))
(defun org-transclusion-add-other-file (link plist)
"Return a list for non-Org file LINK object and PLIST.
Return nil if not found."
(and (string= "file" (org-element-property :type link))
(append '(:tc-type "others-default")
(org-transclusion-content-others-default link plist))))