forked from mickeynp/combobulate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
combobulate-manipulation.el
1685 lines (1542 loc) · 80.1 KB
/
combobulate-manipulation.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
;;; combobulate-manipulation.el --- manipulate structured text with combobulate -*- lexical-binding: t; -*-
;; Copyright (C) 2021-23 Mickey Petersen
;; Author: Mickey Petersen <mickey at masteringemacs.org>
;; Package-Requires: ((emacs "29"))
;; Version: 0.1
;; Homepage: https://www.github.com/mickeynp/combobulate
;; Keywords: convenience, tools, languages
;; 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(require 'combobulate-settings)
(require 'combobulate-navigation)
(require 'combobulate-misc)
(require 'combobulate-interface)
(require 'combobulate-procedure)
(require 'combobulate-setup)
(require 'eieio)
(require 'map)
;;; for python-specific indent stuff
(require 'python)
(defvar combobulate-query-ring)
(declare-function combobulate-envelope-expand-instructions "combobulate-envelope")
(declare-function combobulate-display-draw-node-tree "combobulate-display")
(declare-function combobulate-query-build-nested "combobulate-query")
(declare-function combobulate-query-pretty-print "combobulate-query")
(declare-function combobulate-query-ring-current-query "combobulate-query")
(declare-function combobulate-query-ring--execute "combobulate-query")
(defvar combobulate-envelope--undo-on-quit)
(defvar combobulate-procedure-apply-shared-discard-rules)
(defvar combobulate-key-map)
(defun combobulate--refactor-insert-copied-values (values)
(let ((start-marker (point-marker)) (after-marker) (pt))
;; move this into a distinct function that can reproduce stored
;; input.
(goto-char (point-marker))
(combobulate-skip-whitespace-backward)
(just-one-space 0)
(setq pt (point))
(let ((ct 0))
(dolist (s values)
(unless (string-blank-p s)
(save-excursion
(insert s)
(setq pt (point)))
(cl-incf ct)
(when (= ct 1)
(save-excursion
(back-to-indentation)
(setq start-marker (point-marker))))
(goto-char pt))))
(back-to-indentation)
(setq after-marker (point-marker))
(when (combobulate-read indent-after-edit)
(indent-region start-marker (save-excursion
(goto-char after-marker)
(end-of-line)
(point))))
(goto-char start-marker)))
(defun combobulate--refactor-get-overlays (&optional session-id)
(seq-filter
(lambda (ov)
(and (overlay-get ov 'combobulate-refactor-actions)
(or (not session-id)
(equal (overlay-get ov 'combobulate-refactor-session-id)
session-id))))
(car (overlay-lists))))
(defun combobulate--refactor-clear-overlays (&optional session-id)
"Clear all `combobulate-refactor' overlays with SESSION-ID."
(mapc #'delete-overlay (combobulate--refactor-get-overlays session-id)))
;; (defun combobulate--refactor-divide-overlays (keep-overlays)
;; (let ((markers))
;; (dolist (ov-k keep-overlays)
;; (push ov-k markers)
;; (when (eq (overlay-get ov-k 'combobulate-refactor-actions) 'copy-region)
;; (dolist (overlapped-ov (overlays-in (overlay-start ov-k)
;; (overlay-end ov-k)))
;; (when-let (overlapped-ov-action (overlay-get overlapped-ov 'combobulate-refactor-actions))
;; (if (eq overlapped-ov-action 'delete-region)
;; (let ((start-overlaps (in-range (overlay-start overlapped-ov)
;; (overlay-start ov-k)
;; (overlay-end ov-k)))
;; (new-ov))
;; (when start-overlaps
;; (setq new-ov (copy-overlay overlapped-ov))
;; (move-overlay new-ov
;; (overlay-start new-ov)
;; (overlay-start ov-k))
;; (move-overlay overlapped-ov
;; (if start-overlaps
;; (overlay-end ov-k)
;; (overlay-start overlapped-ov))
;; (overlay-end overlapped-ov))
;; (push new-ov markers)))
;; (push overlapped-ov markers))))))
;; markers))
(defvar combobulate-refactor--copied-values nil)
(defvar combobulate-refactor--active-sessions nil
"A list of active `combobulate-refactor' sessions.")
(defun combobulate-refactor--get-active-session (id)
"Get the active `combobulate-refactor' session with the given ID."
(assoc id combobulate-refactor--active-sessions))
(defun combobulate-refactor-setup (&optional id)
"Setup a `combobulate-refactor' session with the given ID."
(let ((id (or id (gensym "combobulate-refactor-"))))
;; only spawn a new session if one doesn't already exist.
(unless (combobulate-refactor--get-active-session id)
(push (cons id nil) combobulate-refactor--active-sessions))
id))
(define-error 'combobulate-refactor-error "Combobulate Refactor Error" 'error)
(define-error 'combobulate-refactor-uncommitted-changes "Combobulate Refactor: Uncommitted Changes" 'combobulate-refactor-error)
(defun combobulate-refactor-delete-session (id)
"Delete a `combobulate-refactor' session with ID"
(let ((session (combobulate-refactor--get-active-session id)))
(when session
(combobulate--refactor-clear-overlays id)
(setq combobulate-refactor--active-sessions
(assq-delete-all id combobulate-refactor--active-sessions)))))
(cl-defmacro combobulate-refactor ((&key (id nil)) &rest body)
(declare (indent defun) (debug (sexp body)))
(let ((--session (gensym))
;; non-nil if we're entering a session that already exists.
(--pre-existing-session (gensym)))
`(let ((,--pre-existing-session (combobulate-refactor--get-active-session ,id))
(,--session (combobulate-refactor-setup ,id)))
(cl-flet* ((add-marker (ov)
(overlay-put ov 'combobulate-refactor-session-id ,--session)
(push ov (alist-get ,--session combobulate-refactor--active-sessions))
ov)
(mark-range-move (beg end position)
(add-marker (combobulate--refactor-mark-move beg end position)))
(mark-range-deleted (beg end)
(add-marker (combobulate--refactor-mark-deleted beg end)))
(mark-range-highlighted (beg end &optional face advance)
(add-marker (combobulate--refactor-mark-highlighted beg end face advance)))
(mark-copy (start end)
(add-marker (combobulate--refactor-mark-copy start end 'combobulate-refactor--copied-values)))
(mark-node-copy (n)
(mark-copy (combobulate-node-start n) (combobulate-node-end n)))
(mark-range-indent (beg end target-pt baseline-column)
(add-marker (combobulate--refactor-mark-indent beg end target-pt baseline-column)))
(mark-node-deleted (n)
(add-marker (combobulate--refactor-mark-deleted (combobulate-node-start n)
(combobulate-node-end n))))
(mark-range-label (beg end label &optional face before)
(add-marker (combobulate--refactor-mark-label beg end label face before)))
(mark-node-highlighted (n &optional face advance)
(mark-range-highlighted (combobulate-node-start n)
(combobulate-node-end n)
face
advance))
(mark-cursor (pt)
(add-marker (combobulate--refactor-mark-cursor pt)))
(mark-node-cursor (n)
(mark-cursor (combobulate-node-start n)))
(mark-field (pt tag &optional text transformer-fn)
(add-marker (combobulate--refactor-mark-field
pt tag (or text (symbol-name tag))
transformer-fn)))
(toggle-field (pt tag)
(combobulate--refactor-toggle-field pt tag))
(update-field (tag text)
(seq-filter
(lambda (ov) (let ((actions (overlay-get ov 'combobulate-refactor-action)))
(combobulate--refactor-update-field ov tag text)))
(alist-get ,--session combobulate-refactor--active-sessions)))
(mark-point (&optional pt)
(add-marker (combobulate--refactor-mark-position (or pt (point)))))
(rollback ()
(combobulate-refactor-delete-session ,--session))
(commit ()
(setq combobulate-refactor--copied-values nil)
(mapc (lambda (ov) (combobulate--refactor-commit ov t))
(seq-sort (lambda (a b)
(and a b
(overlayp a)
(overlayp b)
(> (or (overlay-start a) 0)
(or (overlay-end b) 0))))
(alist-get ,--session combobulate-refactor--active-sessions)))
;; clean up.
(rollback)))
(condition-case err
(prog1 (combobulate-atomic-change-group
,@body)
(when (and (alist-get ,--session combobulate-refactor--active-sessions)
(not ,--pre-existing-session))
(prog1
(signal 'combobulate-refactor-uncommitted-changes
(format "Uncommitted changes in session `%s'" ,--session))
(combobulate-refactor-delete-session ,--session))))
(t (rollback) (signal (car err) (cdr err))))))))
(defun combobulate-tally-nodes (nodes &optional skip-label)
"Groups NODES into labels (if any) and their types and tallies them.
If NODES is a list of `(@label . node)' cons cells, tally nodes by that
first; followed by the node type of each grouped label."
(if nodes
(if (and (consp nodes) (consp (car nodes)))
(mapconcat
(pcase-lambda (`(,label . ,rest))
(let ((string-label (symbol-name label)))
(concat (if skip-label "" (concat (capitalize (string-trim-left string-label "@")) " "))
(combobulate-tally-nodes (mapcar 'cdr rest)))))
(combobulate-group-nodes nodes #'car) ". ")
(string-join (mapcar (lambda (group)
(format
"%s `%s'"
(propertize (int-to-string (length (cdr group))) 'face 'bold)
(propertize (car group) 'face 'combobulate-active-indicator-face)))
(combobulate-group-nodes nodes #'combobulate-pretty-print-node-type))
"; "))
"zero"))
(defun combobulate-splice-parent (&optional arg)
"Vanishes the node at point and attempts to preserve its children."
(interactive "^p")
(with-argument-repetition arg
(with-navigation-nodes (:procedures (combobulate-read procedures-sibling))
(combobulate-splice (combobulate--get-nearest-navigable-node)
'(before after around self)))))
(defun combobulate--swap-node-regions (node-a node-b)
"Swaps the region substring in NODE-A with NODE-B"
(transpose-subr-1 (combobulate-node-range node-a) (combobulate-node-range node-b)))
(defun combobulate-transpose-sexps-1 (backward)
"Capture a transposable node, either forward or BACKWARD."
;; do not set `:nodes' here to allow this function to work with any
;; node type group set in the caller.
(with-navigation-nodes (:procedures (combobulate-read procedures-sexp)
:backward backward :skip-prefix t)
(combobulate-forward-sexp-function-1 backward)))
(defun combobulate-transpose-sexps ()
"Transpose sexp-like nodes around point.
If there are no legitimate sexp nodes around point, fall back to
\\[transpose-sexp]."
(interactive)
;; this covers the most common case where two nodes are "adjacent"
;; to the point.
(if-let ((backward-node (combobulate-transpose-sexps-1 t))
(forward-node (combobulate-transpose-sexps-1 nil)))
(progn
(combobulate--goto-node forward-node t)
(save-excursion
(combobulate--swap-node-regions backward-node forward-node)))
;; for everything else, fall back to the normal (but augmented,
;; because `combobulate-forward-sexp-function' is used by
;; `transpose-sexps') to attempt a transposition by shifting
;; point around.
(transpose-sexps 1 t)))
(defun combobulate-transpose-sexp-function (arg)
;; Here we should try to simulate the behavior of
;; (cons (progn (forward-sexp x) (point))
;; (progn (forward-sexp (- x)) (point)))
;; Except that we don't want to rely on the second forward-sexp
;; putting us back to where we want to be, since forward-sexp-function
;; might do funny things like infix-precedence.
(if (if (> arg 0)
(looking-at "\\sw\\|\\s_")
(and (not (bobp))
(save-excursion
(forward-char -1)
(looking-at "\\sw\\|\\s_"))))
;; Jumping over a symbol. We might be inside it, mind you.
(progn (funcall (if (> arg 0)
#'skip-syntax-backward #'skip-syntax-forward)
"w_")
(cons (save-excursion (forward-sexp arg) (point)) (point)))
;; Otherwise, we're between sexps. Take a step back before jumping
;; to make sure we'll obey the same precedence no matter which
;; direction we're going.
(funcall (if (> arg 0) #'skip-syntax-backward #'skip-syntax-forward)
" .")
(cons (save-excursion (forward-sexp arg) (point))
(progn (while (or (forward-comment (if (> arg 0) 1 -1))
(not (zerop (funcall (if (> arg 0)
#'skip-syntax-forward
#'skip-syntax-backward)
".")))))
(point)))))
(defun combobulate--consume-node (node &optional balance)
"Consume NODE in the current buffer.
If BALANCE is non-nil, more than the requested NODE may be consumeed
also (and appended to the final string, including any whitespace
between NODE and the balancing node whitespace) if consuming NODE
results in one or more `ERROR' nodes appearing in the tree.
If consuming the balancing node leaves the tree in an error state,
then that consume is undone and only the first consume is kept."
(let ((num-errors (length (combobulate-get-error-nodes)))
(start) (end)
(node-texts))
(save-excursion
;; use point as the start and not the node so we capture the
;; whitespace also.
(setq start (point)
end (combobulate-node-end node))
(push (delete-and-extract-region start end) node-texts)
(when (and balance (combobulate-get-error-nodes))
(push (let ((text))
(combobulate-with-change-group
(setq text (delete-and-extract-region
(point)
(save-excursion
(combobulate-skip-whitespace-forward t)
(combobulate-node-end (combobulate-node-at-point)))))
(when (> (length (combobulate-get-error-nodes)) num-errors)
(cancel-changes)
(setq text nil)))
text)
node-texts)))
(string-join (nreverse node-texts) "")))
(defun combobulate--kill-nodes (nodes)
"Kill between the smallest and greatest range of NODES."
(if-let (bounds (combobulate-node-range-extent nodes))
(kill-region (car bounds) (cdr bounds))
(error "No nodes to kill")))
(defun combobulate--mark-extent (start end &optional swap beginning-of-line)
"Set mark to START and point to END and activates the mark.
If SWAP is non-nil, the point and mark is exchanged after, thus
reversing the order of point and mark.
If BEGINNING-OF-LINE is non-nil, then the mark is set to the
beginning of line instead of START, but only if the text is
considered whitespace by the mode's syntax table."
(cl-macrolet
((change-position (f)
`(save-excursion
(goto-char ,f)
(skip-chars-backward combobulate-skip-prefix-regexp
(line-beginning-position))
(when (bolp)
(setf ,f (point))))))
(when beginning-of-line
(change-position start)
(change-position end))
(push-mark start t)
(goto-char end)
(activate-mark)
(when swap
(exchange-point-and-mark))
(cons start end)))
(defun combobulate-extend-region-to-whole-lines (start end)
"Extend the region between START and END to whole lines."
(dolist (pos (list start end))
(save-excursion
(goto-char pos)
(skip-chars-backward combobulate-skip-prefix-regexp
(line-beginning-position))
(when (bolp)
(setq start (point)))))
(list start end))
(defun combobulate-node-region-lines (node)
"Return NODE's region but made up of whole lines if possible."
(combobulate-extend-region-to-whole-lines (combobulate-node-start node)
(combobulate-node-end node)))
(defun combobulate-indent-string-first-line (text target-col)
"Corrects the indentation of the first line of TEXT to TARGET-COL."
(combobulate-indent-string text :first-line-operation 'absolute :first-line-amount target-col))
(defun combobulate-indent-string--strip-whitespace (s &optional count)
"Strip S of whitespace, possibly up to COUNT whitespace characters.
If COUNT is nil, then all whitespace is stripped."
(string-trim-left
s (if count (rx-to-string `(** 0 ,(abs count) space))
(rx bol (* space)))))
(defun combobulate-indent-string--count-whitespace (s)
"Count the number of whitespace characters at the beginning of S."
(- (length s) (length (combobulate-indent-string--strip-whitespace s))))
(defun combobulate-indent-string-1 (line operation amount)
"Indent LINE as per OPERATION and AMOUNT.
If OPERATION is `add', then AMOUNT is added to the current
indentation.
If OPERATION is `subtract', then AMOUNT is subtracted from the
current indentation.
If OPERATION is `absolute', then AMOUNT is used as the new
indentation."
;; operation must be: `add', `subtract', `absolute'.
(cl-assert (member operation '(add subtract absolute)))
;; see if we can invert operations if the amount warrants it.
(cond
((and (eq operation 'add) (< amount 0))
(setq operation 'subtract
amount (- amount)))
((and (eq operation 'subtract) (< amount 0))
(setq operation 'add
amount (- amount))))
(let ((current-indent (combobulate-indent-string--count-whitespace line))
(line-without-indent (combobulate-indent-string--strip-whitespace line)))
(cond ((eq operation 'add)
;; if the amount is zero, then there is nothing to add.
(if (= amount 0) line
(concat (make-string (+ current-indent amount) ? ) line-without-indent)))
((eq operation 'subtract)
;; check for whether we're subtracting more than we
;; have. If so, then we subtract the exact amount we need.
(cond ((>= current-indent amount)
(concat (make-string (- current-indent amount) ? ) line-without-indent))
(t
(concat (make-string 0 ? ) line-without-indent))))
((eq operation 'absolute)
(cl-assert (>= amount 0) "Absolute indentation must be positive.")
(concat (make-string amount ? ) line-without-indent)))))
(cl-defun combobulate-indent-string (text &key (first-line-operation nil)
(first-line-amount 0)
(rest-lines-operation nil)
(rest-lines-amount 0))
"Indent TEXT specifically for the first and rest of the lines.
FIRST-LINE-OPERATION is the operation to perform on the first
line of TEXT. It can be `add', `subtract', or `absolute'.
FIRST-LINE-AMOUNT is the amount to add, subtract, or set the
first line's indentation to.
REST-LINES-OPERATION is the operation to perform on the rest of
the lines of TEXT. It can be `relative', `add', `subtract', or
`absolute'. `relative' means that the indentation of the rest of
the lines is relative to the first line's *changed*
indentation. In other words, if the first line's indentation is
changed by 2 spaces, then the rest of the lines' indentation will
be changed by 2 spaces (in the same direction) as well.
REST-LINES-AMOUNT is the amount to add, subtract, or set the rest
of the lines' indentation to. It cannot be used with `relative'."
(cl-assert (member first-line-operation '(add subtract absolute relative nil)))
(cl-assert (member rest-lines-operation '(relative add subtract absolute nil)))
;; `rest-lines-amount' cannot be used with `relative'.
(cl-assert (or (not (eq rest-lines-operation 'relative))
(and (eq rest-lines-operation 'relative)
(eq rest-lines-amount 0))))
(let* ((lines (split-string text "\n"))
;; indentation of the first line before we modify it
(first-line-indentation (combobulate-indent-string--count-whitespace (car lines)))
(first-line (if first-line-operation
(combobulate-indent-string-1
(car lines)
(if (equal first-line-operation 'relative) 'subtract first-line-operation)
(if (equal first-line-operation 'relative)
(- first-line-indentation first-line-amount)
first-line-amount))
(car lines)))
(new-first-line-indentation (combobulate-indent-string--count-whitespace first-line))
(rest-lines (if rest-lines-operation
(mapcar (lambda (line)
(if (eq rest-lines-operation 'relative)
(combobulate-indent-string-1 line 'add (- new-first-line-indentation
first-line-indentation))
(combobulate-indent-string-1 line rest-lines-operation rest-lines-amount)))
(cdr lines))
(cdr lines))))
(string-join (cons first-line rest-lines) "\n")))
(defun combobulate--clone-node (node position)
"Clone NODE and place it at POSITION."
(combobulate--place-node-or-text position node))
(defun combobulate--place-node-or-text (position node-or-text &optional mode no-trailing-newline)
"Place NODE-OR-TEXT at POSITION.
NODE-OR-TEXT must be a valid node or a string.
If NODE-OR-TEXT is a NODE, then its first-line indentation is
calculated first and the text indented properly relative to
POSITION.
If NODE-OR-TEXT is a string, then all indentation must be handled
by the caller. The string is inserted at POSITION.
If MODE is non-nil, then it must be either `newline' or
`inline'. Where `newline' forces the placement of NODE-OR-TEXT on
a new line. If MODE is `inline' then it is places inline
alongside other nodes around POSITION.
If NO-TRAILING-NEWLINE is non-nil, then no trailing newline is inserted
after NODE-OR-TEXT."
(let* ((col (save-excursion (goto-char position)
(current-column)))
(node-text)
(newline-insert (and (or (eq mode 'newline) (null mode))
(combobulate-before-point-blank-p position))))
(cond
((stringp node-or-text)
(setq node-text (combobulate-indent-string
node-or-text
:first-line-amount col
:first-line-operation 'absolute
:rest-lines-amount 'relative)))
((or (combobulate-node-p node-or-text)
(combobulate-proxy-node-p node-or-text))
(let ((sequence-separator
;; attempt to guess the sequence separator, almost always
;; an anonymous node, that (usually!) follows nodes --
;; think array/list separators; semicolons after
;; expressions, etc. -- and ensure it is appended to the
;; cloned text. This is of course not the proper way to
;; do this: the `xxx-grammar.json' files contain the
;; rules for sequences and the character to use. This is
;; merely the 90% solution that works for most, but not
;; all, instances.
(save-excursion
(combobulate--goto-node node-or-text t)
(when-let ((node-after (condition-case nil
(combobulate-node-on (point) (1+ (point)) nil nil)
(error nil))))
(cond
;; named nodes get no sequence separator
((combobulate-node-named-p node-after) "")
((and (combobulate-node-anonymous-p node-after)
(member (combobulate-node-text node-after)
(combobulate-read plausible-separators)))
(combobulate-node-text node-after))
(t "")))))
(node-col (save-excursion
(combobulate--goto-node node-or-text)
(current-indentation))))
(setq node-text (if newline-insert
(combobulate-indent-string
;; the first line may not include all of its
;; indentation because the node extents won't
;; include it. This fixes it so it does.
(combobulate-indent-string-first-line
(concat (combobulate-node-text node-or-text) sequence-separator)
node-col)
:first-line-amount (- col node-col)
:first-line-operation 'add)
(concat (combobulate-node-text node-or-text) sequence-separator)))))
(t (error "Cannot place node or text `%s'" node-or-text)))
(goto-char position)
;; If a node has nothing but whitespace preceding it, then it's a
;; "newline-delimited" node. Newline-delimited nodes are regular
;; nodes that exist, usually, on a line of their own. That is on
;; contrast to inline-delimited nodes that are placed to the left
;; or right on a line with other nodes.
(if newline-insert
;; newline-delimited node
(progn
(unless no-trailing-newline (split-line 0))
(combobulate--refactor-insert-copied-values
(list (string-trim-right node-text))))
;; inline-delimited node
(save-excursion
(insert node-text)
(just-one-space 0)
(unless (looking-at "\\s-")
(insert " "))))))
(defun combobulate--mark-node (node &optional swap beginning-of-line)
"Mark NODE in the current buffer.
See `combobulate--mark-extent' for argument explanations."
(when node
(combobulate--mark-extent (combobulate-node-start node)
(combobulate-node-end node)
swap
beginning-of-line)))
(defun combobulate--delete-text (beg end &optional correct-indentation delete-blank-lines)
(save-excursion
(let ((text (save-excursion
(prog1 (delete-and-extract-region beg end)))))
(prog1 (if correct-indentation
(combobulate-indent-string-first-line
text
(save-excursion
(goto-char beg)
(current-indentation)))
text)
(save-excursion
;; Only trim lines if there is more than one as
;; `delete-blank-lines', in case there is only one, will
;; delete that blank line. That can have very bad
;; repercussions if the deletion is used as part of a
;; greater chain of operations, like moving text in a
;; refactor
(if (= (combobulate-string-count "\n" text) 0)
(save-restriction
(goto-char end)
(narrow-to-region (line-beginning-position) (point-max))
(when (and delete-blank-lines (or (> (combobulate-count-lines-ahead (point)) 1)
(= (combobulate-string-count "\n" text) 0)))
(delete-blank-lines)))
(save-restriction
(narrow-to-region (line-beginning-position) (point-max))
(when (and delete-blank-lines (or (> (combobulate-count-lines-ahead (point)) 1)
(= (combobulate-string-count "\n" text) 0)))
(delete-blank-lines)))))))))
(defun combobulate--delete-node (node &optional correct-indentation delete-blank-lines)
"Deletes NODE in the current buffer and returns its text.
If CORRECT-INDENTATION is non-nil, then the node's first-line
indentation is set according to its current indentation in the
buffer.
If DELETE-BLANK-LINES is non-nil, then all blank lines left behind by
the deleted node are removed."
(when node
(combobulate--delete-text (combobulate-node-start node)
(combobulate-node-end node)
correct-indentation
delete-blank-lines)))
(defun combobulate-kill-node-dwim (&optional arg)
"Kill the most likely node on or near point ARG times.
The exact node that is killed will depend on the location of
point relative to the nodes in
`combobulate-navigable-nodes'."
(interactive "p")
(with-argument-repetition arg
(with-navigation-nodes (:procedures (combobulate-read procedures-sibling))
(when-let* ((nearest (save-excursion
(combobulate-skip-whitespace-forward t)
(combobulate--get-nearest-navigable-node)))
(node (combobulate-proxy-node-make-from-nodes
(or (combobulate-nav-get-self-sibling nearest)
nearest))))
;; prevent killing nodes before point; that'd be weird.
(if (combobulate-node-on-or-after-point-p node)
(progn (let ((text (combobulate--consume-node node t)))
(if (eq last-command 'combobulate-kill-node-dwim)
(kill-append text nil)
(kill-new text)))
(combobulate-message "Killed node" node))
(error "No node to kill"))))))
(defvar-keymap combobulate-proffer-map
:parent nil
:doc "Keymap for `combobulate-proffer-choices'.
You can bind regular commands to keys like a normal map, or you
can bind one of the following special symbols:
The symbol `done' will accept the current choice and exit. The
symbol `next' will move to the next choice. The symbol `prev'
will move to the previous choice. The symbol `cancel' will cancel
the current choice and exit."
"TAB" 'next
"S-<tab>" 'prev
"<backtab>" 'prev
"RET" 'done
"C-g" 'cancel
"C-l" 'recenter
"M-c" 'recursive-edit)
(cl-defun combobulate-proffer-action-highlighter (slots)
"Helper for `combobulate-proffer-choices' that highlights the current node."
(with-slots (index current-node proxy-nodes refactor-id) slots
(combobulate-refactor (:id refactor-id)
(mark-node-highlighted current-node))))
(defvar combobulate-proffer-after-action-hook nil
"Hook to run after an action is taken in `combobulate-proffer-choices'.")
(cl-defun combobulate-proffer-choices (nodes action-fn &key
(first-choice nil)
(reset-point-on-abort t) (reset-point-on-accept nil)
(prompt-description nil)
(extra-map nil)
(flash-node nil)
(quiet nil)
(accept-action 'rollback)
(cancel-action 'commit)
(switch-action 'rollback)
(recenter nil)
(allow-numeric-selection nil)
(signal-on-abort nil)
(start-index 0)
(before-switch-fn nil)
(after-switch-fn nil)
(unique-only t))
"Interactively browse NODES one at a time with ACTION-FN applied to it.
Interactively let the user select one of the nodes in NODES and
preview the transformation Combobulate would apply if they accept
that choice. The active node is rendered with ACTION-FN to allow
the user to see what they are selecting and the possible
transformation that will take place if they accept the choice.
The user can then select the node with RET, or abort the
selection with C-g. The user can also cycle through the nodes
with TAB and S-TAB. See `combobulate-proffer-map'.
If there is exactly one node in NODES, then it is automatically
selected and no user interaction is required.
ACTION-FN must be a function that takes four arguments:
(INDEX CURRENT-NODE PROXY-NODES REFACTOR-ID)
Where INDEX is the current index of the node in PROXY-NODES,
which is the same as CURRENT-NODE. PROXY-NODES is a list of proxy
nodes available to the user to choose from. REFACTOR-ID is a
unique identifier for the current refactoring operation. Use
`combobulate-refactor' with the REFACTOR-ID to manipulate the
state of the refactoring operation.
Setting `:first-choice' to non-nil prevents the system from
proffering choices at all; instead, the first choice is
automatically picked, if there is a choice to make.
When `:reset-point-on-abort' or `:reset-point-on-accept' is
non-nil, the point is reset to where it was when the proffer was
first started depending on the outcome of the proffer.
If `:flash-node' is non-nil, then display a node tree in the echo
area alongside the status message.
If non-nil, `:unique-only' filters out duplicate nodes *and*
nodes that share the same range extent. I.e., a `block' and a
`statement' node that effectively encompass the same range in the
buffer.
`:allow-numeric-selection' is a boolean that determines whether
the user can select a node by typing its index. If non-nil, then
the user can type a number to select the node at that index from
1 through to 9.
`:extra-map' is a list of cons cells consisting of (KEY
. COMMAND). The extra keys are mapped into the proffer map,
`combobulate-proffer-map'.
`:accept-action' is a symbol that determines what happens when
the user accepts a choice. The following symbols are supported:
`rollback' - Rollback the refactoring operation.
`commit' - Commit the refactoring operation.
`:cancel-action' and `:switch-action' is the same as
`:accept-action', but for when the user cancels the choice or
interactively switches to a different node.
`:signal-on-abort' is a symbol that determines what happens when
the user aborts the choice. The following symbols are supported:
`error' - Signal an error.
`message' - Display a message in the echo area.
`:prompt-description' is a string that is displayed in the prompt.
`:start-index' is an integer that determines the starting index
of the node in the list of nodes. This is useful when you want to
skip over the first few nodes in the list.
`:recenter' is a boolean that determines whether to recenter the
buffer when the user switches to a different node.
`:quiet' is a boolean that determines whether to suppress the
status message when the user switches to a different node,
accepts or cancels the proffer. "
(setq allow-numeric-selection
;; numeric selection uses `C-1' through to `C-9' which cannot
;; always be typed on a terminal.
(and allow-numeric-selection
(display-graphic-p)
combobulate-proffer-allow-numeric-selection))
(let ((proxy-nodes
(and nodes
(funcall #'combobulate-proxy-node-make-from-nodes
;; strip out duplicate nodes. That
;; includes nodes that are duplicates
;; of one another; however, we also
;; strip out nodes that share the
;; same range extent.
(if unique-only
(seq-uniq nodes (lambda (a b)
(or (equal a b)
(equal (combobulate-node-range a)
(combobulate-node-range b)))))
nodes))))
(result) (state 'continue) (current-node)
(index start-index) (pt (point)) (raw-event)
(refactor-id (combobulate-refactor-setup))
(change-group)
(prompt)
(map (let ((map (make-sparse-keymap)))
(set-keymap-parent map combobulate-proffer-map)
;; do ont bind the same key twice; this could override
;; important keys like RET.
(unless (lookup-key map (this-command-keys))
(define-key map (this-command-keys) 'next))
(when extra-map
(mapc (lambda (k) (define-key map (car k) (cdr k))) extra-map))
(when allow-numeric-selection
(dotimes (i 9)
(define-key map (kbd (format "C-%d" (1+ i))) (1+ i))))
map)))
(unless proxy-nodes (error "There are no choices to make"))
(cl-assert (< start-index (length proxy-nodes)) nil
"Start index %d is greater than the number of nodes %d"
start-index (length proxy-nodes))
(condition-case err
(with-undo-amalgamate
(catch 'exit
(while (eq state 'continue)
(unless change-group
(setq change-group (prepare-change-group)))
(catch 'next
(setq current-node (nth index proxy-nodes))
(combobulate-refactor (:id refactor-id)
(let ((proffer-action
(combobulate-proffer-action-create
:index index
:current-node current-node
:proxy-nodes proxy-nodes
:refactor-id refactor-id
:prompt-description
(or prompt-description "")
:extra-map extra-map
:display-indicator (combobulate-display-indicator index (length proxy-nodes)))))
(funcall action-fn proffer-action)
(with-slots (display-indicator prompt-description) proffer-action
(setq prompt
(substitute-command-keys
(format "%s %s`%s': `%s' or \\`S-TAB' to cycle%s; \\`C-g' quits; rest accepts.%s"
display-indicator
(concat (cond ((stringp prompt-description) prompt-description)
((functionp prompt-description) (funcall prompt-description proffer-action))
(t ""))
" ")
;; (propertize " → " 'face 'shadow)
(propertize (combobulate-pretty-print-node current-node) 'face
'combobulate-tree-highlighted-node-face)
(mapconcat (lambda (k)
(propertize (key-description k) 'face 'help-key-binding))
;; messy; is this really the best way?
(where-is-internal 'next map)
", ")
(if allow-numeric-selection (concat "; \\`C-1' to \\`C-9' to select") "")
(if (and flash-node combobulate-flash-node)
(concat "\n"
(or (combobulate-display-draw-node-tree
(combobulate-proxy-node-to-real-node current-node))
""))
"")))))
(cl-flet ((refactor-action (action)
(cond ((eq action 'commit)
(commit))
((eq action 'rollback)
(rollback))
(t (error "Unknown action: %s" action)))))
(and before-switch-fn (funcall before-switch-fn))
(when recenter (ignore-errors (recenter)))
;; if we have just one item, or if
;; `:first-choice' is non-nil, we pick the first
;; item in `proxy-nodes'
(if (or (= (length proxy-nodes) 1) first-choice)
(progn (refactor-action accept-action)
(setq state 'accept))
(run-hooks 'combobulate-proffer-after-action-hook)
(setq result
(condition-case nil
(lookup-key
map
;; we need to preserve the raw
;; event so we can put it back on
;; the unread event loop later if
;; the key is not recognised.
(setq raw-event
;; hooooo boy; so the
;; terminal does not like
;; certain keys (or key
;; sequences) and misbehaves
;; especially if something
;; like TAB is used. On a
;; console, we'll use the one
;; way I know that does work
;; (albeit imperfectly as it
;; swallows whole complete
;; key sequences not bound in
;; this key map, and it also
;; echoes the key which is
;; annoying). On a graphical
;; display, we'll use the
;; normal way.
(if (display-graphic-p)
(vector (read-key prompt))
(read-key-sequence-vector prompt))))
;; if `condition-case' traps a quit
;; error, then map it into the symbol
;; `cancel', which corresponds to the
;; equivalent event in the state
;; machine below.
(quit 'cancel)
(t (rollback) 'cancel)))
(run-hooks 'combobulate-proffer-after-action-hook)
(and after-switch-fn (funcall after-switch-fn))
(pcase result
('prev
(refactor-action switch-action)
(setq index (mod (1- index) (length proxy-nodes)))
(throw 'next nil))
('next
(refactor-action switch-action)
(setq index (mod (1+ index) (length proxy-nodes)))
(throw 'next nil))
('done
(refactor-action accept-action)
(unless quiet (combobulate-message "Committing" current-node))
(setq state 'accept))
((pred functionp)
(funcall result)
(refactor-action accept-action)
(throw 'next nil))
('cancel
(unless quiet (combobulate-message "Cancelling..."))
(setq state 'abort)
(refactor-action cancel-action)
(keyboard-quit))
;; handle numeric selection `1' to `9'
((and (pred (numberp))
(pred (lambda (n) (and (>= n 1)
(<= n 9)
(<= n (length proxy-nodes)))))
n)
(refactor-action switch-action)
(setq index (1- n))
(throw 'next nil))
(_
(unless quiet (combobulate-message "Committing..."))
;; pushing `raw-event' to
;; `unread-command-events' allows for a
;; seamless exit out of the proffer
;; prompt by preserving the the last,
;; unhandled event the user inputted.
(when (length> raw-event 0)
(push (aref raw-event 0) unread-command-events))
(refactor-action accept-action)
(setq state 'accept)))
(run-hooks 'combobulate-proffer-after-action-hook)))))
(when change-group
(cancel-change-group change-group)))
(activate-change-group change-group))))
(quit (when signal-on-abort
(signal (car err) (cdr err)))))
;; Determine where point is placed on exit and whether we return
;; the current node or not.
(cond
((and (eq state 'abort))
(when reset-point-on-abort (goto-char pt))
nil)
((and (eq state 'accept))
(when reset-point-on-accept
(goto-char pt))
current-node)
(t (error "Unknown termination state `%s'" state)))))