-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathbash-completion.el
1801 lines (1550 loc) · 71.2 KB
/
bash-completion.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
;;; bash-completion.el --- Bash completion for the shell buffer -*- lexical-binding: t -*-
;; Copyright (C) 2009 Stephane Zermatten
;; Author: Stephane Zermatten <szermatt@gmx.net>
;; Maintainer: Stephane Zermatten <szermatt@gmail.com>
;; Version: 3.2.1snapshot
;; Keywords: convenience, unix
;; URL: http://github.com/szermatt/emacs-bash-completion
;; Package-Requires: ((emacs "25.3"))
;; 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 2 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 file defines dynamic completion hooks for `shell-mode' and
;; `shell-command' prompts that are based on Bash completion. You can
;; enable it by invoking `bash-completion-setup' or by adding
;;
;; (bash-completion-setup)
;;
;; to your initialisation file.
;;
;; You can also use bash completion as an additional completion
;; function in any buffer that contains bash commands. To do that, add
;; `bash-completion-capf-nonexclusive' to the buffer-local
;; `completion-at-point-functions'. For example, you can setup bash
;; completion in `eshell-mode' by invoking
;;
;; (add-hook 'eshell-mode-hook
;; (lambda ()
;; (add-hook 'completion-at-point-functions
;; 'bash-completion-capf-nonexclusive nil t)))
;;
;; The completion will be aware of bash builtins, alii and functions.
;; It does file expansion does file expansion inside of
;; colon-separated variables and after redirections (> or <), and
;; escapes special characters when expanding file names. Just like
;; "regular" Bash, it is configurable through programmable bash
;; completion.
;;
;; When the first completion is requested in shell model or a shell
;; command, bash-completion.el starts a separate Bash
;; process. Bash-completion.el then uses this process to do the actual
;; completion and includes it into Emacs completion suggestions.
;;
;; A simpler and more complete alternative to bash-completion.el is to
;; run a Bash shell in a buffer in term mode (M-x `ansi-term').
;; Unfortunately, many Emacs editing features are not available when
;; running in term mode. Also, term mode is not available in
;; shell-command prompts.
;;
;; Bash completion can also be run programmatically, outside of a
;; shell-mode command, by calling
;; `bash-completion-dynamic-complete-nocomint'
;;; Installation:
;; 1. copy bash-completion.el into a directory that's on Emacs load-path
;; 2. add this into your .emacs file:
;; (autoload 'bash-completion-dynamic-complete \"bash-completion\"
;; \"BASH completion hook\")
;; (add-hook 'shell-dynamic-complete-functions
;; 'bash-completion-dynamic-complete)
;;
;; or simpler, but forces you to load this file at startup:
;;
;; (require 'bash-completion)
;; (bash-completion-setup)
;;
;; 3. reload your .emacs (M-x `eval-buffer') or restart
;;
;; Once this is done, use <TAB> as usual to do dynamic completion from
;; shell mode or a shell command minibuffer, such as the one started
;; for M-x `compile'. Note that the first completion is slow, as emacs
;; launches a new Bash process.
;;
;; Naturally, you'll get better results if you turn on programmable
;; Bash completion in your shell. Depending on how your system is set
;; up, this might requires calling:
;; . /etc/bash_completion
;; from your ~/.bashrc.
;;
;; When called from a Bash shell buffer,
;; `bash-completion-dynamic-complete' communicates with the current shell
;; to reproduce, as closely as possible the normal Bash auto-completion,
;; available on full terminals.
;;
;; When called from non-shell buffers, such as the prompt of M-x
;; compile, `bash-completion-dynamic-complete' creates a separate Bash
;; process just for doing completion. Such processes have the
;; environment variable EMACS_BASH_COMPLETE set to t, to help
;; distinguish them from normal shell processes.
;;
;; See the documentation of the function
;; `bash-completion-dynamic-complete-nocomint' to do Bash completion
;; from other buffers or completion engines.
;;; Compatibility:
;; bash-completion.el is known to work with Bash 4.2 and later and
;; Bash 5, on Emacs, starting with version 25.3, under Linux and OSX.
;;; History:
;; Full history is available on
;; https://github.com/szermatt/emacs-bash-completion
;;; Code:
(require 'comint)
(require 'cl-lib)
(require 'shell)
;;; Customization
(defgroup bash-completion nil
"BASH configurable command-line completion."
:group 'shell
:group 'shell-command)
(defcustom bash-completion-enabled t
"Enable/Disable BASH configurable command-line completion globally.
This flag is useful for temporarily disabling bash completion
once it's been installed.
Setting this variable to t is NOT enough to enable BASH completion.
BASH completion is only available in the environment for which
`bash-completion-dynamic-complete' has been registered. See
`bash-completion-setup' for that."
:type '(boolean)
:group 'bash-completion)
(defcustom bash-completion-use-separate-processes nil
"Enable/disable the use of separate processes to perform completion.
When set to a non-nil value, separate processes will always be
used to perform completion. If nil, process associated with the
current buffer will be used to perform completion from a shell
buffer associated to a bash shell, and otherwise a separate process
will be started to do completion."
:type 'boolean
:group 'bash-completion)
(defcustom bash-completion-prog (executable-find "bash")
"Name or path of the BASH executable to run for command-line completion.
This should be either an absolute path to the BASH executable or
the name of the bash command if it is on Emacs' PATH. This should
point to a recent version of BASH 4 or 5, with support for
command-line completion.
This variable is only used when creating separate processes for
performing completion. See
`bash-completion-use-separate-processes' for further
explanation."
:type '(file :must-match t)
:group 'bash-completion)
(defcustom bash-completion-remote-prog "bash"
"Name or path of the remote BASH executable to use.
This is the path of an BASH executable available on the remote machine.
Best is to just specify \"bash\" and rely on the PATH being set correctly
for the remote connection.
This variable is only used when creating separate processes for
performing completion. See
`bash-completion-use-separate-processes' for further
explanation."
:type '(string)
:group 'bash-completion)
(defcustom bash-completion-args '("--noediting")
"Args passed to the BASH shell.
This variable is only used when creating separate processes for
performing completion. See
`bash-completion-use-separate-processes' for further
explanation."
:type '(repeat (string :tag "Argument"))
:group 'bash-completion)
(defcustom bash-completion-process-timeout 2.5
"Number of seconds to wait for an answer from bash.
If bash takes longer than that to answer, the answer will be
ignored."
:type '(float)
:group 'bash-completion)
(defcustom bash-completion-short-command-timeout 0.6
"Number of seconds to wait for bash to start completion.
This is the time it might take for Emacs to notice it's not
actually talking to a functioning Bash process, when
`bash-completion-use-separate-processes` is nil.
This doesn't include the time it takes to execute completion,
which can be quite long, but just the time it normally takes for
the Bash process to respond to Emacs. This should be very short,
unless the remote connection to the Bash process is very slow."
:type '(float)
:group 'bash-completion)
(defcustom bash-completion-command-timeout 30
"Number of seconds to wait for an answer from programmable completion functions.
Programmable completion functions might take an arbitrary long
time to run, so this should be long."
:type '(float)
:group 'bash-completion)
(defcustom bash-completion-message-delay 0.4
"Time to wait before displaying a message while waiting for results.
If completion takes longer than that time, a message is displayed
on the minibuffer to make it clear what's happening. Set to nil
to never display any such message. 0 to always display it.
Only relevant when using bash completion in a shell, through
`bash-completion-dynamic-complete'."
:type '(float)
:group 'bash-completion)
(defcustom bash-completion-initial-timeout 30
"Timeout value to apply when talking to bash for the first time.
The first thing bash is supposed to do is process /etc/bash_complete,
which typically takes a long time.
This variable is only used when creating separate processes for
performing completion. See
`bash-completion-use-separate-processes' for further
explanation."
:type '(float)
:group 'bash-completion)
(defcustom bash-completion-nospace nil
"Never let bash add a final space at the end of a completion.
When there is only one completion candidate, bash sometimes adds
a space at the end of the completion to move the cursor at the
appropriate position to add more command-line arguments. This
feature doesn't always work perfectly with programmable completion.
Enable this option if you find yourself having to often backtrack
to remove the extra space bash adds after a completion."
:type '(boolean)
:group 'bash-completion)
(defvar bash-completion-start-files
(list "~/.emacs_bash.sh" (locate-user-emacs-file "init_bash.sh"))
"Shell files that sourced at the beginning of a bash completion subprocess.
If a listed file does not exist that is silently ignored.
This variable is only used when creating separate processes for
performing completion. See
`bash-completion-use-separate-processes' for further
explanation.")
(defvar bash-completion-wordbreaks ""
"Extra wordbreaks to use when tokenizing, in `bash-completion-tokenize'.")
(defvar bash-completion-output-buffer " *bash-completion*"
"Buffer storing completion results.
This buffer is only used when creating separate processes for
performing completion. See
`bash-completion-use-separate-processes' for further
explanation.")
;;; Internal variables and constants
(defvar bash-completion-processes nil
"Bash processes alist.
Mapping between remote paths as returned by `file-remote-p' and
Bash processes.")
(defconst bash-completion-special-chars "[ -$&-*,:-<>?[-^`{-}]"
"Regexp of characters that must be escaped or quoted.")
(defconst bash-completion--ps1 "'==emacs==ret=$?==.'"
"Value for the special PS1 prompt set for completions, quoted.")
(eval-when-compile
(unless (or (and (= emacs-major-version 25) (>= emacs-minor-version 3))
(>= emacs-major-version 26))
(error
(concat
"Emacs version 25.3 or later is required to run emacs-bash-completion.\n"
"Download emacs-bash-completion version 2.1 to run on Emacs 22 and 23"
"version 3.1.0 to run on Emacs 24."))))
(defvar bash-completion--debug-info nil
"Alist that stores info about the last call to `bash-completion-send'.
Created by `bash-completion-send' and printed by
`bash-completion-debug'.")
;;; Struct
;; The main, completion structure, keeping track of the definition and
;; state of the current completion.
(cl-defstruct (completion (:constructor bash-completion--make)
(:conc-name bash-completion--)
(:copier nil))
line ; the relevant command (string)
words ; line split into words, unescaped (list of strings)
cword ; 0-based index of the word to be completed in words (number)
unparsed-stub ; unparsed version of the thing we are completing,
;;; that is, the part of the last word after the last
;;; wordbreak separator.
stub-start ; start position of the thing we are completing
stub ; parsed version of the stub
open-quote ; quote open at stub end: nil, ?' or ?\""
compgen-args ; compgen arguments for this command (list of strings)
compopt-args ; additional compgen arguments forced with compopt
wordbreaks ; value of COMP_WORDBREAKS active for this completion
)
(defun bash-completion--type (comp)
"Return the type of COMP.
Completion type is `command', if completing a command (cword = 0),
`custom' if there's a custom completion for the current command or
`default' if there isn't or if the completion hasn't been
customized, usually by `bash-completion--customize'."
(cond
((zerop (bash-completion--cword comp)) 'command)
((bash-completion--compgen-args comp) 'custom)
(t 'default)))
(defun bash-completion--nospace (comp)
"Return the value of the nospace option to use for COMP.
The option can be:
- set globally, by setting `bash-completion-nospace' to t
- set for a customized completion, in bash, with
\"-o nospace\".
- set during completion, using compopt"
(or
bash-completion-nospace ; set globally
(eq 'set
(or (bash-completion--get-compgen-option
(bash-completion--compopt-args comp) "nospace")
(bash-completion--get-compgen-option
(bash-completion--compgen-args comp) "nospace")))))
(defun bash-completion--command (comp)
"Return the current command for the completion, if there is one.
Argument COMP is the completion parse."
(file-name-nondirectory (car (bash-completion--words comp))))
(defun bash-completion--get-buffer (process)
"Return the buffer used to store completion results.
PROCESS is the bash process from which completions are
retrieved. When `bash-completion-use-separate-processes' is nil,
PROCESS is not used and `bash-completion-output-buffer' is
returned."
(if bash-completion-use-separate-processes
(process-buffer process)
(get-buffer-create bash-completion-output-buffer)))
(defun bash-completion--setup-bash-common (process)
"Setup PROCESS to be ready for completion."
(unless (zerop
(bash-completion-send
(concat
"echo -n $BASH_VERSION ; "
"[[ ${BASH_VERSINFO[0]} -gt 4 || ( ${BASH_VERSINFO[0]} = 4 && ${BASH_VERSINFO[1]} -ge 2 ) ]]")
process))
(error "bash-completion.el requires at least Bash 4.2, not %s."
(with-current-buffer (bash-completion--get-buffer process)
(buffer-substring-no-properties
(point-min) (point-max)))))
(bash-completion-send
(concat "function __ebcfixdirs {"
" local l; "
" while read l; do "
" [[ \"$l\" = \"==eof==\" ]] && break;"
" if [[ -d \"${l/#\~/$HOME}\" ]]; then echo \"$l/\"; else echo \"$l\"; fi; "
" done; "
"} ; function __ebcompgen {"
" local fd p=$(mktemp -u);"
" mkfifo \"$p\";"
" exec {fd}<>\"$p\";"
" rm -f \"$p\";"
" { __ebcfixdirs & } <&$fd 2>/dev/null;"
" local pid=$!;"
" compgen \"$@\" >&$fd 2>/dev/null; echo ==eof==>&$fd;"
" wait $pid 2>/dev/null;"
" exec {fd}>&-;"
" }; "
"function __ebcwrapper {"
" COMP_TYPE=9; COMP_KEY=9; _EMACS_COMPOPT=\"\";"
" eval $__EBCWRAPPER;"
" local n=$?;"
" if [[ $n = 124 ]]; then"
(bash-completion--side-channel-data "wrapped-status" "124")
" return 1; "
" fi; "
" if [[ -n \"${_EMACS_COMPOPT}\" ]]; then"
(bash-completion--side-channel-data "compopt" "${_EMACS_COMPOPT}")
" fi;"
" return $n;"
"}")
process)
(bash-completion-send
(concat "function compopt {"
" command compopt \"$@\" 2>/dev/null;"
" local ret=$?; "
" if [[ $ret == 1 ]]; then"
" _EMACS_COMPOPT=\"$EMACS_COMPOPT $*\";"
" return 0;"
" fi;"
" return $ret; "
"}")
process)
(bash-completion-send "echo -n $BASH_VERSION" process)
(process-put process 'bash-version
(with-current-buffer (bash-completion--get-buffer process)
(buffer-substring-no-properties
(point-min) (point-max))))
(bash-completion-send "echo -n ${COMP_WORDBREAKS}" process)
(process-put process 'wordbreaks
(with-current-buffer (bash-completion--get-buffer process)
(buffer-substring-no-properties
(point-min) (point-max))))
(bash-completion-send "echo -n ${BASH_COMPLETION_VERSINFO[*]}" process)
(process-put process 'bash-completion-scripts-version
(with-current-buffer (bash-completion--get-buffer process)
(buffer-substring-no-properties
(point-min) (point-max))))
(bash-completion-send "bind -v 2>/dev/null" process)
(process-put process 'completion-ignore-case
(with-current-buffer (bash-completion--get-buffer process)
(save-excursion
(goto-char (point-min))
(and (search-forward "completion-ignore-case on" nil 'noerror) t)))))
;;; Inline functions
(defsubst bash-completion-tokenize-get-range (token)
"Return the TOKEN range as a cons: (start . end)."
(cdr (assq 'range token)))
(defsubst bash-completion-tokenize-set-end (token)
"Set the end position of TOKEN to the cursor position."
(setcdr (bash-completion-tokenize-get-range token) (point)))
(defsubst bash-completion-tokenize-append-str (token str)
"Append to TOKEN the string STR."
(let ((str-cons (assq 'str token)))
(setcdr str-cons (concat (cdr str-cons) str))))
(defsubst bash-completion-tokenize-get-str (token)
"Return the TOKEN string."
(cdr (assq 'str token)))
(defsubst bash-completion-tokenize-open-quote (tokens)
"Return the quote character that was still open in the last token.
TOKENS is a list of token as returned by
`bash-completion-tokenize'."
(cdr (assq 'quote (car (last tokens)))))
;;; Functions: completion
;;;###autoload
(progn
;; The following definition is wrapped in a `progn' to force the
;; autoload scraper to pull the entire definition into the autoload
;; file. That way this function can be invoked without having to
;; immediately load the entire file. This will be done when
;; `bash-completion-dynamic-complete' is actually used by the
;; completion system.
(defun bash-completion-setup ()
"Register bash completion for the shell buffer and shell command line.
This function adds `bash-completion-dynamic-complete' to the completion
function list of shell mode, `shell-dynamic-complete-functions'."
(add-hook 'shell-dynamic-complete-functions
#'bash-completion-dynamic-complete)))
;;;###autoload
(defun bash-completion-dynamic-complete ()
"Return the completion table for bash command at point.
This function is meant to be added into
`shell-dynamic-complete-functions'. It uses `comint' to figure
out what the current command is and returns a completion table or
nil if no completions available.
When doing completion outside of a comint buffer, call
`bash-completion-dynamic-complete-nocomint' instead."
(let ((message-timer
(if (and (not (window-minibuffer-p))
(not (null bash-completion-message-delay)))
(run-at-time
bash-completion-message-delay nil
(lambda () (message "Bash completion..."))))))
(unwind-protect
(bash-completion-dynamic-complete-nocomint
(comint-line-beginning-position)
(point)
'dynamic-table)
;; cleanup
(if message-timer
(cancel-timer message-timer)))))
;;;###autoload
(defun bash-completion-capf-nonexclusive ()
"Bash completion function for `completion-at-point-functions'.
Returns the same list as the one returned by
`bash-completion-dynamic-complete-nocomint' appended with
\(:exclusive no) so that other completion functions are tried
when bash-completion fails to match the text at point."
(let ((compl (bash-completion-dynamic-complete-nocomint
(line-beginning-position)
(point) t)))
(when compl
(append compl '(:exclusive no)))))
;;;###autoload
(defun bash-completion-dynamic-complete-nocomint
(comp-start &optional comp-pos dynamic-table)
"Return completion information for bash command at an arbitrary position.
The bash command to be completed begins at COMP-START in the
current buffer. This must specify where the current command
starts, usually right after the prompt.
COMP-POS is the point where completion should happen, usually
just (point). Note that a bash command can span across multiple
line, so COMP-START is not necessarily on the same line as
COMP-POS.
This function does not assume that the current buffer is a shell
or even comint buffer. It can safely be called from any buffer
where a bash command appears, including `completion-at-point'.
If DYNAMIC-TABLE is passed a non-nil value, the resulting
collection will be a function that fetches the result lazily,
when it's called.
When calling from `completion-at-point', make sure to pass a
non-nil value to DYNAMIC-TABLE. This isn't just an optimization:
returning a function instead of a list tells Emacs it should
avoids post-filtering the results and possibly discarding useful
completion from bash.
When calling from another completion engine, make sure to treat
the returned completion as reliable and not post-process them
further.
Returns (list stub-start stub-end completions) with
- stub-start, the position at which the completed region starts
- stub-end, the position at which the completed region ends
- completions, a possibly empty list of completion candidates
or a function, if DYNAMIC-TABLE is non-nil, a lambda such as the one
returned by `completion-table-dynamic'"
(when bash-completion-enabled
(let ((comp-start (or comp-start (line-beginning-position)))
(comp-pos (or comp-pos (point)))
(bash-completion-use-separate-processes
bash-completion-use-separate-processes)
(process (bash-completion--get-process)))
(when (and (not process) (not bash-completion-use-separate-processes))
;; no process associated with the current buffer, create a
;; separate completion process
(setq bash-completion-use-separate-processes t)
(setq process (bash-completion--get-process)))
(let* ((comp (bash-completion--parse
comp-start comp-pos
(process-get process 'wordbreaks)))
(stub-start (bash-completion--stub-start comp)))
(bash-completion--customize process comp)
(list
stub-start
comp-pos
(if dynamic-table
(bash-completion--completion-table-with-cache
comp process)
(bash-completion-comm comp process)))))))
(defun bash-completion--find-last (elt array)
"Return the position of the last instance of ELT in ARRAY or nil."
(catch 'bash-completion-return
(let ((array-len (length array)))
(dotimes (index array-len)
(if (eq elt (aref array (- array-len index 1)))
(throw 'bash-completion-return (- array-len index 1)))))
nil))
;;; Functions: parsing and tokenizing
(defun bash-completion-join (words)
"Join WORDS into a shell command line.
All words that contain even mildly suspicious characters are
quoted using single quotes to avoid the shell interpreting them
when it shouldn't.
Return one string containing WORDS."
(if words
(mapconcat
'bash-completion-quote
words " ")
""))
(defun bash-completion-quote (word)
"Put single quotes around WORD unless it's crearly unnecessary.
If WORD contains characters that aren't known to be harmless, this
functions adds single quotes around it and return the result."
(cond
((string= "" word)
"''")
((string-match "^[a-zA-Z0-9_./-]*$" word)
word)
(t
(concat "'"
(replace-regexp-in-string "'" "'\\''" word nil t)
"'"))))
(defun bash-completion--parse (comp-start comp-pos wordbreaks)
"Process a command from COMP-START to COMP-POS.
WORDBREAK is the value of COMP_WORDBREAKS to use for this completion,
usually taken from the current process.
Returns a completion struct."
(let* ((all-tokens (bash-completion-tokenize
comp-start comp-pos wordbreaks))
(line-tokens (bash-completion-parse-current-command all-tokens))
(first-token (car line-tokens))
(last-token (car (last line-tokens)))
(open-quote (bash-completion-tokenize-open-quote line-tokens))
(start (or (car (bash-completion-tokenize-get-range first-token)) comp-pos))
(end (or (cdr (bash-completion-tokenize-get-range last-token)) comp-pos))
(words (bash-completion-strings-from-tokens line-tokens))
(rebuilt-line) (stub-start) (unparsed-stub) (parsed-stub))
;; Note about rebuilt-line: When using readline, line and words
;; would be passed unquoted to the functions. This doesn't work,
;; however, when called from Emacs as when readline 'compgen -f'
;; behaves differently and does not unquote the string it's
;; passed. This is why words and the last word of the line are
;; passed unquoted. This makes the standard bash completion
;; scripts work - possibly at the cost of more inconsistencies
;; with other scripts.
(if (or (> comp-pos end) (= start end))
(setq stub-start comp-pos
unparsed-stub ""
parsed-stub ""
words (append words '(""))
rebuilt-line (buffer-substring-no-properties start comp-pos))
(setq stub-start (car (bash-completion-tokenize-get-range last-token))
parsed-stub (bash-completion-tokenize-get-str last-token)
unparsed-stub (buffer-substring-no-properties stub-start comp-pos)
rebuilt-line (concat
(buffer-substring-no-properties
start (car (cdr (assq 'range (car (last line-tokens))))))
(cdr (assq 'str (car (last line-tokens)))))))
(bash-completion--make
:line rebuilt-line
:cword (- (length words) 1)
:words words
:stub-start stub-start
:unparsed-stub unparsed-stub
:stub parsed-stub
:open-quote open-quote
:wordbreaks wordbreaks)))
(defun bash-completion-parse-current-command (tokens)
"Extract from TOKENS the tokens forming the current command.
This function takes a list of TOKENS created by
`bash-completion-tokenize' for the current buffer and select the
tokens on this list that form the current command given that the
word to be completed is the last token.
For example, given this stream of tokens:
cd /var/tmp && ls -l
if the last token is -l, it will select:
ls -l
if the last token is /var/tmp, it will select:
cd /var/tmp
Return a sublist of TOKENS."
(nreverse
(catch 'bash-completion-return
(let ((command nil) (state 'initial))
(dolist (token tokens)
(let* ((string (bash-completion-tokenize-get-str token))
(is-terminal
(and (member string '(";" "&" "|" "&&" "||" "\n"))
(let ((range (bash-completion-tokenize-get-range token)))
(= (- (cdr range) (car range))
(length string))))))
(cond
(is-terminal
(setq state 'initial)
(setq command nil))
((and (eq state 'initial)
(null (string-match "=" string)))
(setq state 'args)
(push token command))
((eq state 'args)
(push token command)))))
(or command (last tokens))))))
(defun bash-completion-strings-from-tokens (tokens)
"Extract the strings from TOKENS.
This function takes all strings from TOKENS and return it as a
list of strings.
TOKENS should be in the format returned by `bash-completion-tokenize'."
(mapcar 'bash-completion-tokenize-get-str tokens))
(defun bash-completion-tokenize (start end &optional wordbreaks)
"Tokenize the portion of the current buffer between START and END.
This function splits a BASH command line into tokens. It knows
about quotes, escape characters and special command separators such
as ;, | and &&. If specified WORDBREAKS contains extra word breaks,
usually taken from COMP_WORDBREAKS, to apply while tokenizing.
This method returns a list of tokens found between START and END,
ordered by position. Tokens contain a string and a range.
The string in a token is an unescaped version of the token. For
example, if the token is \\='hello world\\=', the string contains
\"hello world\", without the quotes. It can be accessed using
`bash-completion-tokenize-get-str'. It can be modified using
`bash-completion-tokenize-append-str'.
The range is a cons containing the start and end position of the
token (start . end). Start is the position of the first character
that belongs to the token. End is the position of the first
character that doesn't belong to the token. For example in the
string \" hello world \", the first token range is (2 . 7) and
the second token range (9 . 14). It can be accessed using
`bash-completion-tokenize-get-range'. The end position can be
set using `bash-completion-tokenize-set-end'.
Tokens should always be accessed using the functions specified above,
never directly as they're likely to change as this code evolves.
The current format of a token is \\='(string . (start . end))."
(let ((tokens nil)
(bash-completion-wordbreaks
(mapconcat 'char-to-string
(delq nil (mapcar
(lambda (c)
(if (memq c '(?\; ?& ?| ?' ?\")) nil c))
(or wordbreaks "")))
"")))
(save-excursion
(goto-char start)
(while (progn (skip-chars-forward " \t\r" end)
(< (point) end))
(setq tokens
(bash-completion-tokenize-new-element end tokens)))
(nreverse tokens))))
(defun bash-completion-tokenize-new-element (limit tokens)
"Tokenize an element from point, up until LIMIT and complete TOKENS.
This function is meant to be called exclusively from
`bash-completion-tokenize' and `bash-completion-tokenize-0'.
This function expects the point to be at the start of a new
element to be added to the list of tokens. It parses the line
until the limit of that element or until LIMIT.
It leaves the point at the position where parsing should
continue.
Return TOKENS with new tokens prepended."
(skip-chars-forward " \t\r" limit)
(if (eq ?\n (char-after))
(progn
(goto-char (1+ (point)))
(cons `((str . "\n") (range ,(point) . ,(1+ (point)))) tokens))
(bash-completion-tokenize-0
limit tokens
(list
(cons 'str "")
(cons 'range (cons (point) nil))))))
(defun bash-completion-tokenize-0 (end tokens token)
"Tokenize the rest of the token until END and add it into TOKENS.
This function is meant to be called exclusively from
`bash-completion-tokenize-new-element'.
This function expect the point to be at the start of a new token
section, either at the start of the token or just after a quote
has been closed in the token. It detects new opening quotes and
calls `bash-completion-tokenize-1'.
END specifies the point at which tokenization should stop.
TOKENS is the list of tokens built so farin reverse order.
TOKEN is the token currently being built.
Return TOKENS with new tokens prepended to it."
(let ((char-start (char-after))
(quote nil) )
(when (and char-start (or (= char-start ?') (= char-start ?\")))
(forward-char)
(setq quote char-start))
(bash-completion-tokenize-1 end quote tokens token)))
(defun bash-completion-tokenize-1 (end quote tokens token)
"Tokenize the rest of the token.
This function is meant to be called exclusively from
`bash-completion-tokenize-0'.
This function tokenizes the rest of the token and either calls
itself and `bash-completion-tokenize-0' recursively or appends
the token to the list of token and calls
`bash-completion-tokenize-new-element' to look for the next
token.
END specifies the point at which tokenization should stop, even
if the token is not complete.
QUOTE specifies the current quote. It should be nil, ?' or ?\"
TOKENS is the list of tokens built so far in reverse order.
TOKEN is the token currently being built.
Sets the point at the position of the next token. Returns TOKENS
with new tokens prepended to it."
;; parse the token elements at the current position and
;; append them
(let ((local-start (point)))
(when (= (skip-chars-forward
(concat "[;&|" bash-completion-wordbreaks "]")
end)
0)
(skip-chars-forward
(bash-completion-nonsep quote bash-completion-wordbreaks) end))
(bash-completion-tokenize-append-str
token
(buffer-substring-no-properties local-start (point))))
(cond
;; an escaped char, skip, whatever it is
((and (char-before) (= ?\\ (char-before)))
(forward-char)
(let ((str (bash-completion-tokenize-get-str token)))
(aset str (1- (length str)) (char-before)))
(bash-completion-tokenize-1 end quote tokens token))
;; opening quote
((and (not quote) (char-after) (or (= ?' (char-after)) (= ?\" (char-after))))
(bash-completion-tokenize-0 end tokens token))
;; closing quote
((and quote (char-after) (= quote (char-after)))
(forward-char)
(bash-completion-tokenize-0 end tokens token))
;; inside a quote
((and quote (char-after) (not (= quote (char-after))))
(forward-char)
(bash-completion-tokenize-append-str token (char-to-string (char-before)))
(bash-completion-tokenize-1 end quote tokens token))
;; word end
(t
(bash-completion-tokenize-set-end token)
(when quote
(push (cons 'quote quote) token))
(push token tokens))))
(defun bash-completion-nonsep (quote wordbreaks)
"Return the set of non-breaking characters when QUOTE is the current quote.
QUOTE should be nil, ?' or ?\"."
(concat
"^ \t\n\r"
(if (null quote) (concat ";&|'\"" wordbreaks)
(char-to-string quote))))
;;; Functions: getting candidates from bash
(defun bash-completion-comm (comp process)
"Call compgen on COMP for PROCESS, return the result.
COMP should be a struct returned by `bash-completion--parse'
This function starts a separate bash process if necessary, sets
up the completion environment (COMP_LINE, COMP_POINT, COMP_WORDS,
COMP_CWORD) and calls compgen.
The result is a list of candidates, which might be empty."
(let* ((buffer (bash-completion--get-buffer process))
(cmd-timeout (if (eq 'custom (bash-completion--type comp))
bash-completion-command-timeout
bash-completion-process-timeout))
(completion-status))
(setq completion-status (bash-completion-send
(bash-completion-generate-line comp)
process cmd-timeout comp))
(when (eq 124 completion-status)
;; Special 'retry-completion' exit status, typically returned by
;; functions bound by complete -D. Presumably, the function has
;; just setup completion for the current command and is asking
;; us to retry once with the new configuration, retrieved by
;; bash-completion--customize.
(bash-completion--customize process comp 'forced)
(setq completion-status (bash-completion-send
(bash-completion-generate-line comp)
process cmd-timeout comp)))
(let ((candidates (when (eq 0 completion-status)
(bash-completion-extract-candidates comp buffer)))
(compopt (bash-completion--compopt-args comp)))
;; Possibly run compgen as instructed by a call to compopt
;; inside of a function.
(when (or (member "plusdir" compopt)
(and (null candidates)
(or (member "default" compopt)
(member "bashdefault" compopt)
(member "dirnames" compopt)
(member "filenames" compopt))))
(setf (bash-completion--compgen-args comp)
(bash-completion--compopt-args comp))
(when (eq 0 (bash-completion-send
(bash-completion-generate-line comp)
process cmd-timeout comp))
(setq candidates (append candidates
(bash-completion-extract-candidates
comp buffer)))))
candidates)))
(defun bash-completion-extract-candidates (comp buffer)
"Extract the completion candidates for COMP form BUFFER.
This command takes the content of the completion process buffer,
splits it by newlines, post-process the candidates and returns
them as a list of strings.
It should be invoked with the comint buffer as the current buffer
for directory name detection to work.
Post-processing includes escaping special characters, adding a /
to directory names, replacing STUB with UNPARSED-STUB in the
result. See `bash-completion-fix' for more details."
(with-current-buffer buffer
(setf (bash-completion--compopt-args comp)
(bash-completion--parse-side-channel-data "compopt" 'tokenize)))
(let* ((output (with-current-buffer buffer (buffer-string)))
(candidates (delete-dups (split-string output "\n" t))))
(if (eq 1 (length candidates))
(list (bash-completion-fix (car candidates) comp t))
;; multiple candidates
(let ((result (list)))
(dolist (completion candidates)
(push (bash-completion-fix completion comp nil) result))
(delete-dups (nreverse result))))))
(defun bash-completion-fix (str comp single)
"Fix completion candidate in STR for COMP.
STR is the completion candidate to modify, COMP the current
completion operation.
If STR is the single candidate, SINGLE is t.
Return a modified version of STR.
Modification include:
- escaping of special characters in STR
- prepending the stub if STR does not contain all of it, when