* etc/NEWS.26: Copy from emacs-26/etc/NEWS.
[emacs.git] / lisp / progmodes / sh-script.el
blob0bda8bc275dc03d3d5698e9174a6b15b55e19358
1 ;;; sh-script.el --- shell-script editing commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1993-1997, 1999, 2001-2017 Free Software Foundation,
4 ;; Inc.
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
7 ;; Version: 2.0f
8 ;; Maintainer: emacs-devel@gnu.org
9 ;; Keywords: languages, unix
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
29 ;; as various derivatives are supported and easily derived from. Structured
30 ;; statements can be inserted with one command or abbrev. Completion is
31 ;; available for filenames, variables known from the script, the shell and
32 ;; the environment as well as commands.
34 ;;; Known Bugs:
36 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
37 ;; - Variables in `"' strings aren't fontified because there's no way of
38 ;; syntactically distinguishing those from `'' strings.
40 ;; Indentation
41 ;; ===========
42 ;; Indentation for rc and es modes is very limited, but for Bourne shells
43 ;; and its derivatives it is quite customizable.
45 ;; The following description applies to sh and derived shells (bash,
46 ;; zsh, ...).
48 ;; There are various customization variables which allow tailoring to
49 ;; a wide variety of styles. Most of these variables are named
50 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
51 ;; sh-indent-after-if controls the indenting of a line following
52 ;; an if statement, and sh-indent-for-fi controls the indentation
53 ;; of the line containing the fi.
55 ;; You can set each to a numeric value, but it is often more convenient
56 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
57 ;; By changing this one variable you can increase or decrease how much
58 ;; indentation there is. Valid symbols:
60 ;; + Indent right by sh-basic-offset
61 ;; - Indent left by sh-basic-offset
62 ;; ++ Indent right twice sh-basic-offset
63 ;; -- Indent left twice sh-basic-offset
64 ;; * Indent right half sh-basic-offset
65 ;; / Indent left half sh-basic-offset.
67 ;; There are 4 commands to help set the indentation variables:
69 ;; `sh-show-indent'
70 ;; This shows what variable controls the indentation of the current
71 ;; line and its value.
73 ;; `sh-set-indent'
74 ;; This allows you to set the value of the variable controlling the
75 ;; current line's indentation. You can enter a number or one of a
76 ;; number of special symbols to denote the value of sh-basic-offset,
77 ;; or its negative, or half it, or twice it, etc. If you've used
78 ;; cc-mode this should be familiar. If you forget which symbols are
79 ;; valid simply press C-h at the prompt.
81 ;; `sh-learn-line-indent'
82 ;; Simply make the line look the way you want it, then invoke this
83 ;; command. It will set the variable to the value that makes the line
84 ;; indent like that. If called with a prefix argument then it will set
85 ;; the value to one of the symbols if applicable.
87 ;; `sh-learn-buffer-indent'
88 ;; This is the deluxe function! It "learns" the whole buffer (use
89 ;; narrowing if you want it to process only part). It outputs to a
90 ;; buffer *indent* any conflicts it finds, and all the variables it has
91 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
92 ;; easily find where something was set. It is popped to automatically
93 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
94 ;; non-nil.
95 ;; `sh-indent-comment' will be set if all comments follow the same
96 ;; pattern; if they don't it will be set to nil.
97 ;; Whether `sh-basic-offset' is set is determined by variable
98 ;; `sh-learn-basic-offset'.
100 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
101 ;; (e.g. if there are large case statements). Perhaps it does not make
102 ;; sense to run it on large buffers: if lots of lines have different
103 ;; indentation styles it will produce a lot of diagnostics in the
104 ;; *indent* buffer; if there is a consistent style then running
105 ;; `sh-learn-buffer-indent' on a small region of the buffer should
106 ;; suffice.
108 ;; Saving indentation values
109 ;; -------------------------
110 ;; After you've learned the values in a buffer, how to you remember
111 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
112 ;; would make this unnecessary; simply learn the values when you visit
113 ;; the buffer.
114 ;; You can do this automatically like this:
115 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
117 ;; However... `sh-learn-buffer-indent' is extremely slow,
118 ;; especially on large-ish buffer. Also, if there are conflicts the
119 ;; "last one wins" which may not produce the desired setting.
121 ;; So...There is a minimal way of being able to save indentation values and
122 ;; to reload them in another buffer or at another point in time.
124 ;; Use `sh-name-style' to give a name to the indentation settings of
125 ;; the current buffer.
126 ;; Use `sh-load-style' to load indentation settings for the current
127 ;; buffer from a specific style.
128 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
129 ;; in lisp code. You can then store it in a file and later use
130 ;; `load-file' to load it.
132 ;; Indentation variables - buffer local or global?
133 ;; ----------------------------------------------
134 ;; I think that often having them buffer-local makes sense,
135 ;; especially if one is using `sh-learn-buffer-indent'. However, if
136 ;; a user sets values using customization, these changes won't appear
137 ;; to work if the variables are already local!
139 ;; To get round this, there is a variable `sh-make-vars-local' and 2
140 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
142 ;; If `sh-make-vars-local' is non-nil, then these variables become
143 ;; buffer local when the mode is established.
144 ;; If this is nil, then the variables are global. At any time you
145 ;; can make them local with the command `sh-make-vars-local'.
146 ;; Conversely, to update with the global values you can use the
147 ;; command `sh-reset-indent-vars-to-global-values'.
149 ;; This may be awkward, but the intent is to cover all cases.
151 ;; Awkward things, pitfalls
152 ;; ------------------------
153 ;; Indentation for a sh script is complicated for a number of reasons:
155 ;; 1. You can't format by simply looking at symbols, you need to look
156 ;; at keywords. [This is not the case for rc and es shells.]
157 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
158 ;; as a stand-alone symbol (in a case alternative). This makes
159 ;; things quite tricky!
160 ;; 3. Here-documents in a script should be treated "as is", and when
161 ;; they terminate we want to revert to the indentation of the line
162 ;; containing the "<<" symbol.
163 ;; 4. A line may be continued using the "\".
164 ;; 5. The character "#" (outside a string) normally starts a comment,
165 ;; but it doesn't in the sequence "$#"!
167 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
168 ;; uses, that of a text's syntax property. This, however, has 2
169 ;; disadvantages:
170 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
171 ;; case alternative, to find any here documents, and handle "$#".
173 ;; Bugs
174 ;; ----
175 ;; - Indenting many lines is slow. It currently does each line
176 ;; independently, rather than saving state information.
178 ;; - `sh-learn-buffer-indent' is extremely slow.
180 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
181 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
182 ;; coerce sh-script into doing the right thing.
184 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
185 ;; a case-pattern. You need to put the "in" between quotes to coerce
186 ;; sh-script into doing the right thing.
188 ;; - A line starting with "}>foo" is not indented like "} >foo".
190 ;; Richard Sharman <rsharman@pobox.com> June 1999.
192 ;;; Code:
194 ;; page 1: variables and settings
195 ;; page 2: indentation stuff
196 ;; page 3: mode-command and utility functions
197 ;; page 4: statement syntax-commands for various shells
198 ;; page 5: various other commands
200 (eval-when-compile
201 (require 'skeleton)
202 (require 'cl-lib)
203 (require 'comint))
204 (require 'executable)
206 (autoload 'comint-completion-at-point "comint")
207 (autoload 'comint-filename-completion "comint")
208 (autoload 'comint-send-string "comint")
209 (autoload 'shell-command-completion "shell")
210 (autoload 'shell-environment-variable-completion "shell")
212 (defvar font-lock-comment-face)
213 (defvar font-lock-set-defaults)
214 (defvar font-lock-string-face)
217 (defgroup sh nil
218 "Shell programming utilities."
219 :group 'languages)
221 (defgroup sh-script nil
222 "Shell script mode."
223 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
224 :group 'sh
225 :prefix "sh-")
228 (defcustom sh-ancestor-alist
229 '((ash . sh)
230 (bash . jsh)
231 (bash2 . jsh)
232 (dash . ash)
233 (dtksh . ksh)
234 (es . rc)
235 (itcsh . tcsh)
236 (jcsh . csh)
237 (jsh . sh)
238 (ksh . ksh88)
239 (ksh88 . jsh)
240 (oash . sh)
241 (pdksh . ksh88)
242 (mksh . pdksh)
243 (posix . sh)
244 (tcsh . csh)
245 (wksh . ksh88)
246 (wsh . sh)
247 (zsh . ksh88)
248 (rpm . sh))
249 "Alist showing the direct ancestor of various shells.
250 This is the basis for `sh-feature'. See also `sh-alias-alist'.
251 By default we have the following three hierarchies:
253 csh C Shell
254 jcsh C Shell with Job Control
255 tcsh TENEX C Shell
256 itcsh Ian's TENEX C Shell
257 rc Plan 9 Shell
258 es Extensible Shell
259 sh Bourne Shell
260 ash Almquist Shell
261 dash Debian Almquist Shell
262 jsh Bourne Shell with Job Control
263 bash GNU Bourne Again Shell
264 ksh88 Korn Shell '88
265 ksh Korn Shell '93
266 dtksh CDE Desktop Korn Shell
267 pdksh Public Domain Korn Shell
268 mksh MirOS BSD Korn Shell
269 wksh Window Korn Shell
270 zsh Z Shell
271 oash SCO OA (curses) Shell
272 posix IEEE 1003.2 Shell Standard
273 wsh ? Shell"
274 :type '(repeat (cons symbol symbol))
275 :version "24.4" ; added dash
276 :group 'sh-script)
278 (defcustom sh-alias-alist
279 (append (if (eq system-type 'gnu/linux)
280 '((csh . tcsh)
281 (ksh . pdksh)))
282 ;; for the time being
283 '((ksh . ksh88)
284 (bash2 . bash)
285 (sh5 . sh)
286 ;; Android's system shell
287 ("^/system/bin/sh$" . mksh)))
288 "Alist for transforming shell names to what they really are.
289 Use this where the name of the executable doesn't correspond to
290 the type of shell it really is. Keys are regular expressions
291 matched against the full path of the interpreter. (For backward
292 compatibility, keys may also be symbols, which are matched
293 against the interpreter's basename. The values are symbols
294 naming the shell."
295 :type '(repeat (cons (radio
296 (regexp :tag "Regular expression")
297 (symbol :tag "Basename"))
298 (symbol :tag "Shell")))
299 :group 'sh-script)
302 (defcustom sh-shell-file
304 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
305 ;; the executable extension, so comparisons with the list of
306 ;; known shells work.
307 (and (memq system-type '(ms-dos windows-nt))
308 (let* ((shell (getenv "SHELL"))
309 (shell-base
310 (and shell (file-name-nondirectory shell))))
311 ;; shell-script mode doesn't support DOS/Windows shells,
312 ;; so use the default instead.
313 (if (or (null shell)
314 (member (downcase shell-base)
315 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
316 "cmdproxy.exe")))
317 "/bin/sh"
318 (file-name-sans-extension (downcase shell)))))
319 (getenv "SHELL")
320 "/bin/sh")
321 "The executable file name for the shell being programmed."
322 :type 'string
323 :group 'sh-script)
326 (defcustom sh-shell-arg
327 ;; bash does not need any options when run in a shell script,
328 '((bash)
329 (csh . "-f")
330 (pdksh)
331 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
332 (ksh88)
333 ;; -p means don't initialize functions from the environment.
334 (rc . "-p")
335 ;; Someone proposed -motif, but we don't want to encourage
336 ;; use of a non-free widget set.
337 (wksh)
338 ;; -f means don't run .zshrc.
339 (zsh . "-f"))
340 "Single argument string for the magic number. See `sh-feature'."
341 :type '(repeat (cons (symbol :tag "Shell")
342 (choice (const :tag "No Arguments" nil)
343 (string :tag "Arguments")
344 (sexp :format "Evaluate: %v"))))
345 :group 'sh-script)
347 (defcustom sh-imenu-generic-expression
348 `((sh
349 . ((nil
350 ;; function FOO
351 ;; function FOO()
352 "^\\s-*function\\s-+\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
354 ;; FOO()
355 (nil
356 "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
359 "Alist of regular expressions for recognizing shell function definitions.
360 See `sh-feature' and `imenu-generic-expression'."
361 :type '(alist :key-type (symbol :tag "Shell")
362 :value-type (alist :key-type (choice :tag "Title"
363 string
364 (const :tag "None" nil))
365 :value-type
366 (repeat :tag "Regexp, index..." sexp)))
367 :group 'sh-script
368 :version "20.4")
370 (defun sh-current-defun-name ()
371 "Find the name of function or variable at point.
372 For use in `add-log-current-defun-function'."
373 (save-excursion
374 (end-of-line)
375 (when (re-search-backward
376 (concat "\\(?:"
377 ;; function FOO
378 ;; function FOO()
379 "^\\s-*function\\s-+\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
380 "\\)\\|\\(?:"
381 ;; FOO()
382 "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
383 "\\)\\|\\(?:"
384 ;; FOO=
385 "^\\([[:alpha:]_][[:alnum:]_]*\\)="
386 "\\)")
387 nil t)
388 (or (match-string-no-properties 1)
389 (match-string-no-properties 2)
390 (match-string-no-properties 3)))))
392 (defvar sh-shell-variables nil
393 "Alist of shell variable names that should be included in completion.
394 These are used for completion in addition to all the variables named
395 in `process-environment'. Each element looks like (VAR . VAR), where
396 the car and cdr are the same symbol.")
398 (defvar sh-shell-variables-initialized nil
399 "Non-nil if `sh-shell-variables' is initialized.")
401 (defun sh-canonicalize-shell (shell)
402 "Convert a shell name SHELL to the one we should handle it as.
403 SHELL is a full path to the shell interpreter; return a shell
404 name symbol."
405 (cl-loop
406 with shell = (cond ((string-match "\\.exe\\'" shell)
407 (substring shell 0 (match-beginning 0)))
408 (t shell))
409 with shell-base = (intern (file-name-nondirectory shell))
410 for (key . value) in sh-alias-alist
411 if (and (stringp key) (string-match key shell)) return value
412 if (eq key shell-base) return value
413 finally return shell-base))
415 (defvar sh-shell (sh-canonicalize-shell sh-shell-file)
416 "The shell being programmed. This is set by \\[sh-set-shell].")
417 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
419 (define-abbrev-table 'sh-mode-abbrev-table ())
422 (defun sh-mode-syntax-table (table &rest list)
423 "Copy TABLE and set syntax for successive CHARs according to strings S."
424 (setq table (copy-syntax-table table))
425 (while list
426 (modify-syntax-entry (pop list) (pop list) table))
427 table)
429 (defvar sh-mode-syntax-table
430 (sh-mode-syntax-table ()
431 ?\# "<"
432 ?\n ">#"
433 ?\" "\"\""
434 ?\' "\"'"
435 ?\` "\"`"
436 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
437 ;; to work fine. This is needed so that dabbrev-expand
438 ;; $VARNAME works.
439 ?$ "'"
440 ?! "_"
441 ?% "_"
442 ?: "_"
443 ?. "_"
444 ?^ "_"
445 ?~ "_"
446 ?, "_"
447 ?= "."
448 ?\; "."
449 ?| "."
450 ?& "."
451 ?< "."
452 ?> ".")
453 "The syntax table to use for Shell-Script mode.
454 This is buffer-local in every such buffer.")
456 (defvar sh-mode-syntax-table-input
457 `((sh . nil)
458 ;; Treat ' as punctuation rather than a string delimiter, as RPM
459 ;; files often contain prose with apostrophes.
460 (rpm . (,sh-mode-syntax-table ?\' ".")))
461 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
463 (defvar sh-mode-map
464 (let ((map (make-sparse-keymap))
465 (menu-map (make-sparse-keymap)))
466 (define-key map "\C-c(" 'sh-function)
467 (define-key map "\C-c\C-w" 'sh-while)
468 (define-key map "\C-c\C-u" 'sh-until)
469 (define-key map "\C-c\C-t" 'sh-tmp-file)
470 (define-key map "\C-c\C-s" 'sh-select)
471 (define-key map "\C-c\C-r" 'sh-repeat)
472 (define-key map "\C-c\C-o" 'sh-while-getopts)
473 (define-key map "\C-c\C-l" 'sh-indexed-loop)
474 (define-key map "\C-c\C-i" 'sh-if)
475 (define-key map "\C-c\C-f" 'sh-for)
476 (define-key map "\C-c\C-c" 'sh-case)
477 (define-key map "\C-c?" 'sh-show-indent)
478 (define-key map "\C-c=" 'sh-set-indent)
479 (define-key map "\C-c<" 'sh-learn-line-indent)
480 (define-key map "\C-c>" 'sh-learn-buffer-indent)
481 (define-key map "\C-c\C-\\" 'sh-backslash-region)
483 (define-key map "=" 'sh-assignment)
484 (define-key map "\C-c+" 'sh-add)
485 (define-key map "\C-\M-x" 'sh-execute-region)
486 (define-key map "\C-c\C-x" 'executable-interpret)
487 (define-key map "\C-c\C-n" 'sh-send-line-or-region-and-step)
488 (define-key map "\C-c\C-d" 'sh-cd-here)
489 (define-key map "\C-c\C-z" 'sh-show-shell)
491 (define-key map [remap delete-backward-char]
492 'backward-delete-char-untabify)
493 (define-key map "\C-c:" 'sh-set-shell)
494 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
495 (define-key map [remap forward-sentence] 'sh-end-of-command)
496 (define-key map [menu-bar sh-script] (cons "Sh-Script" menu-map))
497 (define-key menu-map [sh-learn-buffer-indent]
498 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
499 :help "Learn how to indent the buffer the way it currently is."))
500 (define-key menu-map [sh-learn-line-indent]
501 '(menu-item "Learn line indentation" sh-learn-line-indent
502 :help "Learn how to indent a line as it currently is indented"))
503 (define-key menu-map [sh-show-indent]
504 '(menu-item "Show indentation" sh-show-indent
505 :help "Show the how the current line would be indented"))
506 (define-key menu-map [sh-set-indent]
507 '(menu-item "Set indentation" sh-set-indent
508 :help "Set the indentation for the current line"))
510 (define-key menu-map [sh-pair]
511 '(menu-item "Insert braces and quotes in pairs"
512 electric-pair-mode
513 :button (:toggle . (bound-and-true-p electric-pair-mode))
514 :help "Inserting a brace or quote automatically inserts the matching pair"))
516 (define-key menu-map [sh-s0] '("--"))
517 ;; Insert
518 (define-key menu-map [sh-function]
519 '(menu-item "Function..." sh-function
520 :help "Insert a function definition"))
521 (define-key menu-map [sh-add]
522 '(menu-item "Addition..." sh-add
523 :help "Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
524 (define-key menu-map [sh-until]
525 '(menu-item "Until Loop" sh-until
526 :help "Insert an until loop"))
527 (define-key menu-map [sh-repeat]
528 '(menu-item "Repeat Loop" sh-repeat
529 :help "Insert a repeat loop definition"))
530 (define-key menu-map [sh-while]
531 '(menu-item "While Loop" sh-while
532 :help "Insert a while loop"))
533 (define-key menu-map [sh-getopts]
534 '(menu-item "Options Loop" sh-while-getopts
535 :help "Insert a while getopts loop."))
536 (define-key menu-map [sh-indexed-loop]
537 '(menu-item "Indexed Loop" sh-indexed-loop
538 :help "Insert an indexed loop from 1 to n."))
539 (define-key menu-map [sh-select]
540 '(menu-item "Select Statement" sh-select
541 :help "Insert a select statement "))
542 (define-key menu-map [sh-if]
543 '(menu-item "If Statement" sh-if
544 :help "Insert an if statement"))
545 (define-key menu-map [sh-for]
546 '(menu-item "For Loop" sh-for
547 :help "Insert a for loop"))
548 (define-key menu-map [sh-case]
549 '(menu-item "Case Statement" sh-case
550 :help "Insert a case/switch statement"))
551 (define-key menu-map [sh-s1] '("--"))
552 (define-key menu-map [sh-exec]
553 '(menu-item "Execute region" sh-execute-region
554 :help "Pass optional header and region to a subshell for noninteractive execution"))
555 (define-key menu-map [sh-exec-interpret]
556 '(menu-item "Execute script..." executable-interpret
557 :help "Run script with user-specified args, and collect output in a buffer"))
558 (define-key menu-map [sh-set-shell]
559 '(menu-item "Set shell type..." sh-set-shell
560 :help "Set this buffer's shell to SHELL (a string)"))
561 (define-key menu-map [sh-backslash-region]
562 '(menu-item "Backslash region" sh-backslash-region
563 :help "Insert, align, or delete end-of-line backslashes on the lines in the region."))
564 map)
565 "Keymap used in Shell-Script mode.")
567 (defvar sh-skeleton-pair-default-alist '((?\( _ ?\)) (?\))
568 (?\[ ?\s _ ?\s ?\]) (?\])
569 (?{ _ ?}) (?\}))
570 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
572 (defcustom sh-dynamic-complete-functions
573 '(shell-environment-variable-completion
574 shell-command-completion
575 comint-filename-completion)
576 "Functions for doing TAB dynamic completion."
577 :type '(repeat function)
578 :group 'sh-script)
580 (defcustom sh-assignment-regexp
581 `((csh . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
582 ;; actually spaces are only supported in let/(( ... ))
583 (ksh88 . ,(concat "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?"
584 "[ \t]*\\(?:[-+*/%&|~^]\\|<<\\|>>\\)?="))
585 (bash . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?\\+?=")
586 (rc . "\\<\\([[:alnum:]_*]+\\)[ \t]*=")
587 (sh . "\\<\\([[:alnum:]_]+\\)="))
588 "Regexp for the variable name and what may follow in an assignment.
589 First grouping matches the variable name. This is upto and including the `='
590 sign. See `sh-feature'."
591 :type '(repeat (cons (symbol :tag "Shell")
592 (choice regexp
593 (sexp :format "Evaluate: %v"))))
594 :group 'sh-script)
597 (defcustom sh-indentation 4
598 "The width for further indentation in Shell-Script mode."
599 :type 'integer
600 :group 'sh-script)
601 (put 'sh-indentation 'safe-local-variable 'integerp)
603 (defcustom sh-remember-variable-min 3
604 "Don't remember variables less than this length for completing reads."
605 :type 'integer
606 :group 'sh-script)
609 (defvar sh-header-marker nil
610 "When non-nil is the end of header for prepending by \\[sh-execute-region].
611 That command is also used for setting this variable.")
612 (make-variable-buffer-local 'sh-header-marker)
614 (defcustom sh-beginning-of-command
615 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
616 "Regexp to determine the beginning of a shell command.
617 The actual command starts at the beginning of the second \\(grouping\\)."
618 :type 'regexp
619 :group 'sh-script)
622 (defcustom sh-end-of-command
623 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
624 "Regexp to determine the end of a shell command.
625 The actual command ends at the end of the first \\(grouping\\)."
626 :type 'regexp
627 :group 'sh-script)
631 (defcustom sh-here-document-word "EOF"
632 "Word to delimit here documents.
633 If the first character of this string is \"-\", this is taken as
634 part of the redirection operator, rather than part of the
635 word (that is, \"<<-\" instead of \"<<\"). This is a feature
636 used by some shells (for example Bash) to indicate that leading
637 tabs inside the here document should be ignored. In this case,
638 Emacs indents the initial body and end of the here document with
639 tabs, to the same level as the start (note that apart from this
640 there is no support for indentation of here documents). This
641 will only work correctly if `sh-basic-offset' is a multiple of
642 `tab-width'.
644 Any quote characters or leading whitespace in the word are
645 removed when closing the here document."
646 :type 'string
647 :group 'sh-script)
650 (defvar sh-test
651 '((sh "[ ]" . 3)
652 (ksh88 "[[ ]]" . 4))
653 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
656 ;; customized this out of sheer bravado. not for the faint of heart.
657 ;; but it *did* have an asterisk in the docstring!
658 (defcustom sh-builtins
659 '((bash sh-append posix
660 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
661 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
662 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
663 "source" "suspend" "typeset" "unalias"
664 ;; bash4
665 "mapfile" "readarray" "coproc")
667 ;; The next entry is only used for defining the others
668 (bourne sh-append shell
669 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
670 "times" "ulimit")
672 (csh sh-append shell
673 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
674 "setenv" "source" "time" "unalias" "unhash")
676 (dtksh sh-append wksh)
678 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
679 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
681 (jsh sh-append sh
682 "bg" "fg" "jobs" "kill" "stop" "suspend")
684 (jcsh sh-append csh
685 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
687 (ksh88 sh-append bourne
688 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
689 "typeset" "unalias" "whence")
691 (oash sh-append sh
692 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
693 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
694 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
695 "wmtitle" "wrefresh")
697 (pdksh sh-append ksh88
698 "bind")
700 (posix sh-append sh
701 "command")
703 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
704 "whatis")
706 (sh sh-append bourne
707 "hash" "test" "type")
709 ;; The next entry is only used for defining the others
710 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
712 (wksh sh-append ksh88)
714 (zsh sh-append ksh88
715 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
716 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
717 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
718 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
719 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
720 "which"))
721 "List of all shell builtins for completing read and fontification.
722 Note that on some systems not all builtins are available or some are
723 implemented as aliases. See `sh-feature'."
724 :type '(repeat (cons (symbol :tag "Shell")
725 (choice (repeat string)
726 (sexp :format "Evaluate: %v"))))
727 :version "24.4" ; bash4 additions
728 :group 'sh-script)
732 (defcustom sh-leading-keywords
733 '((bash sh-append sh
734 "time")
736 (csh "else")
738 (es "true" "unwind-protect" "whatis")
740 (rc "else")
742 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
743 "List of keywords that may be immediately followed by a builtin or keyword.
744 Given some confusion between keywords and builtins depending on shell and
745 system, the distinction here has been based on whether they influence the
746 flow of control or syntax. See `sh-feature'."
747 :type '(repeat (cons (symbol :tag "Shell")
748 (choice (repeat string)
749 (sexp :format "Evaluate: %v"))))
750 :group 'sh-script)
753 (defcustom sh-other-keywords
754 '((bash sh-append bourne
755 "bye" "logout" "select")
757 ;; The next entry is only used for defining the others
758 (bourne sh-append sh
759 "function")
761 (csh sh-append shell
762 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
763 "if" "logout" "onintr" "repeat" "switch" "then" "while")
765 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
766 "return" "throw" "while")
768 (ksh88 sh-append bourne
769 "select")
771 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
772 "while")
774 (sh sh-append shell
775 "done" "esac" "fi" "for" "in" "return")
777 ;; The next entry is only used for defining the others
778 (shell "break" "case" "continue" "exec" "exit")
780 (zsh sh-append bash
781 "select" "foreach"))
782 "List of keywords not in `sh-leading-keywords'.
783 See `sh-feature'."
784 :type '(repeat (cons (symbol :tag "Shell")
785 (choice (repeat string)
786 (sexp :format "Evaluate: %v"))))
787 :group 'sh-script)
791 (defvar sh-variables
792 '((bash sh-append sh
793 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
794 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
795 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
796 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
797 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
798 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
799 "HISTIGNORE" "history_control" "HISTSIZE"
800 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
801 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
802 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
803 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
804 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
805 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
806 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
808 (csh sh-append shell
809 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
810 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
811 "shell" "status" "time" "verbose")
813 (es sh-append shell
814 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
815 "pid" "prompt" "signals")
817 (jcsh sh-append csh
818 "notify")
820 (ksh88 sh-append sh
821 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
822 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
823 "TMOUT")
825 (oash sh-append sh
826 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
828 (rc sh-append shell
829 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
830 "prompt" "status")
832 (sh sh-append shell
833 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
835 ;; The next entry is only used for defining the others
836 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
837 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
838 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
839 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
841 (tcsh sh-append csh
842 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
843 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
844 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
845 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
846 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
847 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
848 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
849 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
850 "wordchars")
852 (zsh sh-append ksh88
853 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
854 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
855 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
856 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
857 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
858 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
859 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
860 "List of all shell variables available for completing read.
861 See `sh-feature'.")
864 ;; Font-Lock support
866 (defface sh-heredoc
867 '((((min-colors 88) (class color)
868 (background dark))
869 (:foreground "yellow1" :weight bold))
870 (((class color)
871 (background dark))
872 (:foreground "yellow" :weight bold))
873 (((class color)
874 (background light))
875 (:foreground "tan1" ))
877 (:weight bold)))
878 "Face to show a here-document."
879 :group 'sh-indentation)
881 ;; These colors are probably icky. It's just a placeholder though.
882 (defface sh-quoted-exec
883 '((((class color) (background dark))
884 (:foreground "salmon"))
885 (((class color) (background light))
886 (:foreground "magenta"))
888 (:weight bold)))
889 "Face to show quoted execs like \\=`blabla\\=`."
890 :group 'sh-indentation)
892 (defface sh-escaped-newline '((t :inherit font-lock-string-face))
893 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
894 :group 'sh-script
895 :version "22.1")
897 (defvar sh-font-lock-keywords-var
898 '((csh sh-append shell
899 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
900 font-lock-variable-name-face))
902 (es sh-append executable-font-lock-keywords
903 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
904 font-lock-variable-name-face))
906 (rc sh-append es)
907 (bash sh-append sh ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
908 (sh sh-append shell
909 ;; Variable names.
910 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
911 font-lock-variable-name-face)
912 ;; Function names.
913 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
914 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
915 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
916 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
917 1 font-lock-negation-char-face))
919 ;; The next entry is only used for defining the others
920 (shell
921 ;; Using font-lock-string-face here confuses sh-get-indent-info.
922 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
923 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
924 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
925 font-lock-variable-name-face))
926 (rpm sh-append rpm2
927 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
928 (rpm2 sh-append shell
929 ("^Summary:\\(.*\\)$" (1 font-lock-doc-face t))
930 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
931 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
933 (defvar sh-font-lock-keywords-var-1
934 '((sh "[ \t]in\\>"))
935 "Subdued level highlighting for Shell Script modes.")
937 (defvar sh-font-lock-keywords-var-2 ()
938 "Gaudy level highlighting for Shell Script modes.")
940 ;; These are used for the syntax table stuff (derived from cperl-mode).
941 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
942 (defconst sh-st-punc (string-to-syntax "."))
943 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
945 (eval-and-compile
946 (defconst sh-escaped-line-re
947 ;; Should match until the real end-of-continued-line, but if that is not
948 ;; possible (because we bump into EOB or the search bound), then we should
949 ;; match until the search bound.
950 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
952 (defconst sh-here-doc-open-re
953 (concat "[^<]<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|[-/~._]\\)+\\)"
954 sh-escaped-line-re "\\(\n\\)")))
956 (defun sh--inside-noncommand-expression (pos)
957 (save-excursion
958 (let ((ppss (syntax-ppss pos)))
959 (when (nth 1 ppss)
960 (goto-char (nth 1 ppss))
962 (pcase (char-after)
963 ;; ((...)) or $((...)) or $[...] or ${...}. Nested
964 ;; parenthesis can occur inside the first of these forms, so
965 ;; parse backward recursively.
966 (`?\( (eq ?\( (char-before)))
967 ((or `?\{ `?\[) (eq ?\$ (char-before))))
968 (sh--inside-noncommand-expression (1- (point))))))))
970 (defun sh-font-lock-open-heredoc (start string eol)
971 "Determine the syntax of the \\n after a <<EOF.
972 START is the position of <<.
973 STRING is the actual word used as delimiter (e.g. \"EOF\").
974 INDENTED is non-nil if the here document's content (and the EOF mark) can
975 be indented (i.e. a <<- was used rather than just <<).
976 Point is at the beginning of the next line."
977 (unless (or (memq (char-before start) '(?< ?>))
978 (sh-in-comment-or-string start)
979 (sh--inside-noncommand-expression start))
980 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
981 ;; font-lock keywords to detect the end of this here document.
982 (let ((str (replace-regexp-in-string "['\"]" "" string))
983 (ppss (save-excursion (syntax-ppss eol))))
984 (if (nth 4 ppss)
985 ;; The \n not only starts the heredoc but also closes a comment.
986 ;; Let's close the comment just before the \n.
987 (put-text-property (1- eol) eol 'syntax-table '(12))) ;">"
988 (if (or (nth 5 ppss) (> (count-lines start eol) 1))
989 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
990 ;; several lines, make sure we refontify them together.
991 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
992 ;; escaped), it means the right \n is actually further down.
993 ;; Don't bother fixing it now, but place a multiline property so
994 ;; that when jit-lock-context-* refontifies the rest of the
995 ;; buffer, it also refontifies the current line with it.
996 (put-text-property start (1+ eol) 'syntax-multiline t))
997 (put-text-property eol (1+ eol) 'sh-here-doc-marker str)
998 (prog1 sh-here-doc-syntax
999 (goto-char (+ 2 start))))))
1001 (defun sh-syntax-propertize-here-doc (end)
1002 (let ((ppss (syntax-ppss)))
1003 (when (eq t (nth 3 ppss))
1004 (let ((key (get-text-property (nth 8 ppss) 'sh-here-doc-marker))
1005 (case-fold-search nil))
1006 (when (re-search-forward
1007 (concat "^\\([ \t]*\\)" (regexp-quote key) "\\(\n\\)")
1008 end 'move)
1009 (let ((eol (match-beginning 2)))
1010 (put-text-property eol (1+ eol)
1011 'syntax-table sh-here-doc-syntax)))))))
1013 (defun sh-font-lock-quoted-subshell (limit)
1014 "Search for a subshell embedded in a string.
1015 Find all the unescaped \" characters within said subshell, remembering that
1016 subshells can nest."
1017 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1018 ;; bingo we have a $( or a ` inside a ""
1019 (let (;; `state' can be: double-quote, backquote, code.
1020 (state (if (eq (char-before) ?`) 'backquote 'code))
1021 (startpos (point))
1022 ;; Stacked states in the context.
1023 (states '(double-quote)))
1024 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1025 (< (point) limit)))
1026 ;; unescape " inside a $( ... ) construct.
1027 (pcase (char-after)
1028 (?\' (pcase state
1029 (`double-quote nil)
1030 (_ (forward-char 1)
1031 ;; FIXME: mark skipped double quotes as punctuation syntax.
1032 (let ((spos (point)))
1033 (skip-chars-forward "^'" limit)
1034 (save-excursion
1035 (let ((epos (point)))
1036 (goto-char spos)
1037 (while (search-forward "\"" epos t)
1038 (put-text-property (point) (1- (point))
1039 'syntax-table '(1)))))))))
1040 (?\\ (forward-char 1))
1041 (?\" (pcase state
1042 (`double-quote (setq state (pop states)))
1043 (_ (push state states) (setq state 'double-quote)))
1044 (if state (put-text-property (point) (1+ (point))
1045 'syntax-table '(1))))
1046 (?\` (pcase state
1047 (`backquote (setq state (pop states)))
1048 (_ (push state states) (setq state 'backquote))))
1049 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1051 (forward-char 1)
1052 (pcase state
1053 (_ (push state states) (setq state 'code)))))
1054 (?\( (pcase state
1055 (`double-quote nil)
1056 (_ (push state states) (setq state 'code))))
1057 (?\) (pcase state
1058 (`double-quote nil)
1059 (_ (setq state (pop states)))))
1060 (_ (error "Internal error in sh-font-lock-quoted-subshell")))
1061 (forward-char 1))
1062 (when (< startpos (line-beginning-position))
1063 (put-text-property startpos (point) 'syntax-multiline t)
1064 (add-hook 'syntax-propertize-extend-region-functions
1065 'syntax-propertize-multiline nil t))
1069 (defun sh-is-quoted-p (pos)
1070 (and (eq (char-before pos) ?\\)
1071 (not (sh-is-quoted-p (1- pos)))))
1073 (defun sh-font-lock-paren (start)
1074 (unless (nth 8 (syntax-ppss))
1075 (save-excursion
1076 (let ((open nil))
1077 (goto-char start)
1078 ;; Skip through all patterns
1079 (while
1080 (progn
1081 (while
1082 (progn
1083 (forward-comment (- (point-max)))
1084 (when (and (eolp) (sh-is-quoted-p (point)))
1085 (forward-char -1)
1086 t)))
1087 ;; Skip through one pattern
1088 (while
1089 (or (/= 0 (skip-syntax-backward "w_"))
1090 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1091 (and (sh-is-quoted-p (1- (point)))
1092 (goto-char (- (point) 2)))
1093 (when (memq (char-before) '(?\" ?\' ?\}))
1094 (condition-case nil (progn (backward-sexp 1) t)
1095 (error nil)))))
1096 ;; Patterns can be preceded by an open-paren (bug#1320).
1097 (when (eq (char-before (point)) ?\()
1098 (backward-char 1)
1099 (setq open (point)))
1100 (while (progn
1101 (forward-comment (- (point-max)))
1102 ;; Maybe we've bumped into an escaped newline.
1103 (sh-is-quoted-p (point)))
1104 (backward-char 1))
1105 (when (eq (char-before) ?|)
1106 (backward-char 1) t)))
1107 (and (> (point) (1+ (point-min)))
1108 (progn (backward-char 2)
1109 (if (> start (line-end-position))
1110 (put-text-property (point) (1+ start)
1111 'syntax-multiline t))
1112 ;; FIXME: The `in' may just be a random argument to
1113 ;; a normal command rather than the real `in' keyword.
1114 ;; I.e. we should look back to try and find the
1115 ;; corresponding `case'.
1116 (and (looking-at ";[;&]\\|\\_<in")
1117 ;; ";; esac )" is a case that looks
1118 ;; like a case-pattern but it's really just a close
1119 ;; paren after a case statement. I.e. if we skipped
1120 ;; over `esac' just now, we're not looking
1121 ;; at a case-pattern.
1122 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1123 (progn
1124 (when open
1125 (put-text-property open (1+ open) 'syntax-table sh-st-punc))
1126 sh-st-punc))))))
1128 (defun sh-font-lock-backslash-quote ()
1129 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1130 ;; In a '...' the backslash is not escaping.
1131 sh-st-punc
1132 nil))
1134 (defun sh-syntax-propertize-function (start end)
1135 (goto-char start)
1136 (sh-syntax-propertize-here-doc end)
1137 (funcall
1138 (syntax-propertize-rules
1139 (sh-here-doc-open-re
1140 (2 (sh-font-lock-open-heredoc
1141 (1+ (match-beginning 0)) (match-string 1) (match-beginning 2))))
1142 ("\\s|" (0 (prog1 nil (sh-syntax-propertize-here-doc end))))
1143 ;; A `#' begins a comment when it is unquoted and at the
1144 ;; beginning of a word. In the shell, words are separated by
1145 ;; metacharacters. The list of special chars is taken from
1146 ;; the single-unix spec of the shell command language (under
1147 ;; `quoting') but with `$' removed.
1148 ("\\(?:[^|&;<>()`\\\"' \t\n]\\|\\${\\)\\(#+\\)" (1 "_"))
1149 ;; In a '...' the backslash is not escaping.
1150 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1151 ;; Make sure $@ and $? are correctly recognized as sexps.
1152 ("\\$\\([?@]\\)" (1 "_"))
1153 ;; Distinguish the special close-paren in `case'.
1154 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1155 ;; Highlight (possibly nested) subshells inside "" quoted
1156 ;; regions correctly.
1157 ("\"\\(?:\\(?:[^\\\"]\\|\\\\.\\)*?\\)??\\(\\$(\\|`\\)"
1158 (1 (ignore
1159 (if (nth 8 (save-excursion (syntax-ppss (match-beginning 0))))
1160 (goto-char (1+ (match-beginning 0)))
1161 ;; Save excursion because we want to also apply other
1162 ;; syntax-propertize rules within the affected region.
1163 (save-excursion
1164 (sh-font-lock-quoted-subshell end)))))))
1165 (point) end))
1166 (defun sh-font-lock-syntactic-face-function (state)
1167 (let ((q (nth 3 state)))
1168 (if q
1169 (if (characterp q)
1170 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1171 'sh-heredoc)
1172 font-lock-comment-face)))
1174 (defgroup sh-indentation nil
1175 "Variables controlling indentation in shell scripts.
1177 Note: customizing these variables will not affect existing buffers if
1178 `sh-make-vars-local' is non-nil. See the documentation for
1179 variable `sh-make-vars-local', command `sh-make-vars-local'
1180 and command `sh-reset-indent-vars-to-global-values'."
1181 :group 'sh-script)
1184 (defcustom sh-set-shell-hook nil
1185 "Hook run by `sh-set-shell'."
1186 :type 'hook
1187 :group 'sh-script)
1189 (defcustom sh-mode-hook '(sh-electric-here-document-mode)
1190 "Hook run by `sh-mode'."
1191 :type 'hook
1192 :options '(sh-electric-here-document-mode)
1193 :group 'sh-script)
1195 (defcustom sh-learn-basic-offset nil
1196 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1198 nil mean: never.
1199 t means: only if there seems to be an obvious value.
1200 Anything else means: whenever we have a \"good guess\" as to the value."
1201 :type '(choice
1202 (const :tag "Never" nil)
1203 (const :tag "Only if sure" t)
1204 (const :tag "If have a good guess" usually))
1205 :group 'sh-indentation)
1207 (defcustom sh-popup-occur-buffer nil
1208 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1209 If t it is always shown. If nil, it is shown only when there
1210 are conflicts."
1211 :type '(choice
1212 (const :tag "Only when there are conflicts." nil)
1213 (const :tag "Always" t))
1214 :group 'sh-indentation)
1216 (defcustom sh-blink t
1217 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1218 The position on the line is not necessarily meaningful.
1219 In some cases the line will be the matching keyword, but this is not
1220 always the case."
1221 :type 'boolean
1222 :group 'sh-indentation)
1224 (defcustom sh-first-lines-indent 0
1225 "The indentation of the first non-blank non-comment line.
1226 Usually 0 meaning first column.
1227 Can be set to a number, or to nil which means leave it as is."
1228 :type '(choice
1229 (const :tag "Leave as is" nil)
1230 (integer :tag "Column number"
1231 :menu-tag "Indent to this col (0 means first col)" ))
1232 :group 'sh-indentation)
1235 (defcustom sh-basic-offset 4
1236 "The default indentation increment.
1237 This value is used for the `+' and `-' symbols in an indentation variable."
1238 :type 'integer
1239 :group 'sh-indentation)
1240 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1242 (defcustom sh-indent-comment t
1243 "How a comment line is to be indented.
1244 nil means leave it as it is;
1245 t means indent it as a normal line, aligning it to previous non-blank
1246 non-comment line;
1247 a number means align to that column, e.g. 0 means first column."
1248 :type '(choice
1249 (const :tag "Leave as is." nil)
1250 (const :tag "Indent as a normal line." t)
1251 (integer :menu-tag "Indent to this col (0 means first col)."
1252 :tag "Indent to column number.") )
1253 :version "24.3"
1254 :group 'sh-indentation)
1257 (defvar sh-debug nil
1258 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1261 ;; Uncomment this defun and comment the defmacro for debugging.
1262 ;; (defun sh-debug (&rest args)
1263 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1264 ;; (if sh-debug
1265 ;; (apply 'message args)))
1266 (defmacro sh-debug (&rest _args))
1268 (defconst sh-symbol-list
1269 '((const :tag "+ " :value +
1270 :menu-tag "+ Indent right by sh-basic-offset")
1271 (const :tag "- " :value -
1272 :menu-tag "- Indent left by sh-basic-offset")
1273 (const :tag "++" :value ++
1274 :menu-tag "++ Indent right twice sh-basic-offset")
1275 (const :tag "--" :value --
1276 :menu-tag "-- Indent left twice sh-basic-offset")
1277 (const :tag "* " :value *
1278 :menu-tag "* Indent right half sh-basic-offset")
1279 (const :tag "/ " :value /
1280 :menu-tag "/ Indent left half sh-basic-offset")))
1282 (defcustom sh-indent-for-else 0
1283 "How much to indent an `else' relative to its `if'. Usually 0."
1284 :type `(choice
1285 (integer :menu-tag "A number (positive=>indent right)"
1286 :tag "A number")
1287 (const :tag "--") ;; separator!
1288 ,@ sh-symbol-list
1290 :group 'sh-indentation)
1292 (defconst sh-number-or-symbol-list
1293 (append '((integer :menu-tag "A number (positive=>indent right)"
1294 :tag "A number")
1295 (const :tag "--")) ; separator
1296 sh-symbol-list))
1298 (defcustom sh-indent-for-fi 0
1299 "How much to indent a `fi' relative to its `if'. Usually 0."
1300 :type `(choice ,@ sh-number-or-symbol-list )
1301 :group 'sh-indentation)
1303 (defcustom sh-indent-for-done 0
1304 "How much to indent a `done' relative to its matching stmt. Usually 0."
1305 :type `(choice ,@ sh-number-or-symbol-list )
1306 :group 'sh-indentation)
1308 (defcustom sh-indent-after-else '+
1309 "How much to indent a statement after an `else' statement."
1310 :type `(choice ,@ sh-number-or-symbol-list )
1311 :group 'sh-indentation)
1313 (defcustom sh-indent-after-if '+
1314 "How much to indent a statement after an `if' statement.
1315 This includes lines after `else' and `elif' statements, too, but
1316 does not affect the `else', `elif' or `fi' statements themselves."
1317 :type `(choice ,@ sh-number-or-symbol-list )
1318 :group 'sh-indentation)
1320 (defcustom sh-indent-for-then 0
1321 "How much to indent a `then' relative to its `if'."
1322 :type `(choice ,@ sh-number-or-symbol-list )
1323 :group 'sh-indentation)
1325 (defcustom sh-indent-for-do 0
1326 "How much to indent a `do' statement.
1327 This is relative to the statement before the `do', typically a
1328 `while', `until', `for', `repeat' or `select' statement."
1329 :type `(choice ,@ sh-number-or-symbol-list)
1330 :group 'sh-indentation)
1332 (defcustom sh-indent-after-do '+
1333 "How much to indent a line after a `do' statement.
1334 This is used when the `do' is the first word of the line.
1335 This is relative to the statement before the `do', typically a
1336 `while', `until', `for', `repeat' or `select' statement."
1337 :type `(choice ,@ sh-number-or-symbol-list)
1338 :group 'sh-indentation)
1340 (defcustom sh-indent-after-loop-construct '+
1341 "How much to indent a statement after a loop construct.
1343 This variable is used when the keyword `do' is on the same line as the
1344 loop statement (e.g., `until', `while' or `for').
1345 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1346 :type `(choice ,@ sh-number-or-symbol-list)
1347 :group 'sh-indentation)
1350 (defcustom sh-indent-after-done 0
1351 "How much to indent a statement after a `done' keyword.
1352 Normally this is 0, which aligns the `done' to the matching
1353 looping construct line.
1354 Setting it non-zero allows you to have the `do' statement on a line
1355 by itself and align the done under to do."
1356 :type `(choice ,@ sh-number-or-symbol-list)
1357 :group 'sh-indentation)
1359 (defcustom sh-indent-for-case-label '+
1360 "How much to indent a case label statement.
1361 This is relative to the line containing the `case' statement."
1362 :type `(choice ,@ sh-number-or-symbol-list)
1363 :group 'sh-indentation)
1365 (defcustom sh-indent-for-case-alt '++
1366 "How much to indent statements after the case label.
1367 This is relative to the line containing the `case' statement."
1368 :type `(choice ,@ sh-number-or-symbol-list)
1369 :group 'sh-indentation)
1372 (defcustom sh-indent-for-continuation '+
1373 "How much to indent for a continuation statement."
1374 :type `(choice ,@ sh-number-or-symbol-list)
1375 :group 'sh-indentation)
1377 (defcustom sh-indent-after-open '+
1378 "How much to indent after a line with an opening parenthesis or brace.
1379 For an open paren after a function, `sh-indent-after-function' is used."
1380 :type `(choice ,@ sh-number-or-symbol-list)
1381 :group 'sh-indentation)
1383 (defcustom sh-indent-after-function '+
1384 "How much to indent after a function line."
1385 :type `(choice ,@ sh-number-or-symbol-list)
1386 :group 'sh-indentation)
1388 ;; These 2 are for the rc shell:
1390 (defcustom sh-indent-after-switch '+
1391 "How much to indent a `case' statement relative to the `switch' statement.
1392 This is for the rc shell."
1393 :type `(choice ,@ sh-number-or-symbol-list)
1394 :group 'sh-indentation)
1396 (defcustom sh-indent-after-case '+
1397 "How much to indent a statement relative to the `case' statement.
1398 This is for the rc shell."
1399 :type `(choice ,@ sh-number-or-symbol-list)
1400 :group 'sh-indentation)
1402 (defcustom sh-backslash-column 48
1403 "Column in which `sh-backslash-region' inserts backslashes."
1404 :type 'integer
1405 :group 'sh)
1407 (defcustom sh-backslash-align t
1408 "If non-nil, `sh-backslash-region' will align backslashes."
1409 :type 'boolean
1410 :group 'sh)
1412 ;; Internal use - not designed to be changed by the user:
1414 (defun sh-mkword-regexpr (word)
1415 "Make a regexp which matches WORD as a word.
1416 This specifically excludes an occurrence of WORD followed by
1417 punctuation characters like `-'."
1418 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1420 (defconst sh-re-done (sh-mkword-regexpr "done"))
1423 (defconst sh-kws-for-done
1424 '((sh . ( "while" "until" "for" ) )
1425 (bash . ( "while" "until" "for" "select" ) )
1426 (ksh88 . ( "while" "until" "for" "select" ) )
1427 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1428 "Which keywords can match the word `done' in this shell.")
1431 (defconst sh-indent-supported
1432 '((sh . sh)
1433 (csh . nil)
1434 (rc . rc))
1435 "Indentation rule set to use for each shell type.")
1437 (defvar sh-indent-supported-here nil
1438 "Non-nil if we support indentation for the current buffer's shell type.")
1440 (defconst sh-var-list
1442 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1443 sh-indent-after-do sh-indent-after-done
1444 sh-indent-after-else
1445 sh-indent-after-if
1446 sh-indent-after-loop-construct
1447 sh-indent-after-open
1448 sh-indent-comment
1449 sh-indent-for-case-alt
1450 sh-indent-for-case-label
1451 sh-indent-for-continuation
1452 sh-indent-for-do
1453 sh-indent-for-done
1454 sh-indent-for-else
1455 sh-indent-for-fi
1456 sh-indent-for-then
1458 "A list of variables used by script mode to control indentation.
1459 This list is used when switching between buffer-local and global
1460 values of variables, and for the commands using indentation styles.")
1462 (defvar sh-make-vars-local t
1463 "Controls whether indentation variables are local to the buffer.
1464 If non-nil, indentation variables are made local initially.
1465 If nil, you can later make the variables local by invoking
1466 command `sh-make-vars-local'.
1467 The default is t because I assume that in one Emacs session one is
1468 frequently editing existing scripts with different styles.")
1471 ;; inferior shell interaction
1472 ;; TODO: support multiple interactive shells
1473 (defvar-local sh-shell-process nil
1474 "The inferior shell process for interaction.")
1476 (defvar explicit-shell-file-name)
1478 (defun sh-shell-process (force)
1479 "Get a shell process for interaction.
1480 If FORCE is non-nil and no process found, create one."
1481 (if (process-live-p sh-shell-process)
1482 sh-shell-process
1483 (setq sh-shell-process
1484 (let ((found nil) proc
1485 (procs (process-list)))
1486 (while (and (not found) procs
1487 (process-live-p (setq proc (pop procs)))
1488 (process-command proc))
1489 (when (string-equal sh-shell (file-name-nondirectory
1490 (car (process-command proc))))
1491 (setq found proc)))
1492 (or found
1493 (and force
1494 (get-buffer-process
1495 (let ((explicit-shell-file-name sh-shell-file))
1496 (shell)))))))))
1498 (defun sh-show-shell ()
1499 "Pop the shell interaction buffer."
1500 (interactive)
1501 (pop-to-buffer (process-buffer (sh-shell-process t))))
1503 (defun sh-send-text (text)
1504 "Send the text to the `sh-shell-process'."
1505 (comint-send-string (sh-shell-process t) (concat text "\n")))
1507 (defun sh-cd-here ()
1508 "Change directory in the current interaction shell to the current one."
1509 (interactive)
1510 (sh-send-text (concat "cd " default-directory)))
1512 (defun sh-send-line-or-region-and-step ()
1513 "Send the current line to the inferior shell and step to the next line.
1514 When the region is active, send the region instead."
1515 (interactive)
1516 (let (from to end)
1517 (if (use-region-p)
1518 (setq from (region-beginning)
1519 to (region-end)
1520 end to)
1521 (setq from (line-beginning-position)
1522 to (line-end-position)
1523 end (1+ to)))
1524 (sh-send-text (buffer-substring-no-properties from to))
1525 (goto-char end)))
1528 ;; mode-command and utility functions
1530 (defun sh-after-hack-local-variables ()
1531 (when (assq 'sh-shell file-local-variables-alist)
1532 (sh-set-shell (if (symbolp sh-shell)
1533 (symbol-name sh-shell)
1534 sh-shell))))
1536 ;;;###autoload
1537 (define-derived-mode sh-mode prog-mode "Shell-script"
1538 "Major mode for editing shell scripts.
1539 This mode works for many shells, since they all have roughly the same syntax,
1540 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1541 Unless the file's magic number indicates the shell, your usual shell is
1542 assumed. Since filenames rarely give a clue, they are not further analyzed.
1544 This mode adapts to the variations between shells (see `sh-set-shell') by
1545 means of an inheritance based feature lookup (see `sh-feature'). This
1546 mechanism applies to all variables (including skeletons) that pertain to
1547 shell-specific features. Shell script files can use the `sh-shell' local
1548 variable to indicate the shell variant to be used for the file.
1550 The default style of this mode is that of Rosenblatt's Korn shell book.
1551 The syntax of the statements varies with the shell being used. The
1552 following commands are available, based on the current shell's syntax:
1553 \\<sh-mode-map>
1554 \\[sh-case] case statement
1555 \\[sh-for] for loop
1556 \\[sh-function] function definition
1557 \\[sh-if] if statement
1558 \\[sh-indexed-loop] indexed loop from 1 to n
1559 \\[sh-while-getopts] while getopts loop
1560 \\[sh-repeat] repeat loop
1561 \\[sh-select] select loop
1562 \\[sh-until] until loop
1563 \\[sh-while] while loop
1565 For sh and rc shells indentation commands are:
1566 \\[sh-show-indent] Show the variable controlling this line's indentation.
1567 \\[sh-set-indent] Set then variable controlling this line's indentation.
1568 \\[sh-learn-line-indent] Change the indentation variable so this line
1569 would indent to the way it currently is.
1570 \\[sh-learn-buffer-indent] Set the indentation variables so the
1571 buffer indents as it currently is indented.
1574 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1575 \\[sh-end-of-command] Go to end of successive commands.
1576 \\[sh-beginning-of-command] Go to beginning of successive commands.
1577 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1578 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1580 `sh-electric-here-document-mode' controls whether insertion of two
1581 unquoted < insert a here document. You can control this behavior by
1582 modifying `sh-mode-hook'.
1584 If you generally program a shell different from your login shell you can
1585 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1586 indicate what shell it is use `sh-alias-alist' to translate.
1588 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1589 with your script for an edit-interpret-debug cycle."
1590 (make-local-variable 'sh-shell-file)
1591 (make-local-variable 'sh-shell)
1593 (setq-local skeleton-pair-default-alist
1594 sh-skeleton-pair-default-alist)
1596 (setq-local paragraph-start (concat page-delimiter "\\|$"))
1597 (setq-local paragraph-separate (concat paragraph-start "\\|#!/"))
1598 (setq-local comment-start "# ")
1599 (setq-local comment-start-skip "#+[\t ]*")
1600 (setq-local local-abbrev-table sh-mode-abbrev-table)
1601 (setq-local comint-dynamic-complete-functions
1602 sh-dynamic-complete-functions)
1603 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t)
1604 ;; we can't look if previous line ended with `\'
1605 (setq-local comint-prompt-regexp "^[ \t]*")
1606 (setq-local imenu-case-fold-search nil)
1607 (setq font-lock-defaults
1608 `((sh-font-lock-keywords
1609 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1610 nil nil
1611 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1612 (font-lock-syntactic-face-function
1613 . sh-font-lock-syntactic-face-function)))
1614 (setq-local syntax-propertize-function #'sh-syntax-propertize-function)
1615 (add-hook 'syntax-propertize-extend-region-functions
1616 #'syntax-propertize-multiline 'append 'local)
1617 (setq-local skeleton-pair-alist '((?` _ ?`)))
1618 (setq-local skeleton-pair-filter-function 'sh-quoted-p)
1619 (setq-local skeleton-further-elements
1620 '((< '(- (min sh-indentation (current-column))))))
1621 (setq-local skeleton-filter-function 'sh-feature)
1622 (setq-local skeleton-newline-indent-rigidly t)
1623 (setq-local defun-prompt-regexp
1624 (concat
1625 "^\\("
1626 "\\(function[ \t]\\)?[ \t]*[[:alnum:]]+[ \t]*([ \t]*)"
1627 "\\|"
1628 "function[ \t]+[[:alnum:]]+[ \t]*\\(([ \t]*)\\)?"
1629 "\\)[ \t]*"))
1630 (setq-local add-log-current-defun-function #'sh-current-defun-name)
1631 (add-hook 'completion-at-point-functions
1632 #'sh-completion-at-point-function nil t)
1633 ;; Parse or insert magic number for exec, and set all variables depending
1634 ;; on the shell thus determined.
1635 (sh-set-shell
1636 (cond ((save-excursion
1637 (goto-char (point-min))
1638 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1639 (match-string 2))
1640 ((not buffer-file-name) sh-shell-file)
1641 ;; Checks that use `buffer-file-name' follow.
1642 ((string-match "\\.m?spec\\'" buffer-file-name) "rpm")
1643 ((string-match "[.]sh\\>" buffer-file-name) "sh")
1644 ((string-match "[.]bash\\>" buffer-file-name) "bash")
1645 ((string-match "[.]ksh\\>" buffer-file-name) "ksh")
1646 ((string-match "[.]mkshrc\\>" buffer-file-name) "mksh")
1647 ((string-match "[.]t?csh\\(rc\\)?\\>" buffer-file-name) "csh")
1648 ((string-match "[.]zsh\\(rc\\|env\\)?\\>" buffer-file-name) "zsh")
1649 ((equal (file-name-nondirectory buffer-file-name) ".profile") "sh")
1650 (t sh-shell-file))
1651 nil nil)
1652 (add-hook 'hack-local-variables-hook
1653 #'sh-after-hack-local-variables nil t))
1655 ;;;###autoload
1656 (defalias 'shell-script-mode 'sh-mode)
1659 (defun sh-font-lock-keywords (&optional keywords)
1660 "Function to get simple fontification based on `sh-font-lock-keywords'.
1661 This adds rules for comments and assignments."
1662 (sh-feature sh-font-lock-keywords-var
1663 (when (stringp (sh-feature sh-assignment-regexp))
1664 (lambda (list)
1665 `((,(sh-feature sh-assignment-regexp)
1666 1 font-lock-variable-name-face)
1667 ,@keywords
1668 ,@list
1669 ,@executable-font-lock-keywords)))))
1671 (defun sh-font-lock-keywords-1 (&optional builtins)
1672 "Function to get better fontification including keywords."
1673 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1674 (regexp-opt (sh-feature sh-leading-keywords) t)
1675 "[ \t]+\\)?"
1676 (regexp-opt (append (sh-feature sh-leading-keywords)
1677 (sh-feature sh-other-keywords))
1678 t))))
1679 (sh-font-lock-keywords
1680 `(,@(if builtins
1681 `((,(concat keywords "[ \t]+\\)?"
1682 (regexp-opt (sh-feature sh-builtins) t)
1683 "\\>")
1684 (2 font-lock-keyword-face nil t)
1685 (6 font-lock-builtin-face))
1686 ,@(sh-feature sh-font-lock-keywords-var-2)))
1687 (,(concat keywords "\\)\\>")
1688 2 font-lock-keyword-face)
1689 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1691 (defun sh-font-lock-keywords-2 ()
1692 "Function to get better fontification including keywords and builtins."
1693 (sh-font-lock-keywords-1 t))
1695 ;;; Completion
1697 (defun sh--vars-before-point ()
1698 (save-excursion
1699 (let ((vars ()))
1700 (while (re-search-backward "^[ \t]*\\([[:alnum:]_]+\\)=" nil t)
1701 (push (match-string 1) vars))
1702 vars)))
1704 ;; (defun sh--var-completion-table (string pred action)
1705 ;; (complete-with-action action (sh--vars-before-point) string pred))
1707 (defun sh--cmd-completion-table (string pred action)
1708 (let ((cmds
1709 (append (when (fboundp 'imenu--make-index-alist)
1710 (mapcar #'car
1711 (condition-case nil
1712 (imenu--make-index-alist)
1713 (imenu-unavailable nil))))
1714 (mapcar (lambda (v) (concat v "="))
1715 (sh--vars-before-point))
1716 (locate-file-completion-table
1717 exec-path exec-suffixes string pred t)
1718 '("if" "while" "until" "for"))))
1719 (complete-with-action action cmds string pred)))
1721 (defun sh-completion-at-point-function ()
1722 (save-excursion
1723 (skip-chars-forward "[:alnum:]_")
1724 (let ((end (point))
1725 (_ (skip-chars-backward "[:alnum:]_"))
1726 (start (point)))
1727 (cond
1728 ((eq (char-before) ?$)
1729 (list start end (sh--vars-before-point)))
1730 ((sh-smie--keyword-p)
1731 (list start end #'sh--cmd-completion-table))))))
1733 ;;; Indentation and navigation with SMIE.
1735 (require 'smie)
1737 ;; The SMIE code should generally be preferred, but it currently does not obey
1738 ;; the various indentation custom-vars, and it misses some important features
1739 ;; of the old code, mostly: sh-learn-line/buffer-indent, sh-show-indent,
1740 ;; sh-name/save/load-style.
1741 (defvar sh-use-smie t
1742 "Whether to use the SMIE code for navigation and indentation.")
1744 (defun sh-smie--keyword-p ()
1745 "Non-nil if we're at a keyword position.
1746 A keyword position is one where if we're looking at something that looks
1747 like a keyword, then it is a keyword."
1748 (let ((prev (funcall smie-backward-token-function)))
1749 (if (zerop (length prev))
1750 (looking-back "\\`\\|\\s(" (1- (point)))
1751 (assoc prev smie-grammar))))
1753 (defun sh-smie--newline-semi-p (&optional tok)
1754 "Return non-nil if a newline should be treated as a semi-colon.
1755 Here we assume that a newline should be treated as a semi-colon unless it
1756 comes right after a special keyword.
1757 This function does not pay attention to line-continuations.
1758 If TOK is nil, point should be before the newline; otherwise, TOK is the token
1759 before the newline and in that case point should be just before the token."
1760 (save-excursion
1761 (unless tok
1762 (setq tok (funcall smie-backward-token-function)))
1763 (if (and (zerop (length tok))
1764 (looking-back "\\s(" (1- (point))))
1766 (not (numberp (nth 2 (assoc tok smie-grammar)))))))
1768 ;;;; SMIE support for `sh'.
1770 (defconst sh-smie-sh-grammar
1771 (smie-prec2->grammar
1772 (smie-bnf->prec2
1773 '((exp) ;A constant, or a $var, or a sequence of them...
1774 (cmd ("case" exp "in" branches "esac")
1775 ("if" cmd "then" cmd "fi")
1776 ("if" cmd "then" cmd "else" cmd "fi")
1777 ("if" cmd "then" cmd "elif" cmd "then" cmd "fi")
1778 ("if" cmd "then" cmd "elif" cmd "then" cmd "else" cmd "fi")
1779 ("if" cmd "then" cmd "elif" cmd "then" cmd
1780 "elif" cmd "then" cmd "else" cmd "fi")
1781 ("while" cmd "do" cmd "done")
1782 ("until" cmd "do" cmd "done")
1783 ("for" exp "in" cmd "do" cmd "done")
1784 ("for" exp "do" cmd "done")
1785 ("select" exp "in" cmd "do" cmd "done") ;bash&zsh&ksh88.
1786 ("repeat" exp "do" cmd "done") ;zsh.
1787 (exp "always" exp) ;zsh.
1788 (cmd "|" cmd) (cmd "|&" cmd)
1789 (cmd "&&" cmd) (cmd "||" cmd)
1790 (cmd ";" cmd) (cmd "&" cmd))
1791 (rpattern (rpattern "|" rpattern))
1792 (pattern (rpattern) ("case-(" rpattern))
1793 (branches (branches ";;" branches)
1794 (branches ";&" branches) (branches ";;&" branches) ;bash.
1795 (pattern "case-)" cmd)))
1796 '((assoc ";;" ";&" ";;&"))
1797 '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1799 (defconst sh-smie--sh-operators
1800 (delq nil (mapcar (lambda (x)
1801 (setq x (car x))
1802 (and (stringp x)
1803 (not (string-match "\\`[a-z]" x))
1805 sh-smie-sh-grammar)))
1807 (defconst sh-smie--sh-operators-re (regexp-opt sh-smie--sh-operators))
1808 (defconst sh-smie--sh-operators-back-re
1809 (concat "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*"
1810 "\\(" sh-smie--sh-operators-re "\\)"))
1812 (defun sh-smie--sh-keyword-in-p ()
1813 "Assuming we're looking at \"in\", return non-nil if it's a keyword.
1814 Does not preserve point."
1815 (let ((forward-sexp-function nil)
1816 (words nil) ;We've seen words.
1817 (newline nil) ;We've seen newlines after the words.
1818 (res nil)
1819 prev)
1820 (while (not res)
1821 (setq prev (funcall smie-backward-token-function))
1822 (cond
1823 ((zerop (length prev))
1824 (cond
1825 (newline (cl-assert words) (setq res 'word))
1826 ((bobp) (setq res 'word))
1828 (setq words t)
1829 (condition-case nil
1830 (forward-sexp -1)
1831 (scan-error (setq res 'unknown))))))
1832 ((equal prev ";")
1833 (if words (setq newline t)
1834 (setq res 'keyword)))
1835 ((member prev '("case" "for" "select")) (setq res 'keyword))
1836 ((assoc prev smie-grammar) (setq res 'word))
1838 (if newline
1839 (progn (cl-assert words) (setq res 'word))
1840 (setq words t)))))
1841 (eq res 'keyword)))
1843 (defun sh-smie--sh-keyword-p (tok)
1844 "Non-nil if TOK (at which we're looking) really is a keyword."
1845 (cond
1846 ((looking-at "[[:alnum:]_]+=") nil)
1847 ((equal tok "in") (sh-smie--sh-keyword-in-p))
1848 (t (sh-smie--keyword-p))))
1850 (defun sh-smie--default-forward-token ()
1851 (forward-comment (point-max))
1852 (buffer-substring-no-properties
1853 (point)
1854 (progn (if (zerop (skip-syntax-forward "."))
1855 (while (progn (skip-syntax-forward "w_'")
1856 (looking-at "\\\\"))
1857 (forward-char 2)))
1858 (point))))
1860 (defun sh-smie--default-backward-token ()
1861 (forward-comment (- (point)))
1862 (let ((pos (point))
1863 (n (skip-syntax-backward ".")))
1864 (if (or (zerop n)
1865 (and (eq n -1)
1866 (let ((p (point)))
1867 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1869 (goto-char p)
1870 nil))))
1871 (while
1872 (progn (skip-syntax-backward "w_'")
1873 (or (not (zerop (skip-syntax-backward "\\")))
1874 (when (eq ?\\ (char-before (1- (point))))
1875 (let ((p (point)))
1876 (forward-char -1)
1877 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1879 (goto-char p)
1880 nil))))))
1881 (goto-char (- (point) (% (skip-syntax-backward "\\") 2))))
1882 (buffer-substring-no-properties (point) pos)))
1884 (defun sh-smie-sh-forward-token ()
1885 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1886 (save-excursion
1887 (skip-chars-backward " \t")
1888 (not (bolp))))
1889 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1890 ;; Right before a here-doc.
1891 (let ((forward-sexp-function nil))
1892 (forward-sexp 1)
1893 ;; Pretend the here-document is a "newline representing a
1894 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1895 ";")
1896 (unless (eobp)
1897 (let ((semi (sh-smie--newline-semi-p)))
1898 (forward-line 1)
1899 (if (or semi (eobp)) ";"
1900 (sh-smie-sh-forward-token)))))
1901 (forward-comment (point-max))
1902 (cond
1903 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1904 ((looking-at sh-smie--sh-operators-re)
1905 (goto-char (match-end 0))
1906 (let ((tok (match-string-no-properties 0)))
1907 (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1908 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1909 (forward-line 1))
1910 tok))
1912 (let* ((pos (point))
1913 (tok (sh-smie--default-forward-token)))
1914 (cond
1915 ((equal tok ")") "case-)")
1916 ((equal tok "(") "case-(")
1917 ((and tok (string-match "\\`[a-z]" tok)
1918 (assoc tok smie-grammar)
1919 (not
1920 (save-excursion
1921 (goto-char pos)
1922 (sh-smie--sh-keyword-p tok))))
1923 " word ")
1924 (t tok)))))))
1926 (defun sh-smie--looking-back-at-continuation-p ()
1927 (save-excursion
1928 (and (if (eq (char-before) ?\n) (progn (forward-char -1) t) (eolp))
1929 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1930 (line-beginning-position)))))
1932 (defun sh-smie-sh-backward-token ()
1933 (let ((bol (line-beginning-position)))
1934 (forward-comment (- (point)))
1935 (cond
1936 ((and (bolp) (not (bobp))
1937 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1938 (not (nth 3 (syntax-ppss))))
1939 ;; Right after a here-document.
1940 (let ((forward-sexp-function nil))
1941 (forward-sexp -1)
1942 ;; Pretend the here-document is a "newline representing a
1943 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1944 ";"))
1945 ((< (point) bol)
1946 (cond
1947 ((sh-smie--looking-back-at-continuation-p)
1948 (forward-char -1)
1949 (funcall smie-backward-token-function))
1950 ((sh-smie--newline-semi-p) ";")
1951 (t (funcall smie-backward-token-function))))
1952 ((looking-back sh-smie--sh-operators-back-re
1953 (line-beginning-position) 'greedy)
1954 (goto-char (match-beginning 1))
1955 (match-string-no-properties 1))
1957 (let ((tok (sh-smie--default-backward-token)))
1958 (cond
1959 ((equal tok ")") "case-)")
1960 ((equal tok "(") "case-(")
1961 ((and tok (string-match "\\`[a-z]" tok)
1962 (assoc tok smie-grammar)
1963 (not (save-excursion (sh-smie--sh-keyword-p tok))))
1964 " word ")
1965 (t tok)))))))
1967 (defcustom sh-indent-after-continuation t
1968 "If non-nil, indent relative to the continued line's beginning.
1969 Continued lines can either be indented as \"one long wrapped line\" without
1970 paying attention to the actual syntactic structure, as in:
1972 for f \\
1973 in a; do \\
1974 toto; \\
1975 done
1977 or as lines that just don't have implicit semi-colons between them, as in:
1979 for f \\
1980 in a; do \\
1981 toto; \\
1982 done
1984 With `always' you get the former behavior whereas with nil you get the latter.
1985 With t, you get the latter as long as that would indent the continuation line
1986 deeper than the initial line."
1987 :version "25.1"
1988 :type '(choice
1989 (const nil :tag "Never")
1990 (const t :tag "Only if needed to make it deeper")
1991 (const always :tag "Always"))
1992 :group 'sh-indentation)
1994 (defun sh-smie--continuation-start-indent ()
1995 "Return the initial indentation of a continued line.
1996 May return nil if the line should not be treated as continued."
1997 (save-excursion
1998 (forward-line -1)
1999 (unless (sh-smie--looking-back-at-continuation-p)
2000 (current-indentation))))
2002 (defun sh-smie--indent-continuation ()
2003 (cond
2004 ((not (and sh-indent-after-continuation
2005 (save-excursion
2006 (ignore-errors
2007 (skip-chars-backward " \t")
2008 (sh-smie--looking-back-at-continuation-p)))))
2009 nil)
2010 ((eq sh-indent-after-continuation 'always)
2011 (save-excursion
2012 (forward-line -1)
2013 (if (sh-smie--looking-back-at-continuation-p)
2014 (current-indentation)
2015 (+ (current-indentation) sh-indentation))))
2017 ;; Just make sure a line-continuation is indented deeper.
2018 (save-excursion
2019 (let ((indent (let ((sh-indent-after-continuation nil))
2020 (smie-indent-calculate)))
2021 (max most-positive-fixnum))
2022 (if (not (numberp indent)) indent
2023 (while (progn
2024 (forward-line -1)
2025 (let ((ci (current-indentation)))
2026 (cond
2027 ;; Previous line is less indented, we're good.
2028 ((< ci indent) nil)
2029 ((sh-smie--looking-back-at-continuation-p)
2030 (setq max (min max ci))
2031 ;; Previous line is itself a continuation.
2032 ;; If it's indented like us, we're good, otherwise
2033 ;; check the line before that one.
2034 (> ci indent))
2035 (t ;Previous line is the beginning of the continued line.
2036 (setq indent (min (+ ci sh-indentation) max))
2037 nil)))))
2038 indent))))))
2040 (defun sh-smie-sh-rules (kind token)
2041 (pcase (cons kind token)
2042 (`(:elem . basic) sh-indentation)
2043 (`(:after . "case-)") (- (sh-var-value 'sh-indent-for-case-alt)
2044 (sh-var-value 'sh-indent-for-case-label)))
2045 (`(:before . ,(or `"(" `"{" `"[" "while" "if" "for" "case"))
2046 (if (not (smie-rule-prev-p "&&" "||" "|"))
2047 (when (smie-rule-hanging-p)
2048 (smie-rule-parent))
2049 (unless (smie-rule-bolp)
2050 (while (equal "|" (nth 2 (smie-backward-sexp 'halfexp))))
2051 `(column . ,(smie-indent-virtual)))))
2052 ;; FIXME: Maybe this handling of ;; should be made into
2053 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
2054 (`(:before . ,(or `";;" `";&" `";;&"))
2055 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
2056 (cons 'column (smie-indent-keyword ";"))
2057 (smie-rule-separator kind)))
2058 (`(:after . ,(or `";;" `";&" `";;&"))
2059 (with-demoted-errors
2060 (smie-backward-sexp token)
2061 (cons 'column
2062 (if (or (smie-rule-bolp)
2063 (save-excursion
2064 (and (member (funcall smie-backward-token-function)
2065 '("in" ";;"))
2066 (smie-rule-bolp))))
2067 (current-column)
2068 (smie-indent-calculate)))))
2069 (`(:before . ,(or `"|" `"&&" `"||"))
2070 (unless (smie-rule-parent-p token)
2071 (smie-backward-sexp token)
2072 `(column . ,(+ (funcall smie-rules-function :elem 'basic)
2073 (smie-indent-virtual)))))
2075 ;; Attempt at backward compatibility with the old config variables.
2076 (`(:before . "fi") (sh-var-value 'sh-indent-for-fi))
2077 (`(:before . "done") (sh-var-value 'sh-indent-for-done))
2078 (`(:after . "else") (sh-var-value 'sh-indent-after-else))
2079 (`(:after . "if") (sh-var-value 'sh-indent-after-if))
2080 (`(:before . "then") (sh-var-value 'sh-indent-for-then))
2081 (`(:before . "do") (sh-var-value 'sh-indent-for-do))
2082 (`(:after . "do")
2083 (sh-var-value (if (smie-rule-hanging-p)
2084 'sh-indent-after-loop-construct 'sh-indent-after-do)))
2085 ;; sh-indent-after-done: aligned completely differently.
2086 (`(:after . "in") (sh-var-value 'sh-indent-for-case-label))
2087 ;; sh-indent-for-continuation: Line continuations are handled differently.
2088 (`(:after . ,(or `"(" `"{" `"["))
2089 (if (not (looking-at ".[ \t]*[^\n \t#]"))
2090 (sh-var-value 'sh-indent-after-open)
2091 (goto-char (1- (match-end 0)))
2092 `(column . ,(current-column))))
2093 ;; sh-indent-after-function: we don't handle it differently.
2096 ;; (defconst sh-smie-csh-grammar
2097 ;; (smie-prec2->grammar
2098 ;; (smie-bnf->prec2
2099 ;; '((exp) ;A constant, or a $var, or a sequence of them...
2100 ;; (elseifcmd (cmd)
2101 ;; (cmd "else" "else-if" exp "then" elseifcmd))
2102 ;; (cmd ("switch" branches "endsw")
2103 ;; ("if" exp)
2104 ;; ("if" exp "then" cmd "endif")
2105 ;; ("if" exp "then" cmd "else" cmd "endif")
2106 ;; ("if" exp "then" elseifcmd "endif")
2107 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
2108 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2109 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2110 ;; ;; "else" cmd "endif")
2111 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2112 ;; ;; "else" "if" exp "then" cmd "endif")
2113 ;; ("while" cmd "end")
2114 ;; ("foreach" cmd "end")
2115 ;; (cmd "|" cmd) (cmd "|&" cmd)
2116 ;; (cmd "&&" cmd) (cmd "||" cmd)
2117 ;; (cmd ";" cmd) (cmd "&" cmd))
2118 ;; ;; This is a lie, but (combined with the corresponding disambiguation
2119 ;; ;; rule) it makes it more clear that `case' and `default' are the key
2120 ;; ;; separators and the `:' is a secondary tokens.
2121 ;; (branches (branches "case" branches)
2122 ;; (branches "default" branches)
2123 ;; (exp ":" branches)))
2124 ;; '((assoc "else" "then" "endif"))
2125 ;; '((assoc "case" "default") (nonassoc ":"))
2126 ;; '((assoc ";;" ";&" ";;&"))
2127 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2129 ;;;; SMIE support for `rc'.
2131 (defconst sh-smie-rc-grammar
2132 (smie-prec2->grammar
2133 (smie-bnf->prec2
2134 '((exp) ;A constant, or a $var, or a sequence of them...
2135 (cmd (cmd "case" cmd)
2136 ("if" exp)
2137 ("switch" exp)
2138 ("for" exp) ("while" exp)
2139 (cmd "|" cmd) (cmd "|&" cmd)
2140 (cmd "&&" cmd) (cmd "||" cmd)
2141 (cmd ";" cmd) (cmd "&" cmd))
2142 (pattern (pattern "|" pattern))
2143 (branches (branches ";;" branches)
2144 (branches ";&" branches) (branches ";;&" branches) ;bash.
2145 (pattern "case-)" cmd)))
2146 '((assoc ";;" ";&" ";;&"))
2147 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2149 (defun sh-smie--rc-after-special-arg-p ()
2150 "Check if we're after the first arg of an if/while/for/... construct.
2151 Returns the construct's token and moves point before it, if so."
2152 (forward-comment (- (point)))
2153 (when (looking-back ")\\|\\_<not" (- (point) 3))
2154 (ignore-errors
2155 (let ((forward-sexp-function nil))
2156 (forward-sexp -1)
2157 (car (member (funcall smie-backward-token-function)
2158 '("if" "for" "switch" "while")))))))
2160 (defun sh-smie--rc-newline-semi-p ()
2161 "Return non-nil if a newline should be treated as a semi-colon.
2162 Point should be before the newline."
2163 (save-excursion
2164 (let ((tok (funcall smie-backward-token-function)))
2165 (if (or (when (equal tok "not") (forward-word-strictly 1) t)
2166 (and (zerop (length tok)) (eq (char-before) ?\))))
2167 (not (sh-smie--rc-after-special-arg-p))
2168 (sh-smie--newline-semi-p tok)))))
2170 (defun sh-smie-rc-forward-token ()
2171 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2172 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2173 (save-excursion
2174 (skip-chars-backward " \t")
2175 (not (bolp))))
2176 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2177 ;; Right before a here-doc.
2178 (let ((forward-sexp-function nil))
2179 (forward-sexp 1)
2180 ;; Pretend the here-document is a "newline representing a
2181 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2182 ";")
2183 (let ((semi (sh-smie--rc-newline-semi-p)))
2184 (forward-line 1)
2185 (if (or semi (eobp)) ";"
2186 (sh-smie-rc-forward-token))))
2187 (forward-comment (point-max))
2188 (cond
2189 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2190 ;; ((looking-at sh-smie--rc-operators-re)
2191 ;; (goto-char (match-end 0))
2192 ;; (let ((tok (match-string-no-properties 0)))
2193 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2194 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2195 ;; (forward-line 1))
2196 ;; tok))
2198 (let* ((pos (point))
2199 (tok (sh-smie--default-forward-token)))
2200 (cond
2201 ;; ((equal tok ")") "case-)")
2202 ((and tok (string-match "\\`[a-z]" tok)
2203 (assoc tok smie-grammar)
2204 (not
2205 (save-excursion
2206 (goto-char pos)
2207 (sh-smie--keyword-p))))
2208 " word ")
2209 (t tok)))))))
2211 (defun sh-smie-rc-backward-token ()
2212 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
2213 (let ((bol (line-beginning-position)))
2214 (forward-comment (- (point)))
2215 (cond
2216 ((and (bolp) (not (bobp))
2217 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2218 (not (nth 3 (syntax-ppss))))
2219 ;; Right after a here-document.
2220 (let ((forward-sexp-function nil))
2221 (forward-sexp -1)
2222 ;; Pretend the here-document is a "newline representing a
2223 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2224 ";"))
2225 ((< (point) bol) ;We skipped over a newline.
2226 (cond
2227 ;; A continued line.
2228 ((and (eolp)
2229 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2230 (line-beginning-position)))
2231 (forward-char -1)
2232 (funcall smie-backward-token-function))
2233 ((sh-smie--rc-newline-semi-p) ";")
2234 (t (funcall smie-backward-token-function))))
2235 ;; ((looking-back sh-smie--sh-operators-back-re
2236 ;; (line-beginning-position) 'greedy)
2237 ;; (goto-char (match-beginning 1))
2238 ;; (match-string-no-properties 1))
2240 (let ((tok (sh-smie--default-backward-token)))
2241 (cond
2242 ;; ((equal tok ")") "case-)")
2243 ((and tok (string-match "\\`[a-z]" tok)
2244 (assoc tok smie-grammar)
2245 (not (save-excursion (sh-smie--keyword-p))))
2246 " word ")
2247 (t tok)))))))
2249 (defun sh-smie-rc-rules (kind token)
2250 (pcase (cons kind token)
2251 (`(:elem . basic) sh-indentation)
2252 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
2253 (`(:after . ";")
2254 (if (smie-rule-parent-p "case")
2255 (smie-rule-parent (sh-var-value 'sh-indent-after-case))))
2256 (`(:before . "{")
2257 (save-excursion
2258 (when (sh-smie--rc-after-special-arg-p)
2259 `(column . ,(current-column)))))
2260 (`(:before . ,(or `"(" `"{" `"["))
2261 (if (smie-rule-hanging-p) (smie-rule-parent)))
2262 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2263 ;; treated as an arg to (exp) by default, which indents it all wrong.
2264 ;; To handle it right, we should extend smie-indent-exps so that the
2265 ;; preceding keyword can give special rules. Currently the only special
2266 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2267 ;; with "(exp)", which is rarely the right thing to do, but is better
2268 ;; than nothing.
2269 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
2270 ;; sh-indent-after-switch: handled implicitly by the default { rule.
2273 ;;; End of SMIE code.
2275 (defvar sh-regexp-for-done nil
2276 "A buffer-local regexp to match opening keyword for done.")
2278 (defvar sh-kw-alist nil
2279 "A buffer-local, since it is shell-type dependent, list of keywords.")
2281 ;; ( key-word first-on-this on-prev-line )
2282 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2283 ;; having 3 elements:
2284 ;; a keyword
2285 ;; a rule to check when the keyword appears on "this" line
2286 ;; a rule to check when the keyword appears on "the previous" line
2287 ;; The keyword is usually a string and is the first word on a line.
2288 ;; If this keyword appears on the line whose indentation is to be
2289 ;; calculated, the rule in element 2 is called. If this returns
2290 ;; non-zero, the resulting point (which may be changed by the rule)
2291 ;; is used as the default indentation.
2292 ;; If it returned false or the keyword was not found in the table,
2293 ;; then the keyword from the previous line is looked up and the rule
2294 ;; in element 3 is called. In this case, however,
2295 ;; `sh-get-indent-info' does not stop but may keep going and test
2296 ;; other keywords against rules in element 3. This is because the
2297 ;; preceding line could have, for example, an opening "if" and an
2298 ;; opening "while" keyword and we need to add the indentation offsets
2299 ;; for both.
2301 (defconst sh-kw
2302 '((sh
2303 ("if" nil sh-handle-prev-if)
2304 ("elif" sh-handle-this-else sh-handle-prev-else)
2305 ("else" sh-handle-this-else sh-handle-prev-else)
2306 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2307 ("then" sh-handle-this-then sh-handle-prev-then)
2308 ("(" nil sh-handle-prev-open)
2309 ("{" nil sh-handle-prev-open)
2310 ("[" nil sh-handle-prev-open)
2311 ("}" sh-handle-this-close nil)
2312 (")" sh-handle-this-close nil)
2313 ("]" sh-handle-this-close nil)
2314 ("case" nil sh-handle-prev-case)
2315 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2316 (case-label nil sh-handle-after-case-label) ;; ???
2317 (";;" nil sh-handle-prev-case-alt-end) ;; ???
2318 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2319 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2320 ("done" sh-handle-this-done sh-handle-prev-done)
2321 ("do" sh-handle-this-do sh-handle-prev-do))
2323 ;; Note: we don't need specific stuff for bash and zsh shells;
2324 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2325 ;; these shells use.
2327 ("{" nil sh-handle-prev-open)
2328 ("}" sh-handle-this-close nil)
2329 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
2333 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
2334 "Set this buffer's shell to SHELL (a string).
2335 When used interactively, insert the proper starting #!-line,
2336 and make the visited file executable via `executable-set-magic',
2337 perhaps querying depending on the value of `executable-query'.
2339 When this function is called noninteractively, INSERT-FLAG (the third
2340 argument) controls whether to insert a #!-line and think about making
2341 the visited file executable, and NO-QUERY-FLAG (the second argument)
2342 controls whether to query about making the visited file executable.
2344 Calls the value of `sh-set-shell-hook' if set.
2346 Shell script files can cause this function be called automatically
2347 when the file is visited by having a `sh-shell' file-local variable
2348 whose value is the shell name (don't quote it)."
2349 (interactive (list (completing-read
2350 (format "Shell (default %s): "
2351 sh-shell-file)
2352 ;; This used to use interpreter-mode-alist, but that is
2353 ;; no longer appropriate now that uses regexps.
2354 ;; Maybe there could be a separate variable that lists
2355 ;; the shells, used here and to construct i-mode-alist.
2356 ;; But the following is probably good enough:
2357 (append (mapcar (lambda (e) (symbol-name (car e)))
2358 sh-ancestor-alist)
2359 '("csh" "rc" "sh"))
2360 nil nil nil nil sh-shell-file)
2361 (eq executable-query 'function)
2363 (if (string-match "\\.exe\\'" shell)
2364 (setq shell (substring shell 0 (match-beginning 0))))
2365 (setq sh-shell (sh-canonicalize-shell shell))
2366 (if insert-flag
2367 (setq sh-shell-file
2368 (executable-set-magic shell (sh-feature sh-shell-arg)
2369 no-query-flag insert-flag)))
2370 (setq mode-line-process (format "[%s]" sh-shell))
2371 (setq-local sh-shell-variables nil)
2372 (setq-local sh-shell-variables-initialized nil)
2373 (setq-local imenu-generic-expression
2374 (sh-feature sh-imenu-generic-expression))
2375 (let ((tem (sh-feature sh-mode-syntax-table-input)))
2376 (when tem
2377 (setq-local sh-mode-syntax-table
2378 (apply 'sh-mode-syntax-table tem))
2379 (set-syntax-table sh-mode-syntax-table)))
2380 (dolist (var (sh-feature sh-variables))
2381 (sh-remember-variable var))
2382 (if (setq-local sh-indent-supported-here
2383 (sh-feature sh-indent-supported))
2384 (progn
2385 (message "Setting up indent for shell type %s" sh-shell)
2386 (let ((mksym (lambda (name)
2387 (intern (format "sh-smie-%s-%s"
2388 sh-indent-supported-here name)))))
2389 (add-function :around (local 'smie--hanging-eolp-function)
2390 (lambda (orig)
2391 (if (looking-at "[ \t]*\\\\\n")
2392 (goto-char (match-end 0))
2393 (funcall orig))))
2394 (add-hook 'smie-indent-functions #'sh-smie--indent-continuation nil t)
2395 (smie-setup (symbol-value (funcall mksym "grammar"))
2396 (funcall mksym "rules")
2397 :forward-token (funcall mksym "forward-token")
2398 :backward-token (funcall mksym "backward-token")))
2399 (setq-local parse-sexp-lookup-properties t)
2400 (unless sh-use-smie
2401 (setq-local sh-kw-alist (sh-feature sh-kw))
2402 (let ((regexp (sh-feature sh-kws-for-done)))
2403 (if regexp
2404 (setq-local sh-regexp-for-done
2405 (sh-mkword-regexpr (regexp-opt regexp t)))))
2406 (message "setting up indent stuff")
2407 ;; sh-mode has already made indent-line-function local
2408 ;; but do it in case this is called before that.
2409 (setq-local indent-line-function 'sh-indent-line))
2410 (if sh-make-vars-local
2411 (sh-make-vars-local))
2412 (message "Indentation setup for shell type %s" sh-shell))
2413 (message "No indentation for this shell type.")
2414 (setq-local indent-line-function 'sh-basic-indent-line))
2415 (when font-lock-mode
2416 (setq font-lock-set-defaults nil)
2417 (font-lock-set-defaults)
2418 (font-lock-flush))
2419 (setq sh-shell-process nil)
2420 (run-hooks 'sh-set-shell-hook))
2423 (defun sh-feature (alist &optional function)
2424 "Index ALIST by the current shell.
2425 If ALIST isn't a list where every element is a cons, it is returned as is.
2426 Else indexing follows an inheritance logic which works in two ways:
2428 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2429 the alist contains no value for the current shell.
2430 The ultimate default is always `sh'.
2432 - If the value thus looked up is a list starting with `sh-append',
2433 we call the function `sh-append' with the rest of the list as
2434 arguments, and use the value. However, the next element of the
2435 list is not used as-is; instead, we look it up recursively
2436 in ALIST to allow the function called to define the value for
2437 one shell to be derived from another shell.
2438 The value thus determined is physically replaced into the alist.
2440 If FUNCTION is non-nil, it is called with one argument,
2441 the value thus obtained, and the result is used instead."
2442 (or (if (consp alist)
2443 ;; Check for something that isn't a valid alist.
2444 (let ((l alist))
2445 (while (and l (consp (car l)))
2446 (setq l (cdr l)))
2447 (if l alist)))
2449 (let ((orig-sh-shell sh-shell))
2450 (let ((sh-shell sh-shell)
2451 elt val)
2452 (while (and sh-shell
2453 (not (setq elt (assq sh-shell alist))))
2454 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2455 ;; If the shell is not known, treat it as sh.
2456 (unless elt
2457 (setq elt (assq 'sh alist)))
2458 (setq val (cdr elt))
2459 (if (and (consp val)
2460 (memq (car val) '(sh-append sh-modify)))
2461 (setq val
2462 (apply (car val)
2463 ;; Refer to the value for a different shell,
2464 ;; as a kind of inheritance.
2465 (let ((sh-shell (car (cdr val))))
2466 (sh-feature alist))
2467 (cddr val))))
2468 (if function
2469 (setq sh-shell orig-sh-shell
2470 val (funcall function val)))
2471 val))))
2475 (defun sh-append (ancestor &rest list)
2476 "Return list composed of first argument (a list) physically appended to rest."
2477 (nconc list ancestor))
2480 (defun sh-modify (skeleton &rest list)
2481 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2482 (setq skeleton (copy-sequence skeleton))
2483 (while list
2484 (setcar (or (nthcdr (car list) skeleton)
2485 (error "Index %d out of bounds" (car list)))
2486 (car (cdr list)))
2487 (setq list (nthcdr 2 list)))
2488 skeleton)
2491 (defun sh-basic-indent-line ()
2492 "Indent a line for Sh mode (shell script mode).
2493 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2494 Lines containing only comments are considered empty."
2495 (interactive)
2496 (let ((previous (save-excursion
2497 (while (and (progn (beginning-of-line)
2498 (not (bobp)))
2499 (progn
2500 (forward-line -1)
2501 (back-to-indentation)
2502 (or (eolp)
2503 (eq (following-char) ?#)))))
2504 (current-column)))
2505 current)
2506 (save-excursion
2507 (indent-to (if (or (eq this-command 'newline-and-indent)
2508 (and electric-indent-mode (eq this-command 'newline)))
2509 previous
2510 (if (< (current-column)
2511 (setq current (progn (back-to-indentation)
2512 (current-column))))
2513 (if (eolp) previous 0)
2514 (delete-region (point)
2515 (progn (beginning-of-line) (point)))
2516 (if (eolp)
2517 (max previous (* (1+ (/ current sh-indentation))
2518 sh-indentation))
2519 (* (1+ (/ current sh-indentation)) sh-indentation))))))
2520 (if (< (current-column) (current-indentation))
2521 (skip-chars-forward " \t"))))
2524 (defun sh-execute-region (start end &optional flag)
2525 "Pass optional header and region to a subshell for noninteractive execution.
2526 The working directory is that of the buffer, and only environment variables
2527 are already set which is why you can mark a header within the script.
2529 With a positive prefix ARG, instead of sending region, define header from
2530 beginning of buffer to point. With a negative prefix ARG, instead of sending
2531 region, clear header."
2532 (interactive "r\nP")
2533 (if flag
2534 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2535 (point-marker)))
2536 (if sh-header-marker
2537 (save-excursion
2538 (let (buffer-undo-list)
2539 (goto-char sh-header-marker)
2540 (append-to-buffer (current-buffer) start end)
2541 (shell-command-on-region (point-min)
2542 (setq end (+ sh-header-marker
2543 (- end start)))
2544 sh-shell-file)
2545 (delete-region sh-header-marker end)))
2546 (shell-command-on-region start end (concat sh-shell-file " -")))))
2549 (defun sh-remember-variable (var)
2550 "Make VARIABLE available for future completing reads in this buffer."
2551 (or (< (length var) sh-remember-variable-min)
2552 (getenv var)
2553 (assoc var sh-shell-variables)
2554 (push (cons var var) sh-shell-variables))
2555 var)
2559 (defun sh-quoted-p ()
2560 "Is point preceded by an odd number of backslashes?"
2561 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
2563 ;; Indentation stuff.
2564 (defun sh-must-support-indent ()
2565 "Signal an error if the shell type for this buffer is not supported.
2566 Also, the buffer must be in Shell-script mode."
2567 (unless sh-indent-supported-here
2568 (error "This buffer's shell does not support indentation through Emacs")))
2570 (defun sh-make-vars-local ()
2571 "Make the indentation variables local to this buffer.
2572 Normally they already are local. This command is provided in case
2573 variable `sh-make-vars-local' has been set to nil.
2575 To revert all these variables to the global values, use
2576 command `sh-reset-indent-vars-to-global-values'."
2577 (interactive)
2578 (mapc 'make-local-variable sh-var-list)
2579 (message "Indentation variables are now local."))
2581 (defun sh-reset-indent-vars-to-global-values ()
2582 "Reset local indentation variables to the global values.
2583 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2584 (interactive)
2585 (mapc 'kill-local-variable sh-var-list)
2586 (if sh-make-vars-local
2587 (mapcar 'make-local-variable sh-var-list)))
2590 ;; Theoretically these are only needed in shell and derived modes.
2591 ;; However, the routines which use them are only called in those modes.
2592 (defconst sh-special-keywords "then\\|do")
2594 (defun sh-help-string-for-variable (var)
2595 "Construct a string for `sh-read-variable' when changing variable VAR ."
2596 (let ((msg (documentation-property var 'variable-documentation))
2597 (msg2 ""))
2598 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
2599 (setq msg2
2600 (format "\n
2601 You can enter a number (positive to increase indentation,
2602 negative to decrease indentation, zero for no change to indentation).
2604 Or, you can enter one of the following symbols which are relative to
2605 the value of variable `sh-basic-offset'
2606 which in this buffer is currently %s.
2608 \t%s."
2609 sh-basic-offset
2610 (mapconcat (lambda (x)
2611 (nth (1- (length x)) x))
2612 sh-symbol-list "\n\t"))))
2613 (concat
2614 ;; The following shows the global not the local value!
2615 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2616 msg msg2)))
2618 (defun sh-read-variable (var)
2619 "Read a new value for indentation variable VAR."
2620 (let ((minibuffer-help-form `(sh-help-string-for-variable
2621 (quote ,var)))
2622 val)
2623 (setq val (read-from-minibuffer
2624 (format "New value for %s (press %s for help): "
2625 var (single-key-description help-char))
2626 (format "%s" (symbol-value var))
2627 nil t))
2628 val))
2632 (defun sh-in-comment-or-string (start)
2633 "Return non-nil if START is in a comment or string."
2634 (save-excursion
2635 (let ((state (syntax-ppss start)))
2636 (or (nth 3 state) (nth 4 state)))))
2638 (defun sh-goto-matching-if ()
2639 "Go to the matching if for a fi.
2640 This handles nested if..fi pairs."
2641 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2642 (if found
2643 (goto-char found))))
2646 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2647 ;; line whose indentation is being handled contain XXX;
2648 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2650 (defun sh-handle-prev-if ()
2651 (list '(+ sh-indent-after-if)))
2653 (defun sh-handle-this-else ()
2654 (if (sh-goto-matching-if)
2655 ;; (list "aligned to if")
2656 (list "aligned to if" '(+ sh-indent-for-else))
2660 (defun sh-handle-prev-else ()
2661 (if (sh-goto-matching-if)
2662 (list '(+ sh-indent-after-if))
2665 (defun sh-handle-this-fi ()
2666 (if (sh-goto-matching-if)
2667 (list "aligned to if" '(+ sh-indent-for-fi))
2671 (defun sh-handle-prev-fi ()
2672 ;; Why do we have this rule? Because we must go back to the if
2673 ;; to get its indent. We may continue back from there.
2674 ;; We return nil because we don't have anything to add to result,
2675 ;; the side affect of setting align-point is all that matters.
2676 ;; we could return a comment (a string) but I can't think of a good one...
2677 (sh-goto-matching-if)
2678 nil)
2680 (defun sh-handle-this-then ()
2681 (let ((p (sh-goto-matching-if)))
2682 (if p
2683 (list '(+ sh-indent-for-then))
2686 (defun sh-handle-prev-then ()
2687 (let ((p (sh-goto-matching-if)))
2688 (if p
2689 (list '(+ sh-indent-after-if))
2692 (defun sh-handle-prev-open ()
2693 (save-excursion
2694 (let ((x (sh-prev-stmt)))
2695 (if (and x
2696 (progn
2697 (goto-char x)
2699 (looking-at "function\\b")
2700 (looking-at "\\s-*\\S-+\\s-*()")
2702 (list '(+ sh-indent-after-function))
2703 (list '(+ sh-indent-after-open)))
2706 (defun sh-handle-this-close ()
2707 (forward-char 1) ;; move over ")"
2708 (if (sh-safe-forward-sexp -1)
2709 (list "aligned to opening paren")))
2711 (defun sh-goto-matching-case ()
2712 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2713 (if found (goto-char found))))
2715 (defun sh-handle-prev-case ()
2716 ;; This is typically called when point is on same line as a case
2717 ;; we shouldn't -- and can't find prev-case
2718 (if (looking-at ".*\\<case\\>")
2719 (list '(+ sh-indent-for-case-label))
2720 (error "We don't seem to be on a line with a case"))) ;; debug
2722 (defun sh-handle-this-esac ()
2723 (if (sh-goto-matching-case)
2724 (list "aligned to matching case")))
2726 (defun sh-handle-prev-esac ()
2727 (if (sh-goto-matching-case)
2728 (list "matching case")))
2730 (defun sh-handle-after-case-label ()
2731 (if (sh-goto-matching-case)
2732 (list '(+ sh-indent-for-case-alt))))
2734 (defun sh-handle-prev-case-alt-end ()
2735 (if (sh-goto-matching-case)
2736 (list '(+ sh-indent-for-case-label))))
2738 (defun sh-safe-forward-sexp (&optional arg)
2739 "Try and do a `forward-sexp', but do not error.
2740 Return new point if successful, nil if an error occurred."
2741 (condition-case nil
2742 (progn
2743 (forward-sexp (or arg 1))
2744 (point)) ;; return point if successful
2745 (error
2746 (sh-debug "oops!(1) %d" (point))
2747 nil))) ;; return nil if fail
2749 (defun sh-goto-match-for-done ()
2750 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2751 (if found
2752 (goto-char found))))
2754 (defun sh-handle-this-done ()
2755 (if (sh-goto-match-for-done)
2756 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2758 (defun sh-handle-prev-done ()
2759 (if (sh-goto-match-for-done)
2760 (list "previous done")))
2762 (defun sh-handle-this-do ()
2763 (if (sh-goto-match-for-done)
2764 (list '(+ sh-indent-for-do))))
2766 (defun sh-handle-prev-do ()
2767 (cond
2768 ((save-restriction
2769 (narrow-to-region (point) (line-beginning-position))
2770 (sh-goto-match-for-done))
2771 (sh-debug "match for done found on THIS line")
2772 (list '(+ sh-indent-after-loop-construct)))
2773 ((sh-goto-match-for-done)
2774 (sh-debug "match for done found on PREV line")
2775 (list '(+ sh-indent-after-do)))
2777 (message "match for done NOT found")
2778 nil)))
2780 ;; for rc:
2781 (defun sh-find-prev-switch ()
2782 "Find the line for the switch keyword matching this line's case keyword."
2783 (re-search-backward "\\<switch\\>" nil t))
2785 (defun sh-handle-this-rc-case ()
2786 (if (sh-find-prev-switch)
2787 (list '(+ sh-indent-after-switch))
2788 ;; (list '(+ sh-indent-for-case-label))
2789 nil))
2791 (defun sh-handle-prev-rc-case ()
2792 (list '(+ sh-indent-after-case)))
2794 (defun sh-check-rule (n thing)
2795 (let ((rule (nth n (assoc thing sh-kw-alist)))
2796 (val nil))
2797 (if rule
2798 (progn
2799 (setq val (funcall rule))
2800 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2801 n thing (point) rule val)))
2802 val))
2805 (defun sh-get-indent-info ()
2806 "Return indent-info for this line.
2807 This is a list. nil means the line is to be left as is.
2808 Otherwise it contains one or more of the following sublists:
2809 \(t NUMBER) NUMBER is the base location in the buffer that indentation is
2810 relative to. If present, this is always the first of the
2811 sublists. The indentation of the line in question is
2812 derived from the indentation of this point, possibly
2813 modified by subsequent sublists.
2814 \(+ VAR)
2815 \(- VAR) Get the value of variable VAR and add to or subtract from
2816 the indentation calculated so far.
2817 \(= VAR) Get the value of variable VAR and *replace* the
2818 indentation with its value. This only occurs for
2819 special variables such as `sh-indent-comment'.
2820 STRING This is ignored for the purposes of calculating
2821 indentation, it is printed in certain cases to help show
2822 what the indentation is based on."
2823 ;; See comments before `sh-kw'.
2824 (save-excursion
2825 (let ((have-result nil)
2826 this-kw
2828 (result nil)
2829 (align-point nil)
2830 prev-line-end x)
2831 (beginning-of-line)
2832 ;; Note: setting result to t means we are done and will return nil.
2833 ;;(This function never returns just t.)
2834 (cond
2835 ((or (nth 3 (syntax-ppss (point)))
2836 (eq (get-text-property (point) 'face) 'sh-heredoc))
2837 ;; String continuation -- don't indent
2838 (setq result t)
2839 (setq have-result t))
2840 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2841 (if (bobp)
2842 (setq result t) ;; return nil if 1st line!
2843 (setq result (list '(= sh-indent-comment)))
2844 ;; we still need to get previous line in case
2845 ;; sh-indent-comment is t (indent as normal)
2846 (setq align-point (sh-prev-line nil))
2847 (setq have-result nil)
2849 ) ;; cond
2851 (unless have-result
2852 ;; Continuation lines are handled specially
2853 (if (sh-this-is-a-continuation)
2854 (progn
2855 (setq result
2856 (if (save-excursion
2857 (beginning-of-line)
2858 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2859 ;; By convention, if the continuation \ is not
2860 ;; preceded by a SPC or a TAB it means that the line
2861 ;; is cut at a place where spaces cannot be freely
2862 ;; added/removed. I.e. do not indent the line.
2863 (list '(= nil))
2864 ;; We assume the line being continued is already
2865 ;; properly indented...
2866 ;; (setq prev-line-end (sh-prev-line))
2867 (setq align-point (sh-prev-line nil))
2868 (list '(+ sh-indent-for-continuation))))
2869 (setq have-result t))
2870 (beginning-of-line)
2871 (skip-chars-forward " \t")
2872 (setq this-kw (sh-get-kw)))
2874 ;; Handle "this" keyword: first word on the line we're
2875 ;; calculating indentation info for.
2876 (if this-kw
2877 (if (setq val (sh-check-rule 1 this-kw))
2878 (progn
2879 (setq align-point (point))
2880 (sh-debug
2881 "this - setting align-point to %d" align-point)
2882 (setq result (append result val))
2883 (setq have-result t)
2884 ;; set prev-line to continue processing remainder
2885 ;; of this line as a previous line
2886 (setq prev-line-end (point))
2887 ))))
2889 (unless have-result
2890 (setq prev-line-end (sh-prev-line 'end)))
2892 (if prev-line-end
2893 (save-excursion
2894 ;; We start off at beginning of this line.
2895 ;; Scan previous statements while this is <=
2896 ;; start of previous line.
2897 (goto-char prev-line-end)
2898 (setq x t)
2899 (while (and x (setq x (sh-prev-thing)))
2900 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2901 (cond
2902 ((and (equal x ")")
2903 (equal (get-text-property (1- (point)) 'syntax-table)
2904 sh-st-punc))
2905 (sh-debug "Case label) here")
2906 (setq x 'case-label)
2907 (if (setq val (sh-check-rule 2 x))
2908 (progn
2909 (setq result (append result val))
2910 (setq align-point (point))))
2911 (or (bobp)
2912 (forward-char -1))
2913 ;; FIXME: This charset looks too much like a regexp. --Stef
2914 (skip-chars-forward "[a-z0-9]*?")
2916 ((string-match "[])}]" x)
2917 (setq x (sh-safe-forward-sexp -1))
2918 (if x
2919 (progn
2920 (setq align-point (point))
2921 (setq result (append result
2922 (list "aligned to opening paren")))
2924 ((string-match "[[({]" x)
2925 (sh-debug "Checking special thing: %s" x)
2926 (if (setq val (sh-check-rule 2 x))
2927 (setq result (append result val)))
2928 (forward-char -1)
2929 (setq align-point (point)))
2930 ((string-match "[\"'`]" x)
2931 (sh-debug "Skipping back for %s" x)
2932 ;; this was oops-2
2933 (setq x (sh-safe-forward-sexp -1)))
2934 ((stringp x)
2935 (sh-debug "Checking string %s at %s" x (point))
2936 (if (setq val (sh-check-rule 2 x))
2937 ;; (or (eq t (car val))
2938 ;; (eq t (car (car val))))
2939 (setq result (append result val)))
2940 ;; not sure about this test Wed Jan 27 23:48:35 1999
2941 (setq align-point (point))
2942 (unless (bolp)
2943 (forward-char -1)))
2945 (error "Don't know what to do with %s" x))
2947 ) ;; while
2948 (sh-debug "result is %s" result)
2950 (sh-debug "No prev line!")
2951 (sh-debug "result: %s align-point: %s" result align-point)
2954 (if align-point
2955 ;; was: (setq result (append result (list (list t align-point))))
2956 (setq result (append (list (list t align-point)) result))
2958 (sh-debug "result is now: %s" result)
2960 (or result
2961 (setq result (list (if prev-line-end
2962 (list t prev-line-end)
2963 (list '= 'sh-first-lines-indent)))))
2965 (if (eq result t)
2966 (setq result nil))
2967 (sh-debug "result is: %s" result)
2968 result
2969 ) ;; let
2973 (defun sh-get-indent-var-for-line (&optional info)
2974 "Return the variable controlling indentation for this line.
2975 If there is not [just] one such variable, return a string
2976 indicating the problem.
2977 If INFO is supplied it is used, else it is calculated."
2978 (let ((var nil)
2979 (result nil)
2980 (reason nil)
2981 sym elt)
2982 (or info
2983 (setq info (sh-get-indent-info)))
2984 (if (null info)
2985 (setq result "this line to be left as is")
2986 (while (and info (null result))
2987 (setq elt (car info))
2988 (cond
2989 ((stringp elt)
2990 (setq reason elt)
2992 ((not (listp elt))
2993 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2994 ;; so it is a list
2995 ((eq t (car elt))
2996 ) ;; nothing
2997 ((symbolp (setq sym (nth 1 elt)))
2998 ;; A bit of a kludge - when we see the sh-indent-comment
2999 ;; ignore other variables. Otherwise it is tricky to
3000 ;; "learn" the comment indentation.
3001 (if (eq var 'sh-indent-comment)
3002 (setq result var)
3003 (if var
3004 (setq result
3005 "this line is controlled by more than 1 variable.")
3006 (setq var sym))))
3008 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
3009 (setq info (cdr info))
3011 (or result
3012 (setq result var))
3013 (or result
3014 (setq result reason))
3015 (if (null result)
3016 ;; e.g. just had (t POS)
3017 (setq result "line has default indentation"))
3018 result))
3022 ;; Finding the previous line isn't trivial.
3023 ;; We must *always* go back one more and see if that is a continuation
3024 ;; line -- it is the PREVIOUS line which is continued, not the one
3025 ;; we are going to!
3026 ;; Also, we want to treat a whole "here document" as one big line,
3027 ;; because we may want to a align to the beginning of it.
3029 ;; What we do:
3030 ;; - go back to previous non-empty line
3031 ;; - if this is in a here-document, go to the beginning of it
3032 ;; - while previous line is continued, go back one line
3033 (defun sh-prev-line (&optional end)
3034 "Back to end of previous non-comment non-empty line.
3035 Go to beginning of logical line unless END is non-nil, in which case
3036 we go to the end of the previous line and do not check for continuations."
3037 (save-excursion
3038 (beginning-of-line)
3039 (forward-comment (- (point-max)))
3040 (unless end (beginning-of-line))
3041 (when (and (not (bobp))
3042 (eq (get-text-property (1- (point)) 'face) 'sh-heredoc))
3043 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
3044 (when p1
3045 (goto-char p1)
3046 (if end
3047 (end-of-line)
3048 (beginning-of-line)))))
3049 (unless end
3050 ;; we must check previous lines to see if they are continuation lines
3051 ;; if so, we must return position of first of them
3052 (while (and (sh-this-is-a-continuation)
3053 (>= 0 (forward-line -1))))
3054 (beginning-of-line)
3055 (skip-chars-forward " \t"))
3056 (point)))
3059 (defun sh-prev-stmt ()
3060 "Return the address of the previous stmt or nil."
3061 ;; This is used when we are trying to find a matching keyword.
3062 ;; Searching backward for the keyword would certainly be quicker, but
3063 ;; it is hard to remove "false matches" -- such as if the keyword
3064 ;; appears in a string or quote. This way is slower, but (I think) safer.
3065 (interactive)
3066 (save-excursion
3067 (let ((going t)
3068 (start (point))
3069 (found nil)
3070 (prev nil))
3071 (skip-chars-backward " \t;|&({[")
3072 (while (and (not found)
3073 (not (bobp))
3074 going)
3075 ;; Do a backward-sexp if possible, else backup bit by bit...
3076 (if (sh-safe-forward-sexp -1)
3077 (progn
3078 (if (looking-at sh-special-keywords)
3079 (progn
3080 (setq found prev))
3081 (setq prev (point))
3083 ;; backward-sexp failed
3084 (if (zerop (skip-chars-backward " \t()[]{};`'"))
3085 (forward-char -1))
3086 (if (bolp)
3087 (let ((back (sh-prev-line nil)))
3088 (if back
3089 (goto-char back)
3090 (setq going nil)))))
3091 (unless found
3092 (skip-chars-backward " \t")
3093 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
3094 (eq (char-before) ?\;)
3095 (looking-at "\\s-*[|&]"))
3096 (setq found (point)))))
3097 (if found
3098 (goto-char found))
3099 (if found
3100 (progn
3101 (skip-chars-forward " \t|&({[")
3102 (setq found (point))))
3103 (if (>= (point) start)
3104 (progn
3105 (debug "We didn't move!")
3106 (setq found nil))
3107 (or found
3108 (sh-debug "Did not find prev stmt.")))
3109 found)))
3112 (defun sh-get-word ()
3113 "Get a shell word skipping whitespace from point."
3114 (interactive)
3115 (skip-chars-forward "\t ")
3116 (let ((start (point)))
3117 (while
3118 (if (looking-at "[\"'`]")
3119 (sh-safe-forward-sexp)
3120 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
3121 (> (skip-chars-forward "-_$[:alnum:]") 0)
3123 (buffer-substring start (point))
3126 (defun sh-prev-thing ()
3127 "Return the previous thing this logical line."
3128 ;; This is called when `sh-get-indent-info' is working backwards on
3129 ;; the previous line(s) finding what keywords may be relevant for
3130 ;; indenting. It moves over sexps if possible, and will stop
3131 ;; on a ; and at the beginning of a line if it is not a continuation
3132 ;; line.
3134 ;; Added a kludge for ";;"
3135 ;; Possible return values:
3136 ;; nil - nothing
3137 ;; a string - possibly a keyword
3139 (if (bolp)
3141 (let ((start (point))
3142 (min-point (if (sh-this-is-a-continuation)
3143 (sh-prev-line nil)
3144 (line-beginning-position))))
3145 (skip-chars-backward " \t;" min-point)
3146 (if (looking-at "\\s-*;[;&]")
3147 ;; (message "Found ;; !")
3148 ";;"
3149 (skip-chars-backward "^)}];\"'`({[" min-point)
3150 (let ((c (if (> (point) min-point) (char-before))))
3151 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
3152 (point) c start min-point)
3153 (if (not (memq c '(?\n nil ?\;)))
3154 ;; c -- return a string
3155 (char-to-string c)
3156 ;; Return the leading keyword of the "command" we supposedly
3157 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
3158 ;; `then' that precedes the actual command), so check whether
3159 ;; we're looking at such a keyword and if so, move back forward.
3160 (let ((boundary (point))
3161 kwd next)
3162 (while
3163 (progn
3164 ;; Skip forward over white space newline and \ at eol.
3165 (skip-chars-forward " \t\n\\\\" start)
3166 (if (>= (point) start)
3167 (progn
3168 (sh-debug "point: %d >= start: %d" (point) start)
3169 nil)
3170 (if next (setq boundary next))
3171 (sh-debug "Now at %d start=%d" (point) start)
3172 (setq kwd (sh-get-word))
3173 (if (member kwd (sh-feature sh-leading-keywords))
3174 (progn
3175 (setq next (point))
3177 nil))))
3178 (goto-char boundary)
3179 kwd)))))))
3182 (defun sh-this-is-a-continuation ()
3183 "Return non-nil if current line is a continuation of previous line."
3184 (save-excursion
3185 (and (zerop (forward-line -1))
3186 (looking-at ".*\\\\$")
3187 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
3188 nil nil nil t))))))
3190 (defun sh-get-kw (&optional where and-move)
3191 "Return first word of line from WHERE.
3192 If AND-MOVE is non-nil then move to end of word."
3193 (let ((start (point)))
3194 (if where
3195 (goto-char where))
3196 (prog1
3197 (buffer-substring (point)
3198 (progn (skip-chars-forward "^ \t\n;&|")(point)))
3199 (unless and-move
3200 (goto-char start)))))
3202 (defun sh-find-prev-matching (open close &optional depth)
3203 "Find a matching token for a set of opening and closing keywords.
3204 This takes into account that there may be nested open..close pairings.
3205 OPEN and CLOSE are regexps denoting the tokens to be matched.
3206 Optional parameter DEPTH (usually 1) says how many to look for."
3207 (let ((parse-sexp-ignore-comments t)
3208 (forward-sexp-function nil)
3209 prev)
3210 (setq depth (or depth 1))
3211 (save-excursion
3212 (condition-case nil
3213 (while (and
3214 (/= 0 depth)
3215 (not (bobp))
3216 (setq prev (sh-prev-stmt)))
3217 (goto-char prev)
3218 (save-excursion
3219 (if (looking-at "\\\\\n")
3220 (progn
3221 (forward-char 2)
3222 (skip-chars-forward " \t")))
3223 (cond
3224 ((looking-at open)
3225 (setq depth (1- depth))
3226 (sh-debug "found open at %d - depth = %d" (point) depth))
3227 ((looking-at close)
3228 (setq depth (1+ depth))
3229 (sh-debug "found close - depth = %d" depth))
3231 ))))
3232 (error nil))
3233 (if (eq depth 0)
3234 prev ;; (point)
3235 nil)
3239 (defun sh-var-value (var &optional ignore-error)
3240 "Return the value of variable VAR, interpreting symbols.
3241 It can also return t or nil.
3242 If an invalid value is found, throw an error unless Optional argument
3243 IGNORE-ERROR is non-nil."
3244 (let ((val (symbol-value var)))
3245 (cond
3246 ((numberp val)
3247 val)
3248 ((eq val t)
3249 val)
3250 ((null val)
3251 val)
3252 ((eq val '+)
3253 sh-basic-offset)
3254 ((eq val '-)
3255 (- sh-basic-offset))
3256 ((eq val '++)
3257 (* 2 sh-basic-offset))
3258 ((eq val '--)
3259 (* 2 (- sh-basic-offset)))
3260 ((eq val '*)
3261 (/ sh-basic-offset 2))
3262 ((eq val '/)
3263 (/ (- sh-basic-offset) 2))
3265 (funcall (if ignore-error #'message #'error)
3266 "Don't know how to handle %s's value of %s" var val)
3267 0))))
3269 (defun sh-set-var-value (var value &optional no-symbol)
3270 "Set variable VAR to VALUE.
3271 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3272 can be represented by a symbol then do so."
3273 (cond
3274 (no-symbol
3275 (set var value))
3276 ((= value sh-basic-offset)
3277 (set var '+))
3278 ((= value (- sh-basic-offset))
3279 (set var '-))
3280 ((eq value (* 2 sh-basic-offset))
3281 (set var '++))
3282 ((eq value (* 2 (- sh-basic-offset)))
3283 (set var '--))
3284 ((eq value (/ sh-basic-offset 2))
3285 (set var '*))
3286 ((eq value (/ (- sh-basic-offset) 2))
3287 (set var '/))
3289 (set var value)))
3293 (defun sh-calculate-indent (&optional info)
3294 "Return the indentation for the current line.
3295 If INFO is supplied it is used, else it is calculated from current line."
3296 (let ((ofs 0)
3297 (base-value 0)
3298 elt a b val)
3299 (or info
3300 (setq info (sh-get-indent-info)))
3301 (when info
3302 (while info
3303 (sh-debug "info: %s ofs=%s" info ofs)
3304 (setq elt (car info))
3305 (cond
3306 ((stringp elt)) ;; do nothing?
3307 ((listp elt)
3308 (setq a (car (car info)))
3309 (setq b (nth 1 (car info)))
3310 (cond
3311 ((eq a t)
3312 (save-excursion
3313 (goto-char b)
3314 (setq val (current-indentation)))
3315 (setq base-value val))
3316 ((symbolp b)
3317 (setq val (sh-var-value b))
3318 (cond
3319 ((eq a '=)
3320 (cond
3321 ((null val)
3322 ;; no indentation
3323 ;; set info to nil so we stop immediately
3324 (setq base-value nil ofs nil info nil))
3325 ((eq val t) (setq ofs 0)) ;; indent as normal line
3327 ;; The following assume the (t POS) come first!
3328 (setq ofs val base-value 0)
3329 (setq info nil)))) ;; ? stop now
3330 ((eq a '+) (setq ofs (+ ofs val)))
3331 ((eq a '-) (setq ofs (- ofs val)))
3333 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3335 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
3337 (error "sh-calculate-indent invalid elt %s" elt)))
3338 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3339 a b val base-value ofs)
3340 (setq info (cdr info)))
3341 ;; return value:
3342 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
3344 (cond
3345 ((or (null base-value)(null ofs))
3346 nil)
3347 ((and (numberp base-value)(numberp ofs))
3348 (sh-debug "base (%d) + ofs (%d) = %d"
3349 base-value ofs (+ base-value ofs))
3350 (+ base-value ofs)) ;; return value
3352 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3353 base-value ofs)
3354 nil)))))
3357 (defun sh-indent-line ()
3358 "Indent the current line."
3359 (interactive)
3360 (let ((indent (sh-calculate-indent))
3361 (pos (- (point-max) (point))))
3362 (when indent
3363 (beginning-of-line)
3364 (skip-chars-forward " \t")
3365 (indent-line-to indent)
3366 ;; If initial point was within line's indentation,
3367 ;; position after the indentation. Else stay at same point in text.
3368 (if (> (- (point-max) pos) (point))
3369 (goto-char (- (point-max) pos))))))
3372 (defun sh-blink (blinkpos &optional msg)
3373 "Move cursor momentarily to BLINKPOS and display MSG."
3374 ;; We can get here without it being a number on first line
3375 (if (numberp blinkpos)
3376 (save-excursion
3377 (goto-char blinkpos)
3378 (if msg (message "%s" msg) (message nil))
3379 (sit-for blink-matching-delay))
3380 (if msg (message "%s" msg) (message nil))))
3382 (defun sh-show-indent (arg)
3383 "Show how the current line would be indented.
3384 This tells you which variable, if any, controls the indentation of
3385 this line.
3386 If optional arg ARG is non-null (called interactively with a prefix),
3387 a pop up window describes this variable.
3388 If variable `sh-blink' is non-nil then momentarily go to the line
3389 we are indenting relative to, if applicable."
3390 (interactive "P")
3391 (sh-must-support-indent)
3392 (if sh-use-smie
3393 (smie-config-show-indent)
3394 (let* ((info (sh-get-indent-info))
3395 (var (sh-get-indent-var-for-line info))
3396 (curr-indent (current-indentation))
3397 val msg)
3398 (if (stringp var)
3399 (message "%s" (setq msg var))
3400 (setq val (sh-calculate-indent info))
3402 (if (eq curr-indent val)
3403 (setq msg (format "%s is %s" var (symbol-value var)))
3404 (setq msg
3405 (if val
3406 (format "%s (%s) would change indent from %d to: %d"
3407 var (symbol-value var) curr-indent val)
3408 (format "%s (%s) would leave line as is"
3409 var (symbol-value var)))
3411 (if (and arg var)
3412 (describe-variable var)))
3413 (if sh-blink
3414 (let ((info (sh-get-indent-info)))
3415 (if (and info (listp (car info))
3416 (eq (car (car info)) t))
3417 (sh-blink (nth 1 (car info)) msg)
3418 (message "%s" msg)))
3419 (message "%s" msg))
3422 (defun sh-set-indent ()
3423 "Set the indentation for the current line.
3424 If the current line is controlled by an indentation variable, prompt
3425 for a new value for it."
3426 (interactive)
3427 (sh-must-support-indent)
3428 (if sh-use-smie
3429 (smie-config-set-indent)
3430 (let* ((info (sh-get-indent-info))
3431 (var (sh-get-indent-var-for-line info))
3432 val old-val indent-val)
3433 (if (stringp var)
3434 (message "Cannot set indent - %s" var)
3435 (setq old-val (symbol-value var))
3436 (setq val (sh-read-variable var))
3437 (condition-case nil
3438 (progn
3439 (set var val)
3440 (setq indent-val (sh-calculate-indent info))
3441 (if indent-val
3442 (message "Variable: %s Value: %s would indent to: %d"
3443 var (symbol-value var) indent-val)
3444 (message "Variable: %s Value: %s would leave line as is."
3445 var (symbol-value var)))
3446 ;; I'm not sure about this, indenting it now?
3447 ;; No. Because it would give the impression that an undo would
3448 ;; restore thing, but the value has been altered.
3449 ;; (sh-indent-line)
3451 (error
3452 (set var old-val)
3453 (message "Bad value for %s, restoring to previous value %s"
3454 var old-val)
3455 (sit-for 1)
3456 nil))
3457 ))))
3460 (defun sh-learn-line-indent (arg)
3461 "Learn how to indent a line as it currently is indented.
3463 If there is an indentation variable which controls this line's indentation,
3464 then set it to a value which would indent the line the way it
3465 presently is.
3467 If the value can be represented by one of the symbols then do so
3468 unless optional argument ARG (the prefix when interactive) is non-nil."
3469 (interactive "*P")
3470 (sh-must-support-indent)
3471 (if sh-use-smie
3472 (smie-config-set-indent)
3473 ;; I'm not sure if we show allow learning on an empty line.
3474 ;; Though it might occasionally be useful I think it usually
3475 ;; would just be confusing.
3476 (if (save-excursion
3477 (beginning-of-line)
3478 (looking-at "\\s-*$"))
3479 (message "sh-learn-line-indent ignores empty lines.")
3480 (let* ((info (sh-get-indent-info))
3481 (var (sh-get-indent-var-for-line info))
3482 ival sval diff new-val
3483 (no-symbol arg)
3484 (curr-indent (current-indentation)))
3485 (cond
3486 ((stringp var)
3487 (message "Cannot learn line - %s" var))
3488 ((eq var 'sh-indent-comment)
3489 ;; This is arbitrary...
3490 ;; - if curr-indent is 0, set to curr-indent
3491 ;; - else if it has the indentation of a "normal" line,
3492 ;; then set to t
3493 ;; - else set to curr-indent.
3494 (setq sh-indent-comment
3495 (if (= curr-indent 0)
3497 (let* ((sh-indent-comment t)
3498 (val2 (sh-calculate-indent info)))
3499 (if (= val2 curr-indent)
3501 curr-indent))))
3502 (message "%s set to %s" var (symbol-value var))
3504 ((numberp (setq sval (sh-var-value var)))
3505 (setq ival (sh-calculate-indent info))
3506 (setq diff (- curr-indent ival))
3508 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3509 curr-indent ival diff var sval)
3510 (setq new-val (+ sval diff))
3511 ;; I commented out this because someone might want to replace
3512 ;; a value of `+' with the current value of sh-basic-offset
3513 ;; or vice-versa.
3514 ;;(if (= 0 diff)
3515 ;; (message "No change needed!")
3516 (sh-set-var-value var new-val no-symbol)
3517 (message "%s set to %s" var (symbol-value var))
3520 (debug)
3521 (message "Cannot change %s" var)))))))
3525 (defun sh-mark-init (buffer)
3526 "Initialize a BUFFER to be used by `sh-mark-line'."
3527 (with-current-buffer (get-buffer-create buffer)
3528 (erase-buffer)
3529 (occur-mode)))
3532 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
3533 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3534 Buffer BUFFER is in `occur-mode'.
3535 If ADD-LINENUM is non-nil the message is preceded by the line number.
3536 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3537 so that `occur-next' and `occur-prev' will work."
3538 (let ((m1 (make-marker))
3539 start
3540 (line ""))
3541 (when point
3542 (set-marker m1 point (current-buffer))
3543 (if add-linenum
3544 (setq line (format "%d: " (1+ (count-lines 1 point))))))
3545 (save-excursion
3546 (if (get-buffer buffer)
3547 (set-buffer (get-buffer buffer))
3548 (set-buffer (get-buffer-create buffer))
3549 (occur-mode)
3551 (goto-char (point-max))
3552 (setq start (point))
3553 (let ((inhibit-read-only t))
3554 (insert line)
3555 (if occur-point
3556 (setq occur-point (point)))
3557 (insert message)
3558 (if point
3559 (add-text-properties
3560 start (point)
3561 '(mouse-face highlight
3562 help-echo "mouse-2: go to the line where I learned this")))
3563 (insert "\n")
3564 (when point
3565 (put-text-property start (point) 'occur-target m1)
3566 (if occur-point
3567 (put-text-property start occur-point
3568 'occur-match t))
3569 )))))
3571 ;; Is this really worth having?
3572 (defvar sh-learned-buffer-hook nil
3573 "An abnormal hook, called with an alist of learned variables.")
3574 ;; Example of how to use sh-learned-buffer-hook
3576 ;; (defun what-i-learned (list)
3577 ;; (let ((p list))
3578 ;; (with-current-buffer "*scratch*"
3579 ;; (goto-char (point-max))
3580 ;; (insert "(setq\n")
3581 ;; (while p
3582 ;; (insert (format " %s %s \n"
3583 ;; (nth 0 (car p)) (nth 1 (car p))))
3584 ;; (setq p (cdr p)))
3585 ;; (insert ")\n")
3586 ;; )))
3588 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3591 ;; Originally this was sh-learn-region-indent (beg end)
3592 ;; However, in practice this was awkward so I changed it to
3593 ;; use the whole buffer. Use narrowing if need be.
3594 (defun sh-learn-buffer-indent (&optional arg)
3595 "Learn how to indent the buffer the way it currently is.
3597 Output in buffer \"*indent*\" shows any lines which have conflicting
3598 values of a variable, and the final value of all variables learned.
3599 When called interactively, pop to this buffer automatically if
3600 there are any discrepancies.
3602 If no prefix ARG is given, then variables are set to numbers.
3603 If a prefix arg is given, then variables are set to symbols when
3604 applicable -- e.g. to symbol `+' if the value is that of the
3605 basic indent.
3606 If a positive numerical prefix is given, then `sh-basic-offset'
3607 is set to the prefix's numerical value.
3608 Otherwise, sh-basic-offset may or may not be changed, according
3609 to the value of variable `sh-learn-basic-offset'.
3611 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3612 function completes. The function is abnormal because it is called
3613 with an alist of variables learned. This feature may be changed or
3614 removed in the future.
3616 This command can often take a long time to run."
3617 (interactive "P")
3618 (sh-must-support-indent)
3619 (if sh-use-smie
3620 (smie-config-guess)
3621 (save-excursion
3622 (goto-char (point-min))
3623 (let ((learned-var-list nil)
3624 (out-buffer "*indent*")
3625 (num-diffs 0)
3626 previous-set-info
3627 (max 17)
3630 (comment-col nil) ;; number if all same, t if seen diff values
3631 (comments-always-default t) ;; nil if we see one not default
3632 initial-msg
3633 (specified-basic-offset (and arg (numberp arg)
3634 (> arg 0)))
3635 (linenum 0)
3636 suggested)
3637 (setq vec (make-vector max 0))
3638 (sh-mark-init out-buffer)
3640 (if specified-basic-offset
3641 (progn
3642 (setq sh-basic-offset arg)
3643 (setq initial-msg
3644 (format "Using specified sh-basic-offset of %d"
3645 sh-basic-offset)))
3646 (setq initial-msg
3647 (format "Initial value of sh-basic-offset: %s"
3648 sh-basic-offset)))
3650 (while (< (point) (point-max))
3651 (setq linenum (1+ linenum))
3652 ;; (if (zerop (% linenum 10))
3653 (message "line %d" linenum)
3654 ;; )
3655 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3656 (let* ((sh-indent-comment t) ;; info must return default indent
3657 (info (sh-get-indent-info))
3658 (var (sh-get-indent-var-for-line info))
3659 sval ival diff new-val
3660 (curr-indent (current-indentation)))
3661 (cond
3662 ((null var)
3663 nil)
3664 ((stringp var)
3665 nil)
3666 ((numberp (setq sval (sh-var-value var 'no-error)))
3667 ;; the numberp excludes comments since sval will be t.
3668 (setq ival (sh-calculate-indent))
3669 (setq diff (- curr-indent ival))
3670 (setq new-val (+ sval diff))
3671 (sh-set-var-value var new-val 'no-symbol)
3672 (unless (looking-at "\\s-*#") ;; don't learn from comments
3673 (if (setq previous-set-info (assoc var learned-var-list))
3674 (progn
3675 ;; it was already there, is it same value ?
3676 (unless (eq (symbol-value var)
3677 (nth 1 previous-set-info))
3678 (sh-mark-line
3679 (format "Variable %s was set to %s"
3680 var (symbol-value var))
3681 (point) out-buffer t t)
3682 (sh-mark-line
3683 (format " but was previously set to %s"
3684 (nth 1 previous-set-info))
3685 (nth 2 previous-set-info) out-buffer t)
3686 (setq num-diffs (1+ num-diffs))
3687 ;; (delete previous-set-info learned-var-list)
3688 (setcdr previous-set-info
3689 (list (symbol-value var) (point)))
3692 (setq learned-var-list
3693 (append (list (list var (symbol-value var)
3694 (point)))
3695 learned-var-list)))
3696 (if (numberp new-val)
3697 (progn
3698 (sh-debug
3699 "This line's indent value: %d" new-val)
3700 (if (< new-val 0)
3701 (setq new-val (- new-val)))
3702 (if (< new-val max)
3703 (aset vec new-val (1+ (aref vec new-val))))))
3705 ((eq var 'sh-indent-comment)
3706 (unless (= curr-indent (sh-calculate-indent info))
3707 ;; this is not the default indentation
3708 (setq comments-always-default nil)
3709 (if comment-col ;; then we have see one before
3710 (or (eq comment-col curr-indent)
3711 (setq comment-col t)) ;; seen a different one
3712 (setq comment-col curr-indent))
3715 (sh-debug "Cannot learn this line!!!")
3717 (sh-debug
3718 "at %s learned-var-list is %s" (point) learned-var-list)
3720 (forward-line 1)
3721 ) ;; while
3722 (if sh-debug
3723 (progn
3724 (setq msg (format
3725 "comment-col = %s comments-always-default = %s"
3726 comment-col comments-always-default))
3727 ;; (message msg)
3728 (sh-mark-line msg nil out-buffer)))
3729 (cond
3730 ((eq comment-col 0)
3731 (setq msg "\nComments are all in 1st column.\n"))
3732 (comments-always-default
3733 (setq msg "\nComments follow default indentation.\n")
3734 (setq comment-col t))
3735 ((numberp comment-col)
3736 (setq msg (format "\nComments are in col %d." comment-col)))
3738 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3739 (setq comment-col nil)
3741 (sh-debug msg)
3742 (sh-mark-line msg nil out-buffer)
3744 (sh-mark-line initial-msg nil out-buffer t t)
3746 (setq suggested (sh-guess-basic-offset vec))
3748 (if (and suggested (not specified-basic-offset))
3749 (let ((new-value
3750 (cond
3751 ;; t => set it if we have a single value as a number
3752 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3753 suggested)
3754 ;; other non-nil => set it if only one value was found
3755 (sh-learn-basic-offset
3756 (if (numberp suggested)
3757 suggested
3758 (if (= (length suggested) 1)
3759 (car suggested))))
3761 nil))))
3762 (if new-value
3763 (progn
3764 (setq learned-var-list
3765 (append (list (list 'sh-basic-offset
3766 (setq sh-basic-offset new-value)
3767 (point-max)))
3768 learned-var-list))
3769 ;; Not sure if we need to put this line in, since
3770 ;; it will appear in the "Learned variable settings".
3771 (sh-mark-line
3772 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3773 nil out-buffer))
3774 (sh-mark-line
3775 (if (listp suggested)
3776 (format "Possible value(s) for sh-basic-offset: %s"
3777 (mapconcat 'int-to-string suggested " "))
3778 (format "Suggested sh-basic-offset: %d" suggested))
3779 nil out-buffer))))
3782 (setq learned-var-list
3783 (append (list (list 'sh-indent-comment comment-col (point-max)))
3784 learned-var-list))
3785 (setq sh-indent-comment comment-col)
3786 (let ((name (buffer-name)))
3787 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3788 (if arg
3789 ;; Set learned variables to symbolic rather than numeric
3790 ;; values where possible.
3791 (dolist (learned-var (reverse learned-var-list))
3792 (let ((var (car learned-var))
3793 (val (nth 1 learned-var)))
3794 (when (and (not (eq var 'sh-basic-offset))
3795 (numberp val))
3796 (sh-set-var-value var val)))))
3797 (dolist (learned-var (reverse learned-var-list))
3798 (let ((var (car learned-var)))
3799 (sh-mark-line (format " %s %s" var (symbol-value var))
3800 (nth 2 learned-var) out-buffer)))
3801 (with-current-buffer out-buffer
3802 (goto-char (point-min))
3803 (let ((inhibit-read-only t))
3804 (insert
3805 (format "Indentation values for buffer %s.\n" name)
3806 (format "%d indentation variable%s different values%s\n\n"
3807 num-diffs
3808 (if (= num-diffs 1)
3809 " has" "s have")
3810 (if (zerop num-diffs)
3811 "." ":"))))))
3812 ;; Are abnormal hooks considered bad form?
3813 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3814 (and (called-interactively-p 'any)
3815 (or sh-popup-occur-buffer (> num-diffs 0))
3816 (pop-to-buffer out-buffer))))))
3818 (defun sh-guess-basic-offset (vec)
3819 "See if we can determine a reasonable value for `sh-basic-offset'.
3820 This is experimental, heuristic and arbitrary!
3821 Argument VEC is a vector of information collected by
3822 `sh-learn-buffer-indent'.
3823 Return values:
3824 number - there appears to be a good single value
3825 list of numbers - no obvious one, here is a list of one or more
3826 reasonable choices
3827 nil - we couldn't find a reasonable one."
3828 (let* ((max (1- (length vec)))
3829 (i 1)
3830 (totals (make-vector max 0)))
3831 (while (< i max)
3832 (cl-incf (aref totals i) (* 4 (aref vec i)))
3833 (if (zerop (% i 2))
3834 (cl-incf (aref totals i) (aref vec (/ i 2))))
3835 (if (< (* i 2) max)
3836 (cl-incf (aref totals i) (aref vec (* i 2))))
3837 (setq i (1+ i)))
3839 (let ((x nil)
3840 (result nil)
3841 tot sum p)
3842 (setq i 1)
3843 (while (< i max)
3844 (if (/= (aref totals i) 0)
3845 (push (cons i (aref totals i)) x))
3846 (setq i (1+ i)))
3848 (setq x (sort (nreverse x) (lambda (a b) (> (cdr a) (cdr b)))))
3849 (setq tot (apply '+ (append totals nil)))
3850 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3851 vec totals tot))
3852 (cond
3853 ((zerop (length x))
3854 (message "no values!")) ;; we return nil
3855 ((= (length x) 1)
3856 (message "only value is %d" (car (car x)))
3857 (setq result (car (car x)))) ;; return single value
3858 ((> (cdr (car x)) (/ tot 2))
3859 ;; 1st is > 50%
3860 (message "basic-offset is probably %d" (car (car x)))
3861 (setq result (car (car x)))) ;; again, return a single value
3862 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3863 ;; 1st is >= 2 * 2nd
3864 (message "basic-offset could be %d" (car (car x)))
3865 (setq result (car (car x))))
3866 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3867 ;; 1st & 2nd together >= 50% - return a list
3868 (setq p x sum 0 result nil)
3869 (while (and p
3870 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3871 (setq result (append result (list (car (car p)))))
3872 (setq p (cdr p)))
3873 (message "Possible choices for sh-basic-offset: %s"
3874 (mapconcat 'int-to-string result " ")))
3876 (message "No obvious value for sh-basic-offset. Perhaps %d"
3877 (car (car x)))
3878 ;; result is nil here
3880 result)))
3882 ;; ========================================================================
3884 ;; Styles -- a quick and dirty way of saving the indentation settings.
3886 (defvar sh-styles-alist nil
3887 "A list of all known shell indentation styles.")
3889 (defun sh-name-style (name &optional confirm-overwrite)
3890 "Name the current indentation settings as a style called NAME.
3891 If this name exists, the command will prompt whether it should be
3892 overwritten if
3893 - - it was called interactively with a prefix argument, or
3894 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3895 ;; (interactive "sName for this style: ")
3896 (interactive
3897 (list
3898 (read-from-minibuffer "Name for this style? " )
3899 (not current-prefix-arg)))
3900 (let ((slist (cons name
3901 (mapcar (lambda (var) (cons var (symbol-value var)))
3902 sh-var-list)))
3903 (style (assoc name sh-styles-alist)))
3904 (if style
3905 (if (and confirm-overwrite
3906 (not (y-or-n-p "This style exists. Overwrite it? ")))
3907 (message "Not changing style %s" name)
3908 (message "Updating style %s" name)
3909 (setcdr style (cdr slist)))
3910 (message "Creating new style %s" name)
3911 (push slist sh-styles-alist))))
3913 (defun sh-load-style (name)
3914 "Set shell indentation values for this buffer from those in style NAME."
3915 (interactive (list (completing-read
3916 "Which style to use for this buffer? "
3917 sh-styles-alist nil t)))
3918 (let ((sl (assoc name sh-styles-alist)))
3919 (if (null sl)
3920 (error "sh-load-style - style %s not known" name)
3921 (dolist (var (cdr sl))
3922 (set (car var) (cdr var))))))
3924 (defun sh-save-styles-to-buffer (buff)
3925 "Save all current styles in elisp to buffer BUFF.
3926 This is always added to the end of the buffer."
3927 (interactive
3928 (list
3929 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3930 (with-current-buffer (get-buffer-create buff)
3931 (goto-char (point-max))
3932 (insert "\n")
3933 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3937 ;; statement syntax-commands for various shells
3939 ;; You are welcome to add the syntax or even completely new statements as
3940 ;; appropriate for your favorite shell.
3942 (defconst sh-non-closing-paren
3943 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3944 ;; that inherits this property, which then confuses the indentation.
3945 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3947 (define-skeleton sh-case
3948 "Insert a case/switch statement. See `sh-feature'."
3949 (csh "expression: "
3950 "switch( " str " )" \n
3951 > "case " (read-string "pattern: ") ?: \n
3952 > _ \n
3953 "breaksw" \n
3954 ( "other pattern, %s: "
3955 < "case " str ?: \n
3956 > _ \n
3957 "breaksw" \n)
3958 < "default:" \n
3959 > _ \n
3960 resume:
3961 < < "endsw" \n)
3962 (es)
3963 (rc "expression: "
3964 > "switch( " str " ) {" \n
3965 > "case " (read-string "pattern: ") \n
3966 > _ \n
3967 ( "other pattern, %s: "
3968 "case " str > \n
3969 > _ \n)
3970 "case *" > \n
3971 > _ \n
3972 resume:
3973 ?\} > \n)
3974 (sh "expression: "
3975 > "case " str " in" \n
3976 ( "pattern, %s: "
3977 > str sh-non-closing-paren \n
3978 > _ \n
3979 ";;" \n)
3980 > "*" sh-non-closing-paren \n
3981 > _ \n
3982 resume:
3983 "esac" > \n))
3985 (define-skeleton sh-for
3986 "Insert a for loop. See `sh-feature'."
3987 (csh sh-modify sh
3988 1 ""
3989 2 "foreach "
3990 4 " ( "
3991 6 " )"
3992 15 '<
3993 16 "end")
3994 (es sh-modify rc
3995 4 " = ")
3996 (rc sh-modify sh
3997 2 "for( "
3998 6 " ) {"
3999 15 ?\} )
4000 (sh "Index variable: "
4001 > "for " str " in " _ "; do" \n
4002 > _ | ?$ & (sh-remember-variable str) \n
4003 "done" > \n))
4007 (define-skeleton sh-indexed-loop
4008 "Insert an indexed loop from 1 to n. See `sh-feature'."
4009 (bash sh-modify posix)
4010 (csh "Index variable: "
4011 "@ " str " = 1" \n
4012 "while( $" str " <= " (read-string "upper limit: ") " )" \n
4013 > _ ?$ str \n
4014 "@ " str "++" \n
4015 < "end" \n)
4016 (es sh-modify rc
4017 4 " =")
4018 (ksh88 "Index variable: "
4019 > "integer " str "=0" \n
4020 > "while (( ( " str " += 1 ) <= "
4021 (read-string "upper limit: ")
4022 " )); do" \n
4023 > _ ?$ (sh-remember-variable str) > \n
4024 "done" > \n)
4025 (posix "Index variable: "
4026 > str "=1" \n
4027 "while [ $" str " -le "
4028 (read-string "upper limit: ")
4029 " ]; do" \n
4030 > _ ?$ str \n
4031 str ?= (sh-add (sh-remember-variable str) 1) \n
4032 "done" > \n)
4033 (rc "Index variable: "
4034 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
4035 (read-string "upper limit: ")
4036 "; i++ ) print i }'`}) {" \n
4037 > _ ?$ (sh-remember-variable str) \n
4038 ?\} > \n)
4039 (sh "Index variable: "
4040 > "for " str " in `awk 'BEGIN { for( i=1; i<="
4041 (read-string "upper limit: ")
4042 "; i++ ) print i }'`; do" \n
4043 > _ ?$ (sh-remember-variable str) \n
4044 "done" > \n))
4047 (defun sh-shell-initialize-variables ()
4048 "Scan the buffer for variable assignments.
4049 Add these variables to `sh-shell-variables'."
4050 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
4051 (save-excursion
4052 (goto-char (point-min))
4053 (setq sh-shell-variables-initialized t)
4054 (while (search-forward "=" nil t)
4055 (sh-assignment 0)))
4056 (message "Scanning buffer `%s' for variable assignments...done"
4057 (buffer-name)))
4059 (defvar sh-add-buffer)
4061 (defun sh-add-completer (string predicate code)
4062 "Do completion using `sh-shell-variables', but initialize it first.
4063 This function is designed for use as the \"completion table\",
4064 so it takes three arguments:
4065 STRING, the current buffer contents;
4066 PREDICATE, the predicate for filtering possible matches;
4067 CODE, which says what kind of things to do.
4068 CODE can be nil, t or `lambda'.
4069 nil means to return the best completion of STRING, or nil if there is none.
4070 t means to return a list of all possible completions of STRING.
4071 `lambda' means to return t if STRING is a valid completion as it stands."
4072 (let ((vars
4073 (with-current-buffer sh-add-buffer
4074 (or sh-shell-variables-initialized
4075 (sh-shell-initialize-variables))
4076 (nconc (mapcar (lambda (var)
4077 (substring var 0 (string-match "=" var)))
4078 process-environment)
4079 sh-shell-variables))))
4080 (complete-with-action code vars string predicate)))
4082 (defun sh-add (var delta)
4083 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
4084 (interactive
4085 (let ((sh-add-buffer (current-buffer)))
4086 (list (completing-read "Variable: " 'sh-add-completer)
4087 (prefix-numeric-value current-prefix-arg))))
4088 (insert (sh-feature '((bash . "$(( ")
4089 (ksh88 . "$(( ")
4090 (posix . "$(( ")
4091 (rc . "`{expr $")
4092 (sh . "`expr $")
4093 (zsh . "$[ ")))
4094 (sh-remember-variable var)
4095 (if (< delta 0) " - " " + ")
4096 (number-to-string (abs delta))
4097 (sh-feature '((bash . " ))")
4098 (ksh88 . " ))")
4099 (posix . " ))")
4100 (rc . "}")
4101 (sh . "`")
4102 (zsh . " ]")))))
4106 (define-skeleton sh-function
4107 "Insert a function definition. See `sh-feature'."
4108 (bash sh-modify ksh88
4109 3 "() {")
4110 (ksh88 "name: "
4111 "function " str " {" \n
4112 > _ \n
4113 < "}" \n)
4114 (rc sh-modify ksh88
4115 1 "fn ")