-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmoldable-emacs.el
2549 lines (2258 loc) · 93 KB
/
moldable-emacs.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
;;; moldable-emacs.el --- Moldable Development Extension -*- lexical-binding: t; -*-
;; Copyright (C) 2023 Andrea
;; Author: Andrea <[email protected]>
;; Version: 20211115-snapshot
;; URL: https://github.com/ag91/moldable-emacs
;; Package-Requires: ((emacs "26.1") (dash "2.19.1") (s "1.12.0") (async "1.9.4"))
;; Keywords: convenience
;; 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/>.
;;; Commentary:
;; This is an extension of Emacs aiming to enable Moldable
;; Development. Or better still, aiming to make you a better story
;; teller when you deal with code.
;;; Code:
(require 'dash)
(require 's)
(require 'async)
(require 'thunk)
(require 'cl-lib)
(defgroup moldable-emacs nil
"Customize group for Moldable-Emacs."
:group 'convenience
:prefix "me-")
(defcustom me-i-know-what-i-am-doing
nil
"Set this to t if don't need to see tutorials."
:group 'moldable-emacs)
(defcustom me-files-with-molds
(--map
(concat
(file-name-directory load-file-name) ; https://stackoverflow.com/questions/26991001/elisp-get-path-to-file-relative-to-script
it)
(list
"molds/core.el"
"molds/contrib.el"))
"Files containing molds."
:group 'moldable-emacs)
(defcustom me-molds-debug-on
nil
"Toggle for debugging information."
:group 'moldable-emacs)
(defcustom me-use-treesitter t
"Use https://github.com/emacs-tree-sitter to produce concrete syntax trees, if nil we will use built-in treesit.el."
:group 'moldable-emacs)
(defun me-setup-molds ()
"Load molds from `me-files-with-molds'."
(-each me-files-with-molds #'load-file))
(defun me-plistp (list)
"Tell if LIST is a property list.
>> (me-plistp '(:a 1 :b 2))
=> t
>> (me-plistp '(:a 1 :b))
=> nil
>> (me-plistp '(1))
=> nil"
(let ((evenp (lambda (x) (= 0 (mod x 2))))
(all-keys t))
(and
(listp list)
(funcall evenp (length list))
(= (/ (length list) 2)
(length
(--keep
(and
(funcall evenp it-index)
(setq
all-keys
(and
all-keys
(symbolp it)
(s-starts-with-p
":"
(symbol-name it))))
it)
list))
)
all-keys)))
(defun me-get-in (plist keys)
"Navigate PLIST's KEYS in sequence.
For example, (me-get-in '(:a (:b (:c 1))) '(:a :b :c)) yields 1.
>> (me-get-in '(:a (:b 1)) '(:a :b))
=> 1
>> (me-get-in '(:a (:b 1)) '(1 :b))
=> 1
>> (me-get-in '((a . ((b . 1)))) '(a b))
=> 1
>> (me-get-in '(:a (1 2 3)) '(:a))
=> (1 2 3)
"
(let ((access
(lambda (key list)
(if (me-plistp plist)
(plist-get list key)
(alist-get key list)))))
(--reduce-from
(if (numberp it)
(nth it acc)
(funcall access it acc))
plist
keys)))
(defmacro me-with-file (file &rest body)
"Open FILE, execute BODY close FILE if it was not already open."
`(let ((old-buffer (current-buffer))
(kill-buffer-p (not (get-file-buffer ,file))))
(unwind-protect
(progn
(find-file ,file)
,@body)
(progn
(when kill-buffer-p (kill-buffer))
(switch-to-buffer old-buffer)))))
(put 'me-with-file 'lisp-indent-function 1)
(defun me-async-map--finish (futures post-fn too-late-p poll-time)
"Run FUTURES and apply POST-FN on their results.
Use TOO-LATE-P and POLL-TIME to stop."
(if (not (-some #'null (mapcar #'async-ready futures)))
(let ((results (--map
(let ((buf (process-buffer it)))
(with-current-buffer buf
(async-handle-result
#'identity
async-callback-value
(current-buffer))))
futures)))
(funcall post-fn results))
(if (funcall too-late-p)
'interrupted
(run-with-timer
poll-time
nil
#'me-async-map--finish
futures
post-fn
too-late-p
poll-time))))
(defun me-async-map (fn els &optional post-fn poll-time timeout) ;; TODO maybe I can just use this https://github.com/chuntaro/emacs-promise
"Run FN async on elements ELS.
Optionally define a POST-FN to run on the results of apply FN on ELS.
Optionally define a POLL-TIME to look for results and a TIMEOUT to fail."
(let* ((start (current-time))
(futures (mapcar
(lambda (el)
(async-start (lambda ()
(setq load-path load-path)
(funcall fn el))))
els))
(too-late-p
(lambda () (>= (time-to-seconds (time-since start)) (or timeout 300)))))
(me-async-map--finish
futures
(or post-fn (lambda (results)
(message (format "me-async-map finished with the following results:\n%s" results))
'completed))
too-late-p
(or poll-time 1))))
;; (me-async-map
;; (lambda (x) (make-directory x 't))
;; (list "/tmp/bla" "/tmp/blo" "/tmp/blu")
;; (lambda (_) (message "%s" (directory-files "/tmp"))))
(defun me-pmap (fn els &optional poll-time timeout) ;; TODO maybe I can just use this https://github.com/chuntaro/emacs-promise
"Run FN in parallel on elements ELS.
Optionally define a POST-FN to run on the results of apply FN on ELS.
Optionally define a POLL-TIME to look for results and a TIMEOUT to fail."
(let* ((start (current-time))
(futures (mapcar
(lambda (el)
(async-start `(lambda ()
(setq load-path ',load-path)
(funcall ,fn (if ,(seqp el) ',el ,el)))))
els))
(too-late-p
`(lambda () (>= (time-to-seconds (time-since ',start)) (or ,timeout 300)))))
(while (some #'null (mapcar #'async-ready futures))
(when (funcall too-late-p) (error "Me-pmap has waited too long: timed out"))
(sleep-for (or poll-time 0.2)))
(--map
(let ((buf (process-buffer it)))
(with-current-buffer buf
(async-handle-result
#'identity
async-callback-value
(current-buffer))))
futures)))
(defun me-print-to-buffer (object &optional buffer)
"Print OBJECT in BUFFER without truncation."
(let ((print-length nil)
(eval-expression-print-length nil))
(pp-display-expression object (or buffer (current-buffer)))))
(defun me-make-org-table (headlines objects)
"Make an Org Table with OBJECTS formats and HEADLINES.
>> (me-make-org-table '((\"a\" . (:extractor identity)) (\"b\" . (:extractor identity :handler (lambda (x) (concat x \"hi\"))))) '(\"1\" \"2\"))
=> \"| a | b |
|--+--|
| 1 | 1hi |
| 2 | 2hi |\""
(concat
(concat "| " (s-join " | " (-map #'car headlines)) " |\n")
(concat "|-" (format (s-repeat (- (length headlines) 1) "-+-")) "-|\n")
(s-join
"\n"
(--map (concat
"| "
(s-join
" | "
(-map
(lambda (headline)
(let ((result (funcall (plist-get (cdr headline) :extractor) it))
(handler (plist-get (cdr headline) :handler)))
(if handler
(funcall handler result)
result)))
headlines))
" |")
objects))))
(defun me-insert-string-table (table-string)
"Insert TABLE-STRING in buffer.
Make sure table is also indented."
(insert table-string)
(save-excursion
(search-backward "|" nil nil 2) ;; count 2 to avoid an extra (empty) row at the bottom
(org-cycle))
(setq-local org-confirm-elisp-link-function nil))
(defun me-insert-org-table (headlines objects)
"Produce org table of OBJECTS formatting with HEADLINES."
(me-insert-string-table (me-make-org-table headlines objects)))
(defun me-alist-to-plist (alist)
"Convert ALIST to a `plist'.
>> (me-alist-to-plist '((a . 1) (b . 2)))
=> (:a 1 :b 2)
>> (me-alist-to-plist '((:a . 1) (:b . 2)))
=> (:a 1 :b 2)
>> (me-alist-to-plist '((\"a\" . 1) (\"b\" . 2)))
=> (:a 1 :b 2)"
(when (-every? #'consp alist)
(-flatten
(--map
(list
(intern
(s-replace
"\""
""
(let ((key (prin1-to-string (car it))))
(if (s-starts-with-p ":" key)
key
(concat ":" key)))))
(cdr it))
alist))))
(defun me-org-table-as-alist-to-plist (alist)
"Convert ALIST to a `plist'.
>> (me-org-table-as-alist-to-plist '((\"a\" \"b\" \"c\") (\"1\" \"2\" \"3\")))
=> ((:a \"1\" :b \"2\" :c \"3\"))"
(let ((keys (ignore-errors
(and (= (length (car alist)) (length (-filter #'stringp (car alist))))
(--map (intern (concat ":" it)) (car alist))))))
(if keys
(--map (-flatten (-zip-lists keys it)) (cdr alist))
alist)))
(defun me-plist-org-table-to-table-with-headings (&optional org-table-lisp)
"Transform a table obtained from a plist (ORG-TABLE-LISP),
so with keyword entries, into a org table with headings.
>> (me-plist-org-table-to-table-with-headings '((\":a\" \"9\" \":b\" \"8\")))
=> \"|a|b|
|9|8|\""
(let ((lisp-table (or org-table-lisp (org-table-to-lisp))))
(--> lisp-table
(--map
(--> (-map 'substring-no-properties it)
(--remove (s-starts-with-p ":" it) it))
it)
(cons (--keep (and (s-starts-with-p ":" it) (s-replace ":" "" (substring-no-properties it))) (car lisp-table)) it)
(--map (format "|%s|" (s-join "|" it)) it)
(s-join "\n" it))))
(defun me-org-table-to-plist (table-string)
"Make TABLE-STRING a plist.
>> (me-org-table-to-plist \"| a | b |
|---+---|
| x | y |
| w | z |
\")
=> (:a (\"x\" \"w\") :b (\"y\" \"z\"))"
(with-temp-buffer
(save-excursion (insert table-string))
(org-table-transpose-table-at-point)
(let ((table (org-table-to-lisp))
result)
(dolist (r table result)
(when (listp r) (setq result (plist-put result (intern (concat ":" (s-replace "\"" "" (car r)))) (cdr r))))))))
(defun me-org-table-to-flat-plist (table-string)
"Convert Org mode table TABLE-STRING to a list of plists."
(let* ((plist (me-org-table-to-plist table-string))
(keys (-filter 'symbolp plist)))
(--> keys
(--map (-map (lambda (x) (list it (substring-no-properties x))) (plist-get plist it)) it)
(apply '-zip it)
(-map '-flatten it))))
(defun me-flat-org-table-to-string (flat-org-table)
"Make a string out of FLAT-ORG-TABLE.
>> (me-flat-org-table-to-string '((:a 1 :b 2) (:a 3 :b 4)))
=> \"| a | b |
|--+--|
| 1 | 2 |
| 3 | 4 |\""
(me-make-org-table
(--map
(list (substring (symbol-name it) 1) . (:extractor `(lambda (x) (format "%s" (plist-get x ,it)))))
(-filter #'keywordp (car flat-org-table)))
flat-org-table))
(defalias 'me-plist-table-to-org-table 'me-flat-org-table-to-string)
(defun me-insert-flat-org-table (flat-org-table)
"Insert FLAT-ORG-TABLE in current buffer."
(me-insert-string-table (me-flat-org-table-to-string flat-org-table)))
(defun me-org-tabletolisp-to-plist (org-table-to-lisp)
"Create a plist of ORG-TABLE-TO-LISP obtained by `org-table-to-lisp' fn."
(--> org-table-to-lisp
(orgtbl-to-orgtbl it nil)
(me-org-table-to-flat-plist it)))
(defmacro me-with-org-parent-heading (&rest body)
"Execute BODY with narrowing on the upmost parent heading if it exists."
`(save-excursion
(while (org-up-heading-safe))
(with-demoted-errors (org-narrow-to-subtree))
(condition-case err
(let ((r__ (progn ,@body)))
(widen)
r__)
(error
(widen)
(error err)))
))
(defun me-first-org-table (&optional buffer)
"Find first org table. Optionally in BUFFER."
(ignore-errors
(when (equal major-mode 'org-mode)
(with-current-buffer (or buffer (current-buffer)) ;; TODO remove org links in table!
(me-with-org-parent-heading
(re-search-forward org-table-line-regexp nil t)
(me-org-tabletolisp-to-plist (org-table-to-lisp)))))))
(defun me-all-flat-org-tables (&optional buffer whole-buffer)
"Find org tables within current headline or in whole buffer if no headline found.
Optionally in input BUFFER. Search in WHOLE-BUFFER, if t."
(ignore-errors
(with-current-buffer (or buffer (current-buffer)) ;; TODO remove org links in table!
(me-with-org-parent-heading
(when whole-buffer
(goto-char 0)
(widen))
(let (result)
(while (and
(re-search-forward org-table-line-regexp nil t)
(goto-char (- (org-table-end) 1)))
(setq result
(cons (me-org-tabletolisp-to-plist (org-table-to-lisp))
result)))
result)))))
(defun me-types (tree)
"List types in current syntax TREE.
>> (me-types '((:type a) (:type b)))
=> (a b)"
(--> tree
(--map (plist-get it :type) it)
-distinct))
(defun me-by-type (type tree)
"Filter TREE entries by TYPE.
>> (me-by-type 'a '((:type a :text \"hi\") (:type b)))
=> ((:type a :text \"hi\"))"
(when (symbolp type)
(--filter (eq (plist-get it :type) type) tree)))
(defun me-by-types (types tree)
"Filter TREE entries by any of the TYPES.
>> (me-by-types '(a b) '((:type a :text \"hi\") (:type b)))
=> ((:type a :text \"hi\") (:type b))"
(--filter (-contains? types (plist-get it :type)) tree))
(defun me-by-node-text (pred tree)
"Filter TREE entries by a PRED on node text.
>> (me-by-node-text (lambda (it) (equal \"hi\" it)) '((:type a :text \"hi\") (:type b)))
=> ((:type a :text \"hi\"))"
(--filter (funcall pred (plist-get it :text)) tree))
(defun me-count-by-key (key list)
"Group LIST by KEY and count groups.
>> (me-count-by-key :a '((:a \"x\") (:a \"x\") (:a \"y\")))
=> ((:a \"x\" :count 2) (:a \"y\" :count 1))"
(--> list
(--group-by (plist-get it key) it)
(--map (list key (car it) :count (length (cdr it))) it)
(--sort (> (plist-get it :count) (plist-get other :count)) it)))
(defun me-mold-treesit-to-parse-tree (&optional node)
"Return list of all abstract syntax tree nodes one step away from leaf nodes.
Optionally start from NODE. Note this keeps text properties in
the :text property of a node."
(let ((root (or
node
(with-demoted-errors "me-mold-treesit-to-parse-tree: %S"
(treesit-parse-string ;; in treesit we parse the file only if using a lang-ts-mode
(buffer-string)
(me-major-mode-to-tree-sitter-grammar major-mode)))))
(make-node (lambda (n level)
(list
:type (intern (treesit-node-type n))
:text (substring-no-properties (treesit-node-text n))
:begin (treesit-node-start n)
:end (treesit-node-end n)
:buffer (buffer-name)
:buffer-file (when buffer-file-name
(s-replace (getenv "HOME") "~"
buffer-file-name))
:mode major-mode
:level level))))
(when root
(cl-labels
((fn (node level)
(mapcar (lambda (n)
(setq acc (cons
(funcall make-node n level)
acc))
(fn n (1+ level)))
(treesit-node-children node))))
(setq-local acc nil)
(fn root 0)
(cons
(funcall make-node root 0)
(reverse acc))))))
(defun me-tree-node-at-point (point)
(if me-use-treesitter
(me-to-parse-tree (tree-sitter-node-at-point :named point))
(treesit-node-at point nil 'named)))
(defun me-mold-treesitter-to-parse-tree (&optional node)
"Return list of all abstract syntax tree nodes one step away from leaf nodes.
Optionally start from NODE."
(let ((root (or
node
(ignore-errors (tsc-root-node tree-sitter-tree)))))
(when root
(cl-labels
((fn (node level)
(tsc-mapc-children
(lambda (n)
(setq acc (cons
(list
:type (tsc-node-type n)
:text (tsc-node-text n)
:begin (tsc-node-start-position n)
:end (tsc-node-end-position n)
:buffer (buffer-name)
:buffer-file (when buffer-file-name
(s-replace (getenv "HOME") "~"
buffer-file-name))
:mode major-mode
:level level)
acc))
(fn n (1+ level)))
node)))
(setq-local acc nil)
(fn root 0)
(cons (list
:type (tsc-node-type root)
:text (tsc-node-text root)
:begin (tsc-node-start-position root)
:end (tsc-node-end-position root)
:buffer (buffer-name)
:buffer-file (when buffer-file-name
(s-replace (getenv "HOME") "~"
buffer-file-name))
:mode major-mode
:level 0)
(reverse acc))))))
(defun me-to-parse-tree (&optional node)
"Return list of all abstract syntax tree nodes one step away from leaf nodes.
Optionally start from NODE."
(if me-use-treesitter
(me-mold-treesitter-to-parse-tree node)
(me-mold-treesit-to-parse-tree node)))
(defun me-extension-to-major-mode (extension)
"Find `major-mode' for EXTENSION.
>> (me-extension-to-major-mode \".el\")
=> emacs-lisp-mode"
(cdr (--find (s-match (car it) extension) auto-mode-alist)))
(defun me-major-mode-to-tree-sitter-grammar (major-mode)
"Find emacs-tree-sitter grammar for MAJOR-MODE."
(if me-use-treesitter
(alist-get major-mode tree-sitter-major-mode-language-alist)
(treesit-language-at (point))))
(defun me-extension-to-tree-sitter-grammar (extension)
"Find emacs-tree-sitter grammar for EXTENSION."
(--> extension
me-extension-to-major-mode
me-major-mode-to-tree-sitter-grammar))
(defun me--treesitter-filepath-to-flattened-tree (file &optional contents)
(when-let ((grammar (me-extension-to-tree-sitter-grammar (file-name-extension file t))))
(with-temp-buffer
(if contents (insert contents) (insert-file-contents-literally file))
(let ((buffer-file-name file)
(tree-sitter-language (tree-sitter-require grammar))
(tree-sitter-parser (tsc-make-parser)))
(tsc-set-language tree-sitter-parser tree-sitter-language)
(--> (tsc--without-restriction
(tsc-parse-chunks tree-sitter-parser #'tsc--buffer-input nil)) ; TODO this seems to break for non unicode files
tsc-root-node
me-to-parse-tree)))))
(defun me--treesit-filepath-to-flattened-tree (file &optional contents)
(when-let ((grammar (me-extension-to-tree-sitter-grammar (file-name-extension file t))))
(--> (or contents (with-temp-buffer (insert-file-contents-literally file) (buffer-string)))
(treesit-parse-string it grammar))
(treesit-parse-string it grammar)
me-to-parse-tree-new))
(defun me-filepath-to-flattened-tree (file &optional contents)
"Return the flattened tree for FILE.
Optionally use CONTENTS string instead of file contents."
(if me-use-treesitter (me--treesitter-filepath-to-flattened-tree file contents)
(me--treesit-filepath-to-flattened-tree file contents)))
(defun me-nodes-with-duplication (self)
"Find nodes that are duplicated for SELF."
(-remove
'null
(--map
(-flatten ; do not need enclosing list
(let ((-compare-fn (lambda (a b) (string= (plist-get a :text) (plist-get b :text)))) ;; this is for making -distinct apply on the :text property
(nodes-for-single-type (cdr it)))
(--reduce-from ; find duplicate
(-remove-first ; by removing only the first matching node text
(lambda (x) (string= (plist-get x :text) (plist-get it :text)))
acc)
nodes-for-single-type
(-distinct nodes-for-single-type))))
(--filter
(symbolp (car it)) ; taking only the nodes that tree-sitter recognize with a syntax identifier
(--group-by (plist-get it :type) self)))))
(defvar me-available-molds nil "Available molds.")
(defvar me-mold-history nil "List of molds produced.")
(defvar me-mold-before-hook nil "Hooks to run before running a mold.")
(defvar me-mold-after-hook nil "Hooks to run after running a mold.")
(defvar me-mold-before-mold-runs-hook nil "Hooks to run before the chosen mold runs.")
(defun me-interpret-given (mold)
"Interpret MOLD :given clause into a sexp to run."
(me-get-in mold '(:given :fn)))
(defun me-interpret-then (mold)
"Interpret MOLD :then clause into a sexp to run."
(let ((then (plist-get mold :then)))
(cond
((ignore-errors (car (plist-get then :async)))
`(let ((_ (async-let ,(plist-get then :async)
(progn
,(plist-get then :fn)
(ignore-errors
(switch-to-buffer-other-window
(get-buffer buffername)))))))
(get-buffer-create buffername)
(with-current-buffer buffername
(erase-buffer)
(insert (format "Loading %s contents..." ,(plist-get mold :key))))))
((ignore-errors (car (plist-get then :no-async)))
`(let* ,(plist-get then :no-async)
(progn
(get-buffer-create buffername)
,(plist-get then :fn)
(ignore-errors
(switch-to-buffer-other-window
(get-buffer buffername))))))
((-contains-p then :fn)
`(progn
(get-buffer-create buffername)
,(plist-get then :fn)
(ignore-errors
(switch-to-buffer-other-window
(get-buffer buffername))))))))
(defun me-mold-buffername (mold)
"Get the resulting buffer name of MOLD."
(concat "*moldable-emacs-" (or (plist-get mold :buffername) (plist-get mold :key)) "*"))
(defmacro me-with-mold-let (mold &rest clause) ;; TODO this must evaluate only once any time is called AND needs to make evaluation of bindings lazy?
"Wrap BODY in a let with :let and :buffername of MOLD, plus add the body for CLAUSE."
(let ((m (-clone mold))) ;; for some strange reason, it seems that a mold with (:let ((1 ..) (2 ..) (3 ..))) ends up with (:let ((1 ..))) if I use thunk-let* on the original mold, so I clone it
`(funcall
(lambda (m clause)
(eval
`(progn
(let ((buffername ,(me-mold-buffername m)))
(,(if (ignore-errors (eq (car clause) :then))
'let*
'thunk-let*)
(,@(plist-get m :let))
(pcase ',clause
('(:given) ,(me-interpret-given m))
('(:then) ,(me-interpret-then m))
(_ ,@clause)))))
't))
,m
',clause)))
(put 'me-with-mold-let 'lisp-indent-function 1)
;; (me-print-to-buffer (let ((mold (me-find-mold "PlistToJson")))
;; (me-with-mold-let mold
;; :then))
;; (get-buffer-create "bla"))
(defun me-mold-run-given (mold)
"Run MOLD :given."
(unless (me-get-in mold '(:given :fn)) (error "For now all molds need to declare :given with :fn"))
(me-with-mold-let (-clone mold)
:given))
(defvar me-usable-mold-stats nil)
(defun me-mold-specificity (mold)
"An attempt to quantify how specific a MOLD is in this context.
This is a naive implementation because we just count how many parentheses are in the :given of the mold: if there is a lot of nesting molds come on top.
Ideally we want to give a score to the specificity of the
predicates in the :given (like checking for a major mode has more
weight than checking for a dependency on the system because you
must have a specific kind of buffer open, while the dependency is
always on the system.) "
(s-count-matches "(" (format "%s" (let* ((given (plist-get mold :given)))
(if (ignore-errors (equal 'me-mold-run-given (car (nth 1 given))))
(plist-get (eval (nth 1 (nth 1 given))) :given)
given)))))
(defun me-usable-molds (&optional molds buffer)
"Return the usable molds among the `me-available-molds'.
Optionally you can pass your own candidate MOLDS.
Optionally you can pass a BUFFER to use instead of the `current-buffer'."
(let ((_ (setq me-usable-mold-stats nil))
(molds (or molds me-available-molds))
(buffer (or buffer (current-buffer))))
(with-current-buffer buffer
(--> molds
(--filter
(let* ((beginning (current-time))
(result (save-excursion
(condition-case err
(me-mold-run-given it)
(error (message "me-usable-molds: error in :given of %s:\n %s" (plist-get it :key) err))))) ; TODO composite molds
(ending (current-time))
(_ (when me-molds-debug-on
(let ((key (plist-get it :key))
(expended-time (time-to-seconds
(time-subtract
ending
beginning))))
(add-to-list 'me-usable-mold-stats (list :mold key
:time
expended-time))
(when (>= expended-time 1)
(warn
(button-buttonize
(format "%s took over 1 sec: %s" key expended-time)
`(lambda (x)
(me-goto-mold-source ,key)))))))))
result) ;; TODO run this in parallel when time goes over 100ms)
it)
;; sort by specificity of molds: TODO using n of parentheses in :then as a shortcut
(--sort (> (me-mold-specificity it)
(me-mold-specificity other))
it)))))
(defun me-usable-p (mold-key)
"Check if MOLD-KEY mold is usable."
(= (length
(-non-nil
(me-usable-molds
(list (me-find-mold mold-key)))))
1))
(defun me-mold-run-then (mold)
"Run MOLD :then."
(unless (me-get-in mold '(:then :fn)) (error "For now all molds need to declare :then with :fn"))
(me-with-mold-let mold :then))
(defvar me-mold-whens nil "All :when clauses of molds to check periodically.")
(defun me-mold (&optional mold-key view-fn)
"Propose a list of available molds for the current context.
Use MOLD-KEY as chosen mold when it is provided and usable.
Use VIEW-FN to show result buffer when provided."
(interactive)
(run-hooks 'me-mold-before-hook)
(let* ((beginning (current-time))
(molds (me-usable-molds))
(keys (--map (plist-get it :key) molds))
(ending (current-time))
(_ (when me-molds-debug-on
(message "Finding molds took %s seconds in total." (time-to-seconds
(time-subtract
ending
beginning))))))
(--> keys
(or (when (-contains-p keys mold-key) mold-key)
(completing-read
"Pick the mold you need:"
it))
(-find
(lambda (x)
(string=
(plist-get x :key)
it))
molds)
(funcall
(lambda (mold)
(--each
me-mold-before-mold-runs-hook
(funcall it mold))
mold)
it)
me-mold-run-then) ; TODO how can I use VIEW-FN ?
(run-hooks 'me-mold-after-hook)))
(defun me-add-when-to-periodic-check (mold)
"Add MOLD :when clause to `me-mold-whens'."
(-when-let* ((w (plist-get mold :when))
(mold-b (me-mold-buffername mold))
(current-b (buffer-name)))
(setq me-mold-whens (-distinct
(cons
(list
:when w
:mold-buffer mold-b
:mold-key (plist-get mold :key)
:current-buffer current-b)
me-mold-whens)))))
(add-hook 'me-mold-before-mold-runs-hook 'me-add-when-to-periodic-check)
(defun me-get-visible-buffers ()
"Return buffer names that are visible now."
(let (result) ; taken from helm-buffers-get-visible-buffers
(walk-windows
(lambda (x)
(push (buffer-name (window-buffer x)) result))
nil 'visible)
result))
(defun me-run-whens ()
"Run molds :then clauses for `me-mold-whens' clauses that are satisfied."
(--each me-mold-whens
(save-excursion
(when (and
;; both original buffer are visible: it means I am looking at them and I want automatic updates
(-contains? (me-get-visible-buffers) (plist-get it :mold-buffer))
(-contains? (me-get-visible-buffers) (plist-get it :current-buffer))
;; the when clause is satisfied
(eval (me-get-in it '(:when :fn))))
;; save current window config
(let ((window-config (current-window-configuration)))
;; go to :current-buffer
(switch-to-buffer (plist-get it :current-buffer))
;; run the :then clause of :mold-key mold
(message "Running then in buffer %s" (buffer-name) )
(me-mold-run-then (me-find-mold (plist-get it :mold-key)))
;; restore old window config
(set-window-configuration window-config))))))
(defcustom me-no-when-updates nil
"When non-nil, it prevents automatic refresh of molds.
When a :when clause is defined on the mold and the relevant buffers are visible,
`moldable-emacs' tries to refresh the mold according to the `:when' clause trigger logic.")
(unless me-no-when-updates (run-with-idle-timer 0.8 t 'me-run-whens))
(defun me-mold-compose-molds (mold1 mold2)
"Compose MOLD1 and MOLD2 in a new mold."
`(
:key ,(format
"CompositionOf%sAnd%s"
(plist-get mold1 :key)
(plist-get mold2 :key))
:given (:fn (me-mold-run-given ',mold1)) ;; we need me-mold-run-given because we need to propagate the :let bindings
:then (:fn
(progn (me-mold-run-then ',mold1)
(me-mold-run-then ',mold2)
;; (delete-window (get-buffer-window (plist-get ',mold1 :buffername)))
(switch-to-buffer buffername)
(kill-buffer-and-window)
(rename-buffer buffername)
(switch-to-buffer buffername)))))
(defun me-mold-compose (m1 m2 &optional props)
"Compose M1 and M2 in a single mold.
Add PROPS (e.g., `(:docs \"...\" :examples nil)') to it."
(let ((mold1 (if (stringp m1) (me-find-mold m1) m1))
(mold2 (if (stringp m2) (me-find-mold m2) m2)))
(if (and mold1 mold2)
(let ((result (me-mold-compose-molds mold1 mold2)))
(--each props
(plist-put result (nth 0 it) (nth 1 it)))
result)
(error (format "Could not find molds, check out: %s." (list m1 m2))))))
(defvar me-temporary-mold-data nil "Holder of mold data before it is assigned to local variable `mold-data'.")
(defun me-setup-self-mold-data ()
"Setup `me-temporary-mold-data' for setting up `mold-data' in mold buffer."
(setq me-temporary-mold-data
(list
:old-self (ignore-errors self)
:old-buffer (buffer-name)
:old-file (buffer-file-name)
:old-point (point)
:old-mode major-mode
:old-date (ignore-errors (plist-get mold-data :date))
:old-mold me-last-used-mold)))
(add-hook 'me-mold-before-hook #'me-setup-self-mold-data)
(defun me-get-marked-dired-files ()
"Get marked `dired' files."
(goto-char (point-min))
(dired-get-marked-files))
(defun me-get-all-dired-files ()
"Get all `dired' files."
(mark-whole-buffer)
(call-interactively #'dired-mark)
(let ((files (dired-get-marked-files)))
(call-interactively #'dired-unmark-all-files)
files))
(defun me-set-dired-self-for-playground ()
"Set Playground `self' to dired list of files."
(when
(and
(s-starts-with-p "Playground" me-last-used-mold)
(ignore-errors mold-data)
(eq (plist-get mold-data :old-mode) 'dired-mode))
(setq-local self
(with-current-buffer (plist-get mold-data :old-buffer)
(or (me-get-marked-dired-files)
(me-get-all-dired-files))))))
(add-hook 'me-mold-after-hook #'me-set-dired-self-for-playground) ;; the order is important: keep before me-set-self-mold-data
(defun me-set-self-mold-data ()
"Set `mold-data'."
(setq-local mold-data
(append
(list
:self (ignore-errors self)
:date (format-time-string "%FT%T%z"))
me-temporary-mold-data)))
(add-hook 'me-mold-after-hook #'me-set-self-mold-data -100)
(defvar me-last-example nil "Last automatically generated example for mold.
This should simplify the testing and documentation of molds.")
(defcustom me-example-resource-dir
(concat (file-name-directory load-file-name) "resources/")
"Directory containing resources for examples (like media files)."
:group 'moldable-emacs
:type 'string)
(defun me-record-given-of-example ()
"Reset and store in `me-last-example' the given of a mold example."
(let* ((type (if (buffer-file-name) 'file 'buffer))
(point (point))
(name (or (buffer-file-name) (buffer-name)))
(mode major-mode)
(contents (if (eq mode 'image-mode)
(let ((filename (concat
me-example-resource-dir
(file-name-nondirectory name))))
(write-region
(point-min)
(point-max)
filename)
filename)
(buffer-substring-no-properties (point-min) (point-max)))))
(setq me-last-example
`(:given
(
:type ,type
:name ,name
:mode ,mode
:contents ,contents
:point ,point)))))
(defun me-record-then-of-example ()
"Reset and store in `me-last-example' the then of a mold example."
(let* ((type (if (buffer-file-name) 'file 'buffer))
(name (or (buffer-file-name) (buffer-name)))
(mode major-mode)
(contents (if (eq mode 'image-mode)
(let ((filename (concat
me-example-resource-dir
(file-name-nondirectory name))))
(write-region
(point-min)
(point-max)
filename)
filename)
(buffer-substring-no-properties (point-min) (point-max)))))
(plist-put
me-last-example
:then
`(
:type ,type
:name ,name
:mode ,mode
:contents ,contents))))
(add-hook 'me-mold-before-hook #'me-record-given-of-example)
(add-hook 'me-mold-after-hook #'me-record-then-of-example)
(defun me-warn-on-run-if-no-example (mold)
"Emit warning if MOLD has no examples."
(unless (or (not me-molds-debug-on) (plist-get mold :examples))
(warn
(button-buttonize