-
Notifications
You must be signed in to change notification settings - Fork 4
/
norns.el
1307 lines (1058 loc) · 48.1 KB
/
norns.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
;;; norns.el --- Interactive development environment for monome norns -*- lexical-binding: t; -*-
;; Copyright (C) 2022 Jordan Besly
;;
;; Version: 0.0.3
;; Keywords: processes, terminals
;; URL: https://github.com/p3r7/norns.el
;; Package-Requires: ((emacs "27.1")(dash "2.17.0")(s "1.12.0")(f "0.20.0")(request "0.3.2")(websocket "1.13")(lua-mode "20221218.605"))
;;
;; SPDX-License-Identifier: MIT
;;; Commentary:
;;
;; This package provides an interactive development for monome norns.
;;
;; This package allows to spawn REPLs that bind to remote matron and
;; SuperCollider REPLs (via commands `norns-matron-repl', `norns-sc-repl')
;; and associated commands to interact with them from Lua and SuperCollider
;; source files.
;;
;; All commands (unless specified otherwise) will analyze if currently
;; visited file is on a norns. If it's the case, this particular norns is
;; targeted by the command execution. Otherwise the default norns instance
;; (configurable w/ `norns-host' / `norns-mdns-domain' is targeted
;; instead). This behaviors can be changed by setting value of
;; `norns-access-policy' to ":current" or ":default".
;;
;; To connect to a REPL, use commands `norns-matron-repl' and
;; `norns-sc-repl'. Those REPL provide prompts but one can send text
;; through the minibuffer with `norns-matron-send' and `norns-sc-send'.
;;
;; Commands that send input to any of the REPL will automatically make the
;; REPL pop in a window if not already visible. This can be turned off by
;; setting `norns-repl-switch-on-cmd' to nil.
;;
;; Additionally, to send a selected region to the appropriate REPL, use
;; `norns-matron-send-selection'.
;;
;; The currently visited script can be loaded with
;; `norns-load-current-script'. If current script has several
;; "sub-scripts", you'll get prompted to select one.
;;
;; `norns-load-script' will list all the scripts on current norns instance
;; and will load the one you would select.
;;
;; For detailed instructions, please look at the README.md at https://github.com/p3r7/norns.el/blob/master/README.md
;;; Code:
;; DEPS
(require 'dash)
(require 's)
(require 'rx)
(require 'f)
(require 'tramp)
(require 'request)
(require 'websocket)
(require 'lua-mode)
;; VARS
(defvar norns-access-policy :current-fallback-default)
(defvar norns-user "we" "Default norns user.")
(defvar norns-host "norns" "Default norns hostname.")
(defvar norns-http-port 80 "Default norns HTTP port.")
(defvar norns-mdns-domain "local" "Default norns mDNS (aka zeroconf).")
(defvar norns-docker-container "norns-test-dummy" "Default norns docker container name.")
(defvar norns-docker-http-port 5000 "Default norns docker HTTP port.")
(defvar norns-lan-domain nil
"Default LAN mDNS (aka zeroconf), typically when accessing a
norns on a network that blocks mDNS.
Routers generally have this set to \"lan\" or \"home\".")
(defvar norns-screenshot-folder "/home/we/dust/" "Folder where to dump screenshots.")
(defvar norns-matron-ws-port 5555 "Default norns matron REPL websocket port.")
(defvar norns-matron-ws-socket-alist nil "Alist containing HOST / MATRON-WS-SOCKET associations.")
(defvar norns-matron-buffer-prefix "matron" "Prefix for name of matron REPL buffers.")
(defvar norns-matron-buff-alist nil "Alist containing HOST / MATRON-COMINT-BUFFER associations.")
(defvar norns-matron-repl-prompt "matron>> " "Customizable matron REPL buffer prompt.")
(defconst norns-matron-repl-prompt-internal "matron>> "
"Version of `norns-matron-repl-prompt' for handling when it gets
redefined at runtime.")
(defvar norns-lua-lib-inspect-url "https://raw.githubusercontent.com/kikito/inspect.lua/master/inspect.lua")
(defvar norns-lua-static-doc-url "https://monome.org/docs/norns/api/modules/")
(defvar norns-sc-ws-port 5556 "Default norns SuperCollider REPL websocket port.")
(defvar norns-sc-ws-socket-alist nil "Alist containing HOST / SC-WS-SOCKET associations.")
(defvar norns-sc-buffer-prefix "norns-sc" "Prefix for name of SuperCollider REPL buffers.")
(defvar norns-sc-buff-alist nil "Alist containing HOST / SC-COMINT-BUFFER associations.")
(defvar norns-sc-repl-prompt "sc>> " "Customizable SuperCollider REPL buffer prompt.")
(defconst norns-sc-repl-prompt-internal "sc>> "
"Version of `norns-sc-repl-prompt' for handling when it gets
redefined at runtime.")
(defvar norns-repl-switch-on-cmd t
"If non-nil, switch to matron/SuperCollider REPL buffer after
sending it a command.")
(defvar norns-repl-switch-fn #'switch-to-buffer-other-window "Function to use when `norns-repl-switch-on-cmd' is non-nil.")
(defvar norns-repl-switch-no-focus t
"If non-nil, don't have popping REPL window steal focus after
calling `norns-repl-switch-fn'.")
(defvar norns-mode-lighter " norns" "Lighter for norns minor mode.")
;; CONSTS - PATHS
(defconst norns-script-path-prefix "/home/we/dust/code/" "Path of script dir on norns.")
(defconst norns-script-rx
(rx bol
(literal norns-script-path-prefix)
(group (one-or-more (any "a-z" "A-Z" "0-9" "-" "_" ".")))
"/"
(group (one-or-more (any "a-z" "A-Z" "0-9" "-" "_" "."))) ".lua"
eol))
(defconst norns-in-script-dir-rx
(rx bol
(literal norns-script-path-prefix)
(group (one-or-more (any "a-z" "A-Z" "0-9" "-" "_")))
"/"))
;; CONSTS - LUA SYMBOLS
(defconst norns-lua-special-fns
'("init" "cleanup"
"redraw"
"key" "enc"
("params" . ("action_read" "action_write" "action_delete"))
("osc" . ("event"))
("midi" . ("add" "remove" "event"))
("arc" . ("add" "remove"))
("grid" . ("add" "remove"))
("keyboard" . ("code" "char"))
("gamepad" . ("dpad" "analog" "axis" "button")))
"List of norns script-redefinable special lua functions.")
(defconst norns-lua-buitin-consts
'("inf")
"List of norns built-in lua constants.")
(defconst norns-lua-buitin-globals
'("_norns" ; weaver
"_startup" "engine"
("keyboard" . ("keymap" "selected_map"))
("norns" . ("battery_current" "battery_percent" "blank" "cpu" "cpu_avg" "crow" "disk" "enc" "encoders" "expand_filesystem" "init_done" "is_norns" "is_shield" "menu" "menu_midi_event" "none" "platform" "pmap" "rerun" "script" "scripterror" "shutdown" "state" "system_cmd" "system_glob" "temp" "try" "version"))
("_path" . ("enabled_mods" "dust" "data" "home" "tape" "code" "keyboard_layout"
"favorites" "extn" "audio"))
("_menu" . ("page" "errormsg" "rebuild_params" "alt" "timer" "panels" "locked" "key" "previewfile" "keychar" "panel" "shownav" "gamepad_axis" "custom_gamepad_axis" "set_page" "mode" "enc" "scripterror" "showstats" "keycode" "draw_panel" "redraw" "penc" "m" "set_mode" "gamepad_button"))
)
"List of norns built-in global lua state vars.")
(defconst norns-lua-buitin-lib-module-methods
'(
;; scheduling
("metro" . ("start" "stop"))
("poll" . ("callback" "time" "start" "stop" "update"))
;; params
("params" . (
;; contructor
"add" "add_separator" "add_group"
"add_trigger" "add_option" "add_number" "add_control"
"add_file" "add_text" "add_taper" "add_binary"
"set_action"
;; visibility
"hide" "show" "visible"
;; lookup props
"print" "list" "get_id" "lookup_param" "t" "get_range" "get_allow_pmap"
;; value
"get" "get_raw" "string"
"set" "set_raw"
"bang" "clear"
;; pset
"write" "read" "delete" "default"
))
;; i/o
("midi" . ("send" "note_on" "note_off" "cc" "pitchbend" "key_pressure" "channel_pressure" "program_change" "start" "stop" "continue" "clock" "song_position" "song_select"))
("arc" . ("led" "all" "segment" "refresh" "delta"))
("grid" . ("led" "all" "refresh" "intensity" ))
("gamepad" . ("up" "down" "left" "right"))
)
"List of norns built-in lua functions.")
(defconst norns-lua-buitin-lib-module-fns
'(
"include"
;; scheduling
("clock" . ("run" "cancel" "sleep" "sleep" "sync" "tempo_change_handler"))
("metro" . ("init" "new" "free" "free_all" "available" "assigned"))
("poll" . ("list_names" "set" "clear_all"))
;; UX
("screen" . ("clear" "update" "update_default" "update_low_battery"
"ping"
"aa" "level" "line_width" "line_cap" "line_join" "miter_limit"
"move" "move_rel"
"pixel"
"line" "line_rel" "rect"
"arc" "circle" "curve" "curve_rel"
"close" "stroke" "fill"
"text" "text_rotate" "text_right" "text_center" "text_center_rotate" "text_extents" "font_face" "font_size"
"display_png" "load_png" "create_image" "display_image" "display_image_region" "draw_to"
"peek" "poke"
"rotate" "translate" "save" "blend_mode"))
;; i/o
("osc" . ("send"))
("midi" . ("connect" "to_msg" "to_data"))
("arc" . ("connect"))
("grid" . ("connect"))
;; utils
("tab" . ("print" "sort" "count" "contains" "invert" "key" "lines" "split" "save" "load" "readonly" "gather" "update" "select_values"))
("util" . ("time" "scandir" "file_exists" "file_size" "make_dir" "os_capture" "string_starts" "trim_string_to_width" "clamp" "linexp" "linlin" "explin" "expexp" "round" "round_up" "s_to_hms" "degs_to_rads" "rads_to_degs" "acronym" "wrap" "wrap_max"))
)
"List of norns built-in lua methods.")
;; CORE
(defun norns--deep-merge-alists (l1 l2)
(let ((l1c (copy-alist l1)))
(mapc (lambda (el)
(if (and (consp el)
(assoc (car el) l1c))
(let* ((k (car el))
(v (cdr el))
(other-v (cdr (assoc k l1c))))
;; (push (cons k (append other-v v)) l1c) ; append (std way to replace value in alist)
(setf (cdr (assoc k l1c)) (append other-v v))) ; set in place
;; else, standard elem
(push el l1c)))
l2)
l1c))
;; EXTRA FONT LOCK - LUA
(defgroup norns-lua-extra-font-lock nil
"Faces for highlighting text."
:prefix "norns-lua-extra-font-lock-"
:group 'faces)
(defface norns-lua-extra-font-lock-norns-constant
'((t :inherit font-lock-constant-face))
"The face used to highlight norns' own builtin."
:group 'norns-lua-extra-font-lock)
(defface norns-lua-extra-font-lock-norns-builtin
'((t :inherit font-lock-builtin-face))
"The face used to highlight norns' own builtin."
:group 'norns-lua-extra-font-lock)
(defface norns-lua-extra-font-lock-norns-special-fn
'((t :inherit font-lock-warning-face))
"The face used to highlight norns' own builtin."
:group 'norns-lua-extra-font-lock)
(defun norns-lua-get-buitin-lib-modules ()
(-reduce #'norns--deep-merge-alists (list norns-lua-buitin-globals norns-lua-buitin-lib-module-fns norns-lua-buitin-lib-module-methods)))
(eval-and-compile
(defconst
norns--lua-special-fns-rx
(cl-labels
((module-name-re (x)
(concat "\\(?1:\\_<"
(if (listp x) (car x) x)
"\\_>\\)"))
(module-members-re (x) (if (listp x)
(concat "\\(?:[ \t]*\\.[ \t]*"
"\\_<\\(?2:"
(regexp-opt (cdr x))
"\\)\\_>\\)?")
"")))
(concat
;; common prefix:
;; - beginning-of-line
;; - or neither of [ '.', ':' ] to exclude "foo.string.rep"
;; - or concatenation operator ".."
"\\(?:^\\|[^:. \t]\\|[.][.]\\)"
;; optional whitespace
"[ \t]*"
"\\(?:"
;; any of modules/functions
(mapconcat (lambda (x) (concat (module-name-re x)
(module-members-re x)))
norns-lua-special-fns
"\\|")
"\\)"))
"A regexp that matches norns' special script-level functions."))
;; NB; instpired by `lua-mode''s `lua--builtins'
(eval-and-compile
(defconst
norns--lua-builtins-rx
(let*
((modules (norns-lua-get-buitin-lib-modules)))
(cl-labels
((module-name-re (x)
(concat "\\(?1:\\_<"
(if (listp x) (car x) x)
"\\_>\\)"))
(module-members-re (x) (if (listp x)
(concat "\\(?:[ \t]*\\.[ \t]*"
"\\_<\\(?2:"
(regexp-opt (cdr x))
"\\)\\_>\\)?")
"")))
(concat
;; common prefix:
;; - beginning-of-line
;; - or neither of [ '.', ':' ] to exclude "foo.string.rep"
;; - or concatenation operator ".."
"\\(?:^\\|[^:. \t]\\|[.][.]\\)"
;; optional whitespace
"[ \t]*"
"\\(?:"
;; any of modules/functions
(mapconcat (lambda (x) (concat (module-name-re x)
(module-members-re x)))
modules
"\\|")
"\\)")))
"A regexp that matches norns' Lua builtin functions & variables."))
(eval-and-compile
(defconst
norns--lua-builtins-params-rx
(let*
((modules
`(("params" . ,(cdr (assoc "params" norns-lua-buitin-lib-module-methods))))))
(cl-labels
((module-name-re (x)
(concat "\\(?1:\\_<"
(if (listp x) (car x) x)
"\\_>\\)"))
(module-members-re (x) (if (listp x)
(concat "\\(?:[ \t]*:[ \t]*"
"\\_<\\(?2:"
(regexp-opt (cdr x))
"\\)\\_>\\)?")
"")))
(concat
;; common prefix:
;; - beginning-of-line
;; - or neither of [ '.', ':' ] to exclude "foo.string.rep"
;; - or concatenation operator ".."
"\\(?:^\\|[^:. \t]\\|[.][.]\\)"
;; optional whitespace
"[ \t]*"
"\\(?:"
;; any of modules/functions
(mapconcat (lambda (x) (concat (module-name-re x)
(module-members-re x)))
modules
"\\|")
"\\)"))))
"A regexp that matches norns' Lua builtin global \"params\" object.")
(defun norns--lua-make-font-lock-keywords ()
`((,norns--lua-builtins-rx
(1 'norns-lua-extra-font-lock-norns-builtin) (2 'norns-lua-extra-font-lock-norns-builtin nil noerror))
(,norns--lua-builtins-params-rx
(1 'norns-lua-extra-font-lock-norns-builtin) (2 'norns-lua-extra-font-lock-norns-builtin nil noerror))
(,norns--lua-special-fns-rx
(1 'norns-lua-extra-font-lock-norns-special-fn) (2 'norns-lua-extra-font-lock-norns-special-fn nil noerror))))
;; DOC
(defvar norns--lua-modules-doc-aliases
'(("screen" . "Screen")
("tab" . "lib.tabutil")
("util" . "lib.util"))
"Aliases between norns lua modules as found in code and reference in doc")
;; inspired by `lua-search-documentation'
(defun norns--std-lua-search-doc (fn)
(let ((url (concat lua-documentation-url "#pdf-" fn)))
(funcall lua-documentation-function url)))
(defun norns--norns-lua-search-doc (fn)
(let* ((module (car (s-split-up-to "." fn 1)))
(url (concat norns-lua-static-doc-url module ".html#" fn)))
(funcall lua-documentation-function url)))
(defun norns--lua-fn-doc ()
(interactive)
(let ((fn (lua-funcname-at-point)))
(norns--std-lua-search-doc fn)
))
;; CORE - PATH
(defun norns--core-curr-fq-path ()
"Get path (i.e. file-name in Emacs lingo) of current buffer.
it is fully qualified, i.e. w/ a TRAMP prefix if the connection is remote."
(if (member major-mode '(dired-mode shell-mode))
default-directory
(buffer-file-name)))
(defun norns--core-tramp-extract-path (tramp-path)
"Remove tramp prefix out of TRAMP-PATH, keeping only the filesystem path."
(let (vec _localname)
(setq vec (ignore-errors (tramp-dissect-file-name tramp-path)))
(if vec
(tramp-file-name-localname vec)
(user-error "Couldn't parse tramp path %s" tramp-path))))
(defun norns--core-untrampify-path-maybe (fp)
"If FP is a TRAMP path, keep only the filesystem path (remove prefix)."
(if (file-remote-p fp)
(norns--core-tramp-extract-path fp)
fp))
(defun norns--core-trampify-path-maybe (fp)
"If `default-directory' is remote, add TRAMP prefix to FP."
(if (file-remote-p default-directory)
;; REVIEW: there's certainly a TRAMP fn to do this...
(let ((tramp-prefix (s-chop-suffix (norns--core-untrampify-path-maybe default-directory)
default-directory)))
(concat tramp-prefix fp))
fp))
(defun norns--core-curr-path ()
"Get current buffer filesystem path."
(norns--core-untrampify-path-maybe (norns--core-curr-fq-path)))
(defun norns--host-sans-domain (host)
"Remove any mDNS suffix"
(--> host
(s-chop-suffix (concat "." norns-mdns-domain) it)
(if norns-lan-domain (s-chop-suffix (concat "." norns-lan-domain) it) it)))
(defun norns--host-with-domain (host)
(let ((domain (or norns-lan-domain norns-mdns-domain)))
(concat host "." domain)))
(defun norns--core-curr-host-sans-domain ()
"Get current hostname (for matron / sc), sans mDNS domain suffix.
Defaults to \"localhost\" if not a TRAMP path."
(let ((remote-host (file-remote-p default-directory 'host)))
(cond
((and remote-host
(s-starts-with? "/docker:" default-directory))
"localhost")
(remote-host
(norns--host-sans-domain remote-host))
(t
"localhost"))))
(defun norns--core-curr-host ()
"Get current hostname (for matron / sc)."
(norns--host-with-domain (norns--core-curr-host-sans-domain)))
(defun norns--core-curr-http-port ()
"Get current HTTP port (for matron web)."
(cond
((and (file-remote-p default-directory 'host)
(s-starts-with? "/docker:" default-directory))
norns-docker-http-port)
(t
norns-http-port)))
;; CORE - WEBSOCKET-BACKED COMINT BUFFER
(defun norns--comint-true-line-beginning-position ()
"Get true line beginning position.
Indeed, `comint-mode' tricks w/ `line-beginning-position' to make
it ignore the prompt."
(save-excursion
(let ((pos (line-beginning-position))
(linum (line-number-at-pos)))
(beginning-of-line)
(left-char)
(if (eq linum (line-number-at-pos)) ; on prompt line
(line-beginning-position) ; true position
pos))))
(defun norns--comint-process ()
"Get (dummy) process for (current) comint buffer."
(get-buffer-process (current-buffer)))
(defun norns--comint-set-pm (pos)
"Set marker POS for (dummy) process in (current) comint buffer."
(set-marker (process-mark (get-buffer-process (current-buffer))) pos))
(defun norns--comint-pm nil
"Get marker for last output of (dummy) process."
(process-mark (get-buffer-process (current-buffer))))
(defun norns--comint-async-output-for-host (host-buff-alist host prompt txt)
"Write TXT to comint buffer for HOST.
The comint buffer for HOST is stored in value of symbol HOST-BUFF-ALIST.
Ends output with a PROMPT to make comint believe it was a
standard command execution."
(let* ((buff (cdr (assoc host (symbol-value host-buff-alist))))
(visiting-windows (get-buffer-window-list buff 't))
(eof-visiting-windows (--filter (with-selected-window it
(eobp))
visiting-windows))
(output (concat txt prompt))
prompt-entry)
(with-current-buffer buff
(save-excursion
(goto-char (point-max))
;; remove active prompt
(unless (eq (norns--comint-true-line-beginning-position) (line-end-position))
(unless (eq (line-beginning-position) (line-end-position))
(setq prompt-entry (buffer-substring (line-beginning-position) (line-end-position))))
(delete-region (norns--comint-true-line-beginning-position) (line-end-position)))
;; insert incoming line + new prompt
(comint-output-filter (norns--comint-process) output)
(when prompt-entry
(goto-char (point-max))
(insert prompt-entry)))
;; make visiting windows "follow" (akin to `eshell-scroll-to-bottom-on-output')
(when visiting-windows
(message "moving: %s" eof-visiting-windows)
(--map (set-window-point it (point-max)) eof-visiting-windows)))))
(defun norns--comint-register-buffer-for-host (host-buff-alist host prefix comint-mode)
"Create new comint buffer for HOST and register it in HOST-BUFF-ALIST.
This buffer will have major COMINT-MODE activated on it and be
named \"*PREFIX/HOST*\"."
(let ((buff (get-buffer-create (concat "*" prefix "/" host "*"))))
(with-current-buffer buff
(funcall comint-mode))
(add-to-list host-buff-alist
(cons host buff))
buff))
(defun norns--comint-ensure-buffer-for-host-exists (host-buff-alist host buff-register-fn)
"Ensure comint buffer for HOST exists.
If not, create it and register it in HOST-BUFF-ALIST by calling
BUFF-REGISTER-FN."
(let ((buff (cdr (assoc host (symbol-value host-buff-alist)))))
(if (buffer-live-p buff)
buff
(funcall buff-register-fn host))))
(defun norns--comint-ensure-host-ws-open (host-ws-alist
host ws-port
ensure-host-buffer-exists-fn comint-output-fn)
"Ensure websocket for norns HOST is open.
The websocket for HOST is stored in value of symbol HOST-WS-ALIST.
Also ensures the existence of associated comint output buffer by
calling ENSURE-HOST-BUFFER-EXISTS-FN. WS-PORT is the remote
websocket listening port.
COMINT-OUTPUT-FN is the function that
gets called to pipe websocket output to the associated comint
buffer."
(unless (websocket-openp (cdr (assoc host (symbol-value host-ws-alist))))
(add-to-list
host-ws-alist
(cons
host
(websocket-open (format "ws://%s:%d" host ws-port)
:custom-header-alist '((Sec-WebSocket-Protocol . "bus.sp.nanomsg.org"))
:on-open (lambda (_ws)
(funcall ensure-host-buffer-exists-fn host))
:on-message (lambda (_ws frame)
(funcall ensure-host-buffer-exists-fn host)
(funcall comint-output-fn host (websocket-frame-text frame)))
:on-close (lambda (_ws)
(funcall ensure-host-buffer-exists-fn host)
(funcall comint-output-fn host "\nwebsocket closed\n")))))))
(defun norns--ws-send (cmd
host-ws-alist host-comint-buff-alist
ensure-ws-open-fn ensure-comint-buff-exists-fn)
"Send CMD to current norns via websocket.
Depending on value of `norns-repl-switch-on-cmd', eventually pop
a window to its associated REPL (comint buffer).
Current norns is determined with
`norns--location-from-access-policy', depending on the value of
`norns-access-policy'.
From it the associated websocket and comint buffer are retrieved
from HOST-WS-ALIST and HOST-COMINT-BUFF-ALIST, respectively.
We ensure those two exist by calling ENSURE-WS-OPEN-FN and
ENSURE-COMINT-BUFF-EXISTS-FN."
(let* ((default-directory (norns--location-from-access-policy))
(host (norns--core-curr-host)))
(funcall ensure-ws-open-fn host)
(funcall ensure-comint-buff-exists-fn host)
(let* ((frame (selected-frame))
(win (selected-window))
(comint-buff (cdr (assoc host (symbol-value host-comint-buff-alist))))
(visiting-windows (get-buffer-window-list comint-buff)))
(websocket-send-text (cdr (assoc host (symbol-value host-ws-alist))) (concat cmd "\n"))
(when (and norns-repl-switch-on-cmd
(null visiting-windows))
(apply norns-repl-switch-fn (list comint-buff))
(goto-char (point-max))
(when norns-repl-switch-no-focus
(set-frame-selected-window frame win))))))
;; NORNS - PATH
(defun norns--current-host-norns-p ()
"Return t if host of `default-directory' is a norns."
(f-directory? (norns--core-trampify-path-maybe "/home/we/dust")))
(defun norns--make-default-norns-tramp-prefix ()
"Build the tramp prefix for default norns (`norns-user' @ `norns-host').
If `tramp-default-method' is \"docker\" we assume a local docker instance.
In that case `norns-user' @ `norns-docker-container' gets used."
(let* ((hostname (cond
((string= tramp-default-method "docker") norns-docker-container)
(t (norns--host-with-domain norns-host)))))
(concat "/" tramp-default-method ":"
norns-user "@" hostname ":")))
(defun norns--make-default-norns-tramp-path ()
"Build the tramp path for default norns (`norns-user' @ `norns-host')."
(concat (norns--make-default-norns-tramp-prefix) "/home/" norns-user "/dust/"))
(defun norns--location-from-access-policy ()
"Find current norns file path to work on based on `norns-access-policy'.
With default value \":current-fallback-default\", tries first on
`default-directory' (assuming we're visiting a norns), then
fallback to remote `norns-host'.
With value \"current\", will only try `default-directory' and
fail if it's not a norns.
With value \"default\", will always ignore `default-directory'
and use remote `norns-host'."
(cond
((eq norns-access-policy :current-fallback-default)
(or (and (norns--current-host-norns-p) default-directory)
(norns--make-default-norns-tramp-path)))
((eq norns-access-policy :current)
(unless (norns--current-host-norns-p)
(user-error "Not visiting a norns!"))
default-directory)
(:default
(norns--make-default-norns-tramp-path))))
;; NORNS - PATH - SCRIPTS
(defun norns--script-path-p (fp)
"Return t if FP is a script path."
(s-matches-p norns-script-rx fp))
(defun norns--script-from-path (fp)
"Extract script name from FP."
(cdr (s-match norns-script-rx fp)))
(defun norns--in-script-dir-path-p (fp)
"Return t if FP is visiting somewhere under a script dir."
(s-matches-p norns-in-script-dir-rx fp))
(defun norns--script-dir-from-path (fp)
"Extract script dir name from FP."
(nth 1 (s-match norns-in-script-dir-rx fp)))
(defun norns-all-scripts ()
"Get list of scripts on current norns.
Current norns is determined with
`norns--location-from-access-policy', depending on the value of
`norns-access-policy'."
(let ((default-directory (norns--location-from-access-policy)))
(--> (f-glob (norns--core-trampify-path-maybe
(concat norns-script-path-prefix "*/*.lua")))
(-map #'norns--core-untrampify-path-maybe it)
(-map #'norns--script-from-path it))))
(defun norns-current-scripts ()
"Get list of scripts corresponding to currently visited buffer."
(unless (norns--current-host-norns-p)
(user-error "Not visiting a norns!"))
(let* ((fp (norns--core-curr-path)))
(unless (s-starts-with? norns-script-path-prefix fp)
(user-error "Not visiting a script source!"))
(cond
((norns--script-path-p fp)
(list (norns--script-from-path fp)))
((norns--in-script-dir-path-p fp)
(let ((script-dir (norns--script-dir-from-path fp)))
(--> (f-glob (norns--core-trampify-path-maybe
(concat norns-script-path-prefix script-dir "/*.lua")))
(-map #'norns--core-untrampify-path-maybe it)
(-map #'norns--script-from-path it))))
(:default (error "Unexpected error")))))
;; NORNS - MATRON
(defun norns--matron-output (host txt)
"Function to forward output TXT from matron websocket to the
corresponding comint buffer for HOST."
(norns--comint-async-output-for-host 'norns-matron-buff-alist host norns-matron-repl-prompt-internal txt))
(defun norns--register-matron-buffer (host)
"Create a new matron comint buffer for HOST and register it in
`norns-matron-buff-alist'."
(norns--comint-register-buffer-for-host 'norns-matron-buff-alist host norns-matron-buffer-prefix #'norns-matron-repl-mode))
(defun norns--ensure-host-matron-buffer-exists (host)
"Ensure that a matron comint buffer for HOST exists in `norns-matron-buff-alist'."
(norns--comint-ensure-buffer-for-host-exists 'norns-matron-buff-alist host #'norns--register-matron-buffer))
(defun norns--ensure-host-matron-ws-open (host)
"Ensure socket for norns HOST is open.
The REPL (comint buffer) for HOST is stored in `norns-matron-ws-socket-alist'.
Also ensures the existence of matron output buffer (stored in
`norns-matron-buff-alist')."
(norns--comint-ensure-host-ws-open 'norns-matron-ws-socket-alist host
norns-matron-ws-port
#'norns--ensure-host-matron-buffer-exists
#'norns--matron-output))
(defun norns--remove-lua-comments (cmd)
"Remove Lua comments from CMD."
(--> cmd
(replace-regexp-in-string "--\\[\\[\\(.\\|\n\\)*?\\]\\]" "" it) ; multi-line: --[[ ... ]]
(replace-regexp-in-string "--.*" "" it))) ; single-line: -- ...
(defun norns-matron-send (cmd)
"Send CMD to norns via matron and eventually pop a window to the REPL buffer."
(interactive "s> ")
(cond
((string= ";restart" cmd)
(norns-matron-restart))
;; REVIEW: isn't working, might be a CORS thing
;; ((s-starts-with? ";install " cmd)
;; (norns-matron-install-script (s-chop-prefix ";install " cmd)))
(:default
(norns--ws-send (s-replace "\n" "; " (norns--remove-lua-comments cmd))
'norns-matron-ws-socket-alist
'norns-matron-buff-alist
#'norns--ensure-host-matron-ws-open
#'norns--ensure-host-matron-buffer-exists))))
(defun norns-matron-send-selection ()
"Send selected buffer region to matron."
(interactive)
(cond
((use-region-p)
(norns-matron-send (buffer-substring (region-beginning) (region-end)))
(deactivate-mark))
(:default (message "no selection"))))
(defun norns--inject-inspect-lib ()
"Inject inspect.lua library onto norns."
(let* ((default-directory (norns--location-from-access-policy))
(tmp-dir (--> (temporary-file-directory)
(if (s-ends-with? "/" it) it (concat it "/"))))
(dest-file (concat tmp-dir "inspect.lua")))
(unless (file-exists-p dest-file)
(url-copy-file norns-lua-lib-inspect-url dest-file))))
(defun norns-matron-inspect-symbol (symbol)
"Inspect value of SYMBOL at point in matron.
If no symbol at point, prompt.
Please note that it will only work properly for non-local lua vars."
(interactive (list
(if (use-region-p)
(let ((selection (buffer-substring (region-beginning) (region-end))))
(read-string (format "var (%s): " selection)
nil nil selection))
(let ((tap (thing-at-point 'symbol)))
(if tap
(read-string (format "var (%s): " tap)
nil nil tap)
(read-string "var: "))))))
(norns--inject-inspect-lib)
(norns-matron-send (s-join "; " (list "local inspect = require '/tmp/inspect'"
(concat "print(inspect(" symbol "))")))))
;; COMMANDS - SCRIPT LOAD
(defun norns-rerun ()
"Rerun current script, if any."
(interactive)
(norns-matron-send "if norns.state.name ~= \"none\" then norns.rerun() end"))
(defun norns-load-script-raw (script-name)
"Ask norns to load SCRIPT-NAME."
(interactive "sName: ")
(unless (s-contains? "/" script-name)
(setq script-name (concat script-name "/" script-name)))
(norns-matron-send (concat "norns.script.load(\"code/" script-name ".lua\")")))
(defun norns--load-script-helper (scripts)
"Prompt user to select one of the SCRIPTS and then ask for norns to launch it."
(let ((scripts-prompt (--map
(if (string= (car it) (nth 1 it))
it
(cons (s-join "/" it) it))
scripts))
script)
(if (eq (length scripts) 1)
(setq script (car scripts))
(setq script (--> (completing-read "Choose: " scripts-prompt)
(cdr (assoc it scripts-prompt)))))
(if script
(norns-load-script-raw (s-join "/" script))
(message "canceled"))))
(defun norns-load-script ()
"Load script from list.
Prompt user to select any of the existing scripts and then ask
for current norns to launch it.
Current norns is determined with
`norns--location-from-access-policy', depending on the value of
`norns-access-policy'."
(interactive)
(norns--load-script-helper (norns-all-scripts)))
(defun norns-load-current-script ()
"Load currently visited script.
If visiting a script folder, and more than 1 script is found in
it, prompt user to select one."
(interactive)
(let ((norns-access-policy :current))
(norns--load-script-helper (norns-current-scripts))))
;; MAJOR MODE - MATRON REPL
(defun norns--matron-input-sender (_proc input)
"Send comint INPUT to norns' matron (via websocket).
Output is processed asyncronously by `norns--matron-output'."
(norns-matron-send input))
(define-derived-mode norns-matron-repl-mode comint-mode "matron-repl"
"Major mode for interracting w/ a monome norns' matron REPL."
:keymap (let ((mmap (make-sparse-keymap)))
mmap)
(setq comint-prompt-regexp (concat "^" (regexp-quote norns-matron-repl-prompt)))
(setq comint-input-sender #'norns--matron-input-sender)
(setq comint-process-echoes nil)
;; A dummy process to keep comint happy. It will never get any input
(unless (comint-check-proc (current-buffer))
;; Was cat, but on non-Unix platforms that might not exist, so
;; use hexl instead, which is part of the Emacs distribution.
(condition-case nil
(start-process "matron" (current-buffer) "hexl")
(file-error (start-process "matron" (current-buffer) "cat")))
(set-process-query-on-exit-flag (norns--comint-process) nil)
(goto-char (point-max))
(norns--comint-set-pm (point-max))
(unless comint-use-prompt-regexp
(let ((inhibit-read-only t))
(add-text-properties
(point-min) (point-max)
'(rear-nonsticky t field output inhibit-line-move-field-capture t))))
(comint-output-filter (norns--comint-process) norns-matron-repl-prompt-internal)
(set-marker comint-last-input-start (norns--comint-pm))
(set-process-filter (get-buffer-process (current-buffer)) #'comint-output-filter)))
(defun norns-matron-repl ()
"Connect to the matron REPL for current norns and switch to it.
If already connected, just switch to the buffer.
Current norns is determined depending on the value of `norns-access-policy'."
(interactive)
(let* ((default-directory (norns--location-from-access-policy))
(host (norns--core-curr-host)))
(switch-to-buffer (norns--ensure-host-matron-buffer-exists host))))
(defun norns-docker-matron-repl ()
"Same as `norns-matron-repl' but assuming a local docker instance.
See values of `norns-docker-container' for the targeted instance."
(interactive)
(unless (assoc "docker" tramp-methods)
(user-error "Missing \"docker\" TRAMP method, plase install package `docker-tramp'."))
(let ((norns-access-policy :default)
(tramp-default-method "docker"))
(call-interactively #'norns-matron-repl)))
(defun norns--matron-repl-after-start (dd)
"Force reconnection to matron REPL upon (re)start.
Host is identified by it's path DD."
(let* ((default-directory dd)
(host (norns--core-curr-host))
(frame (selected-frame))
(win (selected-window))
(matron-buff (norns--ensure-host-matron-buffer-exists host))
(matron-visiting-windows (get-buffer-window-list matron-buff)))
(when (and norns-repl-switch-on-cmd
(null matron-visiting-windows))
(funcall norns-repl-switch-fn matron-buff)
(goto-char (point-max))
(when norns-repl-switch-no-focus
(set-frame-selected-window frame win))))
;; NB: REPLs seem to need a "ping" to send their startup logs
(run-at-time
0.1 nil
`(lambda ()
(let ((default-directory ,dd))
(norns-matron-send "")))))
(defun norns-matron-restart ()
"Restart matron REPL for current norns."
(interactive)
(let* ((default-directory (norns--location-from-access-policy))
(dd default-directory)
(host (norns--core-curr-host))
(port (number-to-string (norns--core-curr-http-port))))
(request
(concat "http://" host ":" port "/api/v1/unit/norns-matron.service")
:params '(("do" . "restart"))
:parser 'json-read
:success (cl-function
(lambda (&key _data &allow-other-keys)
(norns--matron-repl-after-start dd)
;; (message "Got: %S" data)
)))))
(defun norns-matron-install-script (script-url)
"Install norns SCRIPT-URL."
(interactive "s> ")
(let* ((default-directory (norns--location-from-access-policy))
(host (norns--core-curr-host))
(port (number-to-string (norns--core-curr-http-port))))