-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathq-mode.el
More file actions
1756 lines (1549 loc) · 72.8 KB
/
q-mode.el
File metadata and controls
1756 lines (1549 loc) · 72.8 KB
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
;;; q-mode.el --- A q editing mode -*- lexical-binding: t -*-
;; Copyright (C) 2006-2026 Nick Psaris <nick.psaris@gmail.com>
;; Keywords: faces files q
;; Package-Requires: ((emacs "28"))
;; Created: 8 Jun 2015
;; Version: 0.1
;; URL: https://github.com/psaris/q-mode
;; This file is not part of GNU Emacs.
;; This file 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, or (at your option)
;; any later version.
;; This file 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:
;; A major mode for editing q (the language written by Kx Systems, see
;; URL `https://code.kx.com') in Emacs.
;; Some of its major features include:
;;
;; - syntax highlighting (font-lock-mode),
;;
;; - syntax checking (flymake-mode),
;;
;; - interaction with inferior q[con] instance (comint-mode),
;;
;; - variable and function indexing (imenu),
;;
;; - completion at point (CAPF),
;;
;; - signature help (eldoc),
;;
;; - definition/reference navigation (xref),
;;
;; - code folding (hideshow).
;;
;; To load `q-mode' on-demand, instead of at startup, add this to your
;; initialization file
;; (autoload 'q-mode "q-mode")
;; Then add the following to your initialization file to open all .k
;; and .q files with q-mode as major mode automatically:
;; (add-to-list 'auto-mode-alist '("\\.[kq]\\'" . q-mode))
;; If you load ess-mode, it will attempt to associate the .q extension
;; with S-mode. To stop this, add the following lines to your
;; initialization file.
;; (defun remove-ess-q-extn ()
;; (when (assoc "\\.[qsS]\\'" auto-mode-alist)
;; (setq auto-mode-alist
;; (remassoc "\\.[qsS]\\'" auto-mode-alist))))
;; (add-hook 'ess-mode-hook 'remove-ess-q-extn)
;; (add-hook 'inferior-ess-mode-hook 'remove-ess-q-extn)
;; Use `M-x q' to start an inferior q shell. Or use `M-x q-qcon' to
;; create an inferior qcon shell to communicate with an existing q
;; process. Both can be prefixed with the universal-argument `C-u` to
;; customize the arguments used to start the processes.
;; The first q[con] session opened becomes the activated buffer.
;; To open a new session and send code to the new buffer, it must be
;; activated. Switch to the desired buffer and type `C-c M-RET' to
;; activate it.
;; Displaying tables with many columns will wrap around the buffer -
;; making the data hard to read. You can use the
;; `toggle-truncate-lines' function to prevent the wrapping. You can
;; then scroll left and right in the buffer to see all the columns.
;; The following commands are available to interact with an inferior
;; q[con] process/buffer. `C-c C-j' (as well as `C-c C-l' and
;; `C-M-x') sends a single line, `C-c C-f' sends the surrounding
;; function, `C-c C-s' sends the symbol at point, `C-c C-r' sends
;; the selected region and `C-c C-b' sends the whole buffer. If
;; prefixed with `C-u C-u', or pressing `C-c M-j' `C-c M-f' `C-c
;; M-s' `C-c M-r' respectively, will also switch point to the active
;; q process buffer for direct interaction.
;; If the source file exists on the same machine as the q process,
;; `C-c M-l' can be used to load the file associated with the active
;; buffer.
;; `C-c C-g' triggers a manual rescan of the project, re-scanning only
;; files whose mtime has changed. Prefix with `C-u' to force all files
;; to be re-scanned regardless of mtime, which is useful after a branch
;; switch where file timestamps may be preserved.
;; Quick access to variable and function definitions can be obtained
;; using the `imenu' binding `M-g i'. Completion is available via
;; `completion-at-point' (usually `M-TAB'). Candidates are annotated
;; with their kind (<function>, <variable>, <keyword>, or <builtin>).
;; Eldoc displays signatures while you type, and xref provides `M-.'
;; for definitions, `M-?' for references, and `C-M-.' for apropos
;; search across all known identifiers in the project.
;; Code folding is available via `hs-minor-mode'. Once enabled, use
;; the standard hideshow bindings to fold and unfold {} blocks.
;; `which-function-mode' is supported and will display the name of the
;; enclosing function in the mode line as you move point. Enable it
;; globally with (which-function-mode 1) in your initialization file,
;; or per-buffer with M-x which-function-mode.
;; `M-x customize-group' can be used to customize the `q' group.
;; Specifically, the `q-program' and `q-qcon-program' variables can be
;; changed depending on your environment. The `q-rescan-idle-delay'
;; variable controls how long to wait after a save before rescanning;
;; it debounces rapid saves and defers the check for out-of-band disk
;; changes such as those made by git pull.
;; Q-mode indents each level based on `q-indent-step'. To indent code
;; based on {}-, ()-, and []-groups instead of equal width tabs, you
;; can set this value to nil.
;; The variables `q-msg-prefix' and `q-msg-postfix' can be customized
;; to prefix and postfix every msg sent to the inferior q[con]
;; process. This can be used to change directories before evaluating
;; definitions within the q process and then changing back to the root
;; directory. To make the variables change values depending on which
;; file they are sent from, values can be defined in a single line at
;; the top of each .q file:
;; / -*- q-msg-prefix: "system \"d .jnp\";"; q-msg-postfix: ";system \"d .\"";-*-
;; or at the end:
;; / Local Variables:
;; / q-msg-prefix: "system \"d .jnp\";"
;; / q-msg-postfix: ";system \"d .\""
;; / End:
(require 'cl-lib)
(require 'comint)
(require 'compile)
(require 'auth-source nil t)
(require 'hideshow nil t)
(require 'project nil t)
(require 'xref nil t)
;;; Code:
;; local variable for the flymake-dedicated q process
(defvar-local q--flymake-proc nil)
(defgroup q nil "Major mode for editing q code." :group 'languages)
(defcustom q-program "q"
"Program name for invoking an inferior q."
:type 'file
:group 'q)
(defcustom q-host ""
"If non-nil, Q-Shell will ssh to the remote host before executing q."
:safe 'stringp
:type 'string
:group 'q)
(defcustom q-user ""
"User to use when `ssh'-ing to the remote host."
:safe 'stringp
:type 'string
:group 'q)
(defcustom q-indent-step 1
"Length of indent used by `q-indent-line`.
If nil, code is aligned to {}-, ()-, and []-groups. Otherwise,
each level is indented by this amount."
:type '(choice (const nil) integer)
:group 'q)
(defcustom q-comment-start "/"
"String to insert to start a new comment (some prefer a double forward slash).
Note: this only affects comment insertion and recognition by commands such
as `comment-region' and `comment-dwim'. Syntax highlighting and sexp
navigation always treat a bare / as the comment delimiter."
:safe 'stringp
:type 'string
:group 'q)
(defcustom q-msg-prefix ""
"String to prefix every message sent to inferior q[con] process."
:safe 'stringp
:type 'string
:group 'q)
(defcustom q-msg-postfix ""
"String to postfix every message sent to inferior q[con] process."
:safe 'stringp
:type 'string
:group 'q)
(defcustom q-flymake-on-save nil
"If non-nil, only run Flymake checks after saving the buffer.
If nil, run checks for unsaved buffers by writing the current
buffer contents to a temporary file before invoking q."
:safe 'booleanp
:type 'boolean
:group 'q)
(defcustom q-allow-shell-buffer nil
"If non-nil, allow any live comint buffer as the active q buffer.
This lets you point `q-active-buffer' at a `*shell*' buffer (or
similar) that is running a q process directly, even though it is
not a `q-shell-mode' buffer. When nil (the default) only buffers
in `q-shell-mode' are accepted."
:safe 'booleanp
:type 'boolean
:group 'q)
(defcustom q-rescan-idle-delay 1.0
"Seconds of idle time before rescanning after a save.
Debounces rapid successive saves and defers the check for out-of-band
disk changes (e.g. from git pull) until Emacs has been idle this long."
:safe 'numberp
:type 'number
:group 'q)
(defgroup q-init nil "Q initialization variables." :group 'q)
(defcustom q-init-port 0
"If non-zero, Q-Shell will start with the specified server port."
:safe 'integerp
:type 'integer
:group 'q-init)
(defcustom q-init-slaves 0
"If non-zero, Q-Shell will start with the specified number of slaves."
:safe 'integerp
:type 'integer
:group 'q-init)
(defcustom q-init-workspace 0
"If non-zero, Q-Shell will start with the specified workspace limit."
:safe 'integerp
:type 'integer
:group 'q-init)
(defcustom q-init-garbage-collect nil
"If non-nil, Q-Shell will start with garbage collection enabled."
:safe 'booleanp
:type 'boolean
:group 'q-init)
(defcustom q-init-file ""
"If non-empty, Q-Shell will load the specified file."
:type 'file
:group 'q-init)
(defgroup q-qcon nil "Q qcon arguments." :group 'q)
(defcustom q-qcon-program "qcon"
"Program name for invoking an inferior qcon."
:type 'file
:group 'q-qcon)
(defcustom q-qcon-server ""
"Remote q server."
:safe 'stringp
:type 'string
:group 'q-qcon)
(defcustom q-qcon-port 5000
"Port for remote q server."
:safe 'integerp
:type 'integer
:group 'q-qcon)
(defcustom q-qcon-user ""
"If non-nil, qcon will log in to remote q server with this id."
:safe 'stringp
:type 'string
:group 'q-qcon)
(defcustom q-qcon-password ""
"Password for remote q server.
If empty, `auth-source-search' is consulted instead.
Warning: the `:safe' predicate means this value is accepted without
prompting from `.dir-locals.el', which risks exposing credentials if
that file is committed to version control."
:safe 'stringp
:type 'string
:group 'q-qcon)
(defun q-customize ()
"Customize `q-mode'."
(interactive)
(customize-group "q"))
(defvar q-active-buffer nil
"The q-shell buffer to send q commands.")
(defun q-activate-this-buffer ()
"Set the `q-activate-buffer' to the currently active buffer."
(interactive)
(q-activate-buffer (current-buffer)))
(defun q-shell-buffer-p (buffer)
"Return non-nil if BUFFER is a live Q shell buffer.
BUFFER can be a buffer object, buffer name, or cons cell from completion.
When `q-allow-shell-buffer' is non-nil, any live comint buffer with a
running process is accepted, not just `q-shell-mode' buffers."
(let* ((target (if (consp buffer) (car buffer) buffer))
(buf (and target (get-buffer target))))
(and buf
(buffer-live-p buf)
(comint-check-proc buf)
(with-current-buffer buf
(or (eq major-mode 'q-shell-mode)
(and q-allow-shell-buffer
(derived-mode-p 'comint-mode)))))))
(defun q-activate-buffer (buffer)
"Set the `q-active-buffer' to the supplied BUFFER.
Prompt with a list of live Q Shell buffers if called interactively."
(interactive
(list (read-buffer "activate buffer: "
nil
t
#'q-shell-buffer-p)))
(when (called-interactively-p 'any) (display-buffer buffer))
(setq q-active-buffer (get-buffer buffer)))
(defun q-default-args ()
"Build the default q command-line argument string from `q-init-*' variables."
(concat
(unless (equal q-init-file "") (format " %s" (shell-quote-argument q-init-file)))
(unless (equal q-init-port 0) (format " -p %s" q-init-port))
(unless (equal q-init-slaves 0) (format " -s %s" q-init-slaves))
(unless (equal q-init-workspace 0) (format " -w %s" q-init-workspace))
(when q-init-garbage-collect " -g 1")))
(defun q--qcon-password ()
"Return the qcon password from `q-qcon-password'.
Fall back to `auth-source-search' if unset."
(if (not (equal q-qcon-password ""))
q-qcon-password
(when (featurep 'auth-source)
(let ((creds (car (auth-source-search :host q-qcon-server
:user q-qcon-user
:max 1))))
(when creds (auth-info-password creds))))))
(defun q-qcon-default-args ()
"Build the default qcon command-line argument string from `q-qcon-*' variables."
(concat (format "%s:%s" q-qcon-server q-qcon-port)
(unless (equal q-qcon-user "")
(format ":%s:%s" q-qcon-user (q--qcon-password)))))
(defun q-shell-name (server port)
"Build name of q-shell based on SERVER and PORT."
(if (and (equal server "") (equal port ""))
"q"
(concat "q-"
(if (equal server "") "localhost" server)
(unless (equal port "") (format ":%s" port)))))
;;;###autoload
(defun q (&optional host user args)
"Start a new q process.
The optional argument HOST and USER allow the q process to be
started on a remote machine. The optional ARGS argument
specifies the command line args to use when executing q; the
default ARGS are obtained from the q-init customization
variables. In interactive use, a prefix argument directs this
command to read the command line arguments from the minibuffer."
(interactive (let* ((args (q-default-args))
(user q-user)
(host q-host))
(if current-prefix-arg
(list (read-string "Host: " host)
(read-string "User: " user)
(read-string "Q command line args: " args))
(list host user args))))
(unless (equal (or user "") "") (setq host (format "%s@%s" user host)))
(let* ((cmd q-program)
(args (or args ""))
(host (or host ""))
(cmd (if (equal args "") cmd (concat cmd args)))
(qs (not (equal host "")))
(port (let ((case-fold-search nil))
(if (string-match "-p *\\([0-9]+\\)" args) (match-string 1 args) "")))
(buffer (get-buffer-create (format "*%s*" (q-shell-name host port))))
(command (if qs "ssh" (or shell-file-name (getenv "SHELL") "/bin/sh")))
(switches (append (if qs (list "-t" host) (list "-c")) (list cmd)))
;; disable kdb-x rlwrap functionality
(process-environment (cons "KX_LINE=0" process-environment))
process)
(when (called-interactively-p 'any) (pop-to-buffer buffer))
(when (or current-prefix-arg (not (q-shell-buffer-p buffer)))
(with-current-buffer buffer
(message "q: starting q with command \"%s\"" cmd)
(q-shell-mode)
(let ((comint-args (list buffer "q" command nil switches)))
(setq process (get-buffer-process (apply 'comint-exec comint-args))))
(setq comint-input-ring-file-name "~/.q_history")
(comint-read-input-ring t)
(set-process-sentinel process 'q-process-sentinel)))
(q-activate-buffer buffer)
process))
;;;###autoload
(defun q-qcon (&optional args)
"Connect to a pre-existing q process.
Optional argument ARGS specifies the command line args to use
when executing qcon; the default ARGS are obtained from the
`q-host' and `q-init-port' customization variables.
In interactive use, a prefix argument directs this command
to read the command line arguments from the minibuffer."
(interactive (let* ((args (q-qcon-default-args)))
(list (if current-prefix-arg
(read-string "qcon command line args: " args)
args))))
(let* ((buffer (get-buffer-create (format "*qcon-%s*" args)))
process)
(when (called-interactively-p 'any) (pop-to-buffer buffer))
(when (or current-prefix-arg (not (q-shell-buffer-p buffer)))
(with-current-buffer buffer
(message "q: starting qcon with command \"%s\"" (concat q-qcon-program " " args))
(q-shell-mode)
(setq comint-process-echoes nil)
(setq process (get-buffer-process (comint-exec buffer "qcon" q-qcon-program nil (list args))))
(setq comint-input-ring-file-name (concat (getenv "HOME") "/.qcon_history"))
(comint-read-input-ring)
(set-process-sentinel process 'q-process-sentinel)))
(q-activate-buffer buffer)
process))
(defun q-show-q-buffer ()
"Switch to the active q process, or start a new one (passing in args)."
(interactive)
(unless (q-shell-buffer-p q-active-buffer)
(q))
(if (called-interactively-p 'any)
(pop-to-buffer q-active-buffer)
(display-buffer q-active-buffer)))
(defun q-kill-q-buffer ()
"Kill the q process and its buffer."
(interactive)
(when q-active-buffer
(kill-buffer q-active-buffer)
(unless (buffer-live-p q-active-buffer) (setq q-active-buffer nil))))
(defun q-process-sentinel (process message)
"Sentinel for use with q processes.
This marks the PROCESS with a MESSAGE, at a particular time point."
(comint-write-input-ring)
(let ((buffer (process-buffer process))
(text (format "\nProcess %s %s at %s\n"
(process-name process)
(replace-regexp-in-string "[\r\n]+\\'" "" (or message ""))
(current-time-string))))
(when (buffer-live-p buffer)
(with-current-buffer buffer
(goto-char (point-max))
(insert-before-markers text)))))
(defun q-strip (text)
"Strip TEXT of all trailing comments, newlines and excessive whitespace.
The order of operations matters and must not be rearranged."
(setq text (replace-regexp-in-string "^\\(?:[^\\\\].*\\)?[ \t]\\(/.*\\)\n" "" text t t 1)) ; / comments
(setq text (replace-regexp-in-string "^/.+$" "" text t t)) ; / comments
(setq text (replace-regexp-in-string "[ \t\n]+$" "" text t t)) ; excess white space
(setq text (replace-regexp-in-string "\n[ \t]+" "" text t t)) ; fold functions
text)
(defun q-send-string (string)
"Send STRING to the inferior q process stored in `q-active-buffer'."
(unless (stringp string)
(user-error "Nothing to send"))
(unless (q-shell-buffer-p q-active-buffer)
(user-error "No active q buffer; run `M-x q` or activate a q shell with `C-c M-RET`"))
(let ((msg (concat q-msg-prefix string q-msg-postfix)))
(with-current-buffer q-active-buffer
(unless comint-process-echoes
(goto-char (point-max))
(insert-before-markers (concat msg "\n")))
(comint-simple-send (get-buffer-process q-active-buffer) msg)))
;; Allow `M-g n' (and `q-next-error'/`C-c `') from source buffers.
(setq next-error-last-buffer q-active-buffer)
(when (equal current-prefix-arg '(16)) (q-show-q-buffer)))
(defun q-eval-region (start end)
"Send the region between START and END to the inferior q[con] process."
(interactive "r")
(q-send-string (q-strip (buffer-substring start end)))
(setq deactivate-mark t))
(defun q-eval-line ()
"Send the current line to the inferior q[con] process."
(interactive)
(q-eval-region (line-beginning-position) (line-end-position)))
(defun q-eval-line-and-step ()
"Send the current line to the inferior q[con] process and step to the next line."
(interactive)
(q-eval-line)
(forward-line))
(defun q-eval-symbol ()
"Send the symbol at point to the inferior q[con] process."
(interactive)
(let ((symbol (thing-at-point 'symbol)))
(unless symbol
(user-error "No symbol at point"))
(q-send-string symbol)))
(defun q-eval-buffer ()
"Load current buffer into the inferior q[con] process."
(interactive)
(q-eval-region (point-min) (point-max)))
(defconst q-symbol-regex
"`\\(?:\\(?:\\w\\|[.]\\)\\(?:\\w\\|[_.]\\)*\\)?"
"Regular expression used to find symbols.")
(defconst q-file-regex
(concat q-symbol-regex ":\\(?:\\w\\|[/:_.]\\)*")
"Regular expression used to find files.")
(defconst q-name-regex
"\\_<\\([.]?[a-zA-Z]\\(?:\\w\\|[_.]\\)*\\)\\s-*"
"Regular expression used to find variable or function names.")
(defconst q-function-regex
(concat q-name-regex
":" ; assignment
":?" ; view
"\\s-*" ; potential white space
"\\(?:" ; one of the following
"{" ; function declaration
"\\|'\\s-*\\[" ; composition
"\\|[^;{\n]*?\\(?:::\\|[-.~=!@#$%^&*_+|,<>?/\\:']" ; trailing binary operator
"\\)"
"\\s-*" ; potential white space
"\\(?:\\s<\\|$\\|;\\)" ; opening comment, new line, or semicolon
"\\)"
)
"Regular expression used to find function declarations.")
(defconst q-variable-regex
(concat q-name-regex
"[-.~=!@#$%^&*_+|,<>?]?" ; potential compound assignment
":" ; assignment
":?" ; view
"\\s-*" ; potential space
"[^ )}:;\n]" ; something else
)
"Regular expression used to find variable declarations.")
;; q runtime stack traces include entries like:
;; [2] /path/to/file.q:42: expr
;; Reuse the same pattern for both Flymake parsing and shell navigation.
(defconst q--stack-frame-regexp
" *\\[[0-9]+\\] *\\(.*\\.[kq]\\):\\([0-9]+\\): "
"Regular expression matching a q stack-frame location (file + line).")
(defun q-eval-function ()
"Send the current function to the inferior q[con] process."
(interactive)
(condition-case nil
(save-excursion
(goto-char (line-end-position)) ; go to end of line
(let ((start (re-search-backward (concat "^" q-function-regex))) ; find beginning of function
(end (re-search-forward ":")) ; find end of function name
(fun (thing-at-point 'sexp))) ; find function body
(unless fun
(user-error "Could not parse function body"))
(q-send-string (q-strip (concat (buffer-substring start end) fun)))))
(search-failed
(user-error "No function found around point"))))
(defun q-and-go (fun)
"Call FUN interactively and show active q buffer."
(let ((current-prefix-arg '(16))) (call-interactively fun)))
(defun q-eval-line-and-go ()
"Send the current line to the inferior q[con] process and show active q buffer."
(interactive)
(q-and-go 'q-eval-line))
(defun q-eval-function-and-go ()
"Send the function to the inferior q[con] process and show active q buffer."
(interactive) (q-and-go 'q-eval-function))
(defun q-eval-region-and-go ()
"Send the active region to the inferior q[con] process and show active q buffer."
(interactive)
(q-and-go 'q-eval-region))
(defun q-eval-symbol-and-go ()
"Send current symbol to the inferior q[con] process and show active q buffer."
(interactive)
(q-and-go 'q-eval-symbol))
(defun q-load-file ()
"Load current buffer's file into the inferior q[con] process after saving."
(interactive)
(unless buffer-file-name
(user-error "Current buffer is not visiting a file"))
(save-buffer)
(q-send-string (format "\\l %s" (shell-quote-argument buffer-file-name))))
(defun q-next-error (&optional n)
"Jump to the Nth next stack-frame error in the active q shell buffer."
(interactive "p")
(unless (q-shell-buffer-p q-active-buffer)
(user-error "No active q buffer; run `M-x q` or activate a q shell with `C-c M-RET`"))
(setq next-error-last-buffer q-active-buffer)
(next-error (or n 1)))
(defun q-rescan-project (&optional force)
"Rescan the current project, skipping files whose mtime is unchanged.
With a prefix argument FORCE, re-scan all files regardless of mtime."
(interactive "P")
(q--project-plist-put :file-list-sentinel nil)
(when force
(q--project-plist-put :scan-state nil))
(q--do-full-rescan (current-buffer)
(if force "forced rescan" "manual rescan")
t))
;; keymaps
(defvar q-shell-mode-map
(let ((q-shell-mode-map (make-sparse-keymap)))
(define-key q-shell-mode-map (kbd "C-c M-RET") 'q-activate-this-buffer)
(set-keymap-parent q-shell-mode-map comint-mode-map)
q-shell-mode-map)
"Keymap for inferior q mode.")
(defvar q-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-l" 'q-eval-line)
(define-key map "\C-c\C-j" 'q-eval-line)
(define-key map "\C-c\M-j" 'q-eval-line-and-go)
(define-key map (kbd "<C-return>") 'q-eval-line-and-step)
(define-key map "\C-\M-x" 'q-eval-function)
(define-key map "\C-c\C-f" 'q-eval-function)
(define-key map "\C-c\M-f" 'q-eval-function-and-go)
(define-key map "\C-c\C-r" 'q-eval-region)
(define-key map "\C-c\M-r" 'q-eval-region-and-go)
(define-key map "\C-c\C-s" 'q-eval-symbol)
(define-key map "\C-c\M-s" 'q-eval-symbol-and-go)
(define-key map "\C-c\C-b" 'q-eval-buffer)
(define-key map "\C-c\M-l" 'q-load-file)
(define-key map (kbd "C-c M-RET") 'q-activate-buffer)
(define-key map "\C-c\C-q" 'q-show-q-buffer)
(define-key map "\C-c\C-\\" 'q-kill-q-buffer)
(define-key map "\C-c\C-z" 'q-customize)
(define-key map "\C-c\C-c" 'comment-region)
(define-key map "\C-c\C-g" 'q-rescan-project)
(define-key map "\C-c`" 'q-next-error)
map)
"Keymap for q major mode.")
;; menu bars
(easy-menu-define q-menu q-mode-map
"Menubar for q script commands."
'("Q"
["Eval Line" q-eval-line t]
["Eval Line and Step" q-eval-line-and-step t]
["Eval Line and Go" q-eval-line-and-go t]
["Eval Function" q-eval-function t]
["Eval Function and Go" q-eval-function-and-go t]
["Eval Region" q-eval-region t]
["Eval Region and Go" q-eval-region-and-go t]
["Eval Symbol" q-eval-symbol t]
["Eval Symbol and Go" q-eval-symbol-and-go t]
["Eval Buffer" q-eval-buffer t]
["Load File" q-load-file t]
"---"
["Comment Region" comment-region t]
"---"
["Rescan Project" q-rescan-project t]
["Next Error" q-next-error t]
"---"
["Customize Q" q-customize t]
["Show Q Shell" q-show-q-buffer t]
["Kill Q Shell" q-kill-q-buffer t]
))
(easy-menu-define q-shell-menu q-shell-mode-map
"Menubar for q shell commands."
'("Q-Shell"
["Activate Buffer" q-activate-this-buffer t]
))
;; faces
;; font-lock-comment-face font-lock-comment-delimiter-face
;; font-lock-string-face font-loc-doc-face
;; font-lock-keyword-face font-lock-builtin-face
;; font-lock-function-name-face
;; font-lock-variable-name-face font-lock-type-face
;; font-lock-constant-face font-lock-warning-face
;; font-lock-negation-char-face font-lock-preprocessor-face
(defconst q-keyword-list
'("abs" "acos" "asin" "atan" "avg" "bin" "binr" "by" "cor" "cos" "cov" "dev" "delete"
"div" "do" "enlist" "exec" "exit" "exp" "from" "getenv" "hopen" "if" "in" "insert" "last"
"like" "log" "max" "min" "prd" "select" "setenv" "sin" "sqrt" "ss"
"sum" "tan" "update" "var" "wavg" "while" "within" "wsum" "xexp")
"Keywords for q mode defined in .Q.res.")
(defconst q-keywords
(concat "\\_<"
"\\(?:[_]\\)?" ; leading _ is not a symbol
(regexp-opt q-keyword-list t)
"\\_>")
"Keyword regex for q mode defined in .Q.res.")
(defconst q-builtin-word-list
'("aj" "aj0" "ajf" "ajf0" "all" "and" "any" "asc" "asof" "attr" "avgs" "ceiling"
"cols" "count" "cross" "csv" "cut" "deltas" "desc"
"differ" "distinct" "dsave" "each" "ej" "ema" "eval" "except" "fby" "fills"
"first" "fkeys" "flip" "floor" "get" "group" "gtime" "hclose" "hcount"
"hdel" "hsym" "iasc" "idesc" "ij" "ijf" "inter" "inv" "key" "keys"
"lj" "ljf" "load" "lower" "lsq" "ltime" "ltrim" "mavg" "maxs" "mcount" "md5"
"mdev" "med" "meta" "mins" "mmax" "mmin" "mmu" "mod" "msum" "neg"
"next" "not" "null" "or" "over" "parse" "peach" "pj" "prds" "prior"
"prev" "rand" "rank" "ratios" "raze" "read0" "read1" "reciprocal" "reval"
"reverse" "rload" "rotate" "rsave" "rtrim" "save" "scan" "scov" "sdev" "set" "show"
"signum" "ssr" "string" "sublist" "sums" "sv" "svar" "system" "tables" "til"
"trim" "type" "uj" "ujf" "ungroup" "union" "upper" "upsert" "use" "value"
"view" "views" "vs" "where" "wj" "wj1" "ww" "xasc" "xbar" "xcol" "xcols" "xdesc"
"xgroup" "xkey" "xlog" "xprev" "xrank")
"Builtin functions for q mode defined in q.k.")
(defconst q-builtin-words
(concat "\\_<"
"\\(?:[_]\\)?" ; leading _ is not a symbol
"\\("
"\\(?:[.]q[.]\\)?"
(regexp-opt q-builtin-word-list)
"\\)"
"\\_>")
"Builtin function regex for q mode defined in q.k.")
(defconst q-builtin-dot-z-word-list
'(".z.D" ".z.H" ".z.K" ".z.N" ".z.P" ".z.T" ".z.W" ".z.X" ".z.Z" ".z.a"
".z.ac" ".z.b" ".z.bm" ".z.c" ".z.d" ".z.e" ".z.ex" ".z.exit"
".z.ey" ".z.f" ".z.h" ".z.i" ".z.k" ".z.l" ".z.n" ".z.o" ".z.p"
".z.pc" ".z.pd" ".z.pg" ".z.ph" ".z.pi" ".z.pm" ".z.po" ".z.pp"
".z.pq" ".z.ps" ".z.pw" ".z.q" ".z.r" ".z.s" ".z.t" ".z.ts" ".z.u"
".z.vs" ".z.w" ".z.wc" ".z.wo" ".z.ws" ".z.x" ".z.z" ".z.zd")
"Builtin .z functions/constants defined for q mode.")
(defconst q-builtin-dot-z-words
(concat "\\_<"
"\\(?:[_]\\)?" ; leading _ is not a symbol
(regexp-opt q-builtin-dot-z-word-list t)
"\\_>")
"Builtin .z functions/constants regex defined for q mode.")
(defconst q-builtin-dot-Q-word-list
'(".Q.a" ".Q.A" ".Q.b6" ".Q.chk" ".Q.cn" ".Q.def" ".Q.dpft" ".Q.dsftg"
".Q.en" ".Q.ens" ".Q.f" ".Q.fc" ".Q.fmt" ".Q.fp" ".Q.fqk" ".Q.fs"
".Q.fsn" ".Q.ft" ".Q.fu" ".Q.gc" ".Q.hdpf" ".Q.hg" ".Q.hp" ".Q.id"
".Q.j10" ".Q.j12" ".Q.k" ".Q.l" ".Q.n" ".Q.nA" ".Q.pd" ".Q.pf"
".Q.pn" ".Q.pt" ".Q.pv" ".Q.pw" ".Q.qp" ".Q.qt" ".Q.res" ".Q.s"
".Q.s1" ".Q.s2" ".Q.sbt" ".Q.sha" ".Q.t" ".Q.te" ".Q.trp" ".Q.ts"
".Q.ty" ".Q.u" ".Q.v" ".Q.vp" ".Q.w" ".Q.x10" ".Q.x12" ".Q.xf"
".Q.xR" ".Q.xs")
"Builtin .Q functions/constants defined for q mode.")
(defconst q-builtin-dot-Q-words
(concat "\\_<"
"\\(?:[_]\\)?" ; leading _ is not a symbol
(regexp-opt q-builtin-dot-Q-word-list t)
"\\_>")
"Builtin .Q functions/constants regex defined for q mode.")
(defconst q-builtin-dot-h-word-list
'(".h.hn" ".h.hp" ".h.hr" ".h.ht" ".h.hta" ".h.htac" ".h.htc" ".h.html"
".h.http" ".h.hu" ".h.hug" ".h.hy" ".h.jx" ".h.pre" ".h.ta" ".h.td"
".h.text" ".h.th" ".h.tr" ".h.tx" ".h.ty" ".h.val" ".h.xd" ".h.xmp"
".h.xs" ".h.xt")
"Builtin .h functions/constants defined for q mode.")
(defconst q-builtin-dot-h-words
(concat "\\_<"
"\\(?:[_]\\)?" ; leading _ is not a symbol
(regexp-opt q-builtin-dot-h-word-list t)
"\\_>")
"Builtin .h functions/constants regex defined for q mode.")
(defconst q-builtin-dot-j-word-list
'(".j.j" ".j.jd" ".j.k")
"Builtin .j functions/constants defined for q mode.")
(defconst q-builtin-dot-j-words
(concat "\\_<"
"\\(?:[_]\\)?" ; leading _ is not a symbol
(regexp-opt q-builtin-dot-j-word-list t)
"\\_>")
"Builtin .j functions/constants regex defined for q mode.")
(defconst q-font-lock-keywords ;; keywords
(list
;; q single-letter system commands keep comments
'("^\\\\\\(?:\\w\\|[_]\\)\\(?:\\s-.*?\\)?$" 0 font-lock-preprocessor-face keep)
;; os multi-letter system commands ignore comments
'("^\\\\\\w\\w.*?$" 0 font-lock-preprocessor-face prepend)
'("^'.*" . font-lock-warning-face) ; error
(list (concat "[; ]\\('" q-symbol-regex "\\)") 1 font-lock-warning-face nil) ; signal
(cons q-file-regex 'font-lock-preprocessor-face) ; files
(cons q-symbol-regex 'font-lock-constant-face) ; symbols
)
"Minimal highlighting expressions for q mode.")
(defconst q-font-lock-keywords-1 ; symbols
(append q-font-lock-keywords
(list
(list q-keywords 1 'font-lock-keyword-face nil) ; select from
'("\\b[0-2]:" . font-lock-builtin-face) ; IO/IPC
(list q-builtin-words 1 'font-lock-builtin-face nil) ; q.k
(list q-builtin-dot-z-words 1 'font-lock-builtin-face nil) ; .z.*
(list q-builtin-dot-Q-words 1 'font-lock-builtin-face nil) ; .Q.*
(list q-builtin-dot-h-words 1 'font-lock-builtin-face nil) ; .h.*
(list q-builtin-dot-j-words 1 'font-lock-builtin-face nil) ; .j.*
))
"More highlighting expressions for q mode.")
(defconst q-font-lock-keywords-2 ; function/variable names and literals
(append q-font-lock-keywords-1
(list
(list q-function-regex 1 'font-lock-function-name-face nil) ; functions
(list q-variable-regex 1 'font-lock-variable-name-face nil) ; variables
'("\\_<[0-9]\\{4\\}\\.[0-9]\\{2\\}\\(?:m\\|\\.[0-9]\\{2\\}\\(?:T\\(?:[0-9]\\{2\\}\\(?::[0-9]\\{2\\}\\(?::[0-9]\\{2\\}\\(?:\\.[0-9]*\\)?\\)?\\)?\\)?\\)?\\)\\_>" . font-lock-constant-face) ; month/date/datetime
'("\\_<\\(?:[0-9]\\{4\\}\\.[0-9]\\{2\\}\\.[0-9]\\{2\\}\\|[0-9]+\\)D\\(?:[0-9]\\(?:[0-9]\\(?::[0-9]\\{2\\}\\(?::[0-9]\\{2\\}\\(?:\\.[0-9]*\\)?\\)?\\)?\\)?\\)?\\_>" . font-lock-constant-face) ; timespan/timestamp
'("\\_<[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\_>" . font-lock-constant-face) ; guid
'("\\_<[0-9]\\{2\\}:[0-9]\\{2\\}\\(?::[0-9]\\{2\\}\\(?:\\.[0-9]\\|\\.[0-9]\\{2\\}\\|\\.[0-9]\\{3\\}\\)?\\)?\\_>" . font-lock-constant-face) ; time
'("\\_<\\(?:[0-9]+\\.\\(?:[0-9]*\\)?\\|\\.[0-9]+\\)\\(?:[eE][+-]?[0-9]+\\)?[ef]?\\_>" . font-lock-constant-face) ; floats/reals
'("\\_<[0-9]+[cefhijnptuv]?\\_>" . font-lock-constant-face) ; char/real/float/short/int/long/time-types
'("\\_<[01]+b\\_>" . font-lock-constant-face) ; bool
'("\\_<0x[0-9a-fA-F]+\\_>" . font-lock-constant-face) ; bytes
'("\\_<0[nNwW][cefghijmndzuvtp]?\\_>" . font-lock-constant-face) ; null/infinity
'("\\(?:TODO\\|NOTE\\)\\:?" 0 font-lock-warning-face t) ; TODO
))
"Most highlighting expressions for q mode.")
(defconst q-font-lock-defaults
'((q-font-lock-keywords q-font-lock-keywords-1 q-font-lock-keywords-2)
nil nil nil nil)
"Font lock defaults for q mode.
Syntactic context (strings, comments) is handled by
`q-syntax-propertize', not by `font-lock-syntactic-keywords'.")
;; syntax table
(defvar q-mode-syntax-table
(let ((table (make-syntax-table)))
(modify-syntax-entry ?\" ". " table) ; treat " as punctuation
(modify-syntax-entry ?\/ ". " table) ; treat / as punctuation
(modify-syntax-entry ?\. "_ " table) ; treat . as symbol
(modify-syntax-entry ?\_ "_ " table) ; treat _ as symbol
(modify-syntax-entry ?\\ ". " table) ; treat \ as punctuation
(modify-syntax-entry ?\$ ". " table) ; treat $ as punctuation
(modify-syntax-entry ?\% ". " table) ; treat % as punctuation
(modify-syntax-entry ?\& ". " table) ; treat & as punctuation
(modify-syntax-entry ?\+ ". " table) ; treat + as punctuation
(modify-syntax-entry ?\, ". " table) ; treat , as punctuation
(modify-syntax-entry ?\- ". " table) ; treat - as punctuation
(modify-syntax-entry ?\= ". " table) ; treat = as punctuation
(modify-syntax-entry ?\* ". " table) ; treat * as punctuation
(modify-syntax-entry ?\< ". " table) ; treat < as punctuation
(modify-syntax-entry ?\> ". " table) ; treat > as punctuation
(modify-syntax-entry ?\| ". " table) ; treat | as punctuation
(modify-syntax-entry ?\` ". " table) ; treat ` as punctuation
table)
"Syntax table for `q-mode'.")
(defun q-syntax-propertize (start end)
"Apply syntax properties for q strings and comments between START and END."
(funcall
(syntax-propertize-rules
;; bare / line opens a block comment
("^\\(/\\)[ \t]*$"
(1 (unless (nth 4 (syntax-ppss)) (string-to-syntax "< b"))))
;; bare \ line closes a block comment
("^\\(\\\\\\)[ \t]*$"
(1 (when (nth 4 (syntax-ppss)) (string-to-syntax "> b"))))
;; " opens or closes a string, honouring \" escapes
("\\(\"\\)\\(?:[^\"\\\\]\\|\\\\.\\)*\\(\"\\)?"
(1 (string-to-syntax "\""))
(2 (string-to-syntax "\"")))
;; / after whitespace or BOL starts a line comment, not inside a string;
;; also mark the terminating newline as comment-ender since \n has no
;; comment-ender syntax in the table (handled entirely via text properties)
("\\(?:^\\|[ \t]\\)\\(/\\)\\([^\n]*\\)\\(\n\\)"
(1 (unless (nth 3 (syntax-ppss)) (string-to-syntax "<")))
(3 (unless (nth 3 (syntax-ppss)) (string-to-syntax ">")))))
start end))
;; flymake
(defun q-flymake (report-fn &rest _args)
"Flymake backend using the q program.
Takes a Flymake callback REPORT-FN as argument, as expected of a member
of `flymake-diagnostic-functions'. q evaluates source code while
checking it; this backend therefore performs a runtime check.
When `q-flymake-on-save' is nil, diagnostics are produced from the
current buffer by checking a temporary file."
(when (process-live-p q--flymake-proc)
(kill-process q--flymake-proc))
(let ((source (current-buffer))
(file (buffer-file-name))
(default-directory (file-name-directory (buffer-file-name))))
(cond
((not file)
(funcall report-fn nil))
((and q-flymake-on-save (buffer-modified-p))
(funcall report-fn nil))
(t
(let ((input-file file))
(when (buffer-modified-p)
(save-restriction
(widen)
(setq input-file (make-temp-file "q-flymake-" nil ".q"))
(write-region (point-min) (point-max) input-file nil 'silent)))
;; reset the `q--flymake-proc' process to a new q process
(setq
q--flymake-proc
(make-process
:name "q-flymake" :noquery t :connection-type 'pipe
:buffer (generate-new-buffer " *q-flymake*")
:command (list q-program input-file)
:sentinel
(lambda (proc _event)
;; check that the process has exited (not just suspended)
(when (memq (process-status proc) '(exit signal))
(unwind-protect
;; only proceed if `proc' is the same as
;; `q--flymake-proc', which indicates that `proc' is
;; not an obsolete process
(if (and (buffer-live-p source)
(with-current-buffer source (eq proc q--flymake-proc)))
(with-current-buffer (process-buffer proc)
(goto-char (point-min))
(cl-loop
while (search-forward-regexp
(concat
"^'[0-9.:T]* \\(.*\\)" ; error message
"\\(?:.\\|\\\n\\)*\\\n" ; stack trace
"\\(" q--stack-frame-regexp "\\).*\\\n" ; line number
"\\( +^\\)$" ; carat showing column of error
)
nil t)
for msg = (match-string 1)
for prefix = (match-string 2)
for row = (string-to-number (match-string 4))
for carat = (match-string 5)
for col = (- (length carat) (length prefix))
for (beg . end) = (flymake-diag-region source row col)
when (and beg end)
collect (flymake-make-diagnostic source beg end :error msg)
into diags
finally (funcall report-fn diags)))
(flymake-log :warning "Canceling obsolete check %s" proc))
(when (and input-file (not (equal input-file file)))
(ignore-errors (delete-file input-file)))
(kill-buffer (process-buffer proc))))))))
(process-send-eof q--flymake-proc)))))
(defconst q-capf-core-words
(let ((ht (make-hash-table :test #'equal)))
(dolist (w (append q-keyword-list q-builtin-word-list q-builtin-dot-z-word-list
q-builtin-dot-Q-word-list q-builtin-dot-h-word-list
q-builtin-dot-j-word-list))
(puthash w t ht))
ht)
"Core words used for q completion candidates (hash table for O(1) lookup).")
;; Project scan caches
;;
;; Design goals:
;; 1. eldoc / CAPF never block on I/O or file-list expansion.
;; 2. Rescans happen on an idle timer, not inline on every keystroke.