Document reserved keys
[emacs.git] / lisp / progmodes / sh-script.el
bloba4cb4856a84888fae7c65a3a1a87dca204db5e47
1 ;;; sh-script.el --- shell-script editing commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1993-1997, 1999, 2001-2018 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)
596 (define-obsolete-variable-alias 'sh-indentation 'sh-basic-offset "26.1")
597 (put 'sh-indentation 'safe-local-variable 'integerp)
599 (defcustom sh-remember-variable-min 3
600 "Don't remember variables less than this length for completing reads."
601 :type 'integer
602 :group 'sh-script)
605 (defvar sh-header-marker nil
606 "When non-nil is the end of header for prepending by \\[sh-execute-region].
607 That command is also used for setting this variable.")
608 (make-variable-buffer-local 'sh-header-marker)
610 (defcustom sh-beginning-of-command
611 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
612 "Regexp to determine the beginning of a shell command.
613 The actual command starts at the beginning of the second \\(grouping\\)."
614 :type 'regexp
615 :group 'sh-script)
618 (defcustom sh-end-of-command
619 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
620 "Regexp to determine the end of a shell command.
621 The actual command ends at the end of the first \\(grouping\\)."
622 :type 'regexp
623 :group 'sh-script)
627 (defcustom sh-here-document-word "EOF"
628 "Word to delimit here documents.
629 If the first character of this string is \"-\", this is taken as
630 part of the redirection operator, rather than part of the
631 word (that is, \"<<-\" instead of \"<<\"). This is a feature
632 used by some shells (for example Bash) to indicate that leading
633 tabs inside the here document should be ignored. In this case,
634 Emacs indents the initial body and end of the here document with
635 tabs, to the same level as the start (note that apart from this
636 there is no support for indentation of here documents). This
637 will only work correctly if `sh-basic-offset' is a multiple of
638 `tab-width'.
640 Any quote characters or leading whitespace in the word are
641 removed when closing the here document."
642 :type 'string
643 :group 'sh-script)
646 (defvar sh-test
647 '((sh "[ ]" . 3)
648 (ksh88 "[[ ]]" . 4))
649 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
652 ;; customized this out of sheer bravado. not for the faint of heart.
653 ;; but it *did* have an asterisk in the docstring!
654 (defcustom sh-builtins
655 '((bash sh-append posix
656 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
657 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
658 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
659 "source" "suspend" "typeset" "unalias"
660 ;; bash4
661 "mapfile" "readarray" "coproc")
663 ;; The next entry is only used for defining the others
664 (bourne sh-append shell
665 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
666 "times" "ulimit")
668 (csh sh-append shell
669 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
670 "setenv" "source" "time" "unalias" "unhash")
672 (dtksh sh-append wksh)
674 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
675 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
677 (jsh sh-append sh
678 "bg" "fg" "jobs" "kill" "stop" "suspend")
680 (jcsh sh-append csh
681 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
683 (ksh88 sh-append bourne
684 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
685 "typeset" "unalias" "whence")
687 (oash sh-append sh
688 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
689 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
690 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
691 "wmtitle" "wrefresh")
693 (pdksh sh-append ksh88
694 "bind")
696 (posix sh-append sh
697 "command")
699 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
700 "whatis")
702 (sh sh-append bourne
703 "hash" "test" "type")
705 ;; The next entry is only used for defining the others
706 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
708 (wksh sh-append ksh88)
710 (zsh sh-append ksh88
711 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
712 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
713 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
714 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
715 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
716 "which"))
717 "List of all shell builtins for completing read and fontification.
718 Note that on some systems not all builtins are available or some are
719 implemented as aliases. See `sh-feature'."
720 :type '(repeat (cons (symbol :tag "Shell")
721 (choice (repeat string)
722 (sexp :format "Evaluate: %v"))))
723 :version "24.4" ; bash4 additions
724 :group 'sh-script)
728 (defcustom sh-leading-keywords
729 '((bash sh-append sh
730 "time")
732 (csh "else")
734 (es "true" "unwind-protect" "whatis")
736 (rc "else")
738 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
739 "List of keywords that may be immediately followed by a builtin or keyword.
740 Given some confusion between keywords and builtins depending on shell and
741 system, the distinction here has been based on whether they influence the
742 flow of control or syntax. See `sh-feature'."
743 :type '(repeat (cons (symbol :tag "Shell")
744 (choice (repeat string)
745 (sexp :format "Evaluate: %v"))))
746 :group 'sh-script)
749 (defcustom sh-other-keywords
750 '((bash sh-append bourne
751 "bye" "logout" "select")
753 ;; The next entry is only used for defining the others
754 (bourne sh-append sh
755 "function")
757 (csh sh-append shell
758 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
759 "if" "logout" "onintr" "repeat" "switch" "then" "while")
761 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
762 "return" "throw" "while")
764 (ksh88 sh-append bourne
765 "select")
767 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
768 "while")
770 (sh sh-append shell
771 "done" "esac" "fi" "for" "in" "return")
773 ;; The next entry is only used for defining the others
774 (shell "break" "case" "continue" "exec" "exit")
776 (zsh sh-append bash
777 "select" "foreach"))
778 "List of keywords not in `sh-leading-keywords'.
779 See `sh-feature'."
780 :type '(repeat (cons (symbol :tag "Shell")
781 (choice (repeat string)
782 (sexp :format "Evaluate: %v"))))
783 :group 'sh-script)
787 (defvar sh-variables
788 '((bash sh-append sh
789 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
790 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
791 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
792 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
793 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
794 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
795 "HISTIGNORE" "history_control" "HISTSIZE"
796 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
797 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
798 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
799 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
800 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
801 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
802 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
804 (csh sh-append shell
805 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
806 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
807 "shell" "status" "time" "verbose")
809 (es sh-append shell
810 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
811 "pid" "prompt" "signals")
813 (jcsh sh-append csh
814 "notify")
816 (ksh88 sh-append sh
817 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
818 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
819 "TMOUT")
821 (oash sh-append sh
822 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
824 (rc sh-append shell
825 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
826 "prompt" "status")
828 (sh sh-append shell
829 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
831 ;; The next entry is only used for defining the others
832 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
833 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
834 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
835 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
837 (tcsh sh-append csh
838 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
839 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
840 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
841 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
842 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
843 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
844 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
845 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
846 "wordchars")
848 (zsh sh-append ksh88
849 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
850 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
851 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
852 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
853 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
854 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
855 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
856 "List of all shell variables available for completing read.
857 See `sh-feature'.")
860 ;; Font-Lock support
862 (defface sh-heredoc
863 '((((min-colors 88) (class color)
864 (background dark))
865 (:foreground "yellow1" :weight bold))
866 (((class color)
867 (background dark))
868 (:foreground "yellow" :weight bold))
869 (((class color)
870 (background light))
871 (:foreground "tan1" ))
873 (:weight bold)))
874 "Face to show a here-document."
875 :group 'sh-indentation)
877 ;; These colors are probably icky. It's just a placeholder though.
878 (defface sh-quoted-exec
879 '((((class color) (background dark))
880 (:foreground "salmon"))
881 (((class color) (background light))
882 (:foreground "magenta"))
884 (:weight bold)))
885 "Face to show quoted execs like \\=`blabla\\=`."
886 :group 'sh-indentation)
888 (defface sh-escaped-newline '((t :inherit font-lock-string-face))
889 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
890 :group 'sh-script
891 :version "22.1")
893 (defvar sh-font-lock-keywords-var
894 '((csh sh-append shell
895 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
896 font-lock-variable-name-face))
898 (es sh-append executable-font-lock-keywords
899 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
900 font-lock-variable-name-face))
902 (rc sh-append es)
903 (bash sh-append sh ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
904 (sh sh-append shell
905 ;; Variable names.
906 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
907 font-lock-variable-name-face)
908 ;; Function names.
909 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
910 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
911 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
912 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
913 1 font-lock-negation-char-face))
915 ;; The next entry is only used for defining the others
916 (shell
917 ;; Using font-lock-string-face here confuses sh-get-indent-info.
918 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
919 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
920 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
921 font-lock-variable-name-face))
922 (rpm sh-append rpm2
923 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
924 (rpm2 sh-append shell
925 ("^Summary:\\(.*\\)$" (1 font-lock-doc-face t))
926 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
927 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
929 (defvar sh-font-lock-keywords-var-1
930 '((sh "[ \t]in\\>"))
931 "Subdued level highlighting for Shell Script modes.")
933 (defvar sh-font-lock-keywords-var-2 ()
934 "Gaudy level highlighting for Shell Script modes.")
936 ;; These are used for the syntax table stuff (derived from cperl-mode).
937 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
938 (defconst sh-st-punc (string-to-syntax "."))
939 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
941 (eval-and-compile
942 (defconst sh-escaped-line-re
943 ;; Should match until the real end-of-continued-line, but if that is not
944 ;; possible (because we bump into EOB or the search bound), then we should
945 ;; match until the search bound.
946 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
948 (defconst sh-here-doc-open-re
949 (concat "[^<]<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|[-/~._]\\)+\\)"
950 sh-escaped-line-re "\\(\n\\)")))
952 (defun sh--inside-noncommand-expression (pos)
953 (save-excursion
954 (let ((ppss (syntax-ppss pos)))
955 (when (nth 1 ppss)
956 (goto-char (nth 1 ppss))
958 (pcase (char-after)
959 ;; ((...)) or $((...)) or $[...] or ${...}. Nested
960 ;; parenthesis can occur inside the first of these forms, so
961 ;; parse backward recursively.
962 (`?\( (eq ?\( (char-before)))
963 ((or `?\{ `?\[) (eq ?\$ (char-before))))
964 (sh--inside-noncommand-expression (1- (point))))))))
966 (defun sh-font-lock-open-heredoc (start string eol)
967 "Determine the syntax of the \\n after a <<EOF.
968 START is the position of <<.
969 STRING is the actual word used as delimiter (e.g. \"EOF\").
970 INDENTED is non-nil if the here document's content (and the EOF mark) can
971 be indented (i.e. a <<- was used rather than just <<).
972 Point is at the beginning of the next line."
973 (unless (or (memq (char-before start) '(?< ?>))
974 (sh-in-comment-or-string start)
975 (sh--inside-noncommand-expression start))
976 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
977 ;; font-lock keywords to detect the end of this here document.
978 (let ((str (replace-regexp-in-string "['\"]" "" string))
979 (ppss (save-excursion (syntax-ppss eol))))
980 (if (nth 4 ppss)
981 ;; The \n not only starts the heredoc but also closes a comment.
982 ;; Let's close the comment just before the \n.
983 (put-text-property (1- eol) eol 'syntax-table '(12))) ;">"
984 (if (or (nth 5 ppss) (> (count-lines start eol) 1))
985 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
986 ;; several lines, make sure we refontify them together.
987 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
988 ;; escaped), it means the right \n is actually further down.
989 ;; Don't bother fixing it now, but place a multiline property so
990 ;; that when jit-lock-context-* refontifies the rest of the
991 ;; buffer, it also refontifies the current line with it.
992 (put-text-property start (1+ eol) 'syntax-multiline t))
993 (put-text-property eol (1+ eol) 'sh-here-doc-marker str)
994 (prog1 sh-here-doc-syntax
995 (goto-char (+ 2 start))))))
997 (defun sh-syntax-propertize-here-doc (end)
998 (let ((ppss (syntax-ppss)))
999 (when (eq t (nth 3 ppss))
1000 (let ((key (get-text-property (nth 8 ppss) 'sh-here-doc-marker))
1001 (case-fold-search nil))
1002 (when (re-search-forward
1003 (concat "^\\([ \t]*\\)" (regexp-quote key) "\\(\n\\)")
1004 end 'move)
1005 (let ((eol (match-beginning 2)))
1006 (put-text-property eol (1+ eol)
1007 'syntax-table sh-here-doc-syntax)))))))
1009 (defun sh-font-lock-quoted-subshell (limit)
1010 "Search for a subshell embedded in a string.
1011 Find all the unescaped \" characters within said subshell, remembering that
1012 subshells can nest."
1013 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1014 ;; bingo we have a $( or a ` inside a ""
1015 (let (;; `state' can be: double-quote, backquote, code.
1016 (state (if (eq (char-before) ?`) 'backquote 'code))
1017 (startpos (point))
1018 ;; Stacked states in the context.
1019 (states '(double-quote)))
1020 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1021 (< (point) limit)))
1022 ;; unescape " inside a $( ... ) construct.
1023 (pcase (char-after)
1024 (?\' (pcase state
1025 (`double-quote nil)
1026 (_ (forward-char 1)
1027 ;; FIXME: mark skipped double quotes as punctuation syntax.
1028 (let ((spos (point)))
1029 (skip-chars-forward "^'" limit)
1030 (save-excursion
1031 (let ((epos (point)))
1032 (goto-char spos)
1033 (while (search-forward "\"" epos t)
1034 (put-text-property (point) (1- (point))
1035 'syntax-table '(1)))))))))
1036 (?\\ (forward-char 1))
1037 (?\" (pcase state
1038 (`double-quote (setq state (pop states)))
1039 (_ (push state states) (setq state 'double-quote)))
1040 (if state (put-text-property (point) (1+ (point))
1041 'syntax-table '(1))))
1042 (?\` (pcase state
1043 (`backquote (setq state (pop states)))
1044 (_ (push state states) (setq state 'backquote))))
1045 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1047 (forward-char 1)
1048 (pcase state
1049 (_ (push state states) (setq state 'code)))))
1050 (?\( (pcase state
1051 (`double-quote nil)
1052 (_ (push state states) (setq state 'code))))
1053 (?\) (pcase state
1054 (`double-quote nil)
1055 (_ (setq state (pop states)))))
1056 (_ (error "Internal error in sh-font-lock-quoted-subshell")))
1057 (forward-char 1))
1058 (when (< startpos (line-beginning-position))
1059 (put-text-property startpos (point) 'syntax-multiline t)
1060 (add-hook 'syntax-propertize-extend-region-functions
1061 'syntax-propertize-multiline nil t))
1065 (defun sh-is-quoted-p (pos)
1066 (and (eq (char-before pos) ?\\)
1067 (not (sh-is-quoted-p (1- pos)))))
1069 (defun sh-font-lock-paren (start)
1070 (unless (nth 8 (syntax-ppss))
1071 (save-excursion
1072 (let ((open nil))
1073 (goto-char start)
1074 ;; Skip through all patterns
1075 (while
1076 (progn
1077 (while
1078 (progn
1079 (forward-comment (- (point-max)))
1080 (when (and (eolp) (sh-is-quoted-p (point)))
1081 (forward-char -1)
1082 t)))
1083 ;; Skip through one pattern
1084 (while
1085 (or (/= 0 (skip-syntax-backward "w_"))
1086 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1087 (and (sh-is-quoted-p (1- (point)))
1088 (goto-char (- (point) 2)))
1089 (when (memq (char-before) '(?\" ?\' ?\}))
1090 (condition-case nil (progn (backward-sexp 1) t)
1091 (error nil)))))
1092 ;; Patterns can be preceded by an open-paren (bug#1320).
1093 (when (eq (char-before (point)) ?\()
1094 (backward-char 1)
1095 (setq open (point)))
1096 (while (progn
1097 (forward-comment (- (point-max)))
1098 ;; Maybe we've bumped into an escaped newline.
1099 (sh-is-quoted-p (point)))
1100 (backward-char 1))
1101 (when (eq (char-before) ?|)
1102 (backward-char 1) t)))
1103 (and (> (point) (1+ (point-min)))
1104 (progn (backward-char 2)
1105 (if (> start (line-end-position))
1106 (put-text-property (point) (1+ start)
1107 'syntax-multiline t))
1108 ;; FIXME: The `in' may just be a random argument to
1109 ;; a normal command rather than the real `in' keyword.
1110 ;; I.e. we should look back to try and find the
1111 ;; corresponding `case'.
1112 (and (looking-at ";[;&]\\|\\_<in")
1113 ;; ";; esac )" is a case that looks
1114 ;; like a case-pattern but it's really just a close
1115 ;; paren after a case statement. I.e. if we skipped
1116 ;; over `esac' just now, we're not looking
1117 ;; at a case-pattern.
1118 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1119 (progn
1120 (when open
1121 (put-text-property open (1+ open) 'syntax-table sh-st-punc))
1122 sh-st-punc))))))
1124 (defun sh-font-lock-backslash-quote ()
1125 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1126 ;; In a '...' the backslash is not escaping.
1127 sh-st-punc
1128 nil))
1130 (defun sh-syntax-propertize-function (start end)
1131 (goto-char start)
1132 (sh-syntax-propertize-here-doc end)
1133 (funcall
1134 (syntax-propertize-rules
1135 (sh-here-doc-open-re
1136 (2 (sh-font-lock-open-heredoc
1137 (1+ (match-beginning 0)) (match-string 1) (match-beginning 2))))
1138 ("\\s|" (0 (prog1 nil (sh-syntax-propertize-here-doc end))))
1139 ;; A `#' begins a comment when it is unquoted and at the
1140 ;; beginning of a word. In the shell, words are separated by
1141 ;; metacharacters. The list of special chars is taken from
1142 ;; the single-unix spec of the shell command language (under
1143 ;; `quoting') but with `$' removed.
1144 ("\\(?:[^|&;<>()`\\\"' \t\n]\\|\\${\\)\\(#+\\)" (1 "_"))
1145 ;; In a '...' the backslash is not escaping.
1146 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1147 ;; Make sure $@ and $? are correctly recognized as sexps.
1148 ("\\$\\([?@]\\)" (1 "_"))
1149 ;; Distinguish the special close-paren in `case'.
1150 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1151 ;; Highlight (possibly nested) subshells inside "" quoted
1152 ;; regions correctly.
1153 ("\"\\(?:\\(?:[^\\\"]\\|\\\\.\\)*?\\)??\\(\\$(\\|`\\)"
1154 (1 (ignore
1155 (if (nth 8 (save-excursion (syntax-ppss (match-beginning 0))))
1156 (goto-char (1+ (match-beginning 0)))
1157 ;; Save excursion because we want to also apply other
1158 ;; syntax-propertize rules within the affected region.
1159 (save-excursion
1160 (sh-font-lock-quoted-subshell end)))))))
1161 (point) end))
1162 (defun sh-font-lock-syntactic-face-function (state)
1163 (let ((q (nth 3 state)))
1164 (if q
1165 (if (characterp q)
1166 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1167 'sh-heredoc)
1168 font-lock-comment-face)))
1170 (defgroup sh-indentation nil
1171 "Variables controlling indentation in shell scripts.
1173 Note: customizing these variables will not affect existing buffers if
1174 `sh-make-vars-local' is non-nil. See the documentation for
1175 variable `sh-make-vars-local', command `sh-make-vars-local'
1176 and command `sh-reset-indent-vars-to-global-values'."
1177 :group 'sh-script)
1180 (defcustom sh-set-shell-hook nil
1181 "Hook run by `sh-set-shell'."
1182 :type 'hook
1183 :group 'sh-script)
1185 (defcustom sh-mode-hook '(sh-electric-here-document-mode)
1186 "Hook run by `sh-mode'."
1187 :type 'hook
1188 :options '(sh-electric-here-document-mode)
1189 :group 'sh-script)
1191 (defcustom sh-learn-basic-offset nil
1192 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1194 nil mean: never.
1195 t means: only if there seems to be an obvious value.
1196 Anything else means: whenever we have a \"good guess\" as to the value."
1197 :type '(choice
1198 (const :tag "Never" nil)
1199 (const :tag "Only if sure" t)
1200 (const :tag "If have a good guess" usually))
1201 :group 'sh-indentation)
1203 (defcustom sh-popup-occur-buffer nil
1204 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1205 If t it is always shown. If nil, it is shown only when there
1206 are conflicts."
1207 :type '(choice
1208 (const :tag "Only when there are conflicts." nil)
1209 (const :tag "Always" t))
1210 :group 'sh-indentation)
1212 (defcustom sh-blink t
1213 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1214 The position on the line is not necessarily meaningful.
1215 In some cases the line will be the matching keyword, but this is not
1216 always the case."
1217 :type 'boolean
1218 :group 'sh-indentation)
1220 (defcustom sh-first-lines-indent 0
1221 "The indentation of the first non-blank non-comment line.
1222 Usually 0 meaning first column.
1223 Can be set to a number, or to nil which means leave it as is."
1224 :type '(choice
1225 (const :tag "Leave as is" nil)
1226 (integer :tag "Column number"
1227 :menu-tag "Indent to this col (0 means first col)" ))
1228 :group 'sh-indentation)
1231 (defcustom sh-basic-offset 4
1232 "The default indentation increment.
1233 This value is used for the `+' and `-' symbols in an indentation variable."
1234 :type 'integer
1235 :group 'sh-indentation)
1236 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1238 (defcustom sh-indent-comment t
1239 "How a comment line is to be indented.
1240 nil means leave it as it is;
1241 t means indent it as a normal line, aligning it to previous non-blank
1242 non-comment line;
1243 a number means align to that column, e.g. 0 means first column."
1244 :type '(choice
1245 (const :tag "Leave as is." nil)
1246 (const :tag "Indent as a normal line." t)
1247 (integer :menu-tag "Indent to this col (0 means first col)."
1248 :tag "Indent to column number.") )
1249 :version "24.3"
1250 :group 'sh-indentation)
1253 (defvar sh-debug nil
1254 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1257 ;; Uncomment this defun and comment the defmacro for debugging.
1258 ;; (defun sh-debug (&rest args)
1259 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1260 ;; (if sh-debug
1261 ;; (apply 'message args)))
1262 (defmacro sh-debug (&rest _args))
1264 (defconst sh-symbol-list
1265 '((const :tag "+ " :value +
1266 :menu-tag "+ Indent right by sh-basic-offset")
1267 (const :tag "- " :value -
1268 :menu-tag "- Indent left by sh-basic-offset")
1269 (const :tag "++" :value ++
1270 :menu-tag "++ Indent right twice sh-basic-offset")
1271 (const :tag "--" :value --
1272 :menu-tag "-- Indent left twice sh-basic-offset")
1273 (const :tag "* " :value *
1274 :menu-tag "* Indent right half sh-basic-offset")
1275 (const :tag "/ " :value /
1276 :menu-tag "/ Indent left half sh-basic-offset")))
1278 (defcustom sh-indent-for-else 0
1279 "How much to indent an `else' relative to its `if'. Usually 0."
1280 :type `(choice
1281 (integer :menu-tag "A number (positive=>indent right)"
1282 :tag "A number")
1283 (const :tag "--") ;; separator!
1284 ,@ sh-symbol-list
1286 :group 'sh-indentation)
1288 (defconst sh-number-or-symbol-list
1289 (append '((integer :menu-tag "A number (positive=>indent right)"
1290 :tag "A number")
1291 (const :tag "--")) ; separator
1292 sh-symbol-list))
1294 (defcustom sh-indent-for-fi 0
1295 "How much to indent a `fi' relative to its `if'. Usually 0."
1296 :type `(choice ,@ sh-number-or-symbol-list )
1297 :group 'sh-indentation)
1299 (defcustom sh-indent-for-done 0
1300 "How much to indent a `done' relative to its matching stmt. Usually 0."
1301 :type `(choice ,@ sh-number-or-symbol-list )
1302 :group 'sh-indentation)
1304 (defcustom sh-indent-after-else '+
1305 "How much to indent a statement after an `else' statement."
1306 :type `(choice ,@ sh-number-or-symbol-list )
1307 :group 'sh-indentation)
1309 (defcustom sh-indent-after-if '+
1310 "How much to indent a statement after an `if' statement.
1311 This includes lines after `else' and `elif' statements, too, but
1312 does not affect the `else', `elif' or `fi' statements themselves."
1313 :type `(choice ,@ sh-number-or-symbol-list )
1314 :group 'sh-indentation)
1316 (defcustom sh-indent-for-then 0
1317 "How much to indent a `then' relative to its `if'."
1318 :type `(choice ,@ sh-number-or-symbol-list )
1319 :group 'sh-indentation)
1321 (defcustom sh-indent-for-do 0
1322 "How much to indent a `do' statement.
1323 This is relative to the statement before the `do', typically a
1324 `while', `until', `for', `repeat' or `select' statement."
1325 :type `(choice ,@ sh-number-or-symbol-list)
1326 :group 'sh-indentation)
1328 (defcustom sh-indent-after-do '+
1329 "How much to indent a line after a `do' statement.
1330 This is used when the `do' is the first word of the line.
1331 This is relative to the statement before the `do', typically a
1332 `while', `until', `for', `repeat' or `select' statement."
1333 :type `(choice ,@ sh-number-or-symbol-list)
1334 :group 'sh-indentation)
1336 (defcustom sh-indent-after-loop-construct '+
1337 "How much to indent a statement after a loop construct.
1339 This variable is used when the keyword `do' is on the same line as the
1340 loop statement (e.g., `until', `while' or `for').
1341 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1342 :type `(choice ,@ sh-number-or-symbol-list)
1343 :group 'sh-indentation)
1346 (defcustom sh-indent-after-done 0
1347 "How much to indent a statement after a `done' keyword.
1348 Normally this is 0, which aligns the `done' to the matching
1349 looping construct line.
1350 Setting it non-zero allows you to have the `do' statement on a line
1351 by itself and align the done under to do."
1352 :type `(choice ,@ sh-number-or-symbol-list)
1353 :group 'sh-indentation)
1355 (defcustom sh-indent-for-case-label '+
1356 "How much to indent a case label statement.
1357 This is relative to the line containing the `case' statement."
1358 :type `(choice ,@ sh-number-or-symbol-list)
1359 :group 'sh-indentation)
1361 (defcustom sh-indent-for-case-alt '++
1362 "How much to indent statements after the case label.
1363 This is relative to the line containing the `case' statement."
1364 :type `(choice ,@ sh-number-or-symbol-list)
1365 :group 'sh-indentation)
1368 (defcustom sh-indent-for-continuation '+
1369 "How much to indent for a continuation statement."
1370 :type `(choice ,@ sh-number-or-symbol-list)
1371 :group 'sh-indentation)
1373 (defcustom sh-indent-after-open '+
1374 "How much to indent after a line with an opening parenthesis or brace.
1375 For an open paren after a function, `sh-indent-after-function' is used."
1376 :type `(choice ,@ sh-number-or-symbol-list)
1377 :group 'sh-indentation)
1379 (defcustom sh-indent-after-function '+
1380 "How much to indent after a function line."
1381 :type `(choice ,@ sh-number-or-symbol-list)
1382 :group 'sh-indentation)
1384 ;; These 2 are for the rc shell:
1386 (defcustom sh-indent-after-switch '+
1387 "How much to indent a `case' statement relative to the `switch' statement.
1388 This is for the rc shell."
1389 :type `(choice ,@ sh-number-or-symbol-list)
1390 :group 'sh-indentation)
1392 (defcustom sh-indent-after-case '+
1393 "How much to indent a statement relative to the `case' statement.
1394 This is for the rc shell."
1395 :type `(choice ,@ sh-number-or-symbol-list)
1396 :group 'sh-indentation)
1398 (defcustom sh-backslash-column 48
1399 "Column in which `sh-backslash-region' inserts backslashes."
1400 :type 'integer
1401 :group 'sh)
1403 (defcustom sh-backslash-align t
1404 "If non-nil, `sh-backslash-region' will align backslashes."
1405 :type 'boolean
1406 :group 'sh)
1408 ;; Internal use - not designed to be changed by the user:
1410 (defun sh-mkword-regexpr (word)
1411 "Make a regexp which matches WORD as a word.
1412 This specifically excludes an occurrence of WORD followed by
1413 punctuation characters like `-'."
1414 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1416 (defconst sh-re-done (sh-mkword-regexpr "done"))
1419 (defconst sh-kws-for-done
1420 '((sh . ( "while" "until" "for" ) )
1421 (bash . ( "while" "until" "for" "select" ) )
1422 (ksh88 . ( "while" "until" "for" "select" ) )
1423 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1424 "Which keywords can match the word `done' in this shell.")
1427 (defconst sh-indent-supported
1428 '((sh . sh)
1429 (csh . nil)
1430 (rc . rc))
1431 "Indentation rule set to use for each shell type.")
1433 (defvar sh-indent-supported-here nil
1434 "Non-nil if we support indentation for the current buffer's shell type.")
1436 (defconst sh-var-list
1438 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1439 sh-indent-after-do sh-indent-after-done
1440 sh-indent-after-else
1441 sh-indent-after-if
1442 sh-indent-after-loop-construct
1443 sh-indent-after-open
1444 sh-indent-comment
1445 sh-indent-for-case-alt
1446 sh-indent-for-case-label
1447 sh-indent-for-continuation
1448 sh-indent-for-do
1449 sh-indent-for-done
1450 sh-indent-for-else
1451 sh-indent-for-fi
1452 sh-indent-for-then
1454 "A list of variables used by script mode to control indentation.
1455 This list is used when switching between buffer-local and global
1456 values of variables, and for the commands using indentation styles.")
1458 (defvar sh-make-vars-local t
1459 "Controls whether indentation variables are local to the buffer.
1460 If non-nil, indentation variables are made local initially.
1461 If nil, you can later make the variables local by invoking
1462 command `sh-make-vars-local'.
1463 The default is t because I assume that in one Emacs session one is
1464 frequently editing existing scripts with different styles.")
1467 ;; inferior shell interaction
1468 ;; TODO: support multiple interactive shells
1469 (defvar-local sh-shell-process nil
1470 "The inferior shell process for interaction.")
1472 (defvar explicit-shell-file-name)
1474 (defun sh-shell-process (force)
1475 "Get a shell process for interaction.
1476 If FORCE is non-nil and no process found, create one."
1477 (if (process-live-p sh-shell-process)
1478 sh-shell-process
1479 (setq sh-shell-process
1480 (let ((found nil) proc
1481 (procs (process-list)))
1482 (while (and (not found) procs
1483 (process-live-p (setq proc (pop procs)))
1484 (process-command proc))
1485 (when (string-equal sh-shell (file-name-nondirectory
1486 (car (process-command proc))))
1487 (setq found proc)))
1488 (or found
1489 (and force
1490 (get-buffer-process
1491 (let ((explicit-shell-file-name sh-shell-file))
1492 (shell)))))))))
1494 (defun sh-show-shell ()
1495 "Pop the shell interaction buffer."
1496 (interactive)
1497 (pop-to-buffer (process-buffer (sh-shell-process t))))
1499 (defun sh-send-text (text)
1500 "Send the text to the `sh-shell-process'."
1501 (comint-send-string (sh-shell-process t) (concat text "\n")))
1503 (defun sh-cd-here ()
1504 "Change directory in the current interaction shell to the current one."
1505 (interactive)
1506 (sh-send-text (concat "cd " default-directory)))
1508 (defun sh-send-line-or-region-and-step ()
1509 "Send the current line to the inferior shell and step to the next line.
1510 When the region is active, send the region instead."
1511 (interactive)
1512 (let (from to end)
1513 (if (use-region-p)
1514 (setq from (region-beginning)
1515 to (region-end)
1516 end to)
1517 (setq from (line-beginning-position)
1518 to (line-end-position)
1519 end (1+ to)))
1520 (sh-send-text (buffer-substring-no-properties from to))
1521 (goto-char end)))
1524 ;; mode-command and utility functions
1526 (defun sh-after-hack-local-variables ()
1527 (when (assq 'sh-shell file-local-variables-alist)
1528 (sh-set-shell (if (symbolp sh-shell)
1529 (symbol-name sh-shell)
1530 sh-shell))))
1532 ;;;###autoload
1533 (define-derived-mode sh-mode prog-mode "Shell-script"
1534 "Major mode for editing shell scripts.
1535 This mode works for many shells, since they all have roughly the same syntax,
1536 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1537 Unless the file's magic number indicates the shell, your usual shell is
1538 assumed. Since filenames rarely give a clue, they are not further analyzed.
1540 This mode adapts to the variations between shells (see `sh-set-shell') by
1541 means of an inheritance based feature lookup (see `sh-feature'). This
1542 mechanism applies to all variables (including skeletons) that pertain to
1543 shell-specific features. Shell script files can use the `sh-shell' local
1544 variable to indicate the shell variant to be used for the file.
1546 The default style of this mode is that of Rosenblatt's Korn shell book.
1547 The syntax of the statements varies with the shell being used. The
1548 following commands are available, based on the current shell's syntax:
1549 \\<sh-mode-map>
1550 \\[sh-case] case statement
1551 \\[sh-for] for loop
1552 \\[sh-function] function definition
1553 \\[sh-if] if statement
1554 \\[sh-indexed-loop] indexed loop from 1 to n
1555 \\[sh-while-getopts] while getopts loop
1556 \\[sh-repeat] repeat loop
1557 \\[sh-select] select loop
1558 \\[sh-until] until loop
1559 \\[sh-while] while loop
1561 For sh and rc shells indentation commands are:
1562 \\[sh-show-indent] Show the variable controlling this line's indentation.
1563 \\[sh-set-indent] Set then variable controlling this line's indentation.
1564 \\[sh-learn-line-indent] Change the indentation variable so this line
1565 would indent to the way it currently is.
1566 \\[sh-learn-buffer-indent] Set the indentation variables so the
1567 buffer indents as it currently is indented.
1570 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1571 \\[sh-end-of-command] Go to end of successive commands.
1572 \\[sh-beginning-of-command] Go to beginning of successive commands.
1573 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1574 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1576 `sh-electric-here-document-mode' controls whether insertion of two
1577 unquoted < insert a here document. You can control this behavior by
1578 modifying `sh-mode-hook'.
1580 If you generally program a shell different from your login shell you can
1581 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1582 indicate what shell it is use `sh-alias-alist' to translate.
1584 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1585 with your script for an edit-interpret-debug cycle."
1586 (make-local-variable 'sh-shell-file)
1587 (make-local-variable 'sh-shell)
1589 (setq-local skeleton-pair-default-alist
1590 sh-skeleton-pair-default-alist)
1592 (setq-local paragraph-start (concat page-delimiter "\\|$"))
1593 (setq-local paragraph-separate (concat paragraph-start "\\|#!/"))
1594 (setq-local comment-start "# ")
1595 (setq-local comment-start-skip "#+[\t ]*")
1596 (setq-local local-abbrev-table sh-mode-abbrev-table)
1597 (setq-local comint-dynamic-complete-functions
1598 sh-dynamic-complete-functions)
1599 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t)
1600 ;; we can't look if previous line ended with `\'
1601 (setq-local comint-prompt-regexp "^[ \t]*")
1602 (setq-local imenu-case-fold-search nil)
1603 (setq font-lock-defaults
1604 `((sh-font-lock-keywords
1605 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1606 nil nil
1607 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1608 (font-lock-syntactic-face-function
1609 . sh-font-lock-syntactic-face-function)))
1610 (setq-local syntax-propertize-function #'sh-syntax-propertize-function)
1611 (add-hook 'syntax-propertize-extend-region-functions
1612 #'syntax-propertize-multiline 'append 'local)
1613 (setq-local skeleton-pair-alist '((?` _ ?`)))
1614 (setq-local skeleton-pair-filter-function 'sh-quoted-p)
1615 (setq-local skeleton-further-elements
1616 '((< '(- (min sh-basic-offset (current-column))))))
1617 (setq-local skeleton-filter-function 'sh-feature)
1618 (setq-local skeleton-newline-indent-rigidly t)
1619 (setq-local defun-prompt-regexp
1620 (concat
1621 "^\\("
1622 "\\(function[ \t]\\)?[ \t]*[[:alnum:]]+[ \t]*([ \t]*)"
1623 "\\|"
1624 "function[ \t]+[[:alnum:]]+[ \t]*\\(([ \t]*)\\)?"
1625 "\\)[ \t]*"))
1626 (setq-local add-log-current-defun-function #'sh-current-defun-name)
1627 (add-hook 'completion-at-point-functions
1628 #'sh-completion-at-point-function nil t)
1629 ;; Parse or insert magic number for exec, and set all variables depending
1630 ;; on the shell thus determined.
1631 (sh-set-shell
1632 (cond ((save-excursion
1633 (goto-char (point-min))
1634 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1635 (match-string 2))
1636 ((not buffer-file-name) sh-shell-file)
1637 ;; Checks that use `buffer-file-name' follow.
1638 ((string-match "\\.m?spec\\'" buffer-file-name) "rpm")
1639 ((string-match "[.]sh\\>" buffer-file-name) "sh")
1640 ((string-match "[.]bash\\>" buffer-file-name) "bash")
1641 ((string-match "[.]ksh\\>" buffer-file-name) "ksh")
1642 ((string-match "[.]mkshrc\\>" buffer-file-name) "mksh")
1643 ((string-match "[.]t?csh\\(rc\\)?\\>" buffer-file-name) "csh")
1644 ((string-match "[.]zsh\\(rc\\|env\\)?\\>" buffer-file-name) "zsh")
1645 ((equal (file-name-nondirectory buffer-file-name) ".profile") "sh")
1646 (t sh-shell-file))
1647 nil nil)
1648 (add-hook 'hack-local-variables-hook
1649 #'sh-after-hack-local-variables nil t))
1651 ;;;###autoload
1652 (defalias 'shell-script-mode 'sh-mode)
1655 (defun sh-font-lock-keywords (&optional keywords)
1656 "Function to get simple fontification based on `sh-font-lock-keywords'.
1657 This adds rules for comments and assignments."
1658 (sh-feature sh-font-lock-keywords-var
1659 (when (stringp (sh-feature sh-assignment-regexp))
1660 (lambda (list)
1661 `((,(sh-feature sh-assignment-regexp)
1662 1 font-lock-variable-name-face)
1663 ,@keywords
1664 ,@list
1665 ,@executable-font-lock-keywords)))))
1667 (defun sh-font-lock-keywords-1 (&optional builtins)
1668 "Function to get better fontification including keywords."
1669 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1670 (regexp-opt (sh-feature sh-leading-keywords) t)
1671 "[ \t]+\\)?"
1672 (regexp-opt (append (sh-feature sh-leading-keywords)
1673 (sh-feature sh-other-keywords))
1674 t))))
1675 (sh-font-lock-keywords
1676 `(,@(if builtins
1677 `((,(concat keywords "[ \t]+\\)?"
1678 (regexp-opt (sh-feature sh-builtins) t)
1679 "\\>")
1680 (2 font-lock-keyword-face nil t)
1681 (6 font-lock-builtin-face))
1682 ,@(sh-feature sh-font-lock-keywords-var-2)))
1683 (,(concat keywords "\\)\\>")
1684 2 font-lock-keyword-face)
1685 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1687 (defun sh-font-lock-keywords-2 ()
1688 "Function to get better fontification including keywords and builtins."
1689 (sh-font-lock-keywords-1 t))
1691 ;;; Completion
1693 (defun sh--vars-before-point ()
1694 (save-excursion
1695 (let ((vars ()))
1696 (while (re-search-backward "^[ \t]*\\([[:alnum:]_]+\\)=" nil t)
1697 (push (match-string 1) vars))
1698 vars)))
1700 ;; (defun sh--var-completion-table (string pred action)
1701 ;; (complete-with-action action (sh--vars-before-point) string pred))
1703 (defun sh--cmd-completion-table (string pred action)
1704 (let ((cmds
1705 (append (when (fboundp 'imenu--make-index-alist)
1706 (mapcar #'car
1707 (condition-case nil
1708 (imenu--make-index-alist)
1709 (imenu-unavailable nil))))
1710 (mapcar (lambda (v) (concat v "="))
1711 (sh--vars-before-point))
1712 (locate-file-completion-table
1713 exec-path exec-suffixes string pred t)
1714 '("if" "while" "until" "for"))))
1715 (complete-with-action action cmds string pred)))
1717 (defun sh-completion-at-point-function ()
1718 (save-excursion
1719 (skip-chars-forward "[:alnum:]_")
1720 (let ((end (point))
1721 (_ (skip-chars-backward "[:alnum:]_"))
1722 (start (point)))
1723 (cond
1724 ((eq (char-before) ?$)
1725 (list start end (sh--vars-before-point)))
1726 ((sh-smie--keyword-p)
1727 (list start end #'sh--cmd-completion-table))))))
1729 ;;; Indentation and navigation with SMIE.
1731 (require 'smie)
1733 ;; The SMIE code should generally be preferred, but it currently does not obey
1734 ;; the various indentation custom-vars, and it misses some important features
1735 ;; of the old code, mostly: sh-learn-line/buffer-indent, sh-show-indent,
1736 ;; sh-name/save/load-style.
1737 (defvar sh-use-smie t
1738 "Whether to use the SMIE code for navigation and indentation.")
1740 (defun sh-smie--keyword-p ()
1741 "Non-nil if we're at a keyword position.
1742 A keyword position is one where if we're looking at something that looks
1743 like a keyword, then it is a keyword."
1744 (let ((prev (funcall smie-backward-token-function)))
1745 (if (zerop (length prev))
1746 (looking-back "\\`\\|\\s(" (1- (point)))
1747 (assoc prev smie-grammar))))
1749 (defun sh-smie--newline-semi-p (&optional tok)
1750 "Return non-nil if a newline should be treated as a semi-colon.
1751 Here we assume that a newline should be treated as a semi-colon unless it
1752 comes right after a special keyword.
1753 This function does not pay attention to line-continuations.
1754 If TOK is nil, point should be before the newline; otherwise, TOK is the token
1755 before the newline and in that case point should be just before the token."
1756 (save-excursion
1757 (unless tok
1758 (setq tok (funcall smie-backward-token-function)))
1759 (if (and (zerop (length tok))
1760 (looking-back "\\s(" (1- (point))))
1762 (not (numberp (nth 2 (assoc tok smie-grammar)))))))
1764 ;;;; SMIE support for `sh'.
1766 (defconst sh-smie-sh-grammar
1767 (smie-prec2->grammar
1768 (smie-bnf->prec2
1769 '((exp) ;A constant, or a $var, or a sequence of them...
1770 (cmd ("case" exp "in" branches "esac")
1771 ("if" cmd "then" cmd "fi")
1772 ("if" cmd "then" cmd "else" cmd "fi")
1773 ("if" cmd "then" cmd "elif" cmd "then" cmd "fi")
1774 ("if" cmd "then" cmd "elif" cmd "then" cmd "else" cmd "fi")
1775 ("if" cmd "then" cmd "elif" cmd "then" cmd
1776 "elif" cmd "then" cmd "else" cmd "fi")
1777 ("while" cmd "do" cmd "done")
1778 ("until" cmd "do" cmd "done")
1779 ("for" exp "in" cmd "do" cmd "done")
1780 ("for" exp "do" cmd "done")
1781 ("select" exp "in" cmd "do" cmd "done") ;bash&zsh&ksh88.
1782 ("repeat" exp "do" cmd "done") ;zsh.
1783 (exp "always" exp) ;zsh.
1784 (cmd "|" cmd) (cmd "|&" cmd)
1785 (cmd "&&" cmd) (cmd "||" cmd)
1786 (cmd ";" cmd) (cmd "&" cmd))
1787 (rpattern (rpattern "|" rpattern))
1788 (pattern (rpattern) ("case-(" rpattern))
1789 (branches (branches ";;" branches)
1790 (branches ";&" branches) (branches ";;&" branches) ;bash.
1791 (pattern "case-)" cmd)))
1792 '((assoc ";;" ";&" ";;&"))
1793 '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1795 (defconst sh-smie--sh-operators
1796 (delq nil (mapcar (lambda (x)
1797 (setq x (car x))
1798 (and (stringp x)
1799 (not (string-match "\\`[a-z]" x))
1801 sh-smie-sh-grammar)))
1803 (defconst sh-smie--sh-operators-re (regexp-opt sh-smie--sh-operators))
1804 (defconst sh-smie--sh-operators-back-re
1805 (concat "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*"
1806 "\\(" sh-smie--sh-operators-re "\\)"))
1808 (defun sh-smie--sh-keyword-in-p ()
1809 "Assuming we're looking at \"in\", return non-nil if it's a keyword.
1810 Does not preserve point."
1811 (let ((forward-sexp-function nil)
1812 (words nil) ;We've seen words.
1813 (newline nil) ;We've seen newlines after the words.
1814 (res nil)
1815 prev)
1816 (while (not res)
1817 (setq prev (funcall smie-backward-token-function))
1818 (cond
1819 ((zerop (length prev))
1820 (cond
1821 (newline (cl-assert words) (setq res 'word))
1822 ((bobp) (setq res 'word))
1824 (setq words t)
1825 (condition-case nil
1826 (forward-sexp -1)
1827 (scan-error (setq res 'unknown))))))
1828 ((equal prev ";")
1829 (if words (setq newline t)
1830 (setq res 'keyword)))
1831 ((member prev '("case" "for" "select")) (setq res 'keyword))
1832 ((assoc prev smie-grammar) (setq res 'word))
1834 (if newline
1835 (progn (cl-assert words) (setq res 'word))
1836 (setq words t)))))
1837 (eq res 'keyword)))
1839 (defun sh-smie--sh-keyword-p (tok)
1840 "Non-nil if TOK (at which we're looking) really is a keyword."
1841 (cond
1842 ((looking-at "[[:alnum:]_]+=") nil)
1843 ((equal tok "in") (sh-smie--sh-keyword-in-p))
1844 (t (sh-smie--keyword-p))))
1846 (defun sh-smie--default-forward-token ()
1847 (forward-comment (point-max))
1848 (buffer-substring-no-properties
1849 (point)
1850 (progn (if (zerop (skip-syntax-forward "."))
1851 (while (progn (skip-syntax-forward "w_'")
1852 (looking-at "\\\\"))
1853 (forward-char 2)))
1854 (point))))
1856 (defun sh-smie--default-backward-token ()
1857 (forward-comment (- (point)))
1858 (let ((pos (point))
1859 (n (skip-syntax-backward ".")))
1860 (if (or (zerop n)
1861 (and (eq n -1)
1862 (let ((p (point)))
1863 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1865 (goto-char p)
1866 nil))))
1867 (while
1868 (progn (skip-syntax-backward "w_'")
1869 (or (not (zerop (skip-syntax-backward "\\")))
1870 (when (eq ?\\ (char-before (1- (point))))
1871 (let ((p (point)))
1872 (forward-char -1)
1873 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1875 (goto-char p)
1876 nil))))))
1877 (goto-char (- (point) (% (skip-syntax-backward "\\") 2))))
1878 (buffer-substring-no-properties (point) pos)))
1880 (defun sh-smie-sh-forward-token ()
1881 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1882 (save-excursion
1883 (skip-chars-backward " \t")
1884 (not (bolp))))
1885 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1886 ;; Right before a here-doc.
1887 (let ((forward-sexp-function nil))
1888 (forward-sexp 1)
1889 ;; Pretend the here-document is a "newline representing a
1890 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1891 ";")
1892 (unless (eobp)
1893 (let ((semi (sh-smie--newline-semi-p)))
1894 (forward-line 1)
1895 (if (or semi (eobp)) ";"
1896 (sh-smie-sh-forward-token)))))
1897 (forward-comment (point-max))
1898 (cond
1899 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1900 ((looking-at sh-smie--sh-operators-re)
1901 (goto-char (match-end 0))
1902 (let ((tok (match-string-no-properties 0)))
1903 (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1904 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1905 (forward-line 1))
1906 tok))
1908 (let* ((pos (point))
1909 (tok (sh-smie--default-forward-token)))
1910 (cond
1911 ((equal tok ")") "case-)")
1912 ((equal tok "(") "case-(")
1913 ((and tok (string-match "\\`[a-z]" tok)
1914 (assoc tok smie-grammar)
1915 (not
1916 (save-excursion
1917 (goto-char pos)
1918 (sh-smie--sh-keyword-p tok))))
1919 " word ")
1920 (t tok)))))))
1922 (defun sh-smie--looking-back-at-continuation-p ()
1923 (save-excursion
1924 (and (if (eq (char-before) ?\n) (progn (forward-char -1) t) (eolp))
1925 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1926 (line-beginning-position)))))
1928 (defun sh-smie-sh-backward-token ()
1929 (let ((bol (line-beginning-position)))
1930 (forward-comment (- (point)))
1931 (cond
1932 ((and (bolp) (not (bobp))
1933 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1934 (not (nth 3 (syntax-ppss))))
1935 ;; Right after a here-document.
1936 (let ((forward-sexp-function nil))
1937 (forward-sexp -1)
1938 ;; Pretend the here-document is a "newline representing a
1939 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1940 ";"))
1941 ((< (point) bol)
1942 (cond
1943 ((sh-smie--looking-back-at-continuation-p)
1944 (forward-char -1)
1945 (funcall smie-backward-token-function))
1946 ((sh-smie--newline-semi-p) ";")
1947 (t (funcall smie-backward-token-function))))
1948 ((looking-back sh-smie--sh-operators-back-re
1949 (line-beginning-position) 'greedy)
1950 (goto-char (match-beginning 1))
1951 (match-string-no-properties 1))
1953 (let ((tok (sh-smie--default-backward-token)))
1954 (cond
1955 ((equal tok ")") "case-)")
1956 ((equal tok "(") "case-(")
1957 ((and tok (string-match "\\`[a-z]" tok)
1958 (assoc tok smie-grammar)
1959 (not (save-excursion (sh-smie--sh-keyword-p tok))))
1960 " word ")
1961 (t tok)))))))
1963 (defcustom sh-indent-after-continuation t
1964 "If non-nil, indent relative to the continued line's beginning.
1965 Continued lines can either be indented as \"one long wrapped line\" without
1966 paying attention to the actual syntactic structure, as in:
1968 for f \\
1969 in a; do \\
1970 toto; \\
1971 done
1973 or as lines that just don't have implicit semi-colons between them, as in:
1975 for f \\
1976 in a; do \\
1977 toto; \\
1978 done
1980 With `always' you get the former behavior whereas with nil you get the latter.
1981 With t, you get the latter as long as that would indent the continuation line
1982 deeper than the initial line."
1983 :version "25.1"
1984 :type '(choice
1985 (const nil :tag "Never")
1986 (const t :tag "Only if needed to make it deeper")
1987 (const always :tag "Always"))
1988 :group 'sh-indentation)
1990 (defun sh-smie--continuation-start-indent ()
1991 "Return the initial indentation of a continued line.
1992 May return nil if the line should not be treated as continued."
1993 (save-excursion
1994 (forward-line -1)
1995 (unless (sh-smie--looking-back-at-continuation-p)
1996 (current-indentation))))
1998 (defun sh-smie--indent-continuation ()
1999 (cond
2000 ((not (and sh-indent-after-continuation
2001 (save-excursion
2002 (ignore-errors
2003 (skip-chars-backward " \t")
2004 (sh-smie--looking-back-at-continuation-p)))))
2005 nil)
2006 ((eq sh-indent-after-continuation 'always)
2007 (save-excursion
2008 (forward-line -1)
2009 (if (sh-smie--looking-back-at-continuation-p)
2010 (current-indentation)
2011 (+ (current-indentation) sh-basic-offset))))
2013 ;; Just make sure a line-continuation is indented deeper.
2014 (save-excursion
2015 (let ((indent (let ((sh-indent-after-continuation nil))
2016 (smie-indent-calculate)))
2017 (max most-positive-fixnum))
2018 (if (not (numberp indent)) indent
2019 (while (progn
2020 (forward-line -1)
2021 (let ((ci (current-indentation)))
2022 (cond
2023 ;; Previous line is less indented, we're good.
2024 ((< ci indent) nil)
2025 ((sh-smie--looking-back-at-continuation-p)
2026 (setq max (min max ci))
2027 ;; Previous line is itself a continuation.
2028 ;; If it's indented like us, we're good, otherwise
2029 ;; check the line before that one.
2030 (> ci indent))
2031 (t ;Previous line is the beginning of the continued line.
2032 (setq indent (min (+ ci sh-basic-offset) max))
2033 nil)))))
2034 indent))))))
2036 (defun sh-smie-sh-rules (kind token)
2037 (pcase (cons kind token)
2038 (`(:elem . basic) sh-basic-offset)
2039 (`(:after . "case-)") (- (sh-var-value 'sh-indent-for-case-alt)
2040 (sh-var-value 'sh-indent-for-case-label)))
2041 (`(:before . ,(or `"(" `"{" `"[" "while" "if" "for" "case"))
2042 (if (not (smie-rule-prev-p "&&" "||" "|"))
2043 (when (smie-rule-hanging-p)
2044 (smie-rule-parent))
2045 (unless (smie-rule-bolp)
2046 (while (equal "|" (nth 2 (smie-backward-sexp 'halfexp))))
2047 `(column . ,(smie-indent-virtual)))))
2048 ;; FIXME: Maybe this handling of ;; should be made into
2049 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
2050 (`(:before . ,(or `";;" `";&" `";;&"))
2051 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
2052 (cons 'column (smie-indent-keyword ";"))
2053 (smie-rule-separator kind)))
2054 (`(:after . ,(or `";;" `";&" `";;&"))
2055 (with-demoted-errors
2056 (smie-backward-sexp token)
2057 (cons 'column
2058 (if (or (smie-rule-bolp)
2059 (save-excursion
2060 (and (member (funcall smie-backward-token-function)
2061 '("in" ";;"))
2062 (smie-rule-bolp))))
2063 (current-column)
2064 (smie-indent-calculate)))))
2065 (`(:before . ,(or `"|" `"&&" `"||"))
2066 (unless (smie-rule-parent-p token)
2067 (smie-backward-sexp token)
2068 `(column . ,(+ (funcall smie-rules-function :elem 'basic)
2069 (smie-indent-virtual)))))
2071 ;; Attempt at backward compatibility with the old config variables.
2072 (`(:before . "fi") (sh-var-value 'sh-indent-for-fi))
2073 (`(:before . "done") (sh-var-value 'sh-indent-for-done))
2074 (`(:after . "else") (sh-var-value 'sh-indent-after-else))
2075 (`(:after . "if") (sh-var-value 'sh-indent-after-if))
2076 (`(:before . "then") (sh-var-value 'sh-indent-for-then))
2077 (`(:before . "do") (sh-var-value 'sh-indent-for-do))
2078 (`(:after . "do")
2079 (sh-var-value (if (smie-rule-hanging-p)
2080 'sh-indent-after-loop-construct 'sh-indent-after-do)))
2081 ;; sh-indent-after-done: aligned completely differently.
2082 (`(:after . "in") (sh-var-value 'sh-indent-for-case-label))
2083 ;; sh-indent-for-continuation: Line continuations are handled differently.
2084 (`(:after . ,(or `"(" `"{" `"["))
2085 (if (not (looking-at ".[ \t]*[^\n \t#]"))
2086 (sh-var-value 'sh-indent-after-open)
2087 (goto-char (1- (match-end 0)))
2088 `(column . ,(current-column))))
2089 ;; sh-indent-after-function: we don't handle it differently.
2092 ;; (defconst sh-smie-csh-grammar
2093 ;; (smie-prec2->grammar
2094 ;; (smie-bnf->prec2
2095 ;; '((exp) ;A constant, or a $var, or a sequence of them...
2096 ;; (elseifcmd (cmd)
2097 ;; (cmd "else" "else-if" exp "then" elseifcmd))
2098 ;; (cmd ("switch" branches "endsw")
2099 ;; ("if" exp)
2100 ;; ("if" exp "then" cmd "endif")
2101 ;; ("if" exp "then" cmd "else" cmd "endif")
2102 ;; ("if" exp "then" elseifcmd "endif")
2103 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
2104 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2105 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2106 ;; ;; "else" cmd "endif")
2107 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2108 ;; ;; "else" "if" exp "then" cmd "endif")
2109 ;; ("while" cmd "end")
2110 ;; ("foreach" cmd "end")
2111 ;; (cmd "|" cmd) (cmd "|&" cmd)
2112 ;; (cmd "&&" cmd) (cmd "||" cmd)
2113 ;; (cmd ";" cmd) (cmd "&" cmd))
2114 ;; ;; This is a lie, but (combined with the corresponding disambiguation
2115 ;; ;; rule) it makes it more clear that `case' and `default' are the key
2116 ;; ;; separators and the `:' is a secondary tokens.
2117 ;; (branches (branches "case" branches)
2118 ;; (branches "default" branches)
2119 ;; (exp ":" branches)))
2120 ;; '((assoc "else" "then" "endif"))
2121 ;; '((assoc "case" "default") (nonassoc ":"))
2122 ;; '((assoc ";;" ";&" ";;&"))
2123 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2125 ;;;; SMIE support for `rc'.
2127 (defconst sh-smie-rc-grammar
2128 (smie-prec2->grammar
2129 (smie-bnf->prec2
2130 '((exp) ;A constant, or a $var, or a sequence of them...
2131 (cmd (cmd "case" cmd)
2132 ("if" exp)
2133 ("switch" exp)
2134 ("for" exp) ("while" exp)
2135 (cmd "|" cmd) (cmd "|&" cmd)
2136 (cmd "&&" cmd) (cmd "||" cmd)
2137 (cmd ";" cmd) (cmd "&" cmd))
2138 (pattern (pattern "|" pattern))
2139 (branches (branches ";;" branches)
2140 (branches ";&" branches) (branches ";;&" branches) ;bash.
2141 (pattern "case-)" cmd)))
2142 '((assoc ";;" ";&" ";;&"))
2143 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2145 (defun sh-smie--rc-after-special-arg-p ()
2146 "Check if we're after the first arg of an if/while/for/... construct.
2147 Returns the construct's token and moves point before it, if so."
2148 (forward-comment (- (point)))
2149 (when (looking-back ")\\|\\_<not" (- (point) 3))
2150 (ignore-errors
2151 (let ((forward-sexp-function nil))
2152 (forward-sexp -1)
2153 (car (member (funcall smie-backward-token-function)
2154 '("if" "for" "switch" "while")))))))
2156 (defun sh-smie--rc-newline-semi-p ()
2157 "Return non-nil if a newline should be treated as a semi-colon.
2158 Point should be before the newline."
2159 (save-excursion
2160 (let ((tok (funcall smie-backward-token-function)))
2161 (if (or (when (equal tok "not") (forward-word-strictly 1) t)
2162 (and (zerop (length tok)) (eq (char-before) ?\))))
2163 (not (sh-smie--rc-after-special-arg-p))
2164 (sh-smie--newline-semi-p tok)))))
2166 (defun sh-smie-rc-forward-token ()
2167 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2168 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2169 (save-excursion
2170 (skip-chars-backward " \t")
2171 (not (bolp))))
2172 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2173 ;; Right before a here-doc.
2174 (let ((forward-sexp-function nil))
2175 (forward-sexp 1)
2176 ;; Pretend the here-document is a "newline representing a
2177 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2178 ";")
2179 (let ((semi (sh-smie--rc-newline-semi-p)))
2180 (forward-line 1)
2181 (if (or semi (eobp)) ";"
2182 (sh-smie-rc-forward-token))))
2183 (forward-comment (point-max))
2184 (cond
2185 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2186 ;; ((looking-at sh-smie--rc-operators-re)
2187 ;; (goto-char (match-end 0))
2188 ;; (let ((tok (match-string-no-properties 0)))
2189 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2190 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2191 ;; (forward-line 1))
2192 ;; tok))
2194 (let* ((pos (point))
2195 (tok (sh-smie--default-forward-token)))
2196 (cond
2197 ;; ((equal tok ")") "case-)")
2198 ((and tok (string-match "\\`[a-z]" tok)
2199 (assoc tok smie-grammar)
2200 (not
2201 (save-excursion
2202 (goto-char pos)
2203 (sh-smie--keyword-p))))
2204 " word ")
2205 (t tok)))))))
2207 (defun sh-smie-rc-backward-token ()
2208 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
2209 (let ((bol (line-beginning-position)))
2210 (forward-comment (- (point)))
2211 (cond
2212 ((and (bolp) (not (bobp))
2213 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2214 (not (nth 3 (syntax-ppss))))
2215 ;; Right after a here-document.
2216 (let ((forward-sexp-function nil))
2217 (forward-sexp -1)
2218 ;; Pretend the here-document is a "newline representing a
2219 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2220 ";"))
2221 ((< (point) bol) ;We skipped over a newline.
2222 (cond
2223 ;; A continued line.
2224 ((and (eolp)
2225 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2226 (line-beginning-position)))
2227 (forward-char -1)
2228 (funcall smie-backward-token-function))
2229 ((sh-smie--rc-newline-semi-p) ";")
2230 (t (funcall smie-backward-token-function))))
2231 ;; ((looking-back sh-smie--sh-operators-back-re
2232 ;; (line-beginning-position) 'greedy)
2233 ;; (goto-char (match-beginning 1))
2234 ;; (match-string-no-properties 1))
2236 (let ((tok (sh-smie--default-backward-token)))
2237 (cond
2238 ;; ((equal tok ")") "case-)")
2239 ((and tok (string-match "\\`[a-z]" tok)
2240 (assoc tok smie-grammar)
2241 (not (save-excursion (sh-smie--keyword-p))))
2242 " word ")
2243 (t tok)))))))
2245 (defun sh-smie-rc-rules (kind token)
2246 (pcase (cons kind token)
2247 (`(:elem . basic) sh-basic-offset)
2248 ;; (`(:after . "case") (or sh-basic-offset smie-indent-basic))
2249 (`(:after . ";")
2250 (if (smie-rule-parent-p "case")
2251 (smie-rule-parent (sh-var-value 'sh-indent-after-case))))
2252 (`(:before . "{")
2253 (save-excursion
2254 (when (sh-smie--rc-after-special-arg-p)
2255 `(column . ,(current-column)))))
2256 (`(:before . ,(or `"(" `"{" `"["))
2257 (if (smie-rule-hanging-p) (smie-rule-parent)))
2258 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2259 ;; treated as an arg to (exp) by default, which indents it all wrong.
2260 ;; To handle it right, we should extend smie-indent-exps so that the
2261 ;; preceding keyword can give special rules. Currently the only special
2262 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2263 ;; with "(exp)", which is rarely the right thing to do, but is better
2264 ;; than nothing.
2265 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
2266 ;; sh-indent-after-switch: handled implicitly by the default { rule.
2269 ;;; End of SMIE code.
2271 (defvar sh-regexp-for-done nil
2272 "A buffer-local regexp to match opening keyword for done.")
2274 (defvar sh-kw-alist nil
2275 "A buffer-local, since it is shell-type dependent, list of keywords.")
2277 ;; ( key-word first-on-this on-prev-line )
2278 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2279 ;; having 3 elements:
2280 ;; a keyword
2281 ;; a rule to check when the keyword appears on "this" line
2282 ;; a rule to check when the keyword appears on "the previous" line
2283 ;; The keyword is usually a string and is the first word on a line.
2284 ;; If this keyword appears on the line whose indentation is to be
2285 ;; calculated, the rule in element 2 is called. If this returns
2286 ;; non-zero, the resulting point (which may be changed by the rule)
2287 ;; is used as the default indentation.
2288 ;; If it returned false or the keyword was not found in the table,
2289 ;; then the keyword from the previous line is looked up and the rule
2290 ;; in element 3 is called. In this case, however,
2291 ;; `sh-get-indent-info' does not stop but may keep going and test
2292 ;; other keywords against rules in element 3. This is because the
2293 ;; preceding line could have, for example, an opening "if" and an
2294 ;; opening "while" keyword and we need to add the indentation offsets
2295 ;; for both.
2297 (defconst sh-kw
2298 '((sh
2299 ("if" nil sh-handle-prev-if)
2300 ("elif" sh-handle-this-else sh-handle-prev-else)
2301 ("else" sh-handle-this-else sh-handle-prev-else)
2302 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2303 ("then" sh-handle-this-then sh-handle-prev-then)
2304 ("(" nil sh-handle-prev-open)
2305 ("{" nil sh-handle-prev-open)
2306 ("[" nil sh-handle-prev-open)
2307 ("}" sh-handle-this-close nil)
2308 (")" sh-handle-this-close nil)
2309 ("]" sh-handle-this-close nil)
2310 ("case" nil sh-handle-prev-case)
2311 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2312 (case-label nil sh-handle-after-case-label) ;; ???
2313 (";;" nil sh-handle-prev-case-alt-end) ;; ???
2314 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2315 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2316 ("done" sh-handle-this-done sh-handle-prev-done)
2317 ("do" sh-handle-this-do sh-handle-prev-do))
2319 ;; Note: we don't need specific stuff for bash and zsh shells;
2320 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2321 ;; these shells use.
2323 ("{" nil sh-handle-prev-open)
2324 ("}" sh-handle-this-close nil)
2325 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
2329 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
2330 "Set this buffer's shell to SHELL (a string).
2331 When used interactively, insert the proper starting #!-line,
2332 and make the visited file executable via `executable-set-magic',
2333 perhaps querying depending on the value of `executable-query'.
2335 When this function is called noninteractively, INSERT-FLAG (the third
2336 argument) controls whether to insert a #!-line and think about making
2337 the visited file executable, and NO-QUERY-FLAG (the second argument)
2338 controls whether to query about making the visited file executable.
2340 Calls the value of `sh-set-shell-hook' if set.
2342 Shell script files can cause this function be called automatically
2343 when the file is visited by having a `sh-shell' file-local variable
2344 whose value is the shell name (don't quote it)."
2345 (interactive (list (completing-read
2346 (format "Shell (default %s): "
2347 sh-shell-file)
2348 ;; This used to use interpreter-mode-alist, but that is
2349 ;; no longer appropriate now that uses regexps.
2350 ;; Maybe there could be a separate variable that lists
2351 ;; the shells, used here and to construct i-mode-alist.
2352 ;; But the following is probably good enough:
2353 (append (mapcar (lambda (e) (symbol-name (car e)))
2354 sh-ancestor-alist)
2355 '("csh" "rc" "sh"))
2356 nil nil nil nil sh-shell-file)
2357 (eq executable-query 'function)
2359 (if (string-match "\\.exe\\'" shell)
2360 (setq shell (substring shell 0 (match-beginning 0))))
2361 (setq sh-shell (sh-canonicalize-shell shell))
2362 (if insert-flag
2363 (setq sh-shell-file
2364 (executable-set-magic shell (sh-feature sh-shell-arg)
2365 no-query-flag insert-flag)))
2366 (setq mode-line-process (format "[%s]" sh-shell))
2367 (setq-local sh-shell-variables nil)
2368 (setq-local sh-shell-variables-initialized nil)
2369 (setq-local imenu-generic-expression
2370 (sh-feature sh-imenu-generic-expression))
2371 (let ((tem (sh-feature sh-mode-syntax-table-input)))
2372 (when tem
2373 (setq-local sh-mode-syntax-table
2374 (apply 'sh-mode-syntax-table tem))
2375 (set-syntax-table sh-mode-syntax-table)))
2376 (dolist (var (sh-feature sh-variables))
2377 (sh-remember-variable var))
2378 (if (setq-local sh-indent-supported-here
2379 (sh-feature sh-indent-supported))
2380 (progn
2381 (message "Setting up indent for shell type %s" sh-shell)
2382 (let ((mksym (lambda (name)
2383 (intern (format "sh-smie-%s-%s"
2384 sh-indent-supported-here name)))))
2385 (add-function :around (local 'smie--hanging-eolp-function)
2386 (lambda (orig)
2387 (if (looking-at "[ \t]*\\\\\n")
2388 (goto-char (match-end 0))
2389 (funcall orig))))
2390 (add-hook 'smie-indent-functions #'sh-smie--indent-continuation nil t)
2391 (smie-setup (symbol-value (funcall mksym "grammar"))
2392 (funcall mksym "rules")
2393 :forward-token (funcall mksym "forward-token")
2394 :backward-token (funcall mksym "backward-token")))
2395 (setq-local parse-sexp-lookup-properties t)
2396 (unless sh-use-smie
2397 (setq-local sh-kw-alist (sh-feature sh-kw))
2398 (let ((regexp (sh-feature sh-kws-for-done)))
2399 (if regexp
2400 (setq-local sh-regexp-for-done
2401 (sh-mkword-regexpr (regexp-opt regexp t)))))
2402 (message "setting up indent stuff")
2403 ;; sh-mode has already made indent-line-function local
2404 ;; but do it in case this is called before that.
2405 (setq-local indent-line-function 'sh-indent-line))
2406 (if sh-make-vars-local
2407 (sh-make-vars-local))
2408 (message "Indentation setup for shell type %s" sh-shell))
2409 (message "No indentation for this shell type.")
2410 (setq-local indent-line-function 'sh-basic-indent-line))
2411 (when font-lock-mode
2412 (setq font-lock-set-defaults nil)
2413 (font-lock-set-defaults)
2414 (font-lock-flush))
2415 (setq sh-shell-process nil)
2416 (run-hooks 'sh-set-shell-hook))
2419 (defun sh-feature (alist &optional function)
2420 "Index ALIST by the current shell.
2421 If ALIST isn't a list where every element is a cons, it is returned as is.
2422 Else indexing follows an inheritance logic which works in two ways:
2424 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2425 the alist contains no value for the current shell.
2426 The ultimate default is always `sh'.
2428 - If the value thus looked up is a list starting with `sh-append',
2429 we call the function `sh-append' with the rest of the list as
2430 arguments, and use the value. However, the next element of the
2431 list is not used as-is; instead, we look it up recursively
2432 in ALIST to allow the function called to define the value for
2433 one shell to be derived from another shell.
2434 The value thus determined is physically replaced into the alist.
2436 If FUNCTION is non-nil, it is called with one argument,
2437 the value thus obtained, and the result is used instead."
2438 (or (if (consp alist)
2439 ;; Check for something that isn't a valid alist.
2440 (let ((l alist))
2441 (while (and l (consp (car l)))
2442 (setq l (cdr l)))
2443 (if l alist)))
2445 (let ((orig-sh-shell sh-shell))
2446 (let ((sh-shell sh-shell)
2447 elt val)
2448 (while (and sh-shell
2449 (not (setq elt (assq sh-shell alist))))
2450 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2451 ;; If the shell is not known, treat it as sh.
2452 (unless elt
2453 (setq elt (assq 'sh alist)))
2454 (setq val (cdr elt))
2455 (if (and (consp val)
2456 (memq (car val) '(sh-append sh-modify)))
2457 (setq val
2458 (apply (car val)
2459 ;; Refer to the value for a different shell,
2460 ;; as a kind of inheritance.
2461 (let ((sh-shell (car (cdr val))))
2462 (sh-feature alist))
2463 (cddr val))))
2464 (if function
2465 (setq sh-shell orig-sh-shell
2466 val (funcall function val)))
2467 val))))
2471 (defun sh-append (ancestor &rest list)
2472 "Return list composed of first argument (a list) physically appended to rest."
2473 (nconc list ancestor))
2476 (defun sh-modify (skeleton &rest list)
2477 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2478 (setq skeleton (copy-sequence skeleton))
2479 (while list
2480 (setcar (or (nthcdr (car list) skeleton)
2481 (error "Index %d out of bounds" (car list)))
2482 (car (cdr list)))
2483 (setq list (nthcdr 2 list)))
2484 skeleton)
2487 (defun sh-basic-indent-line ()
2488 "Indent a line for Sh mode (shell script mode).
2489 Indent as far as preceding non-empty line, then by steps of `sh-basic-offset'.
2490 Lines containing only comments are considered empty."
2491 (interactive)
2492 (let ((previous (save-excursion
2493 (while (and (progn (beginning-of-line)
2494 (not (bobp)))
2495 (progn
2496 (forward-line -1)
2497 (back-to-indentation)
2498 (or (eolp)
2499 (eq (following-char) ?#)))))
2500 (current-column)))
2501 current)
2502 (save-excursion
2503 (indent-to (if (or (eq this-command 'newline-and-indent)
2504 (and electric-indent-mode (eq this-command 'newline)))
2505 previous
2506 (if (< (current-column)
2507 (setq current (progn (back-to-indentation)
2508 (current-column))))
2509 (if (eolp) previous 0)
2510 (delete-region (point)
2511 (progn (beginning-of-line) (point)))
2512 (if (eolp)
2513 (max previous (* (1+ (/ current sh-basic-offset))
2514 sh-basic-offset))
2515 (* (1+ (/ current sh-basic-offset)) sh-basic-offset))))))
2516 (if (< (current-column) (current-indentation))
2517 (skip-chars-forward " \t"))))
2520 (defun sh-execute-region (start end &optional flag)
2521 "Pass optional header and region to a subshell for noninteractive execution.
2522 The working directory is that of the buffer, and only environment variables
2523 are already set which is why you can mark a header within the script.
2525 With a positive prefix ARG, instead of sending region, define header from
2526 beginning of buffer to point. With a negative prefix ARG, instead of sending
2527 region, clear header."
2528 (interactive "r\nP")
2529 (if flag
2530 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2531 (point-marker)))
2532 (if sh-header-marker
2533 (save-excursion
2534 (let (buffer-undo-list)
2535 (goto-char sh-header-marker)
2536 (append-to-buffer (current-buffer) start end)
2537 (shell-command-on-region (point-min)
2538 (setq end (+ sh-header-marker
2539 (- end start)))
2540 sh-shell-file)
2541 (delete-region sh-header-marker end)))
2542 (shell-command-on-region start end (concat sh-shell-file " -")))))
2545 (defun sh-remember-variable (var)
2546 "Make VARIABLE available for future completing reads in this buffer."
2547 (or (< (length var) sh-remember-variable-min)
2548 (getenv var)
2549 (assoc var sh-shell-variables)
2550 (push (cons var var) sh-shell-variables))
2551 var)
2555 (defun sh-quoted-p ()
2556 "Is point preceded by an odd number of backslashes?"
2557 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
2559 ;; Indentation stuff.
2560 (defun sh-must-support-indent ()
2561 "Signal an error if the shell type for this buffer is not supported.
2562 Also, the buffer must be in Shell-script mode."
2563 (unless sh-indent-supported-here
2564 (error "This buffer's shell does not support indentation through Emacs")))
2566 (defun sh-make-vars-local ()
2567 "Make the indentation variables local to this buffer.
2568 Normally they already are local. This command is provided in case
2569 variable `sh-make-vars-local' has been set to nil.
2571 To revert all these variables to the global values, use
2572 command `sh-reset-indent-vars-to-global-values'."
2573 (interactive)
2574 (mapc 'make-local-variable sh-var-list)
2575 (message "Indentation variables are now local."))
2577 (defun sh-reset-indent-vars-to-global-values ()
2578 "Reset local indentation variables to the global values.
2579 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2580 (interactive)
2581 (mapc 'kill-local-variable sh-var-list)
2582 (if sh-make-vars-local
2583 (mapcar 'make-local-variable sh-var-list)))
2586 ;; Theoretically these are only needed in shell and derived modes.
2587 ;; However, the routines which use them are only called in those modes.
2588 (defconst sh-special-keywords "then\\|do")
2590 (defun sh-help-string-for-variable (var)
2591 "Construct a string for `sh-read-variable' when changing variable VAR ."
2592 (let ((msg (documentation-property var 'variable-documentation))
2593 (msg2 ""))
2594 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
2595 (setq msg2
2596 (format "\n
2597 You can enter a number (positive to increase indentation,
2598 negative to decrease indentation, zero for no change to indentation).
2600 Or, you can enter one of the following symbols which are relative to
2601 the value of variable `sh-basic-offset'
2602 which in this buffer is currently %s.
2604 \t%s."
2605 sh-basic-offset
2606 (mapconcat (lambda (x)
2607 (nth (1- (length x)) x))
2608 sh-symbol-list "\n\t"))))
2609 (concat
2610 ;; The following shows the global not the local value!
2611 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2612 msg msg2)))
2614 (defun sh-read-variable (var)
2615 "Read a new value for indentation variable VAR."
2616 (let ((minibuffer-help-form `(sh-help-string-for-variable
2617 (quote ,var)))
2618 val)
2619 (setq val (read-from-minibuffer
2620 (format "New value for %s (press %s for help): "
2621 var (single-key-description help-char))
2622 (format "%s" (symbol-value var))
2623 nil t))
2624 val))
2628 (defun sh-in-comment-or-string (start)
2629 "Return non-nil if START is in a comment or string."
2630 (save-excursion
2631 (let ((state (syntax-ppss start)))
2632 (or (nth 3 state) (nth 4 state)))))
2634 (defun sh-goto-matching-if ()
2635 "Go to the matching if for a fi.
2636 This handles nested if..fi pairs."
2637 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2638 (if found
2639 (goto-char found))))
2642 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2643 ;; line whose indentation is being handled contain XXX;
2644 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2646 (defun sh-handle-prev-if ()
2647 (list '(+ sh-indent-after-if)))
2649 (defun sh-handle-this-else ()
2650 (if (sh-goto-matching-if)
2651 ;; (list "aligned to if")
2652 (list "aligned to if" '(+ sh-indent-for-else))
2656 (defun sh-handle-prev-else ()
2657 (if (sh-goto-matching-if)
2658 (list '(+ sh-indent-after-if))
2661 (defun sh-handle-this-fi ()
2662 (if (sh-goto-matching-if)
2663 (list "aligned to if" '(+ sh-indent-for-fi))
2667 (defun sh-handle-prev-fi ()
2668 ;; Why do we have this rule? Because we must go back to the if
2669 ;; to get its indent. We may continue back from there.
2670 ;; We return nil because we don't have anything to add to result,
2671 ;; the side affect of setting align-point is all that matters.
2672 ;; we could return a comment (a string) but I can't think of a good one...
2673 (sh-goto-matching-if)
2674 nil)
2676 (defun sh-handle-this-then ()
2677 (let ((p (sh-goto-matching-if)))
2678 (if p
2679 (list '(+ sh-indent-for-then))
2682 (defun sh-handle-prev-then ()
2683 (let ((p (sh-goto-matching-if)))
2684 (if p
2685 (list '(+ sh-indent-after-if))
2688 (defun sh-handle-prev-open ()
2689 (save-excursion
2690 (let ((x (sh-prev-stmt)))
2691 (if (and x
2692 (progn
2693 (goto-char x)
2695 (looking-at "function\\b")
2696 (looking-at "\\s-*\\S-+\\s-*()")
2698 (list '(+ sh-indent-after-function))
2699 (list '(+ sh-indent-after-open)))
2702 (defun sh-handle-this-close ()
2703 (forward-char 1) ;; move over ")"
2704 (if (sh-safe-forward-sexp -1)
2705 (list "aligned to opening paren")))
2707 (defun sh-goto-matching-case ()
2708 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2709 (if found (goto-char found))))
2711 (defun sh-handle-prev-case ()
2712 ;; This is typically called when point is on same line as a case
2713 ;; we shouldn't -- and can't find prev-case
2714 (if (looking-at ".*\\<case\\>")
2715 (list '(+ sh-indent-for-case-label))
2716 (error "We don't seem to be on a line with a case"))) ;; debug
2718 (defun sh-handle-this-esac ()
2719 (if (sh-goto-matching-case)
2720 (list "aligned to matching case")))
2722 (defun sh-handle-prev-esac ()
2723 (if (sh-goto-matching-case)
2724 (list "matching case")))
2726 (defun sh-handle-after-case-label ()
2727 (if (sh-goto-matching-case)
2728 (list '(+ sh-indent-for-case-alt))))
2730 (defun sh-handle-prev-case-alt-end ()
2731 (if (sh-goto-matching-case)
2732 (list '(+ sh-indent-for-case-label))))
2734 (defun sh-safe-forward-sexp (&optional arg)
2735 "Try and do a `forward-sexp', but do not error.
2736 Return new point if successful, nil if an error occurred."
2737 (condition-case nil
2738 (progn
2739 (forward-sexp (or arg 1))
2740 (point)) ;; return point if successful
2741 (error
2742 (sh-debug "oops!(1) %d" (point))
2743 nil))) ;; return nil if fail
2745 (defun sh-goto-match-for-done ()
2746 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2747 (if found
2748 (goto-char found))))
2750 (defun sh-handle-this-done ()
2751 (if (sh-goto-match-for-done)
2752 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2754 (defun sh-handle-prev-done ()
2755 (if (sh-goto-match-for-done)
2756 (list "previous done")))
2758 (defun sh-handle-this-do ()
2759 (if (sh-goto-match-for-done)
2760 (list '(+ sh-indent-for-do))))
2762 (defun sh-handle-prev-do ()
2763 (cond
2764 ((save-restriction
2765 (narrow-to-region (point) (line-beginning-position))
2766 (sh-goto-match-for-done))
2767 (sh-debug "match for done found on THIS line")
2768 (list '(+ sh-indent-after-loop-construct)))
2769 ((sh-goto-match-for-done)
2770 (sh-debug "match for done found on PREV line")
2771 (list '(+ sh-indent-after-do)))
2773 (message "match for done NOT found")
2774 nil)))
2776 ;; for rc:
2777 (defun sh-find-prev-switch ()
2778 "Find the line for the switch keyword matching this line's case keyword."
2779 (re-search-backward "\\<switch\\>" nil t))
2781 (defun sh-handle-this-rc-case ()
2782 (if (sh-find-prev-switch)
2783 (list '(+ sh-indent-after-switch))
2784 ;; (list '(+ sh-indent-for-case-label))
2785 nil))
2787 (defun sh-handle-prev-rc-case ()
2788 (list '(+ sh-indent-after-case)))
2790 (defun sh-check-rule (n thing)
2791 (let ((rule (nth n (assoc thing sh-kw-alist)))
2792 (val nil))
2793 (if rule
2794 (progn
2795 (setq val (funcall rule))
2796 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2797 n thing (point) rule val)))
2798 val))
2801 (defun sh-get-indent-info ()
2802 "Return indent-info for this line.
2803 This is a list. nil means the line is to be left as is.
2804 Otherwise it contains one or more of the following sublists:
2805 \(t NUMBER) NUMBER is the base location in the buffer that indentation is
2806 relative to. If present, this is always the first of the
2807 sublists. The indentation of the line in question is
2808 derived from the indentation of this point, possibly
2809 modified by subsequent sublists.
2810 \(+ VAR)
2811 \(- VAR) Get the value of variable VAR and add to or subtract from
2812 the indentation calculated so far.
2813 \(= VAR) Get the value of variable VAR and *replace* the
2814 indentation with its value. This only occurs for
2815 special variables such as `sh-indent-comment'.
2816 STRING This is ignored for the purposes of calculating
2817 indentation, it is printed in certain cases to help show
2818 what the indentation is based on."
2819 ;; See comments before `sh-kw'.
2820 (save-excursion
2821 (let ((have-result nil)
2822 this-kw
2824 (result nil)
2825 (align-point nil)
2826 prev-line-end x)
2827 (beginning-of-line)
2828 ;; Note: setting result to t means we are done and will return nil.
2829 ;;(This function never returns just t.)
2830 (cond
2831 ((or (nth 3 (syntax-ppss (point)))
2832 (eq (get-text-property (point) 'face) 'sh-heredoc))
2833 ;; String continuation -- don't indent
2834 (setq result t)
2835 (setq have-result t))
2836 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2837 (if (bobp)
2838 (setq result t) ;; return nil if 1st line!
2839 (setq result (list '(= sh-indent-comment)))
2840 ;; we still need to get previous line in case
2841 ;; sh-indent-comment is t (indent as normal)
2842 (setq align-point (sh-prev-line nil))
2843 (setq have-result nil)
2845 ) ;; cond
2847 (unless have-result
2848 ;; Continuation lines are handled specially
2849 (if (sh-this-is-a-continuation)
2850 (progn
2851 (setq result
2852 (if (save-excursion
2853 (beginning-of-line)
2854 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2855 ;; By convention, if the continuation \ is not
2856 ;; preceded by a SPC or a TAB it means that the line
2857 ;; is cut at a place where spaces cannot be freely
2858 ;; added/removed. I.e. do not indent the line.
2859 (list '(= nil))
2860 ;; We assume the line being continued is already
2861 ;; properly indented...
2862 ;; (setq prev-line-end (sh-prev-line))
2863 (setq align-point (sh-prev-line nil))
2864 (list '(+ sh-indent-for-continuation))))
2865 (setq have-result t))
2866 (beginning-of-line)
2867 (skip-chars-forward " \t")
2868 (setq this-kw (sh-get-kw)))
2870 ;; Handle "this" keyword: first word on the line we're
2871 ;; calculating indentation info for.
2872 (if this-kw
2873 (if (setq val (sh-check-rule 1 this-kw))
2874 (progn
2875 (setq align-point (point))
2876 (sh-debug
2877 "this - setting align-point to %d" align-point)
2878 (setq result (append result val))
2879 (setq have-result t)
2880 ;; set prev-line to continue processing remainder
2881 ;; of this line as a previous line
2882 (setq prev-line-end (point))
2883 ))))
2885 (unless have-result
2886 (setq prev-line-end (sh-prev-line 'end)))
2888 (if prev-line-end
2889 (save-excursion
2890 ;; We start off at beginning of this line.
2891 ;; Scan previous statements while this is <=
2892 ;; start of previous line.
2893 (goto-char prev-line-end)
2894 (setq x t)
2895 (while (and x (setq x (sh-prev-thing)))
2896 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2897 (cond
2898 ((and (equal x ")")
2899 (equal (get-text-property (1- (point)) 'syntax-table)
2900 sh-st-punc))
2901 (sh-debug "Case label) here")
2902 (setq x 'case-label)
2903 (if (setq val (sh-check-rule 2 x))
2904 (progn
2905 (setq result (append result val))
2906 (setq align-point (point))))
2907 (or (bobp)
2908 (forward-char -1))
2909 ;; FIXME: This charset looks too much like a regexp. --Stef
2910 (skip-chars-forward "[a-z0-9]*?")
2912 ((string-match "[])}]" x)
2913 (setq x (sh-safe-forward-sexp -1))
2914 (if x
2915 (progn
2916 (setq align-point (point))
2917 (setq result (append result
2918 (list "aligned to opening paren")))
2920 ((string-match "[[({]" x)
2921 (sh-debug "Checking special thing: %s" x)
2922 (if (setq val (sh-check-rule 2 x))
2923 (setq result (append result val)))
2924 (forward-char -1)
2925 (setq align-point (point)))
2926 ((string-match "[\"'`]" x)
2927 (sh-debug "Skipping back for %s" x)
2928 ;; this was oops-2
2929 (setq x (sh-safe-forward-sexp -1)))
2930 ((stringp x)
2931 (sh-debug "Checking string %s at %s" x (point))
2932 (if (setq val (sh-check-rule 2 x))
2933 ;; (or (eq t (car val))
2934 ;; (eq t (car (car val))))
2935 (setq result (append result val)))
2936 ;; not sure about this test Wed Jan 27 23:48:35 1999
2937 (setq align-point (point))
2938 (unless (bolp)
2939 (forward-char -1)))
2941 (error "Don't know what to do with %s" x))
2943 ) ;; while
2944 (sh-debug "result is %s" result)
2946 (sh-debug "No prev line!")
2947 (sh-debug "result: %s align-point: %s" result align-point)
2950 (if align-point
2951 ;; was: (setq result (append result (list (list t align-point))))
2952 (setq result (append (list (list t align-point)) result))
2954 (sh-debug "result is now: %s" result)
2956 (or result
2957 (setq result (list (if prev-line-end
2958 (list t prev-line-end)
2959 (list '= 'sh-first-lines-indent)))))
2961 (if (eq result t)
2962 (setq result nil))
2963 (sh-debug "result is: %s" result)
2964 result
2965 ) ;; let
2969 (defun sh-get-indent-var-for-line (&optional info)
2970 "Return the variable controlling indentation for this line.
2971 If there is not [just] one such variable, return a string
2972 indicating the problem.
2973 If INFO is supplied it is used, else it is calculated."
2974 (let ((var nil)
2975 (result nil)
2976 (reason nil)
2977 sym elt)
2978 (or info
2979 (setq info (sh-get-indent-info)))
2980 (if (null info)
2981 (setq result "this line to be left as is")
2982 (while (and info (null result))
2983 (setq elt (car info))
2984 (cond
2985 ((stringp elt)
2986 (setq reason elt)
2988 ((not (listp elt))
2989 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2990 ;; so it is a list
2991 ((eq t (car elt))
2992 ) ;; nothing
2993 ((symbolp (setq sym (nth 1 elt)))
2994 ;; A bit of a kludge - when we see the sh-indent-comment
2995 ;; ignore other variables. Otherwise it is tricky to
2996 ;; "learn" the comment indentation.
2997 (if (eq var 'sh-indent-comment)
2998 (setq result var)
2999 (if var
3000 (setq result
3001 "this line is controlled by more than 1 variable.")
3002 (setq var sym))))
3004 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
3005 (setq info (cdr info))
3007 (or result
3008 (setq result var))
3009 (or result
3010 (setq result reason))
3011 (if (null result)
3012 ;; e.g. just had (t POS)
3013 (setq result "line has default indentation"))
3014 result))
3018 ;; Finding the previous line isn't trivial.
3019 ;; We must *always* go back one more and see if that is a continuation
3020 ;; line -- it is the PREVIOUS line which is continued, not the one
3021 ;; we are going to!
3022 ;; Also, we want to treat a whole "here document" as one big line,
3023 ;; because we may want to align to the beginning of it.
3025 ;; What we do:
3026 ;; - go back to previous non-empty line
3027 ;; - if this is in a here-document, go to the beginning of it
3028 ;; - while previous line is continued, go back one line
3029 (defun sh-prev-line (&optional end)
3030 "Back to end of previous non-comment non-empty line.
3031 Go to beginning of logical line unless END is non-nil, in which case
3032 we go to the end of the previous line and do not check for continuations."
3033 (save-excursion
3034 (beginning-of-line)
3035 (forward-comment (- (point-max)))
3036 (unless end (beginning-of-line))
3037 (when (and (not (bobp))
3038 (eq (get-text-property (1- (point)) 'face) 'sh-heredoc))
3039 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
3040 (when p1
3041 (goto-char p1)
3042 (if end
3043 (end-of-line)
3044 (beginning-of-line)))))
3045 (unless end
3046 ;; we must check previous lines to see if they are continuation lines
3047 ;; if so, we must return position of first of them
3048 (while (and (sh-this-is-a-continuation)
3049 (>= 0 (forward-line -1))))
3050 (beginning-of-line)
3051 (skip-chars-forward " \t"))
3052 (point)))
3055 (defun sh-prev-stmt ()
3056 "Return the address of the previous stmt or nil."
3057 ;; This is used when we are trying to find a matching keyword.
3058 ;; Searching backward for the keyword would certainly be quicker, but
3059 ;; it is hard to remove "false matches" -- such as if the keyword
3060 ;; appears in a string or quote. This way is slower, but (I think) safer.
3061 (interactive)
3062 (save-excursion
3063 (let ((going t)
3064 (start (point))
3065 (found nil)
3066 (prev nil))
3067 (skip-chars-backward " \t;|&({[")
3068 (while (and (not found)
3069 (not (bobp))
3070 going)
3071 ;; Do a backward-sexp if possible, else backup bit by bit...
3072 (if (sh-safe-forward-sexp -1)
3073 (progn
3074 (if (looking-at sh-special-keywords)
3075 (progn
3076 (setq found prev))
3077 (setq prev (point))
3079 ;; backward-sexp failed
3080 (if (zerop (skip-chars-backward " \t()[]{};`'"))
3081 (forward-char -1))
3082 (if (bolp)
3083 (let ((back (sh-prev-line nil)))
3084 (if back
3085 (goto-char back)
3086 (setq going nil)))))
3087 (unless found
3088 (skip-chars-backward " \t")
3089 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
3090 (eq (char-before) ?\;)
3091 (looking-at "\\s-*[|&]"))
3092 (setq found (point)))))
3093 (if found
3094 (goto-char found))
3095 (if found
3096 (progn
3097 (skip-chars-forward " \t|&({[")
3098 (setq found (point))))
3099 (if (>= (point) start)
3100 (progn
3101 (debug "We didn't move!")
3102 (setq found nil))
3103 (or found
3104 (sh-debug "Did not find prev stmt.")))
3105 found)))
3108 (defun sh-get-word ()
3109 "Get a shell word skipping whitespace from point."
3110 (interactive)
3111 (skip-chars-forward "\t ")
3112 (let ((start (point)))
3113 (while
3114 (if (looking-at "[\"'`]")
3115 (sh-safe-forward-sexp)
3116 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
3117 (> (skip-chars-forward "-_$[:alnum:]") 0)
3119 (buffer-substring start (point))
3122 (defun sh-prev-thing ()
3123 "Return the previous thing this logical line."
3124 ;; This is called when `sh-get-indent-info' is working backwards on
3125 ;; the previous line(s) finding what keywords may be relevant for
3126 ;; indenting. It moves over sexps if possible, and will stop
3127 ;; on a ; and at the beginning of a line if it is not a continuation
3128 ;; line.
3130 ;; Added a kludge for ";;"
3131 ;; Possible return values:
3132 ;; nil - nothing
3133 ;; a string - possibly a keyword
3135 (if (bolp)
3137 (let ((start (point))
3138 (min-point (if (sh-this-is-a-continuation)
3139 (sh-prev-line nil)
3140 (line-beginning-position))))
3141 (skip-chars-backward " \t;" min-point)
3142 (if (looking-at "\\s-*;[;&]")
3143 ;; (message "Found ;; !")
3144 ";;"
3145 (skip-chars-backward "^)}];\"'`({[" min-point)
3146 (let ((c (if (> (point) min-point) (char-before))))
3147 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
3148 (point) c start min-point)
3149 (if (not (memq c '(?\n nil ?\;)))
3150 ;; c -- return a string
3151 (char-to-string c)
3152 ;; Return the leading keyword of the "command" we supposedly
3153 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
3154 ;; `then' that precedes the actual command), so check whether
3155 ;; we're looking at such a keyword and if so, move back forward.
3156 (let ((boundary (point))
3157 kwd next)
3158 (while
3159 (progn
3160 ;; Skip forward over white space newline and \ at eol.
3161 (skip-chars-forward " \t\n\\\\" start)
3162 (if (>= (point) start)
3163 (progn
3164 (sh-debug "point: %d >= start: %d" (point) start)
3165 nil)
3166 (if next (setq boundary next))
3167 (sh-debug "Now at %d start=%d" (point) start)
3168 (setq kwd (sh-get-word))
3169 (if (member kwd (sh-feature sh-leading-keywords))
3170 (progn
3171 (setq next (point))
3173 nil))))
3174 (goto-char boundary)
3175 kwd)))))))
3178 (defun sh-this-is-a-continuation ()
3179 "Return non-nil if current line is a continuation of previous line."
3180 (save-excursion
3181 (and (zerop (forward-line -1))
3182 (looking-at ".*\\\\$")
3183 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
3184 nil nil nil t))))))
3186 (defun sh-get-kw (&optional where and-move)
3187 "Return first word of line from WHERE.
3188 If AND-MOVE is non-nil then move to end of word."
3189 (let ((start (point)))
3190 (if where
3191 (goto-char where))
3192 (prog1
3193 (buffer-substring (point)
3194 (progn (skip-chars-forward "^ \t\n;&|")(point)))
3195 (unless and-move
3196 (goto-char start)))))
3198 (defun sh-find-prev-matching (open close &optional depth)
3199 "Find a matching token for a set of opening and closing keywords.
3200 This takes into account that there may be nested open..close pairings.
3201 OPEN and CLOSE are regexps denoting the tokens to be matched.
3202 Optional parameter DEPTH (usually 1) says how many to look for."
3203 (let ((parse-sexp-ignore-comments t)
3204 (forward-sexp-function nil)
3205 prev)
3206 (setq depth (or depth 1))
3207 (save-excursion
3208 (condition-case nil
3209 (while (and
3210 (/= 0 depth)
3211 (not (bobp))
3212 (setq prev (sh-prev-stmt)))
3213 (goto-char prev)
3214 (save-excursion
3215 (if (looking-at "\\\\\n")
3216 (progn
3217 (forward-char 2)
3218 (skip-chars-forward " \t")))
3219 (cond
3220 ((looking-at open)
3221 (setq depth (1- depth))
3222 (sh-debug "found open at %d - depth = %d" (point) depth))
3223 ((looking-at close)
3224 (setq depth (1+ depth))
3225 (sh-debug "found close - depth = %d" depth))
3227 ))))
3228 (error nil))
3229 (if (eq depth 0)
3230 prev ;; (point)
3231 nil)
3235 (defun sh-var-value (var &optional ignore-error)
3236 "Return the value of variable VAR, interpreting symbols.
3237 It can also return t or nil.
3238 If an invalid value is found, throw an error unless Optional argument
3239 IGNORE-ERROR is non-nil."
3240 (let ((val (symbol-value var)))
3241 (cond
3242 ((numberp val)
3243 val)
3244 ((eq val t)
3245 val)
3246 ((null val)
3247 val)
3248 ((eq val '+)
3249 sh-basic-offset)
3250 ((eq val '-)
3251 (- sh-basic-offset))
3252 ((eq val '++)
3253 (* 2 sh-basic-offset))
3254 ((eq val '--)
3255 (* 2 (- sh-basic-offset)))
3256 ((eq val '*)
3257 (/ sh-basic-offset 2))
3258 ((eq val '/)
3259 (/ (- sh-basic-offset) 2))
3261 (funcall (if ignore-error #'message #'error)
3262 "Don't know how to handle %s's value of %s" var val)
3263 0))))
3265 (defun sh-set-var-value (var value &optional no-symbol)
3266 "Set variable VAR to VALUE.
3267 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3268 can be represented by a symbol then do so."
3269 (cond
3270 (no-symbol
3271 (set var value))
3272 ((= value sh-basic-offset)
3273 (set var '+))
3274 ((= value (- sh-basic-offset))
3275 (set var '-))
3276 ((eq value (* 2 sh-basic-offset))
3277 (set var '++))
3278 ((eq value (* 2 (- sh-basic-offset)))
3279 (set var '--))
3280 ((eq value (/ sh-basic-offset 2))
3281 (set var '*))
3282 ((eq value (/ (- sh-basic-offset) 2))
3283 (set var '/))
3285 (set var value)))
3289 (defun sh-calculate-indent (&optional info)
3290 "Return the indentation for the current line.
3291 If INFO is supplied it is used, else it is calculated from current line."
3292 (let ((ofs 0)
3293 (base-value 0)
3294 elt a b val)
3295 (or info
3296 (setq info (sh-get-indent-info)))
3297 (when info
3298 (while info
3299 (sh-debug "info: %s ofs=%s" info ofs)
3300 (setq elt (car info))
3301 (cond
3302 ((stringp elt)) ;; do nothing?
3303 ((listp elt)
3304 (setq a (car (car info)))
3305 (setq b (nth 1 (car info)))
3306 (cond
3307 ((eq a t)
3308 (save-excursion
3309 (goto-char b)
3310 (setq val (current-indentation)))
3311 (setq base-value val))
3312 ((symbolp b)
3313 (setq val (sh-var-value b))
3314 (cond
3315 ((eq a '=)
3316 (cond
3317 ((null val)
3318 ;; no indentation
3319 ;; set info to nil so we stop immediately
3320 (setq base-value nil ofs nil info nil))
3321 ((eq val t) (setq ofs 0)) ;; indent as normal line
3323 ;; The following assume the (t POS) come first!
3324 (setq ofs val base-value 0)
3325 (setq info nil)))) ;; ? stop now
3326 ((eq a '+) (setq ofs (+ ofs val)))
3327 ((eq a '-) (setq ofs (- ofs val)))
3329 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3331 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
3333 (error "sh-calculate-indent invalid elt %s" elt)))
3334 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3335 a b val base-value ofs)
3336 (setq info (cdr info)))
3337 ;; return value:
3338 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
3340 (cond
3341 ((or (null base-value)(null ofs))
3342 nil)
3343 ((and (numberp base-value)(numberp ofs))
3344 (sh-debug "base (%d) + ofs (%d) = %d"
3345 base-value ofs (+ base-value ofs))
3346 (+ base-value ofs)) ;; return value
3348 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3349 base-value ofs)
3350 nil)))))
3353 (defun sh-indent-line ()
3354 "Indent the current line."
3355 (interactive)
3356 (let ((indent (sh-calculate-indent))
3357 (pos (- (point-max) (point))))
3358 (when indent
3359 (beginning-of-line)
3360 (skip-chars-forward " \t")
3361 (indent-line-to indent)
3362 ;; If initial point was within line's indentation,
3363 ;; position after the indentation. Else stay at same point in text.
3364 (if (> (- (point-max) pos) (point))
3365 (goto-char (- (point-max) pos))))))
3368 (defun sh-blink (blinkpos &optional msg)
3369 "Move cursor momentarily to BLINKPOS and display MSG."
3370 ;; We can get here without it being a number on first line
3371 (if (numberp blinkpos)
3372 (save-excursion
3373 (goto-char blinkpos)
3374 (if msg (message "%s" msg) (message nil))
3375 (sit-for blink-matching-delay))
3376 (if msg (message "%s" msg) (message nil))))
3378 (defun sh-show-indent (arg)
3379 "Show how the current line would be indented.
3380 This tells you which variable, if any, controls the indentation of
3381 this line.
3382 If optional arg ARG is non-null (called interactively with a prefix),
3383 a pop up window describes this variable.
3384 If variable `sh-blink' is non-nil then momentarily go to the line
3385 we are indenting relative to, if applicable."
3386 (interactive "P")
3387 (sh-must-support-indent)
3388 (if sh-use-smie
3389 (smie-config-show-indent)
3390 (let* ((info (sh-get-indent-info))
3391 (var (sh-get-indent-var-for-line info))
3392 (curr-indent (current-indentation))
3393 val msg)
3394 (if (stringp var)
3395 (message "%s" (setq msg var))
3396 (setq val (sh-calculate-indent info))
3398 (if (eq curr-indent val)
3399 (setq msg (format "%s is %s" var (symbol-value var)))
3400 (setq msg
3401 (if val
3402 (format "%s (%s) would change indent from %d to: %d"
3403 var (symbol-value var) curr-indent val)
3404 (format "%s (%s) would leave line as is"
3405 var (symbol-value var)))
3407 (if (and arg var)
3408 (describe-variable var)))
3409 (if sh-blink
3410 (let ((info (sh-get-indent-info)))
3411 (if (and info (listp (car info))
3412 (eq (car (car info)) t))
3413 (sh-blink (nth 1 (car info)) msg)
3414 (message "%s" msg)))
3415 (message "%s" msg))
3418 (defun sh-set-indent ()
3419 "Set the indentation for the current line.
3420 If the current line is controlled by an indentation variable, prompt
3421 for a new value for it."
3422 (interactive)
3423 (sh-must-support-indent)
3424 (if sh-use-smie
3425 (smie-config-set-indent)
3426 (let* ((info (sh-get-indent-info))
3427 (var (sh-get-indent-var-for-line info))
3428 val old-val indent-val)
3429 (if (stringp var)
3430 (message "Cannot set indent - %s" var)
3431 (setq old-val (symbol-value var))
3432 (setq val (sh-read-variable var))
3433 (condition-case nil
3434 (progn
3435 (set var val)
3436 (setq indent-val (sh-calculate-indent info))
3437 (if indent-val
3438 (message "Variable: %s Value: %s would indent to: %d"
3439 var (symbol-value var) indent-val)
3440 (message "Variable: %s Value: %s would leave line as is."
3441 var (symbol-value var)))
3442 ;; I'm not sure about this, indenting it now?
3443 ;; No. Because it would give the impression that an undo would
3444 ;; restore thing, but the value has been altered.
3445 ;; (sh-indent-line)
3447 (error
3448 (set var old-val)
3449 (message "Bad value for %s, restoring to previous value %s"
3450 var old-val)
3451 (sit-for 1)
3452 nil))
3453 ))))
3456 (defun sh-learn-line-indent (arg)
3457 "Learn how to indent a line as it currently is indented.
3459 If there is an indentation variable which controls this line's indentation,
3460 then set it to a value which would indent the line the way it
3461 presently is.
3463 If the value can be represented by one of the symbols then do so
3464 unless optional argument ARG (the prefix when interactive) is non-nil."
3465 (interactive "*P")
3466 (sh-must-support-indent)
3467 (if sh-use-smie
3468 (smie-config-set-indent)
3469 ;; I'm not sure if we show allow learning on an empty line.
3470 ;; Though it might occasionally be useful I think it usually
3471 ;; would just be confusing.
3472 (if (save-excursion
3473 (beginning-of-line)
3474 (looking-at "\\s-*$"))
3475 (message "sh-learn-line-indent ignores empty lines.")
3476 (let* ((info (sh-get-indent-info))
3477 (var (sh-get-indent-var-for-line info))
3478 ival sval diff new-val
3479 (no-symbol arg)
3480 (curr-indent (current-indentation)))
3481 (cond
3482 ((stringp var)
3483 (message "Cannot learn line - %s" var))
3484 ((eq var 'sh-indent-comment)
3485 ;; This is arbitrary...
3486 ;; - if curr-indent is 0, set to curr-indent
3487 ;; - else if it has the indentation of a "normal" line,
3488 ;; then set to t
3489 ;; - else set to curr-indent.
3490 (setq sh-indent-comment
3491 (if (= curr-indent 0)
3493 (let* ((sh-indent-comment t)
3494 (val2 (sh-calculate-indent info)))
3495 (if (= val2 curr-indent)
3497 curr-indent))))
3498 (message "%s set to %s" var (symbol-value var))
3500 ((numberp (setq sval (sh-var-value var)))
3501 (setq ival (sh-calculate-indent info))
3502 (setq diff (- curr-indent ival))
3504 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3505 curr-indent ival diff var sval)
3506 (setq new-val (+ sval diff))
3507 ;; I commented out this because someone might want to replace
3508 ;; a value of `+' with the current value of sh-basic-offset
3509 ;; or vice-versa.
3510 ;;(if (= 0 diff)
3511 ;; (message "No change needed!")
3512 (sh-set-var-value var new-val no-symbol)
3513 (message "%s set to %s" var (symbol-value var))
3516 (debug)
3517 (message "Cannot change %s" var)))))))
3521 (defun sh-mark-init (buffer)
3522 "Initialize a BUFFER to be used by `sh-mark-line'."
3523 (with-current-buffer (get-buffer-create buffer)
3524 (erase-buffer)
3525 (occur-mode)))
3528 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
3529 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3530 Buffer BUFFER is in `occur-mode'.
3531 If ADD-LINENUM is non-nil the message is preceded by the line number.
3532 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3533 so that `occur-next' and `occur-prev' will work."
3534 (let ((m1 (make-marker))
3535 start
3536 (line ""))
3537 (when point
3538 (set-marker m1 point (current-buffer))
3539 (if add-linenum
3540 (setq line (format "%d: " (1+ (count-lines 1 point))))))
3541 (save-excursion
3542 (if (get-buffer buffer)
3543 (set-buffer (get-buffer buffer))
3544 (set-buffer (get-buffer-create buffer))
3545 (occur-mode)
3547 (goto-char (point-max))
3548 (setq start (point))
3549 (let ((inhibit-read-only t))
3550 (insert line)
3551 (if occur-point
3552 (setq occur-point (point)))
3553 (insert message)
3554 (if point
3555 (add-text-properties
3556 start (point)
3557 '(mouse-face highlight
3558 help-echo "mouse-2: go to the line where I learned this")))
3559 (insert "\n")
3560 (when point
3561 (put-text-property start (point) 'occur-target m1)
3562 (if occur-point
3563 (put-text-property start occur-point
3564 'occur-match t))
3565 )))))
3567 ;; Is this really worth having?
3568 (defvar sh-learned-buffer-hook nil
3569 "An abnormal hook, called with an alist of learned variables.")
3570 ;; Example of how to use sh-learned-buffer-hook
3572 ;; (defun what-i-learned (list)
3573 ;; (let ((p list))
3574 ;; (with-current-buffer "*scratch*"
3575 ;; (goto-char (point-max))
3576 ;; (insert "(setq\n")
3577 ;; (while p
3578 ;; (insert (format " %s %s \n"
3579 ;; (nth 0 (car p)) (nth 1 (car p))))
3580 ;; (setq p (cdr p)))
3581 ;; (insert ")\n")
3582 ;; )))
3584 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3587 ;; Originally this was sh-learn-region-indent (beg end)
3588 ;; However, in practice this was awkward so I changed it to
3589 ;; use the whole buffer. Use narrowing if need be.
3590 (defun sh-learn-buffer-indent (&optional arg)
3591 "Learn how to indent the buffer the way it currently is.
3593 If `sh-use-smie' is non-nil, call `smie-config-guess'.
3594 Otherwise, run the sh-script specific indent learning command, as
3595 described below.
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.
3615 This command can often take a long time to run."
3616 (interactive "P")
3617 (sh-must-support-indent)
3618 (if sh-use-smie
3619 (smie-config-guess)
3620 (save-excursion
3621 (goto-char (point-min))
3622 (let ((learned-var-list nil)
3623 (out-buffer "*indent*")
3624 (num-diffs 0)
3625 previous-set-info
3626 (max 17)
3629 (comment-col nil) ;; number if all same, t if seen diff values
3630 (comments-always-default t) ;; nil if we see one not default
3631 initial-msg
3632 (specified-basic-offset (and arg (numberp arg)
3633 (> arg 0)))
3634 (linenum 0)
3635 suggested)
3636 (setq vec (make-vector max 0))
3637 (sh-mark-init out-buffer)
3639 (if specified-basic-offset
3640 (progn
3641 (setq sh-basic-offset arg)
3642 (setq initial-msg
3643 (format "Using specified sh-basic-offset of %d"
3644 sh-basic-offset)))
3645 (setq initial-msg
3646 (format "Initial value of sh-basic-offset: %s"
3647 sh-basic-offset)))
3649 (while (< (point) (point-max))
3650 (setq linenum (1+ linenum))
3651 ;; (if (zerop (% linenum 10))
3652 (message "line %d" linenum)
3653 ;; )
3654 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3655 (let* ((sh-indent-comment t) ;; info must return default indent
3656 (info (sh-get-indent-info))
3657 (var (sh-get-indent-var-for-line info))
3658 sval ival diff new-val
3659 (curr-indent (current-indentation)))
3660 (cond
3661 ((null var)
3662 nil)
3663 ((stringp var)
3664 nil)
3665 ((numberp (setq sval (sh-var-value var 'no-error)))
3666 ;; the numberp excludes comments since sval will be t.
3667 (setq ival (sh-calculate-indent))
3668 (setq diff (- curr-indent ival))
3669 (setq new-val (+ sval diff))
3670 (sh-set-var-value var new-val 'no-symbol)
3671 (unless (looking-at "\\s-*#") ;; don't learn from comments
3672 (if (setq previous-set-info (assoc var learned-var-list))
3673 (progn
3674 ;; it was already there, is it same value ?
3675 (unless (eq (symbol-value var)
3676 (nth 1 previous-set-info))
3677 (sh-mark-line
3678 (format "Variable %s was set to %s"
3679 var (symbol-value var))
3680 (point) out-buffer t t)
3681 (sh-mark-line
3682 (format " but was previously set to %s"
3683 (nth 1 previous-set-info))
3684 (nth 2 previous-set-info) out-buffer t)
3685 (setq num-diffs (1+ num-diffs))
3686 ;; (delete previous-set-info learned-var-list)
3687 (setcdr previous-set-info
3688 (list (symbol-value var) (point)))
3691 (setq learned-var-list
3692 (append (list (list var (symbol-value var)
3693 (point)))
3694 learned-var-list)))
3695 (if (numberp new-val)
3696 (progn
3697 (sh-debug
3698 "This line's indent value: %d" new-val)
3699 (if (< new-val 0)
3700 (setq new-val (- new-val)))
3701 (if (< new-val max)
3702 (aset vec new-val (1+ (aref vec new-val))))))
3704 ((eq var 'sh-indent-comment)
3705 (unless (= curr-indent (sh-calculate-indent info))
3706 ;; this is not the default indentation
3707 (setq comments-always-default nil)
3708 (if comment-col ;; then we have see one before
3709 (or (eq comment-col curr-indent)
3710 (setq comment-col t)) ;; seen a different one
3711 (setq comment-col curr-indent))
3714 (sh-debug "Cannot learn this line!!!")
3716 (sh-debug
3717 "at %s learned-var-list is %s" (point) learned-var-list)
3719 (forward-line 1)
3720 ) ;; while
3721 (if sh-debug
3722 (progn
3723 (setq msg (format
3724 "comment-col = %s comments-always-default = %s"
3725 comment-col comments-always-default))
3726 ;; (message msg)
3727 (sh-mark-line msg nil out-buffer)))
3728 (cond
3729 ((eq comment-col 0)
3730 (setq msg "\nComments are all in 1st column.\n"))
3731 (comments-always-default
3732 (setq msg "\nComments follow default indentation.\n")
3733 (setq comment-col t))
3734 ((numberp comment-col)
3735 (setq msg (format "\nComments are in col %d." comment-col)))
3737 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3738 (setq comment-col nil)
3740 (sh-debug msg)
3741 (sh-mark-line msg nil out-buffer)
3743 (sh-mark-line initial-msg nil out-buffer t t)
3745 (setq suggested (sh-guess-basic-offset vec))
3747 (if (and suggested (not specified-basic-offset))
3748 (let ((new-value
3749 (cond
3750 ;; t => set it if we have a single value as a number
3751 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3752 suggested)
3753 ;; other non-nil => set it if only one value was found
3754 (sh-learn-basic-offset
3755 (if (numberp suggested)
3756 suggested
3757 (if (= (length suggested) 1)
3758 (car suggested))))
3760 nil))))
3761 (if new-value
3762 (progn
3763 (setq learned-var-list
3764 (append (list (list 'sh-basic-offset
3765 (setq sh-basic-offset new-value)
3766 (point-max)))
3767 learned-var-list))
3768 ;; Not sure if we need to put this line in, since
3769 ;; it will appear in the "Learned variable settings".
3770 (sh-mark-line
3771 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3772 nil out-buffer))
3773 (sh-mark-line
3774 (if (listp suggested)
3775 (format "Possible value(s) for sh-basic-offset: %s"
3776 (mapconcat 'int-to-string suggested " "))
3777 (format "Suggested sh-basic-offset: %d" suggested))
3778 nil out-buffer))))
3781 (setq learned-var-list
3782 (append (list (list 'sh-indent-comment comment-col (point-max)))
3783 learned-var-list))
3784 (setq sh-indent-comment comment-col)
3785 (let ((name (buffer-name)))
3786 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3787 (if arg
3788 ;; Set learned variables to symbolic rather than numeric
3789 ;; values where possible.
3790 (dolist (learned-var (reverse learned-var-list))
3791 (let ((var (car learned-var))
3792 (val (nth 1 learned-var)))
3793 (when (and (not (eq var 'sh-basic-offset))
3794 (numberp val))
3795 (sh-set-var-value var val)))))
3796 (dolist (learned-var (reverse learned-var-list))
3797 (let ((var (car learned-var)))
3798 (sh-mark-line (format " %s %s" var (symbol-value var))
3799 (nth 2 learned-var) out-buffer)))
3800 (with-current-buffer out-buffer
3801 (goto-char (point-min))
3802 (let ((inhibit-read-only t))
3803 (insert
3804 (format "Indentation values for buffer %s.\n" name)
3805 (format "%d indentation variable%s different values%s\n\n"
3806 num-diffs
3807 (if (= num-diffs 1)
3808 " has" "s have")
3809 (if (zerop num-diffs)
3810 "." ":"))))))
3811 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3812 (and (called-interactively-p 'any)
3813 (or sh-popup-occur-buffer (> num-diffs 0))
3814 (pop-to-buffer out-buffer))))))
3816 (defun sh-guess-basic-offset (vec)
3817 "See if we can determine a reasonable value for `sh-basic-offset'.
3818 This is experimental, heuristic and arbitrary!
3819 Argument VEC is a vector of information collected by
3820 `sh-learn-buffer-indent'.
3821 Return values:
3822 number - there appears to be a good single value
3823 list of numbers - no obvious one, here is a list of one or more
3824 reasonable choices
3825 nil - we couldn't find a reasonable one."
3826 (let* ((max (1- (length vec)))
3827 (i 1)
3828 (totals (make-vector max 0)))
3829 (while (< i max)
3830 (cl-incf (aref totals i) (* 4 (aref vec i)))
3831 (if (zerop (% i 2))
3832 (cl-incf (aref totals i) (aref vec (/ i 2))))
3833 (if (< (* i 2) max)
3834 (cl-incf (aref totals i) (aref vec (* i 2))))
3835 (setq i (1+ i)))
3837 (let ((x nil)
3838 (result nil)
3839 tot sum p)
3840 (setq i 1)
3841 (while (< i max)
3842 (if (/= (aref totals i) 0)
3843 (push (cons i (aref totals i)) x))
3844 (setq i (1+ i)))
3846 (setq x (sort (nreverse x) (lambda (a b) (> (cdr a) (cdr b)))))
3847 (setq tot (apply '+ (append totals nil)))
3848 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3849 vec totals tot))
3850 (cond
3851 ((zerop (length x))
3852 (message "no values!")) ;; we return nil
3853 ((= (length x) 1)
3854 (message "only value is %d" (car (car x)))
3855 (setq result (car (car x)))) ;; return single value
3856 ((> (cdr (car x)) (/ tot 2))
3857 ;; 1st is > 50%
3858 (message "basic-offset is probably %d" (car (car x)))
3859 (setq result (car (car x)))) ;; again, return a single value
3860 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3861 ;; 1st is >= 2 * 2nd
3862 (message "basic-offset could be %d" (car (car x)))
3863 (setq result (car (car x))))
3864 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3865 ;; 1st & 2nd together >= 50% - return a list
3866 (setq p x sum 0 result nil)
3867 (while (and p
3868 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3869 (setq result (append result (list (car (car p)))))
3870 (setq p (cdr p)))
3871 (message "Possible choices for sh-basic-offset: %s"
3872 (mapconcat 'int-to-string result " ")))
3874 (message "No obvious value for sh-basic-offset. Perhaps %d"
3875 (car (car x)))
3876 ;; result is nil here
3878 result)))
3880 ;; ========================================================================
3882 ;; Styles -- a quick and dirty way of saving the indentation settings.
3884 (defvar sh-styles-alist nil
3885 "A list of all known shell indentation styles.")
3887 (defun sh-name-style (name &optional confirm-overwrite)
3888 "Name the current indentation settings as a style called NAME.
3889 If this name exists, the command will prompt whether it should be
3890 overwritten if
3891 - - it was called interactively with a prefix argument, or
3892 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3893 ;; (interactive "sName for this style: ")
3894 (interactive
3895 (list
3896 (read-from-minibuffer "Name for this style? " )
3897 (not current-prefix-arg)))
3898 (let ((slist (cons name
3899 (mapcar (lambda (var) (cons var (symbol-value var)))
3900 sh-var-list)))
3901 (style (assoc name sh-styles-alist)))
3902 (if style
3903 (if (and confirm-overwrite
3904 (not (y-or-n-p "This style exists. Overwrite it? ")))
3905 (message "Not changing style %s" name)
3906 (message "Updating style %s" name)
3907 (setcdr style (cdr slist)))
3908 (message "Creating new style %s" name)
3909 (push slist sh-styles-alist))))
3911 (defun sh-load-style (name)
3912 "Set shell indentation values for this buffer from those in style NAME."
3913 (interactive (list (completing-read
3914 "Which style to use for this buffer? "
3915 sh-styles-alist nil t)))
3916 (let ((sl (assoc name sh-styles-alist)))
3917 (if (null sl)
3918 (error "sh-load-style - style %s not known" name)
3919 (dolist (var (cdr sl))
3920 (set (car var) (cdr var))))))
3922 (defun sh-save-styles-to-buffer (buff)
3923 "Save all current styles in elisp to buffer BUFF.
3924 This is always added to the end of the buffer."
3925 (interactive
3926 (list
3927 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3928 (with-current-buffer (get-buffer-create buff)
3929 (goto-char (point-max))
3930 (insert "\n")
3931 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3935 ;; statement syntax-commands for various shells
3937 ;; You are welcome to add the syntax or even completely new statements as
3938 ;; appropriate for your favorite shell.
3940 (defconst sh-non-closing-paren
3941 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3942 ;; that inherits this property, which then confuses the indentation.
3943 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3945 (define-skeleton sh-case
3946 "Insert a case/switch statement. See `sh-feature'."
3947 (csh "expression: "
3948 "switch( " str " )" \n
3949 > "case " (read-string "pattern: ") ?: \n
3950 > _ \n
3951 "breaksw" \n
3952 ( "other pattern, %s: "
3953 < "case " str ?: \n
3954 > _ \n
3955 "breaksw" \n)
3956 < "default:" \n
3957 > _ \n
3958 resume:
3959 < < "endsw" \n)
3960 (es)
3961 (rc "expression: "
3962 > "switch( " str " ) {" \n
3963 > "case " (read-string "pattern: ") \n
3964 > _ \n
3965 ( "other pattern, %s: "
3966 "case " str > \n
3967 > _ \n)
3968 "case *" > \n
3969 > _ \n
3970 resume:
3971 ?\} > \n)
3972 (sh "expression: "
3973 > "case " str " in" \n
3974 ( "pattern, %s: "
3975 > str sh-non-closing-paren \n
3976 > _ \n
3977 ";;" \n)
3978 > "*" sh-non-closing-paren \n
3979 > _ \n
3980 resume:
3981 "esac" > \n))
3983 (define-skeleton sh-for
3984 "Insert a for loop. See `sh-feature'."
3985 (csh sh-modify sh
3986 1 ""
3987 2 "foreach "
3988 4 " ( "
3989 6 " )"
3990 15 '<
3991 16 "end")
3992 (es sh-modify rc
3993 4 " = ")
3994 (rc sh-modify sh
3995 2 "for( "
3996 6 " ) {"
3997 15 ?\} )
3998 (sh "Index variable: "
3999 > "for " str " in " _ "; do" \n
4000 > _ | ?$ & (sh-remember-variable str) \n
4001 "done" > \n))
4005 (define-skeleton sh-indexed-loop
4006 "Insert an indexed loop from 1 to n. See `sh-feature'."
4007 (bash sh-modify posix)
4008 (csh "Index variable: "
4009 "@ " str " = 1" \n
4010 "while( $" str " <= " (read-string "upper limit: ") " )" \n
4011 > _ ?$ str \n
4012 "@ " str "++" \n
4013 < "end" \n)
4014 (es sh-modify rc
4015 4 " =")
4016 (ksh88 "Index variable: "
4017 > "integer " str "=0" \n
4018 > "while (( ( " str " += 1 ) <= "
4019 (read-string "upper limit: ")
4020 " )); do" \n
4021 > _ ?$ (sh-remember-variable str) > \n
4022 "done" > \n)
4023 (posix "Index variable: "
4024 > str "=1" \n
4025 "while [ $" str " -le "
4026 (read-string "upper limit: ")
4027 " ]; do" \n
4028 > _ ?$ str \n
4029 str ?= (sh-add (sh-remember-variable str) 1) \n
4030 "done" > \n)
4031 (rc "Index variable: "
4032 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
4033 (read-string "upper limit: ")
4034 "; i++ ) print i }'`}) {" \n
4035 > _ ?$ (sh-remember-variable str) \n
4036 ?\} > \n)
4037 (sh "Index variable: "
4038 > "for " str " in `awk 'BEGIN { for( i=1; i<="
4039 (read-string "upper limit: ")
4040 "; i++ ) print i }'`; do" \n
4041 > _ ?$ (sh-remember-variable str) \n
4042 "done" > \n))
4045 (defun sh-shell-initialize-variables ()
4046 "Scan the buffer for variable assignments.
4047 Add these variables to `sh-shell-variables'."
4048 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
4049 (save-excursion
4050 (goto-char (point-min))
4051 (setq sh-shell-variables-initialized t)
4052 (while (search-forward "=" nil t)
4053 (sh-assignment 0)))
4054 (message "Scanning buffer `%s' for variable assignments...done"
4055 (buffer-name)))
4057 (defvar sh-add-buffer)
4059 (defun sh-add-completer (string predicate code)
4060 "Do completion using `sh-shell-variables', but initialize it first.
4061 This function is designed for use as the \"completion table\",
4062 so it takes three arguments:
4063 STRING, the current buffer contents;
4064 PREDICATE, the predicate for filtering possible matches;
4065 CODE, which says what kind of things to do.
4066 CODE can be nil, t or `lambda'.
4067 nil means to return the best completion of STRING, or nil if there is none.
4068 t means to return a list of all possible completions of STRING.
4069 `lambda' means to return t if STRING is a valid completion as it stands."
4070 (let ((vars
4071 (with-current-buffer sh-add-buffer
4072 (or sh-shell-variables-initialized
4073 (sh-shell-initialize-variables))
4074 (nconc (mapcar (lambda (var)
4075 (substring var 0 (string-match "=" var)))
4076 process-environment)
4077 sh-shell-variables))))
4078 (complete-with-action code vars string predicate)))
4080 (defun sh-add (var delta)
4081 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
4082 (interactive
4083 (let ((sh-add-buffer (current-buffer)))
4084 (list (completing-read "Variable: " 'sh-add-completer)
4085 (prefix-numeric-value current-prefix-arg))))
4086 (insert (sh-feature '((bash . "$(( ")
4087 (ksh88 . "$(( ")
4088 (posix . "$(( ")
4089 (rc . "`{expr $")
4090 (sh . "`expr $")
4091 (zsh . "$[ ")))
4092 (sh-remember-variable var)
4093 (if (< delta 0) " - " " + ")
4094 (number-to-string (abs delta))
4095 (sh-feature '((bash . " ))")
4096 (ksh88 . " ))")
4097 (posix . " ))")
4098 (rc . "}")
4099 (sh . "`")
4100 (zsh . " ]")))))
4104 (define-skeleton sh-function
4105 "Insert a function definition. See `sh-feature'."
4106 (bash sh-modify ksh88
4107 3 "() {")
4108 (ksh88 "name: "
4109 "function " str " {" \n
4110 > _ \n
4111 < "}" \n)
4112 (rc sh-modify ksh88
4113 1 "fn ")
4114 (sh ()
4115 "() {" \n
4116 > _ \n
4117 < "}" \n))
4121 (define-skeleton sh-if
4122 "Insert an if statement. See `sh-feature'."
4123 (csh "condition: "
4124 "if( " str " ) then" \n
4125 > _ \n
4126 ( "other condition, %s: "
4127 < "else if( " str " ) then" \n
4128 > _ \n)
4129 < "else" \n
4130 > _ \n
4131 resume:
4132 < "endif" \n)
4133 (es "condition: "
4134 > "if { " str " } {" \n
4135 > _ \n
4136 ( "other condition, %s: "
4137 "} { " str " } {" > \n
4138 > _ \n)
4139 "} {" > \n
4140 > _ \n
4141 resume:
4142 ?\} > \n)
4143 (rc "condition: "
4144 > "if( " str " ) {" \n
4145 > _ \n
4146 ( "other condition, %s: "
4147 "} else if( " str " ) {" > \n
4148 > _ \n)
4149 "} else {" > \n
4150 > _ \n
4151 resume:
4152 ?\} > \n)
4153 (sh "condition: "
4154 '(setq input (sh-feature sh-test))
4155 > "if " str "; then" \n
4156 > _ \n
4157 ( "other condition, %s: "
4158 > "elif " str "; then" > \n
4159 > \n)
4160 "else" > \n
4161 > \n
4162 resume:
4163 "fi" > \n))
4167 (define-skeleton sh-repeat
4168 "Insert a repeat loop definition. See `sh-feature'."
4169 (es nil
4170 > "forever {" \n
4171 > _ \n
4172 ?\} > \n)
4173 (zsh "factor: "
4174 > "repeat " str "; do" > \n
4175 > \n
4176 "done" > \n))
4178 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
4182 (define-skeleton sh-select
4183 "Insert a select statement. See `sh-feature'."
4184 (ksh88 "Index variable: "
4185 > "select " str " in " _ "; do" \n
4186 > ?$ str \n
4187 "done" > \n)
4188 (bash sh-append ksh88))
4189 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
4193 (define-skeleton sh-tmp-file
4194 "Insert code to setup temporary file handling. See `sh-feature'."
4195 (bash sh-append ksh88)
4196 (csh (file-name-nondirectory (buffer-file-name))
4197 "set tmp = `mktemp -t " str ".XXXXXX`" \n
4198 "onintr exit" \n _
4199 (and (goto-char (point-max))
4200 (not (bolp))
4201 ?\n)
4202 "exit:\n"
4203 "rm $tmp* >&/dev/null" > \n)
4204 (es (file-name-nondirectory (buffer-file-name))
4205 > "local( signals = $signals sighup sigint;" \n
4206 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
4207 > "catch @ e {" \n
4208 > "rm $tmp^* >[2]/dev/null" \n
4209 "throw $e" \n
4210 "} {" > \n
4211 _ \n
4212 ?\} > \n
4213 ?\} > \n)
4214 (ksh88 sh-modify sh
4215 7 "EXIT")
4216 (rc (file-name-nondirectory (buffer-file-name))
4217 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
4218 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
4219 (sh (file-name-nondirectory (buffer-file-name))
4220 > "TMP=`mktemp -t " str ".XXXXXX`" \n
4221 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
4225 (define-skeleton sh-until
4226 "Insert an until loop. See `sh-feature'."
4227 (sh "condition: "
4228 '(setq input (sh-feature sh-test))
4229 > "until " str "; do" \n
4230 > _ \n
4231 "done" > \n))
4232 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
4236 (define-skeleton sh-while
4237 "Insert a while loop. See `sh-feature'."
4238 (csh sh-modify sh
4239 2 ""
4240 3 "while( "
4241 5 " )"
4242 10 '<
4243 11 "end")
4244 (es sh-modify sh
4245 3 "while { "
4246 5 " } {"
4247 10 ?\} )
4248 (rc sh-modify sh
4249 3 "while( "
4250 5 " ) {"
4251 10 ?\} )
4252 (sh "condition: "
4253 '(setq input (sh-feature sh-test))
4254 > "while " str "; do" \n
4255 > _ \n
4256 "done" > \n))
4260 (define-skeleton sh-while-getopts
4261 "Insert a while getopts loop. See `sh-feature'.
4262 Prompts for an options string which consists of letters for each recognized
4263 option followed by a colon `:' if the option accepts an argument."
4264 (bash sh-modify sh
4265 18 "${0##*/}")
4266 (csh nil
4267 "while( 1 )" \n
4268 > "switch( \"$1\" )" \n
4269 '(setq input '("- x" . 2))
4271 ( "option, %s: "
4272 < "case " '(eval str)
4273 '(if (string-match " +" str)
4274 (setq v1 (substring str (match-end 0))
4275 str (substring str 0 (match-beginning 0)))
4276 (setq v1 nil))
4277 str ?: \n
4278 > "set " v1 & " = $2" | -4 & _ \n
4279 (if v1 "shift") & \n
4280 "breaksw" \n)
4281 < "case --:" \n
4282 > "shift" \n
4283 < "default:" \n
4284 > "break" \n
4285 resume:
4286 < < "endsw" \n
4287 "shift" \n
4288 < "end" \n)
4289 (ksh88 sh-modify sh
4290 16 "print"
4291 18 "${0##*/}"
4292 37 "OPTIND-1")
4293 (posix sh-modify sh
4294 18 "$(basename $0)")
4295 (sh "optstring: "
4296 > "while getopts :" str " OPT; do" \n
4297 > "case $OPT in" \n
4298 '(setq v1 (append (vconcat str) nil))
4299 ( (prog1 (if v1 (char-to-string (car v1)))
4300 (if (eq (nth 1 v1) ?:)
4301 (setq v1 (nthcdr 2 v1)
4302 v2 "\"$OPTARG\"")
4303 (setq v1 (cdr v1)
4304 v2 nil)))
4305 > str "|+" str sh-non-closing-paren \n
4306 > _ v2 \n
4307 > ";;" \n)
4308 > "*" sh-non-closing-paren \n
4309 > "echo" " \"usage: " "`basename $0`"
4310 " [+-" '(setq v1 (point)) str
4311 '(save-excursion
4312 (while (search-backward ":" v1 t)
4313 (replace-match " ARG] [+-" t t)))
4314 (if (eq (preceding-char) ?-) -5)
4315 (if (and (sequencep v1) (length v1)) "] " "} ")
4316 "[--] ARGS...\"" \n
4317 "exit 2" > \n
4318 "esac" >
4319 \n "done"
4320 > \n
4321 "shift " (sh-add "OPTIND" -1) \n
4322 "OPTIND=1" \n))
4326 (defun sh-assignment (arg)
4327 "Remember preceding identifier for future completion and do self-insert."
4328 (interactive "p")
4329 (self-insert-command arg)
4330 (if (<= arg 1)
4331 (sh-remember-variable
4332 (save-excursion
4333 (if (re-search-forward (sh-feature sh-assignment-regexp)
4334 (prog1 (point)
4335 (beginning-of-line 1))
4337 (match-string 1))))))
4340 (defun sh-maybe-here-document (arg)
4341 "Insert self. Without prefix, following unquoted `<' inserts here document.
4342 The document is bounded by `sh-here-document-word'."
4343 (declare (obsolete sh-electric-here-document-mode "24.3"))
4344 (interactive "*P")
4345 (self-insert-command (prefix-numeric-value arg))
4346 (or arg (sh--maybe-here-document)))
4348 (defun sh--maybe-here-document ()
4349 (or (not (looking-back "[^<]<<" (line-beginning-position)))
4350 (save-excursion
4351 (backward-char 2)
4352 (or (sh-quoted-p)
4353 (sh--inside-noncommand-expression (point))))
4354 (nth 8 (syntax-ppss))
4355 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
4356 (make-string (/ (current-indentation) tab-width) ?\t)
4357 ""))
4358 (delim (replace-regexp-in-string "['\"]" ""
4359 sh-here-document-word)))
4360 (insert sh-here-document-word)
4361 (or (eolp) (looking-at "[ \t]") (insert ?\s))
4362 (end-of-line 1)
4363 (while
4364 (sh-quoted-p)
4365 (end-of-line 2))
4366 (insert ?\n tabs)
4367 (save-excursion
4368 (insert ?\n tabs (replace-regexp-in-string
4369 "\\`-?[ \t]*" "" delim))))))
4371 (define-minor-mode sh-electric-here-document-mode
4372 "Make << insert a here document skeleton."
4373 nil nil nil
4374 (if sh-electric-here-document-mode
4375 (add-hook 'post-self-insert-hook #'sh--maybe-here-document nil t)
4376 (remove-hook 'post-self-insert-hook #'sh--maybe-here-document t)))
4378 ;; various other commands
4380 (defun sh-beginning-of-command ()
4381 ;; FIXME: Redefine using SMIE.
4382 "Move point to successive beginnings of commands."
4383 (interactive)
4384 (if (re-search-backward sh-beginning-of-command nil t)
4385 (goto-char (match-beginning 2))))
4387 (defun sh-end-of-command ()
4388 ;; FIXME: Redefine using SMIE.
4389 "Move point to successive ends of commands."
4390 (interactive)
4391 (if (re-search-forward sh-end-of-command nil t)
4392 (goto-char (match-end 1))))
4394 ;; Backslashification. Stolen from make-mode.el.
4396 (defun sh-backslash-region (from to delete-flag)
4397 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4398 With no argument, inserts backslashes and aligns existing backslashes.
4399 With an argument, deletes the backslashes.
4401 This function does not modify the last line of the region if the region ends
4402 right at the start of the following line; it does not modify blank lines
4403 at the start of the region. So you can put the region around an entire
4404 shell command and conveniently use this command."
4405 (interactive "r\nP")
4406 (save-excursion
4407 (goto-char from)
4408 (let ((column sh-backslash-column)
4409 (endmark (make-marker)))
4410 (move-marker endmark to)
4411 ;; Compute the smallest column number past the ends of all the lines.
4412 (if sh-backslash-align
4413 (progn
4414 (if (not delete-flag)
4415 (while (< (point) to)
4416 (end-of-line)
4417 (if (= (preceding-char) ?\\)
4418 (progn (forward-char -1)
4419 (skip-chars-backward " \t")))
4420 (setq column (max column (1+ (current-column))))
4421 (forward-line 1)))
4422 ;; Adjust upward to a tab column, if that doesn't push
4423 ;; past the margin.
4424 (if (> (% column tab-width) 0)
4425 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
4426 tab-width)))
4427 (if (< adjusted (window-width))
4428 (setq column adjusted))))))
4429 ;; Don't modify blank lines at start of region.
4430 (goto-char from)
4431 (while (and (< (point) endmark) (eolp))
4432 (forward-line 1))
4433 ;; Add or remove backslashes on all the lines.
4434 (while (and (< (point) endmark)
4435 ;; Don't backslashify the last line
4436 ;; if the region ends right at the start of the next line.
4437 (save-excursion
4438 (forward-line 1)
4439 (< (point) endmark)))
4440 (if (not delete-flag)
4441 (sh-append-backslash column)
4442 (sh-delete-backslash))
4443 (forward-line 1))
4444 (move-marker endmark nil))))
4446 (defun sh-append-backslash (column)
4447 (end-of-line)
4448 ;; Note that "\\\\" is needed to get one backslash.
4449 (if (= (preceding-char) ?\\)
4450 (progn (forward-char -1)
4451 (delete-horizontal-space)
4452 (indent-to column (if sh-backslash-align nil 1)))
4453 (indent-to column (if sh-backslash-align nil 1))
4454 (insert "\\")))
4456 (defun sh-delete-backslash ()
4457 (end-of-line)
4458 (or (bolp)
4459 (progn
4460 (forward-char -1)
4461 (if (looking-at "\\\\")
4462 (delete-region (1+ (point))
4463 (progn (skip-chars-backward " \t") (point)))))))
4465 (provide 'sh-script)
4467 ;;; sh-script.el ends here