; Auto-commit of loaddefs files.
[emacs.git] / lisp / progmodes / sh-script.el
blob537b180eed6a30df9ff5cd16f5b84ddb57d7f0ed
1 ;;; sh-script.el --- shell-script editing commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1993-1997, 1999, 2001-2015 Free Software Foundation, Inc.
5 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
6 ;; Version: 2.0f
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: languages, unix
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
28 ;; as various derivatives are supported and easily derived from. Structured
29 ;; statements can be inserted with one command or abbrev. Completion is
30 ;; available for filenames, variables known from the script, the shell and
31 ;; the environment as well as commands.
33 ;;; Known Bugs:
35 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
36 ;; - Variables in `"' strings aren't fontified because there's no way of
37 ;; syntactically distinguishing those from `'' strings.
39 ;; Indentation
40 ;; ===========
41 ;; Indentation for rc and es modes is very limited, but for Bourne shells
42 ;; and its derivatives it is quite customizable.
43 ;;
44 ;; The following description applies to sh and derived shells (bash,
45 ;; zsh, ...).
46 ;;
47 ;; There are various customization variables which allow tailoring to
48 ;; a wide variety of styles. Most of these variables are named
49 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
50 ;; sh-indent-after-if controls the indenting of a line following
51 ;; an if statement, and sh-indent-for-fi controls the indentation
52 ;; of the line containing the fi.
53 ;;
54 ;; You can set each to a numeric value, but it is often more convenient
55 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
56 ;; By changing this one variable you can increase or decrease how much
57 ;; indentation there is. Valid symbols:
58 ;;
59 ;; + Indent right by sh-basic-offset
60 ;; - Indent left by sh-basic-offset
61 ;; ++ Indent right twice sh-basic-offset
62 ;; -- Indent left twice sh-basic-offset
63 ;; * Indent right half sh-basic-offset
64 ;; / Indent left half sh-basic-offset.
65 ;;
66 ;; There are 4 commands to help set the indentation variables:
67 ;;
68 ;; `sh-show-indent'
69 ;; This shows what variable controls the indentation of the current
70 ;; line and its value.
71 ;;
72 ;; `sh-set-indent'
73 ;; This allows you to set the value of the variable controlling the
74 ;; current line's indentation. You can enter a number or one of a
75 ;; number of special symbols to denote the value of sh-basic-offset,
76 ;; or its negative, or half it, or twice it, etc. If you've used
77 ;; cc-mode this should be familiar. If you forget which symbols are
78 ;; valid simply press C-h at the prompt.
79 ;;
80 ;; `sh-learn-line-indent'
81 ;; Simply make the line look the way you want it, then invoke this
82 ;; command. It will set the variable to the value that makes the line
83 ;; indent like that. If called with a prefix argument then it will set
84 ;; the value to one of the symbols if applicable.
85 ;;
86 ;; `sh-learn-buffer-indent'
87 ;; This is the deluxe function! It "learns" the whole buffer (use
88 ;; narrowing if you want it to process only part). It outputs to a
89 ;; buffer *indent* any conflicts it finds, and all the variables it has
90 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
91 ;; easily find where something was set. It is popped to automatically
92 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
93 ;; non-nil.
94 ;; `sh-indent-comment' will be set if all comments follow the same
95 ;; pattern; if they don't it will be set to nil.
96 ;; Whether `sh-basic-offset' is set is determined by variable
97 ;; `sh-learn-basic-offset'.
98 ;;
99 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
100 ;; (e.g. if there are large case statements). Perhaps it does not make
101 ;; sense to run it on large buffers: if lots of lines have different
102 ;; indentation styles it will produce a lot of diagnostics in the
103 ;; *indent* buffer; if there is a consistent style then running
104 ;; `sh-learn-buffer-indent' on a small region of the buffer should
105 ;; suffice.
106 ;;
107 ;; Saving indentation values
108 ;; -------------------------
109 ;; After you've learned the values in a buffer, how to you remember
110 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
111 ;; would make this unnecessary; simply learn the values when you visit
112 ;; the buffer.
113 ;; You can do this automatically like this:
114 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
115 ;;
116 ;; However... `sh-learn-buffer-indent' is extremely slow,
117 ;; especially on large-ish buffer. Also, if there are conflicts the
118 ;; "last one wins" which may not produce the desired setting.
119 ;;
120 ;; So...There is a minimal way of being able to save indentation values and
121 ;; to reload them in another buffer or at another point in time.
122 ;;
123 ;; Use `sh-name-style' to give a name to the indentation settings of
124 ;; the current buffer.
125 ;; Use `sh-load-style' to load indentation settings for the current
126 ;; buffer from a specific style.
127 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
128 ;; in lisp code. You can then store it in a file and later use
129 ;; `load-file' to load it.
130 ;;
131 ;; Indentation variables - buffer local or global?
132 ;; ----------------------------------------------
133 ;; I think that often having them buffer-local makes sense,
134 ;; especially if one is using `sh-learn-buffer-indent'. However, if
135 ;; a user sets values using customization, these changes won't appear
136 ;; to work if the variables are already local!
137 ;;
138 ;; To get round this, there is a variable `sh-make-vars-local' and 2
139 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
140 ;;
141 ;; If `sh-make-vars-local' is non-nil, then these variables become
142 ;; buffer local when the mode is established.
143 ;; If this is nil, then the variables are global. At any time you
144 ;; can make them local with the command `sh-make-vars-local'.
145 ;; Conversely, to update with the global values you can use the
146 ;; command `sh-reset-indent-vars-to-global-values'.
147 ;;
148 ;; This may be awkward, but the intent is to cover all cases.
149 ;;
150 ;; Awkward things, pitfalls
151 ;; ------------------------
152 ;; Indentation for a sh script is complicated for a number of reasons:
153 ;;
154 ;; 1. You can't format by simply looking at symbols, you need to look
155 ;; at keywords. [This is not the case for rc and es shells.]
156 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
157 ;; as a stand-alone symbol (in a case alternative). This makes
158 ;; things quite tricky!
159 ;; 3. Here-documents in a script should be treated "as is", and when
160 ;; they terminate we want to revert to the indentation of the line
161 ;; containing the "<<" symbol.
162 ;; 4. A line may be continued using the "\".
163 ;; 5. The character "#" (outside a string) normally starts a comment,
164 ;; but it doesn't in the sequence "$#"!
165 ;;
166 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
167 ;; uses, that of a text's syntax property. This, however, has 2
168 ;; disadvantages:
169 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
170 ;; case alternative, to find any here documents, and handle "$#".
171 ;;
172 ;; Bugs
173 ;; ----
174 ;; - Indenting many lines is slow. It currently does each line
175 ;; independently, rather than saving state information.
176 ;;
177 ;; - `sh-learn-buffer-indent' is extremely slow.
178 ;;
179 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
180 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
181 ;; coerce sh-script into doing the right thing.
182 ;;
183 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
184 ;; a case-pattern. You need to put the "in" between quotes to coerce
185 ;; sh-script into doing the right thing.
186 ;;
187 ;; - A line starting with "}>foo" is not indented like "} >foo".
188 ;;
189 ;; Richard Sharman <rsharman@pobox.com> June 1999.
191 ;;; Code:
193 ;; page 1: variables and settings
194 ;; page 2: indentation stuff
195 ;; page 3: mode-command and utility functions
196 ;; page 4: statement syntax-commands for various shells
197 ;; page 5: various other commands
199 (eval-when-compile
200 (require 'skeleton)
201 (require 'cl-lib)
202 (require 'comint))
203 (require 'executable)
205 (autoload 'comint-completion-at-point "comint")
206 (autoload 'comint-filename-completion "comint")
207 (autoload 'shell-command-completion "shell")
208 (autoload 'shell-environment-variable-completion "shell")
210 (defvar font-lock-comment-face)
211 (defvar font-lock-set-defaults)
212 (defvar font-lock-string-face)
215 (defgroup sh nil
216 "Shell programming utilities."
217 :group 'languages)
219 (defgroup sh-script nil
220 "Shell script mode."
221 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
222 :group 'sh
223 :prefix "sh-")
226 (defcustom sh-ancestor-alist
227 '((ash . sh)
228 (bash . jsh)
229 (bash2 . jsh)
230 (dash . ash)
231 (dtksh . ksh)
232 (es . rc)
233 (itcsh . tcsh)
234 (jcsh . csh)
235 (jsh . sh)
236 (ksh . ksh88)
237 (ksh88 . jsh)
238 (oash . sh)
239 (pdksh . ksh88)
240 (mksh . pdksh)
241 (posix . sh)
242 (tcsh . csh)
243 (wksh . ksh88)
244 (wsh . sh)
245 (zsh . ksh88)
246 (rpm . sh))
247 "Alist showing the direct ancestor of various shells.
248 This is the basis for `sh-feature'. See also `sh-alias-alist'.
249 By default we have the following three hierarchies:
251 csh C Shell
252 jcsh C Shell with Job Control
253 tcsh TENEX C Shell
254 itcsh Ian's TENEX C Shell
255 rc Plan 9 Shell
256 es Extensible Shell
257 sh Bourne Shell
258 ash Almquist Shell
259 dash Debian Almquist Shell
260 jsh Bourne Shell with Job Control
261 bash GNU Bourne Again Shell
262 ksh88 Korn Shell '88
263 ksh Korn Shell '93
264 dtksh CDE Desktop Korn Shell
265 pdksh Public Domain Korn Shell
266 mksh MirOS BSD Korn Shell
267 wksh Window Korn Shell
268 zsh Z Shell
269 oash SCO OA (curses) Shell
270 posix IEEE 1003.2 Shell Standard
271 wsh ? Shell"
272 :type '(repeat (cons symbol symbol))
273 :version "24.4" ; added dash
274 :group 'sh-script)
276 (defcustom sh-alias-alist
277 (append (if (eq system-type 'gnu/linux)
278 '((csh . tcsh)
279 (ksh . pdksh)))
280 ;; for the time being
281 '((ksh . ksh88)
282 (bash2 . bash)
283 (sh5 . sh)
284 ;; Android's system shell
285 ("^/system/bin/sh$" . mksh)))
286 "Alist for transforming shell names to what they really are.
287 Use this where the name of the executable doesn't correspond to
288 the type of shell it really is. Keys are regular expressions
289 matched against the full path of the interpreter. (For backward
290 compatibility, keys may also be symbols, which are matched
291 against the interpreter's basename. The values are symbols
292 naming the shell."
293 :type '(repeat (cons (radio
294 (regexp :tag "Regular expression")
295 (symbol :tag "Basename"))
296 (symbol :tag "Shell")))
297 :group 'sh-script)
300 (defcustom sh-shell-file
301 (or
302 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
303 ;; the executable extension, so comparisons with the list of
304 ;; known shells work.
305 (and (memq system-type '(ms-dos windows-nt))
306 (let* ((shell (getenv "SHELL"))
307 (shell-base
308 (and shell (file-name-nondirectory shell))))
309 ;; shell-script mode doesn't support DOS/Windows shells,
310 ;; so use the default instead.
311 (if (or (null shell)
312 (member (downcase shell-base)
313 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
314 "cmdproxy.exe")))
315 "/bin/sh"
316 (file-name-sans-extension (downcase shell)))))
317 (getenv "SHELL")
318 "/bin/sh")
319 "The executable file name for the shell being programmed."
320 :type 'string
321 :group 'sh-script)
324 (defcustom sh-shell-arg
325 ;; bash does not need any options when run in a shell script,
326 '((bash)
327 (csh . "-f")
328 (pdksh)
329 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
330 (ksh88)
331 ;; -p means don't initialize functions from the environment.
332 (rc . "-p")
333 ;; Someone proposed -motif, but we don't want to encourage
334 ;; use of a non-free widget set.
335 (wksh)
336 ;; -f means don't run .zshrc.
337 (zsh . "-f"))
338 "Single argument string for the magic number. See `sh-feature'."
339 :type '(repeat (cons (symbol :tag "Shell")
340 (choice (const :tag "No Arguments" nil)
341 (string :tag "Arguments")
342 (sexp :format "Evaluate: %v"))))
343 :group 'sh-script)
345 (defcustom sh-imenu-generic-expression
346 `((sh
347 . ((nil
348 ;; function FOO
349 ;; function FOO()
350 "^\\s-*function\\s-+\\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
351 1)
352 ;; FOO()
353 (nil
354 "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
355 1)
356 )))
357 "Alist of regular expressions for recognizing shell function definitions.
358 See `sh-feature' and `imenu-generic-expression'."
359 :type '(alist :key-type (symbol :tag "Shell")
360 :value-type (alist :key-type (choice :tag "Title"
361 string
362 (const :tag "None" nil))
363 :value-type
364 (repeat :tag "Regexp, index..." sexp)))
365 :group 'sh-script
366 :version "20.4")
368 (defun sh-current-defun-name ()
369 "Find the name of function or variable at point.
370 For use in `add-log-current-defun-function'."
371 (save-excursion
372 (end-of-line)
373 (when (re-search-backward
374 (concat "\\(?:"
375 ;; function FOO
376 ;; function FOO()
377 "^\\s-*function\\s-+\\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
378 "\\)\\|\\(?:"
379 ;; FOO()
380 "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
381 "\\)\\|\\(?:"
382 ;; FOO=
383 "^\\([[:alpha:]_][[:alnum:]_]*\\)="
384 "\\)")
385 nil t)
386 (or (match-string-no-properties 1)
387 (match-string-no-properties 2)
388 (match-string-no-properties 3)))))
390 (defvar sh-shell-variables nil
391 "Alist of shell variable names that should be included in completion.
392 These are used for completion in addition to all the variables named
393 in `process-environment'. Each element looks like (VAR . VAR), where
394 the car and cdr are the same symbol.")
396 (defvar sh-shell-variables-initialized nil
397 "Non-nil if `sh-shell-variables' is initialized.")
399 (defun sh-canonicalize-shell (shell)
400 "Convert a shell name SHELL to the one we should handle it as.
401 SHELL is a full path to the shell interpreter; return a shell
402 name symbol."
403 (cl-loop
404 with shell = (cond ((string-match "\\.exe\\'" shell)
405 (substring shell 0 (match-beginning 0)))
406 (t shell))
407 with shell-base = (intern (file-name-nondirectory shell))
408 for (key . value) in sh-alias-alist
409 if (and (stringp key) (string-match key shell)) return value
410 if (eq key shell-base) return value
411 finally return shell-base))
413 (defvar sh-shell (sh-canonicalize-shell sh-shell-file)
414 "The shell being programmed. This is set by \\[sh-set-shell].")
415 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
417 (define-abbrev-table 'sh-mode-abbrev-table ())
420 ;; I turned off this feature because it doesn't permit typing commands
421 ;; in the usual way without help.
422 ;;(defvar sh-abbrevs
423 ;; '((csh sh-abbrevs shell
424 ;; "switch" 'sh-case
425 ;; "getopts" 'sh-while-getopts)
427 ;; (es sh-abbrevs shell
428 ;; "function" 'sh-function)
430 ;; (ksh88 sh-abbrevs sh
431 ;; "select" 'sh-select)
433 ;; (rc sh-abbrevs shell
434 ;; "case" 'sh-case
435 ;; "function" 'sh-function)
437 ;; (sh sh-abbrevs shell
438 ;; "case" 'sh-case
439 ;; "function" 'sh-function
440 ;; "until" 'sh-until
441 ;; "getopts" 'sh-while-getopts)
443 ;; ;; The next entry is only used for defining the others
444 ;; (shell "for" sh-for
445 ;; "loop" sh-indexed-loop
446 ;; "if" sh-if
447 ;; "tmpfile" sh-tmp-file
448 ;; "while" sh-while)
450 ;; (zsh sh-abbrevs ksh88
451 ;; "repeat" 'sh-repeat))
452 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
453 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
454 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
458 (defun sh-mode-syntax-table (table &rest list)
459 "Copy TABLE and set syntax for successive CHARs according to strings S."
460 (setq table (copy-syntax-table table))
461 (while list
462 (modify-syntax-entry (pop list) (pop list) table))
463 table)
465 (defvar sh-mode-syntax-table
466 (sh-mode-syntax-table ()
467 ?\# "<"
468 ?\n ">#"
469 ?\" "\"\""
470 ?\' "\"'"
471 ?\` "\"`"
472 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
473 ;; to work fine. This is needed so that dabbrev-expand
474 ;; $VARNAME works.
475 ?$ "'"
476 ?! "_"
477 ?% "_"
478 ?: "_"
479 ?. "_"
480 ?^ "_"
481 ?~ "_"
482 ?, "_"
483 ?= "."
484 ?\; "."
485 ?| "."
486 ?& "."
487 ?< "."
488 ?> ".")
489 "The syntax table to use for Shell-Script mode.
490 This is buffer-local in every such buffer.")
492 (defvar sh-mode-syntax-table-input
493 '((sh . nil))
494 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
496 (defvar sh-mode-map
497 (let ((map (make-sparse-keymap))
498 (menu-map (make-sparse-keymap)))
499 (define-key map "\C-c(" 'sh-function)
500 (define-key map "\C-c\C-w" 'sh-while)
501 (define-key map "\C-c\C-u" 'sh-until)
502 (define-key map "\C-c\C-t" 'sh-tmp-file)
503 (define-key map "\C-c\C-s" 'sh-select)
504 (define-key map "\C-c\C-r" 'sh-repeat)
505 (define-key map "\C-c\C-o" 'sh-while-getopts)
506 (define-key map "\C-c\C-l" 'sh-indexed-loop)
507 (define-key map "\C-c\C-i" 'sh-if)
508 (define-key map "\C-c\C-f" 'sh-for)
509 (define-key map "\C-c\C-c" 'sh-case)
510 (define-key map "\C-c?" 'sh-show-indent)
511 (define-key map "\C-c=" 'sh-set-indent)
512 (define-key map "\C-c<" 'sh-learn-line-indent)
513 (define-key map "\C-c>" 'sh-learn-buffer-indent)
514 (define-key map "\C-c\C-\\" 'sh-backslash-region)
516 (define-key map "=" 'sh-assignment)
517 (define-key map "\C-c+" 'sh-add)
518 (define-key map "\C-\M-x" 'sh-execute-region)
519 (define-key map "\C-c\C-x" 'executable-interpret)
520 (define-key map "\C-c\C-n" 'sh-send-line-or-region-and-step)
521 (define-key map "\C-c\C-d" 'sh-cd-here)
522 (define-key map "\C-c\C-z" 'sh-show-shell)
524 (define-key map [remap delete-backward-char]
525 'backward-delete-char-untabify)
526 (define-key map "\C-c:" 'sh-set-shell)
527 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
528 (define-key map [remap forward-sentence] 'sh-end-of-command)
529 (define-key map [menu-bar sh-script] (cons "Sh-Script" menu-map))
530 (define-key menu-map [sh-learn-buffer-indent]
531 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
532 :help "Learn how to indent the buffer the way it currently is."))
533 (define-key menu-map [sh-learn-line-indent]
534 '(menu-item "Learn line indentation" sh-learn-line-indent
535 :help "Learn how to indent a line as it currently is indented"))
536 (define-key menu-map [sh-show-indent]
537 '(menu-item "Show indentation" sh-show-indent
538 :help "Show the how the current line would be indented"))
539 (define-key menu-map [sh-set-indent]
540 '(menu-item "Set indentation" sh-set-indent
541 :help "Set the indentation for the current line"))
543 (define-key menu-map [sh-pair]
544 '(menu-item "Insert braces and quotes in pairs"
545 electric-pair-mode
546 :button (:toggle . (bound-and-true-p electric-pair-mode))
547 :help "Inserting a brace or quote automatically inserts the matching pair"))
549 (define-key menu-map [sh-s0] '("--"))
550 ;; Insert
551 (define-key menu-map [sh-function]
552 '(menu-item "Function..." sh-function
553 :help "Insert a function definition"))
554 (define-key menu-map [sh-add]
555 '(menu-item "Addition..." sh-add
556 :help "Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
557 (define-key menu-map [sh-until]
558 '(menu-item "Until Loop" sh-until
559 :help "Insert an until loop"))
560 (define-key menu-map [sh-repeat]
561 '(menu-item "Repeat Loop" sh-repeat
562 :help "Insert a repeat loop definition"))
563 (define-key menu-map [sh-while]
564 '(menu-item "While Loop" sh-while
565 :help "Insert a while loop"))
566 (define-key menu-map [sh-getopts]
567 '(menu-item "Options Loop" sh-while-getopts
568 :help "Insert a while getopts loop."))
569 (define-key menu-map [sh-indexed-loop]
570 '(menu-item "Indexed Loop" sh-indexed-loop
571 :help "Insert an indexed loop from 1 to n."))
572 (define-key menu-map [sh-select]
573 '(menu-item "Select Statement" sh-select
574 :help "Insert a select statement "))
575 (define-key menu-map [sh-if]
576 '(menu-item "If Statement" sh-if
577 :help "Insert an if statement"))
578 (define-key menu-map [sh-for]
579 '(menu-item "For Loop" sh-for
580 :help "Insert a for loop"))
581 (define-key menu-map [sh-case]
582 '(menu-item "Case Statement" sh-case
583 :help "Insert a case/switch statement"))
584 (define-key menu-map [sh-s1] '("--"))
585 (define-key menu-map [sh-exec]
586 '(menu-item "Execute region" sh-execute-region
587 :help "Pass optional header and region to a subshell for noninteractive execution"))
588 (define-key menu-map [sh-exec-interpret]
589 '(menu-item "Execute script..." executable-interpret
590 :help "Run script with user-specified args, and collect output in a buffer"))
591 (define-key menu-map [sh-set-shell]
592 '(menu-item "Set shell type..." sh-set-shell
593 :help "Set this buffer's shell to SHELL (a string)"))
594 (define-key menu-map [sh-backslash-region]
595 '(menu-item "Backslash region" sh-backslash-region
596 :help "Insert, align, or delete end-of-line backslashes on the lines in the region."))
597 map)
598 "Keymap used in Shell-Script mode.")
600 (defvar sh-skeleton-pair-default-alist '((?( _ ?)) (?\))
601 (?[ ?\s _ ?\s ?]) (?\])
602 (?{ _ ?}) (?\}))
603 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
605 (defcustom sh-dynamic-complete-functions
606 '(shell-environment-variable-completion
607 shell-command-completion
608 comint-filename-completion)
609 "Functions for doing TAB dynamic completion."
610 :type '(repeat function)
611 :group 'sh-script)
613 (defcustom sh-assignment-regexp
614 `((csh . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
615 ;; actually spaces are only supported in let/(( ... ))
616 (ksh88 . ,(concat "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?"
617 "[ \t]*\\(?:[-+*/%&|~^]\\|<<\\|>>\\)?="))
618 (bash . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?\\+?=")
619 (rc . "\\<\\([[:alnum:]_*]+\\)[ \t]*=")
620 (sh . "\\<\\([[:alnum:]_]+\\)="))
621 "Regexp for the variable name and what may follow in an assignment.
622 First grouping matches the variable name. This is upto and including the `='
623 sign. See `sh-feature'."
624 :type '(repeat (cons (symbol :tag "Shell")
625 (choice regexp
626 (sexp :format "Evaluate: %v"))))
627 :group 'sh-script)
630 (defcustom sh-indentation 4
631 "The width for further indentation in Shell-Script mode."
632 :type 'integer
633 :group 'sh-script)
634 (put 'sh-indentation 'safe-local-variable 'integerp)
636 (defcustom sh-remember-variable-min 3
637 "Don't remember variables less than this length for completing reads."
638 :type 'integer
639 :group 'sh-script)
642 (defvar sh-header-marker nil
643 "When non-nil is the end of header for prepending by \\[sh-execute-region].
644 That command is also used for setting this variable.")
645 (make-variable-buffer-local 'sh-header-marker)
647 (defcustom sh-beginning-of-command
648 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
649 "Regexp to determine the beginning of a shell command.
650 The actual command starts at the beginning of the second \\(grouping\\)."
651 :type 'regexp
652 :group 'sh-script)
655 (defcustom sh-end-of-command
656 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
657 "Regexp to determine the end of a shell command.
658 The actual command ends at the end of the first \\(grouping\\)."
659 :type 'regexp
660 :group 'sh-script)
664 (defcustom sh-here-document-word "EOF"
665 "Word to delimit here documents.
666 If the first character of this string is \"-\", this is taken as
667 part of the redirection operator, rather than part of the
668 word (that is, \"<<-\" instead of \"<<\"). This is a feature
669 used by some shells (for example Bash) to indicate that leading
670 tabs inside the here document should be ignored. In this case,
671 Emacs indents the initial body and end of the here document with
672 tabs, to the same level as the start (note that apart from this
673 there is no support for indentation of here documents). This
674 will only work correctly if `sh-basic-offset' is a multiple of
675 `tab-width'.
677 Any quote characters or leading whitespace in the word are
678 removed when closing the here document."
679 :type 'string
680 :group 'sh-script)
683 (defvar sh-test
684 '((sh "[ ]" . 3)
685 (ksh88 "[[ ]]" . 4))
686 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
689 ;; customized this out of sheer bravado. not for the faint of heart.
690 ;; but it *did* have an asterisk in the docstring!
691 (defcustom sh-builtins
692 '((bash sh-append posix
693 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
694 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
695 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
696 "source" "suspend" "typeset" "unalias"
697 ;; bash4
698 "mapfile" "readarray" "coproc")
700 ;; The next entry is only used for defining the others
701 (bourne sh-append shell
702 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
703 "times" "ulimit")
705 (csh sh-append shell
706 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
707 "setenv" "source" "time" "unalias" "unhash")
709 (dtksh sh-append wksh)
711 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
712 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
714 (jsh sh-append sh
715 "bg" "fg" "jobs" "kill" "stop" "suspend")
717 (jcsh sh-append csh
718 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
720 (ksh88 sh-append bourne
721 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
722 "typeset" "unalias" "whence")
724 (oash sh-append sh
725 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
726 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
727 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
728 "wmtitle" "wrefresh")
730 (pdksh sh-append ksh88
731 "bind")
733 (posix sh-append sh
734 "command")
736 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
737 "whatis")
739 (sh sh-append bourne
740 "hash" "test" "type")
742 ;; The next entry is only used for defining the others
743 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
745 (wksh sh-append ksh88
746 ;; FIXME: This looks too much like a regexp. --Stef
747 "Xt[A-Z][A-Za-z]*")
749 (zsh sh-append ksh88
750 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
751 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
752 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
753 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
754 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
755 "which"))
756 "List of all shell builtins for completing read and fontification.
757 Note that on some systems not all builtins are available or some are
758 implemented as aliases. See `sh-feature'."
759 :type '(repeat (cons (symbol :tag "Shell")
760 (choice (repeat string)
761 (sexp :format "Evaluate: %v"))))
762 :version "24.4" ; bash4 additions
763 :group 'sh-script)
767 (defcustom sh-leading-keywords
768 '((bash sh-append sh
769 "time")
771 (csh "else")
773 (es "true" "unwind-protect" "whatis")
775 (rc "else")
777 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
778 "List of keywords that may be immediately followed by a builtin or keyword.
779 Given some confusion between keywords and builtins depending on shell and
780 system, the distinction here has been based on whether they influence the
781 flow of control or syntax. See `sh-feature'."
782 :type '(repeat (cons (symbol :tag "Shell")
783 (choice (repeat string)
784 (sexp :format "Evaluate: %v"))))
785 :group 'sh-script)
788 (defcustom sh-other-keywords
789 '((bash sh-append bourne
790 "bye" "logout" "select")
792 ;; The next entry is only used for defining the others
793 (bourne sh-append sh
794 "function")
796 (csh sh-append shell
797 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
798 "if" "logout" "onintr" "repeat" "switch" "then" "while")
800 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
801 "return" "throw" "while")
803 (ksh88 sh-append bourne
804 "select")
806 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
807 "while")
809 (sh sh-append shell
810 "done" "esac" "fi" "for" "in" "return")
812 ;; The next entry is only used for defining the others
813 (shell "break" "case" "continue" "exec" "exit")
815 (zsh sh-append bash
816 "select" "foreach"))
817 "List of keywords not in `sh-leading-keywords'.
818 See `sh-feature'."
819 :type '(repeat (cons (symbol :tag "Shell")
820 (choice (repeat string)
821 (sexp :format "Evaluate: %v"))))
822 :group 'sh-script)
826 (defvar sh-variables
827 '((bash sh-append sh
828 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
829 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
830 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
831 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
832 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
833 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
834 "HISTIGNORE" "history_control" "HISTSIZE"
835 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
836 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
837 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
838 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
839 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
840 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
841 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
843 (csh sh-append shell
844 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
845 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
846 "shell" "status" "time" "verbose")
848 (es sh-append shell
849 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
850 "pid" "prompt" "signals")
852 (jcsh sh-append csh
853 "notify")
855 (ksh88 sh-append sh
856 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
857 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
858 "TMOUT")
860 (oash sh-append sh
861 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
863 (rc sh-append shell
864 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
865 "prompt" "status")
867 (sh sh-append shell
868 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
870 ;; The next entry is only used for defining the others
871 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
872 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
873 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
874 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
876 (tcsh sh-append csh
877 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
878 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
879 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
880 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
881 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
882 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
883 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
884 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
885 "wordchars")
887 (zsh sh-append ksh88
888 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
889 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
890 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
891 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
892 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
893 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
894 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
895 "List of all shell variables available for completing read.
896 See `sh-feature'.")
898 \f
899 ;; Font-Lock support
901 (defface sh-heredoc
902 '((((min-colors 88) (class color)
903 (background dark))
904 (:foreground "yellow1" :weight bold))
905 (((class color)
906 (background dark))
907 (:foreground "yellow" :weight bold))
908 (((class color)
909 (background light))
910 (:foreground "tan1" ))
911 (t
912 (:weight bold)))
913 "Face to show a here-document."
914 :group 'sh-indentation)
916 ;; These colors are probably icky. It's just a placeholder though.
917 (defface sh-quoted-exec
918 '((((class color) (background dark))
919 (:foreground "salmon"))
920 (((class color) (background light))
921 (:foreground "magenta"))
922 (t
923 (:weight bold)))
924 "Face to show quoted execs like \\=`blabla\\=`."
925 :group 'sh-indentation)
926 (define-obsolete-face-alias 'sh-heredoc-face 'sh-heredoc "22.1")
927 (defvar sh-heredoc-face 'sh-heredoc)
929 (defface sh-escaped-newline '((t :inherit font-lock-string-face))
930 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
931 :group 'sh-script
932 :version "22.1")
934 (defvar sh-font-lock-keywords-var
935 '((csh sh-append shell
936 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
937 font-lock-variable-name-face))
939 (es sh-append executable-font-lock-keywords
940 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
941 font-lock-variable-name-face))
943 (rc sh-append es)
944 (bash sh-append sh ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
945 (sh sh-append shell
946 ;; Variable names.
947 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
948 font-lock-variable-name-face)
949 ;; Function names.
950 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
951 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
952 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
953 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
954 1 font-lock-negation-char-face))
956 ;; The next entry is only used for defining the others
957 (shell
958 ;; Using font-lock-string-face here confuses sh-get-indent-info.
959 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
960 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
961 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
962 font-lock-variable-name-face))
963 (rpm sh-append rpm2
964 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
965 (rpm2 sh-append shell
966 ("^Summary:\\(.*\\)$" (1 font-lock-doc-face t))
967 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
968 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
970 (defvar sh-font-lock-keywords-var-1
971 '((sh "[ \t]in\\>"))
972 "Subdued level highlighting for Shell Script modes.")
974 (defvar sh-font-lock-keywords-var-2 ()
975 "Gaudy level highlighting for Shell Script modes.")
977 ;; These are used for the syntax table stuff (derived from cperl-mode).
978 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
979 (defconst sh-st-punc (string-to-syntax "."))
980 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
982 (eval-and-compile
983 (defconst sh-escaped-line-re
984 ;; Should match until the real end-of-continued-line, but if that is not
985 ;; possible (because we bump into EOB or the search bound), then we should
986 ;; match until the search bound.
987 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
989 (defconst sh-here-doc-open-re
990 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|[-/~._]\\)+\\)"
991 sh-escaped-line-re "\\(\n\\)")))
993 (defun sh--inside-noncommand-expression (pos)
994 (save-excursion
995 (let ((ppss (syntax-ppss pos)))
996 (when (nth 1 ppss)
997 (goto-char (nth 1 ppss))
998 (or
999 (pcase (char-after)
1000 ;; ((...)) or $((...)) or $[...] or ${...}. Nested
1001 ;; parenthesis can occur inside the first of these forms, so
1002 ;; parse backward recursively.
1003 (`?\( (eq ?\( (char-before)))
1004 ((or `?\{ `?\[) (eq ?\$ (char-before))))
1005 (sh--inside-noncommand-expression (1- (point))))))))
1007 (defun sh-font-lock-open-heredoc (start string eol)
1008 "Determine the syntax of the \\n after a <<EOF.
1009 START is the position of <<.
1010 STRING is the actual word used as delimiter (e.g. \"EOF\").
1011 INDENTED is non-nil if the here document's content (and the EOF mark) can
1012 be indented (i.e. a <<- was used rather than just <<).
1013 Point is at the beginning of the next line."
1014 (unless (or (memq (char-before start) '(?< ?>))
1015 (sh-in-comment-or-string start)
1016 (sh--inside-noncommand-expression start))
1017 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
1018 ;; font-lock keywords to detect the end of this here document.
1019 (let ((str (replace-regexp-in-string "['\"]" "" string))
1020 (ppss (save-excursion (syntax-ppss eol))))
1021 (if (nth 4 ppss)
1022 ;; The \n not only starts the heredoc but also closes a comment.
1023 ;; Let's close the comment just before the \n.
1024 (put-text-property (1- eol) eol 'syntax-table '(12))) ;">"
1025 (if (or (nth 5 ppss) (> (count-lines start eol) 1))
1026 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
1027 ;; several lines, make sure we refontify them together.
1028 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
1029 ;; escaped), it means the right \n is actually further down.
1030 ;; Don't bother fixing it now, but place a multiline property so
1031 ;; that when jit-lock-context-* refontifies the rest of the
1032 ;; buffer, it also refontifies the current line with it.
1033 (put-text-property start (1+ eol) 'syntax-multiline t))
1034 (put-text-property eol (1+ eol) 'sh-here-doc-marker str)
1035 (prog1 sh-here-doc-syntax
1036 (goto-char (+ 2 start))))))
1038 (defun sh-syntax-propertize-here-doc (end)
1039 (let ((ppss (syntax-ppss)))
1040 (when (eq t (nth 3 ppss))
1041 (let ((key (get-text-property (nth 8 ppss) 'sh-here-doc-marker))
1042 (case-fold-search nil))
1043 (when (re-search-forward
1044 (concat "^\\([ \t]*\\)" (regexp-quote key) "\\(\n\\)")
1045 end 'move)
1046 (let ((eol (match-beginning 2)))
1047 (put-text-property eol (1+ eol)
1048 'syntax-table sh-here-doc-syntax)))))))
1050 (defun sh-font-lock-quoted-subshell (limit)
1051 "Search for a subshell embedded in a string.
1052 Find all the unescaped \" characters within said subshell, remembering that
1053 subshells can nest."
1054 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1055 ;; bingo we have a $( or a ` inside a ""
1056 (let (;; `state' can be: double-quote, backquote, code.
1057 (state (if (eq (char-before) ?`) 'backquote 'code))
1058 (startpos (point))
1059 ;; Stacked states in the context.
1060 (states '(double-quote)))
1061 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1062 (< (point) limit)))
1063 ;; unescape " inside a $( ... ) construct.
1064 (pcase (char-after)
1065 (?\' (pcase state
1066 (`double-quote nil)
1067 (_ (forward-char 1) (skip-chars-forward "^'" limit))))
1068 (?\\ (forward-char 1))
1069 (?\" (pcase state
1070 (`double-quote (setq state (pop states)))
1071 (_ (push state states) (setq state 'double-quote)))
1072 (if state (put-text-property (point) (1+ (point))
1073 'syntax-table '(1))))
1074 (?\` (pcase state
1075 (`backquote (setq state (pop states)))
1076 (_ (push state states) (setq state 'backquote))))
1077 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1078 nil
1079 (forward-char 1)
1080 (pcase state
1081 (_ (push state states) (setq state 'code)))))
1082 (?\( (pcase state
1083 (`double-quote nil)
1084 (_ (push state states) (setq state 'code))))
1085 (?\) (pcase state
1086 (`double-quote nil)
1087 (_ (setq state (pop states)))))
1088 (_ (error "Internal error in sh-font-lock-quoted-subshell")))
1089 (forward-char 1))
1090 (when (< startpos (line-beginning-position))
1091 (put-text-property startpos (point) 'syntax-multiline t)
1092 (add-hook 'syntax-propertize-extend-region-functions
1093 'syntax-propertize-multiline nil t))
1094 )))
1097 (defun sh-is-quoted-p (pos)
1098 (and (eq (char-before pos) ?\\)
1099 (not (sh-is-quoted-p (1- pos)))))
1101 (defun sh-font-lock-paren (start)
1102 (unless (nth 8 (syntax-ppss))
1103 (save-excursion
1104 (let ((open nil))
1105 (goto-char start)
1106 ;; Skip through all patterns
1107 (while
1108 (progn
1109 (while
1110 (progn
1111 (forward-comment (- (point-max)))
1112 (when (and (eolp) (sh-is-quoted-p (point)))
1113 (forward-char -1)
1114 t)))
1115 ;; Skip through one pattern
1116 (while
1117 (or (/= 0 (skip-syntax-backward "w_"))
1118 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1119 (and (sh-is-quoted-p (1- (point)))
1120 (goto-char (- (point) 2)))
1121 (when (memq (char-before) '(?\" ?\' ?\}))
1122 (condition-case nil (progn (backward-sexp 1) t)
1123 (error nil)))))
1124 ;; Patterns can be preceded by an open-paren (bug#1320).
1125 (when (eq (char-before (point)) ?\()
1126 (backward-char 1)
1127 (setq open (point)))
1128 (while (progn
1129 (forward-comment (- (point-max)))
1130 ;; Maybe we've bumped into an escaped newline.
1131 (sh-is-quoted-p (point)))
1132 (backward-char 1))
1133 (when (eq (char-before) ?|)
1134 (backward-char 1) t)))
1135 (and (> (point) (1+ (point-min)))
1136 (progn (backward-char 2)
1137 (if (> start (line-end-position))
1138 (put-text-property (point) (1+ start)
1139 'syntax-multiline t))
1140 ;; FIXME: The `in' may just be a random argument to
1141 ;; a normal command rather than the real `in' keyword.
1142 ;; I.e. we should look back to try and find the
1143 ;; corresponding `case'.
1144 (and (looking-at ";[;&]\\|\\_<in")
1145 ;; ";; esac )" is a case that looks
1146 ;; like a case-pattern but it's really just a close
1147 ;; paren after a case statement. I.e. if we skipped
1148 ;; over `esac' just now, we're not looking
1149 ;; at a case-pattern.
1150 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1151 (progn
1152 (when open
1153 (put-text-property open (1+ open) 'syntax-table sh-st-punc))
1154 sh-st-punc))))))
1156 (defun sh-font-lock-backslash-quote ()
1157 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1158 ;; In a '...' the backslash is not escaping.
1159 sh-st-punc
1160 nil))
1162 (defun sh-syntax-propertize-function (start end)
1163 (goto-char start)
1164 (sh-syntax-propertize-here-doc end)
1165 (funcall
1166 (syntax-propertize-rules
1167 (sh-here-doc-open-re
1168 (2 (sh-font-lock-open-heredoc
1169 (match-beginning 0) (match-string 1) (match-beginning 2))))
1170 ("\\s|" (0 (prog1 nil (sh-syntax-propertize-here-doc end))))
1171 ;; A `#' begins a comment when it is unquoted and at the
1172 ;; beginning of a word. In the shell, words are separated by
1173 ;; metacharacters. The list of special chars is taken from
1174 ;; the single-unix spec of the shell command language (under
1175 ;; `quoting') but with `$' removed.
1176 ("\\(?:[^|&;<>()`\\\"' \t\n]\\|\\${\\)\\(#+\\)" (1 "_"))
1177 ;; In a '...' the backslash is not escaping.
1178 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1179 ;; Make sure $@ and $? are correctly recognized as sexps.
1180 ("\\$\\([?@]\\)" (1 "_"))
1181 ;; Distinguish the special close-paren in `case'.
1182 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1183 ;; Highlight (possibly nested) subshells inside "" quoted
1184 ;; regions correctly.
1185 ("\"\\(?:\\(?:[^\\\"]\\|\\\\.\\)*?\\)??\\(\\$(\\|`\\)"
1186 (1 (ignore
1187 (if (nth 8 (save-excursion (syntax-ppss (match-beginning 0))))
1188 (goto-char (1+ (match-beginning 0)))
1189 ;; Save excursion because we want to also apply other
1190 ;; syntax-propertize rules within the affected region.
1191 (save-excursion
1192 (sh-font-lock-quoted-subshell end)))))))
1193 (point) end))
1194 (defun sh-font-lock-syntactic-face-function (state)
1195 (let ((q (nth 3 state)))
1196 (if q
1197 (if (characterp q)
1198 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1199 sh-heredoc-face)
1200 font-lock-comment-face)))
1202 (defgroup sh-indentation nil
1203 "Variables controlling indentation in shell scripts.
1205 Note: customizing these variables will not affect existing buffers if
1206 `sh-make-vars-local' is non-nil. See the documentation for
1207 variable `sh-make-vars-local', command `sh-make-vars-local'
1208 and command `sh-reset-indent-vars-to-global-values'."
1209 :group 'sh-script)
1212 (defcustom sh-set-shell-hook nil
1213 "Hook run by `sh-set-shell'."
1214 :type 'hook
1215 :group 'sh-script)
1217 (defcustom sh-mode-hook nil
1218 "Hook run by `sh-mode'."
1219 :type 'hook
1220 :group 'sh-script)
1222 (defcustom sh-learn-basic-offset nil
1223 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1225 nil mean: never.
1226 t means: only if there seems to be an obvious value.
1227 Anything else means: whenever we have a \"good guess\" as to the value."
1228 :type '(choice
1229 (const :tag "Never" nil)
1230 (const :tag "Only if sure" t)
1231 (const :tag "If have a good guess" usually))
1232 :group 'sh-indentation)
1234 (defcustom sh-popup-occur-buffer nil
1235 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1236 If t it is always shown. If nil, it is shown only when there
1237 are conflicts."
1238 :type '(choice
1239 (const :tag "Only when there are conflicts." nil)
1240 (const :tag "Always" t))
1241 :group 'sh-indentation)
1243 (defcustom sh-blink t
1244 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1245 The position on the line is not necessarily meaningful.
1246 In some cases the line will be the matching keyword, but this is not
1247 always the case."
1248 :type 'boolean
1249 :group 'sh-indentation)
1251 (defcustom sh-first-lines-indent 0
1252 "The indentation of the first non-blank non-comment line.
1253 Usually 0 meaning first column.
1254 Can be set to a number, or to nil which means leave it as is."
1255 :type '(choice
1256 (const :tag "Leave as is" nil)
1257 (integer :tag "Column number"
1258 :menu-tag "Indent to this col (0 means first col)" ))
1259 :group 'sh-indentation)
1262 (defcustom sh-basic-offset 4
1263 "The default indentation increment.
1264 This value is used for the `+' and `-' symbols in an indentation variable."
1265 :type 'integer
1266 :group 'sh-indentation)
1267 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1269 (defcustom sh-indent-comment t
1270 "How a comment line is to be indented.
1271 nil means leave it as it is;
1272 t means indent it as a normal line, aligning it to previous non-blank
1273 non-comment line;
1274 a number means align to that column, e.g. 0 means first column."
1275 :type '(choice
1276 (const :tag "Leave as is." nil)
1277 (const :tag "Indent as a normal line." t)
1278 (integer :menu-tag "Indent to this col (0 means first col)."
1279 :tag "Indent to column number.") )
1280 :version "24.3"
1281 :group 'sh-indentation)
1284 (defvar sh-debug nil
1285 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1288 ;; Uncomment this defun and comment the defmacro for debugging.
1289 ;; (defun sh-debug (&rest args)
1290 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1291 ;; (if sh-debug
1292 ;; (apply 'message args)))
1293 (defmacro sh-debug (&rest _args))
1295 (defconst sh-symbol-list
1296 '((const :tag "+ " :value +
1297 :menu-tag "+ Indent right by sh-basic-offset")
1298 (const :tag "- " :value -
1299 :menu-tag "- Indent left by sh-basic-offset")
1300 (const :tag "++" :value ++
1301 :menu-tag "++ Indent right twice sh-basic-offset")
1302 (const :tag "--" :value --
1303 :menu-tag "-- Indent left twice sh-basic-offset")
1304 (const :tag "* " :value *
1305 :menu-tag "* Indent right half sh-basic-offset")
1306 (const :tag "/ " :value /
1307 :menu-tag "/ Indent left half sh-basic-offset")))
1309 (defcustom sh-indent-for-else 0
1310 "How much to indent an `else' relative to its `if'. Usually 0."
1311 :type `(choice
1312 (integer :menu-tag "A number (positive=>indent right)"
1313 :tag "A number")
1314 (const :tag "--") ;; separator!
1315 ,@ sh-symbol-list
1317 :group 'sh-indentation)
1319 (defconst sh-number-or-symbol-list
1320 (append '((integer :menu-tag "A number (positive=>indent right)"
1321 :tag "A number")
1322 (const :tag "--")) ; separator
1323 sh-symbol-list))
1325 (defcustom sh-indent-for-fi 0
1326 "How much to indent a `fi' relative to its `if'. Usually 0."
1327 :type `(choice ,@ sh-number-or-symbol-list )
1328 :group 'sh-indentation)
1330 (defcustom sh-indent-for-done 0
1331 "How much to indent a `done' relative to its matching stmt. Usually 0."
1332 :type `(choice ,@ sh-number-or-symbol-list )
1333 :group 'sh-indentation)
1335 (defcustom sh-indent-after-else '+
1336 "How much to indent a statement after an `else' statement."
1337 :type `(choice ,@ sh-number-or-symbol-list )
1338 :group 'sh-indentation)
1340 (defcustom sh-indent-after-if '+
1341 "How much to indent a statement after an `if' statement.
1342 This includes lines after `else' and `elif' statements, too, but
1343 does not affect the `else', `elif' or `fi' statements themselves."
1344 :type `(choice ,@ sh-number-or-symbol-list )
1345 :group 'sh-indentation)
1347 (defcustom sh-indent-for-then 0
1348 "How much to indent a `then' relative to its `if'."
1349 :type `(choice ,@ sh-number-or-symbol-list )
1350 :group 'sh-indentation)
1352 (defcustom sh-indent-for-do 0
1353 "How much to indent a `do' statement.
1354 This is relative to the statement before the `do', typically a
1355 `while', `until', `for', `repeat' or `select' statement."
1356 :type `(choice ,@ sh-number-or-symbol-list)
1357 :group 'sh-indentation)
1359 (defcustom sh-indent-after-do '+
1360 "How much to indent a line after a `do' statement.
1361 This is used when the `do' is the first word of the line.
1362 This is relative to the statement before the `do', typically a
1363 `while', `until', `for', `repeat' or `select' statement."
1364 :type `(choice ,@ sh-number-or-symbol-list)
1365 :group 'sh-indentation)
1367 (defcustom sh-indent-after-loop-construct '+
1368 "How much to indent a statement after a loop construct.
1370 This variable is used when the keyword `do' is on the same line as the
1371 loop statement (e.g., `until', `while' or `for').
1372 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1373 :type `(choice ,@ sh-number-or-symbol-list)
1374 :group 'sh-indentation)
1377 (defcustom sh-indent-after-done 0
1378 "How much to indent a statement after a `done' keyword.
1379 Normally this is 0, which aligns the `done' to the matching
1380 looping construct line.
1381 Setting it non-zero allows you to have the `do' statement on a line
1382 by itself and align the done under to do."
1383 :type `(choice ,@ sh-number-or-symbol-list)
1384 :group 'sh-indentation)
1386 (defcustom sh-indent-for-case-label '+
1387 "How much to indent a case label statement.
1388 This is relative to the line containing the `case' statement."
1389 :type `(choice ,@ sh-number-or-symbol-list)
1390 :group 'sh-indentation)
1392 (defcustom sh-indent-for-case-alt '++
1393 "How much to indent statements after the case label.
1394 This is relative to the line containing the `case' statement."
1395 :type `(choice ,@ sh-number-or-symbol-list)
1396 :group 'sh-indentation)
1399 (defcustom sh-indent-for-continuation '+
1400 "How much to indent for a continuation statement."
1401 :type `(choice ,@ sh-number-or-symbol-list)
1402 :group 'sh-indentation)
1404 (defcustom sh-indent-after-open '+
1405 "How much to indent after a line with an opening parenthesis or brace.
1406 For an open paren after a function, `sh-indent-after-function' is used."
1407 :type `(choice ,@ sh-number-or-symbol-list)
1408 :group 'sh-indentation)
1410 (defcustom sh-indent-after-function '+
1411 "How much to indent after a function line."
1412 :type `(choice ,@ sh-number-or-symbol-list)
1413 :group 'sh-indentation)
1415 ;; These 2 are for the rc shell:
1417 (defcustom sh-indent-after-switch '+
1418 "How much to indent a `case' statement relative to the `switch' statement.
1419 This is for the rc shell."
1420 :type `(choice ,@ sh-number-or-symbol-list)
1421 :group 'sh-indentation)
1423 (defcustom sh-indent-after-case '+
1424 "How much to indent a statement relative to the `case' statement.
1425 This is for the rc shell."
1426 :type `(choice ,@ sh-number-or-symbol-list)
1427 :group 'sh-indentation)
1429 (defcustom sh-backslash-column 48
1430 "Column in which `sh-backslash-region' inserts backslashes."
1431 :type 'integer
1432 :group 'sh)
1434 (defcustom sh-backslash-align t
1435 "If non-nil, `sh-backslash-region' will align backslashes."
1436 :type 'boolean
1437 :group 'sh)
1439 ;; Internal use - not designed to be changed by the user:
1441 (defun sh-mkword-regexpr (word)
1442 "Make a regexp which matches WORD as a word.
1443 This specifically excludes an occurrence of WORD followed by
1444 punctuation characters like '-'."
1445 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1447 (defconst sh-re-done (sh-mkword-regexpr "done"))
1450 (defconst sh-kws-for-done
1451 '((sh . ( "while" "until" "for" ) )
1452 (bash . ( "while" "until" "for" "select" ) )
1453 (ksh88 . ( "while" "until" "for" "select" ) )
1454 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1455 "Which keywords can match the word `done' in this shell.")
1458 (defconst sh-indent-supported
1459 '((sh . sh)
1460 (csh . nil)
1461 (rc . rc))
1462 "Indentation rule set to use for each shell type.")
1464 (defvar sh-indent-supported-here nil
1465 "Non-nil if we support indentation for the current buffer's shell type.")
1467 (defconst sh-var-list
1468 '(
1469 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1470 sh-indent-after-do sh-indent-after-done
1471 sh-indent-after-else
1472 sh-indent-after-if
1473 sh-indent-after-loop-construct
1474 sh-indent-after-open
1475 sh-indent-comment
1476 sh-indent-for-case-alt
1477 sh-indent-for-case-label
1478 sh-indent-for-continuation
1479 sh-indent-for-do
1480 sh-indent-for-done
1481 sh-indent-for-else
1482 sh-indent-for-fi
1483 sh-indent-for-then
1485 "A list of variables used by script mode to control indentation.
1486 This list is used when switching between buffer-local and global
1487 values of variables, and for the commands using indentation styles.")
1489 (defvar sh-make-vars-local t
1490 "Controls whether indentation variables are local to the buffer.
1491 If non-nil, indentation variables are made local initially.
1492 If nil, you can later make the variables local by invoking
1493 command `sh-make-vars-local'.
1494 The default is t because I assume that in one Emacs session one is
1495 frequently editing existing scripts with different styles.")
1497 \f
1498 ;; inferior shell interaction
1499 ;; TODO: support multiple interactive shells
1500 (defvar-local sh-shell-process nil
1501 "The inferior shell process for interaction.")
1503 (defvar explicit-shell-file-name)
1505 (defun sh-shell-process (force)
1506 "Get a shell process for interaction.
1507 If FORCE is non-nil and no process found, create one."
1508 (if (process-live-p sh-shell-process)
1509 sh-shell-process
1510 (setq sh-shell-process
1511 (let ((found nil) proc
1512 (procs (process-list)))
1513 (while (and (not found) procs
1514 (process-live-p (setq proc (pop procs)))
1515 (process-command proc))
1516 (when (string-equal sh-shell (file-name-nondirectory
1517 (car (process-command proc))))
1518 (setq found proc)))
1519 (or found
1520 (and force
1521 (get-buffer-process
1522 (let ((explicit-shell-file-name sh-shell-file))
1523 (shell)))))))))
1525 (defun sh-show-shell ()
1526 "Pop the shell interaction buffer."
1527 (interactive)
1528 (pop-to-buffer (process-buffer (sh-shell-process t))))
1530 (defun sh-send-text (text)
1531 "Send the text to the `sh-shell-process'."
1532 (comint-send-string (sh-shell-process t) (concat text "\n")))
1534 (defun sh-cd-here ()
1535 "Change directory in the current interaction shell to the current one."
1536 (interactive)
1537 (sh-send-text (concat "cd " default-directory)))
1539 (defun sh-send-line-or-region-and-step ()
1540 "Send the current line to the inferior shell and step to the next line.
1541 When the region is active, send the region instead."
1542 (interactive)
1543 (let (from to end)
1544 (if (use-region-p)
1545 (setq from (region-beginning)
1546 to (region-end)
1547 end to)
1548 (setq from (line-beginning-position)
1549 to (line-end-position)
1550 end (1+ to)))
1551 (sh-send-text (buffer-substring-no-properties from to))
1552 (goto-char end)))
1554 \f
1555 ;; mode-command and utility functions
1557 (defun sh-after-hack-local-variables ()
1558 (when (assq 'sh-shell file-local-variables-alist)
1559 (sh-set-shell (if (symbolp sh-shell)
1560 (symbol-name sh-shell)
1561 sh-shell))))
1563 ;;;###autoload
1564 (define-derived-mode sh-mode prog-mode "Shell-script"
1565 "Major mode for editing shell scripts.
1566 This mode works for many shells, since they all have roughly the same syntax,
1567 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1568 Unless the file's magic number indicates the shell, your usual shell is
1569 assumed. Since filenames rarely give a clue, they are not further analyzed.
1571 This mode adapts to the variations between shells (see `sh-set-shell') by
1572 means of an inheritance based feature lookup (see `sh-feature'). This
1573 mechanism applies to all variables (including skeletons) that pertain to
1574 shell-specific features.
1576 The default style of this mode is that of Rosenblatt's Korn shell book.
1577 The syntax of the statements varies with the shell being used. The
1578 following commands are available, based on the current shell's syntax:
1579 \\<sh-mode-map>
1580 \\[sh-case] case statement
1581 \\[sh-for] for loop
1582 \\[sh-function] function definition
1583 \\[sh-if] if statement
1584 \\[sh-indexed-loop] indexed loop from 1 to n
1585 \\[sh-while-getopts] while getopts loop
1586 \\[sh-repeat] repeat loop
1587 \\[sh-select] select loop
1588 \\[sh-until] until loop
1589 \\[sh-while] while loop
1591 For sh and rc shells indentation commands are:
1592 \\[sh-show-indent] Show the variable controlling this line's indentation.
1593 \\[sh-set-indent] Set then variable controlling this line's indentation.
1594 \\[sh-learn-line-indent] Change the indentation variable so this line
1595 would indent to the way it currently is.
1596 \\[sh-learn-buffer-indent] Set the indentation variables so the
1597 buffer indents as it currently is indented.
1600 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1601 \\[sh-end-of-command] Go to end of successive commands.
1602 \\[sh-beginning-of-command] Go to beginning of successive commands.
1603 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1604 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1606 `sh-electric-here-document-mode' controls whether insertion of two
1607 unquoted < insert a here document.
1609 If you generally program a shell different from your login shell you can
1610 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1611 indicate what shell it is use `sh-alias-alist' to translate.
1613 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1614 with your script for an edit-interpret-debug cycle."
1615 (make-local-variable 'sh-shell-file)
1616 (make-local-variable 'sh-shell)
1618 (setq-local skeleton-pair-default-alist
1619 sh-skeleton-pair-default-alist)
1620 (setq-local skeleton-end-hook
1621 (lambda () (or (eolp) (newline) (indent-relative))))
1623 (setq-local paragraph-start (concat page-delimiter "\\|$"))
1624 (setq-local paragraph-separate (concat paragraph-start "\\|#!/"))
1625 (setq-local comment-start "# ")
1626 (setq-local comment-start-skip "#+[\t ]*")
1627 (setq-local local-abbrev-table sh-mode-abbrev-table)
1628 (setq-local comint-dynamic-complete-functions
1629 sh-dynamic-complete-functions)
1630 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t)
1631 ;; we can't look if previous line ended with `\'
1632 (setq-local comint-prompt-regexp "^[ \t]*")
1633 (setq-local imenu-case-fold-search nil)
1634 (setq font-lock-defaults
1635 `((sh-font-lock-keywords
1636 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1637 nil nil
1638 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1639 (font-lock-syntactic-face-function
1640 . sh-font-lock-syntactic-face-function)))
1641 (setq-local syntax-propertize-function #'sh-syntax-propertize-function)
1642 (add-hook 'syntax-propertize-extend-region-functions
1643 #'syntax-propertize-multiline 'append 'local)
1644 (sh-electric-here-document-mode 1)
1645 (setq-local skeleton-pair-alist '((?` _ ?`)))
1646 (setq-local skeleton-pair-filter-function 'sh-quoted-p)
1647 (setq-local skeleton-further-elements
1648 '((< '(- (min sh-indentation (current-column))))))
1649 (setq-local skeleton-filter-function 'sh-feature)
1650 (setq-local skeleton-newline-indent-rigidly t)
1651 (setq-local defun-prompt-regexp
1652 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1653 (setq-local add-log-current-defun-function #'sh-current-defun-name)
1654 (add-hook 'completion-at-point-functions
1655 #'sh-completion-at-point-function nil t)
1656 ;; Parse or insert magic number for exec, and set all variables depending
1657 ;; on the shell thus determined.
1658 (sh-set-shell
1659 (cond ((save-excursion
1660 (goto-char (point-min))
1661 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1662 (match-string 2))
1663 ((not buffer-file-name) sh-shell-file)
1664 ;; Checks that use `buffer-file-name' follow.
1665 ((string-match "\\.m?spec\\'" buffer-file-name) "rpm")
1666 ((string-match "[.]sh\\>" buffer-file-name) "sh")
1667 ((string-match "[.]bash\\>" buffer-file-name) "bash")
1668 ((string-match "[.]ksh\\>" buffer-file-name) "ksh")
1669 ((string-match "[.]csh\\>" buffer-file-name) "csh")
1670 ((equal (file-name-nondirectory buffer-file-name) ".profile") "sh")
1671 (t sh-shell-file))
1672 nil nil)
1673 (add-hook 'hack-local-variables-hook
1674 #'sh-after-hack-local-variables nil t))
1676 ;;;###autoload
1677 (defalias 'shell-script-mode 'sh-mode)
1680 (defun sh-font-lock-keywords (&optional keywords)
1681 "Function to get simple fontification based on `sh-font-lock-keywords'.
1682 This adds rules for comments and assignments."
1683 (sh-feature sh-font-lock-keywords-var
1684 (when (stringp (sh-feature sh-assignment-regexp))
1685 (lambda (list)
1686 `((,(sh-feature sh-assignment-regexp)
1687 1 font-lock-variable-name-face)
1688 ,@keywords
1689 ,@list
1690 ,@executable-font-lock-keywords)))))
1692 (defun sh-font-lock-keywords-1 (&optional builtins)
1693 "Function to get better fontification including keywords."
1694 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1695 (regexp-opt (sh-feature sh-leading-keywords) t)
1696 "[ \t]+\\)?"
1697 (regexp-opt (append (sh-feature sh-leading-keywords)
1698 (sh-feature sh-other-keywords))
1699 t))))
1700 (sh-font-lock-keywords
1701 `(,@(if builtins
1702 `((,(concat keywords "[ \t]+\\)?"
1703 (regexp-opt (sh-feature sh-builtins) t)
1704 "\\>")
1705 (2 font-lock-keyword-face nil t)
1706 (6 font-lock-builtin-face))
1707 ,@(sh-feature sh-font-lock-keywords-var-2)))
1708 (,(concat keywords "\\)\\>")
1709 2 font-lock-keyword-face)
1710 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1712 (defun sh-font-lock-keywords-2 ()
1713 "Function to get better fontification including keywords and builtins."
1714 (sh-font-lock-keywords-1 t))
1716 ;;; Completion
1718 (defun sh--vars-before-point ()
1719 (save-excursion
1720 (let ((vars ()))
1721 (while (re-search-backward "^[ \t]*\\([[:alnum:]_]+\\)=" nil t)
1722 (push (match-string 1) vars))
1723 vars)))
1725 ;; (defun sh--var-completion-table (string pred action)
1726 ;; (complete-with-action action (sh--vars-before-point) string pred))
1728 (defun sh--cmd-completion-table (string pred action)
1729 (let ((cmds
1730 (append (when (fboundp 'imenu--make-index-alist)
1731 (mapcar #'car (imenu--make-index-alist)))
1732 (mapcar (lambda (v) (concat v "="))
1733 (sh--vars-before-point))
1734 (locate-file-completion-table
1735 exec-path exec-suffixes string pred t)
1736 '("if" "while" "until" "for"))))
1737 (complete-with-action action cmds string pred)))
1739 (defun sh-completion-at-point-function ()
1740 (save-excursion
1741 (skip-chars-forward "[:alnum:]_")
1742 (let ((end (point))
1743 (_ (skip-chars-backward "[:alnum:]_"))
1744 (start (point)))
1745 (cond
1746 ((eq (char-before) ?$)
1747 (list start end (sh--vars-before-point)))
1748 ((sh-smie--keyword-p)
1749 (list start end #'sh--cmd-completion-table))))))
1751 ;;; Indentation and navigation with SMIE.
1753 (require 'smie)
1755 ;; The SMIE code should generally be preferred, but it currently does not obey
1756 ;; the various indentation custom-vars, and it misses some important features
1757 ;; of the old code, mostly: sh-learn-line/buffer-indent, sh-show-indent,
1758 ;; sh-name/save/load-style.
1759 (defvar sh-use-smie t
1760 "Whether to use the SMIE code for navigation and indentation.")
1762 (defun sh-smie--keyword-p ()
1763 "Non-nil if we're at a keyword position.
1764 A keyword position is one where if we're looking at something that looks
1765 like a keyword, then it is a keyword."
1766 (let ((prev (funcall smie-backward-token-function)))
1767 (if (zerop (length prev))
1768 (looking-back "\\`\\|\\s(" (1- (point)))
1769 (assoc prev smie-grammar))))
1771 (defun sh-smie--newline-semi-p (&optional tok)
1772 "Return non-nil if a newline should be treated as a semi-colon.
1773 Here we assume that a newline should be treated as a semi-colon unless it
1774 comes right after a special keyword.
1775 This function does not pay attention to line-continuations.
1776 If TOK is nil, point should be before the newline; otherwise, TOK is the token
1777 before the newline and in that case point should be just before the token."
1778 (save-excursion
1779 (unless tok
1780 (setq tok (funcall smie-backward-token-function)))
1781 (if (and (zerop (length tok))
1782 (looking-back "\\s(" (1- (point))))
1783 nil
1784 (not (numberp (nth 2 (assoc tok smie-grammar)))))))
1786 ;;;; SMIE support for `sh'.
1788 (defconst sh-smie-sh-grammar
1789 (smie-prec2->grammar
1790 (smie-bnf->prec2
1791 '((exp) ;A constant, or a $var, or a sequence of them...
1792 (cmd ("case" exp "in" branches "esac")
1793 ("if" cmd "then" cmd "fi")
1794 ("if" cmd "then" cmd "else" cmd "fi")
1795 ("if" cmd "then" cmd "elif" cmd "then" cmd "fi")
1796 ("if" cmd "then" cmd "elif" cmd "then" cmd "else" cmd "fi")
1797 ("if" cmd "then" cmd "elif" cmd "then" cmd
1798 "elif" cmd "then" cmd "else" cmd "fi")
1799 ("while" cmd "do" cmd "done")
1800 ("until" cmd "do" cmd "done")
1801 ("for" exp "in" cmd "do" cmd "done")
1802 ("for" exp "do" cmd "done")
1803 ("select" exp "in" cmd "do" cmd "done") ;bash&zsh&ksh88.
1804 ("repeat" exp "do" cmd "done") ;zsh.
1805 (exp "always" exp) ;zsh.
1806 (cmd "|" cmd) (cmd "|&" cmd)
1807 (cmd "&&" cmd) (cmd "||" cmd)
1808 (cmd ";" cmd) (cmd "&" cmd))
1809 (rpattern (rpattern "|" rpattern))
1810 (pattern (rpattern) ("case-(" rpattern))
1811 (branches (branches ";;" branches)
1812 (branches ";&" branches) (branches ";;&" branches) ;bash.
1813 (pattern "case-)" cmd)))
1814 '((assoc ";;" ";&" ";;&"))
1815 '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1817 (defconst sh-smie--sh-operators
1818 (delq nil (mapcar (lambda (x)
1819 (setq x (car x))
1820 (and (stringp x)
1821 (not (string-match "\\`[a-z]" x))
1822 x))
1823 sh-smie-sh-grammar)))
1825 (defconst sh-smie--sh-operators-re (regexp-opt sh-smie--sh-operators))
1826 (defconst sh-smie--sh-operators-back-re
1827 (concat "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*"
1828 "\\(" sh-smie--sh-operators-re "\\)"))
1830 (defun sh-smie--sh-keyword-in-p ()
1831 "Assuming we're looking at \"in\", return non-nil if it's a keyword.
1832 Does not preserve point."
1833 (let ((forward-sexp-function nil)
1834 (words nil) ;We've seen words.
1835 (newline nil) ;We've seen newlines after the words.
1836 (res nil)
1837 prev)
1838 (while (not res)
1839 (setq prev (funcall smie-backward-token-function))
1840 (cond
1841 ((zerop (length prev))
1842 (cond
1843 (newline (cl-assert words) (setq res 'word))
1844 ((bobp) (setq res 'word))
1845 (t
1846 (setq words t)
1847 (condition-case nil
1848 (forward-sexp -1)
1849 (scan-error (setq res 'unknown))))))
1850 ((equal prev ";")
1851 (if words (setq newline t)
1852 (setq res 'keyword)))
1853 ((member prev '("case" "for" "select")) (setq res 'keyword))
1854 ((assoc prev smie-grammar) (setq res 'word))
1855 (t
1856 (if newline
1857 (progn (cl-assert words) (setq res 'word))
1858 (setq words t)))))
1859 (eq res 'keyword)))
1861 (defun sh-smie--sh-keyword-p (tok)
1862 "Non-nil if TOK (at which we're looking) really is a keyword."
1863 (cond
1864 ((looking-at "[[:alnum:]_]+=") nil)
1865 ((equal tok "in") (sh-smie--sh-keyword-in-p))
1866 (t (sh-smie--keyword-p))))
1868 (defun sh-smie--default-forward-token ()
1869 (forward-comment (point-max))
1870 (buffer-substring-no-properties
1871 (point)
1872 (progn (if (zerop (skip-syntax-forward "."))
1873 (while (progn (skip-syntax-forward "w_'")
1874 (looking-at "\\\\"))
1875 (forward-char 2)))
1876 (point))))
1878 (defun sh-smie--default-backward-token ()
1879 (forward-comment (- (point)))
1880 (let ((pos (point))
1881 (n (skip-syntax-backward ".")))
1882 (if (or (zerop n)
1883 (and (eq n -1)
1884 (let ((p (point)))
1885 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1887 (goto-char p)
1888 nil))))
1889 (while
1890 (progn (skip-syntax-backward "w_'")
1891 (or (not (zerop (skip-syntax-backward "\\")))
1892 (when (eq ?\\ (char-before (1- (point))))
1893 (let ((p (point)))
1894 (forward-char -1)
1895 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1897 (goto-char p)
1898 nil))))))
1899 (goto-char (- (point) (% (skip-syntax-backward "\\") 2))))
1900 (buffer-substring-no-properties (point) pos)))
1902 (defun sh-smie-sh-forward-token ()
1903 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1904 (save-excursion
1905 (skip-chars-backward " \t")
1906 (not (bolp))))
1907 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1908 ;; Right before a here-doc.
1909 (let ((forward-sexp-function nil))
1910 (forward-sexp 1)
1911 ;; Pretend the here-document is a "newline representing a
1912 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1913 ";")
1914 (let ((semi (sh-smie--newline-semi-p)))
1915 (forward-line 1)
1916 (if (or semi (eobp)) ";"
1917 (sh-smie-sh-forward-token))))
1918 (forward-comment (point-max))
1919 (cond
1920 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1921 ((looking-at sh-smie--sh-operators-re)
1922 (goto-char (match-end 0))
1923 (let ((tok (match-string-no-properties 0)))
1924 (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1925 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1926 (forward-line 1))
1927 tok))
1928 (t
1929 (let* ((pos (point))
1930 (tok (sh-smie--default-forward-token)))
1931 (cond
1932 ((equal tok ")") "case-)")
1933 ((equal tok "(") "case-(")
1934 ((and tok (string-match "\\`[a-z]" tok)
1935 (assoc tok smie-grammar)
1936 (not
1937 (save-excursion
1938 (goto-char pos)
1939 (sh-smie--sh-keyword-p tok))))
1940 " word ")
1941 (t tok)))))))
1943 (defun sh-smie--looking-back-at-continuation-p ()
1944 (save-excursion
1945 (and (if (eq (char-before) ?\n) (progn (forward-char -1) t) (eolp))
1946 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1947 (line-beginning-position)))))
1949 (defun sh-smie-sh-backward-token ()
1950 (let ((bol (line-beginning-position)))
1951 (forward-comment (- (point)))
1952 (cond
1953 ((and (bolp) (not (bobp))
1954 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1955 (not (nth 3 (syntax-ppss))))
1956 ;; Right after a here-document.
1957 (let ((forward-sexp-function nil))
1958 (forward-sexp -1)
1959 ;; Pretend the here-document is a "newline representing a
1960 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1961 ";"))
1962 ((< (point) bol)
1963 (cond
1964 ((sh-smie--looking-back-at-continuation-p)
1965 (forward-char -1)
1966 (funcall smie-backward-token-function))
1967 ((sh-smie--newline-semi-p) ";")
1968 (t (funcall smie-backward-token-function))))
1969 ((looking-back sh-smie--sh-operators-back-re
1970 (line-beginning-position) 'greedy)
1971 (goto-char (match-beginning 1))
1972 (match-string-no-properties 1))
1973 (t
1974 (let ((tok (sh-smie--default-backward-token)))
1975 (cond
1976 ((equal tok ")") "case-)")
1977 ((equal tok "(") "case-(")
1978 ((and tok (string-match "\\`[a-z]" tok)
1979 (assoc tok smie-grammar)
1980 (not (save-excursion (sh-smie--sh-keyword-p tok))))
1981 " word ")
1982 (t tok)))))))
1984 (defcustom sh-indent-after-continuation t
1985 "If non-nil, try to make sure text is indented after a line continuation."
1986 :version "24.3"
1987 :type 'boolean
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-sh-rules (kind token)
1999 (pcase (cons kind token)
2000 (`(:elem . basic) sh-indentation)
2001 (`(:after . "case-)") (- (sh-var-value 'sh-indent-for-case-alt)
2002 (sh-var-value 'sh-indent-for-case-label)))
2003 ((and `(:before . ,_)
2004 ;; After a line-continuation, make sure the rest is indented.
2005 (guard sh-indent-after-continuation)
2006 (guard (save-excursion
2007 (ignore-errors
2008 (skip-chars-backward " \t")
2009 (sh-smie--looking-back-at-continuation-p))))
2010 (let initial (sh-smie--continuation-start-indent))
2011 (guard (let* ((sh-indent-after-continuation nil)
2012 (indent (smie-indent-calculate)))
2013 (and (numberp indent) (numberp initial)
2014 (<= indent initial)))))
2015 `(column . ,(+ initial sh-indentation)))
2016 (`(:before . ,(or `"(" `"{" `"[" "while" "if" "for" "case"))
2017 (if (not (smie-rule-prev-p "&&" "||" "|"))
2018 (when (smie-rule-hanging-p)
2019 (smie-rule-parent))
2020 (unless (smie-rule-bolp)
2021 (while (equal "|" (nth 2 (smie-backward-sexp 'halfexp))))
2022 `(column . ,(smie-indent-virtual)))))
2023 ;; FIXME: Maybe this handling of ;; should be made into
2024 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
2025 (`(:before . ,(or `";;" `";&" `";;&"))
2026 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
2027 (cons 'column (smie-indent-keyword ";"))
2028 (smie-rule-separator kind)))
2029 (`(:after . ,(or `";;" `";&" `";;&"))
2030 (with-demoted-errors
2031 (smie-backward-sexp token)
2032 (cons 'column
2033 (if (or (smie-rule-bolp)
2034 (save-excursion
2035 (and (member (funcall smie-backward-token-function)
2036 '("in" ";;"))
2037 (smie-rule-bolp))))
2038 (current-column)
2039 (smie-indent-calculate)))))
2040 (`(:before . ,(or `"|" `"&&" `"||"))
2041 (unless (smie-rule-parent-p token)
2042 (smie-backward-sexp token)
2043 `(column . ,(+ (funcall smie-rules-function :elem 'basic)
2044 (smie-indent-virtual)))))
2046 ;; Attempt at backward compatibility with the old config variables.
2047 (`(:before . "fi") (sh-var-value 'sh-indent-for-fi))
2048 (`(:before . "done") (sh-var-value 'sh-indent-for-done))
2049 (`(:after . "else") (sh-var-value 'sh-indent-after-else))
2050 (`(:after . "if") (sh-var-value 'sh-indent-after-if))
2051 (`(:before . "then") (sh-var-value 'sh-indent-for-then))
2052 (`(:before . "do") (sh-var-value 'sh-indent-for-do))
2053 (`(:after . "do")
2054 (sh-var-value (if (smie-rule-hanging-p)
2055 'sh-indent-after-loop-construct 'sh-indent-after-do)))
2056 ;; sh-indent-after-done: aligned completely differently.
2057 (`(:after . "in") (sh-var-value 'sh-indent-for-case-label))
2058 ;; sh-indent-for-continuation: Line continuations are handled differently.
2059 (`(:after . ,(or `"(" `"{" `"[")) (sh-var-value 'sh-indent-after-open))
2060 ;; sh-indent-after-function: we don't handle it differently.
2061 ))
2063 ;; (defconst sh-smie-csh-grammar
2064 ;; (smie-prec2->grammar
2065 ;; (smie-bnf->prec2
2066 ;; '((exp) ;A constant, or a $var, or a sequence of them...
2067 ;; (elseifcmd (cmd)
2068 ;; (cmd "else" "else-if" exp "then" elseifcmd))
2069 ;; (cmd ("switch" branches "endsw")
2070 ;; ("if" exp)
2071 ;; ("if" exp "then" cmd "endif")
2072 ;; ("if" exp "then" cmd "else" cmd "endif")
2073 ;; ("if" exp "then" elseifcmd "endif")
2074 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
2075 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2076 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2077 ;; ;; "else" cmd "endif")
2078 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2079 ;; ;; "else" "if" exp "then" cmd "endif")
2080 ;; ("while" cmd "end")
2081 ;; ("foreach" cmd "end")
2082 ;; (cmd "|" cmd) (cmd "|&" cmd)
2083 ;; (cmd "&&" cmd) (cmd "||" cmd)
2084 ;; (cmd ";" cmd) (cmd "&" cmd))
2085 ;; ;; This is a lie, but (combined with the corresponding disambiguation
2086 ;; ;; rule) it makes it more clear that `case' and `default' are the key
2087 ;; ;; separators and the `:' is a secondary tokens.
2088 ;; (branches (branches "case" branches)
2089 ;; (branches "default" branches)
2090 ;; (exp ":" branches)))
2091 ;; '((assoc "else" "then" "endif"))
2092 ;; '((assoc "case" "default") (nonassoc ":"))
2093 ;; '((assoc ";;" ";&" ";;&"))
2094 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2096 ;;;; SMIE support for `rc'.
2098 (defconst sh-smie-rc-grammar
2099 (smie-prec2->grammar
2100 (smie-bnf->prec2
2101 '((exp) ;A constant, or a $var, or a sequence of them...
2102 (cmd (cmd "case" cmd)
2103 ("if" exp)
2104 ("switch" exp)
2105 ("for" exp) ("while" exp)
2106 (cmd "|" cmd) (cmd "|&" cmd)
2107 (cmd "&&" cmd) (cmd "||" cmd)
2108 (cmd ";" cmd) (cmd "&" cmd))
2109 (pattern (pattern "|" pattern))
2110 (branches (branches ";;" branches)
2111 (branches ";&" branches) (branches ";;&" branches) ;bash.
2112 (pattern "case-)" cmd)))
2113 '((assoc ";;" ";&" ";;&"))
2114 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2116 (defun sh-smie--rc-after-special-arg-p ()
2117 "Check if we're after the first arg of an if/while/for/... construct.
2118 Returns the construct's token and moves point before it, if so."
2119 (forward-comment (- (point)))
2120 (when (looking-back ")\\|\\_<not" (- (point) 3))
2121 (ignore-errors
2122 (let ((forward-sexp-function nil))
2123 (forward-sexp -1)
2124 (car (member (funcall smie-backward-token-function)
2125 '("if" "for" "switch" "while")))))))
2127 (defun sh-smie--rc-newline-semi-p ()
2128 "Return non-nil if a newline should be treated as a semi-colon.
2129 Point should be before the newline."
2130 (save-excursion
2131 (let ((tok (funcall smie-backward-token-function)))
2132 (if (or (when (equal tok "not") (forward-word 1) t)
2133 (and (zerop (length tok)) (eq (char-before) ?\))))
2134 (not (sh-smie--rc-after-special-arg-p))
2135 (sh-smie--newline-semi-p tok)))))
2137 (defun sh-smie-rc-forward-token ()
2138 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2139 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2140 (save-excursion
2141 (skip-chars-backward " \t")
2142 (not (bolp))))
2143 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2144 ;; Right before a here-doc.
2145 (let ((forward-sexp-function nil))
2146 (forward-sexp 1)
2147 ;; Pretend the here-document is a "newline representing a
2148 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2149 ";")
2150 (let ((semi (sh-smie--rc-newline-semi-p)))
2151 (forward-line 1)
2152 (if (or semi (eobp)) ";"
2153 (sh-smie-rc-forward-token))))
2154 (forward-comment (point-max))
2155 (cond
2156 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2157 ;; ((looking-at sh-smie--rc-operators-re)
2158 ;; (goto-char (match-end 0))
2159 ;; (let ((tok (match-string-no-properties 0)))
2160 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2161 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2162 ;; (forward-line 1))
2163 ;; tok))
2164 (t
2165 (let* ((pos (point))
2166 (tok (sh-smie--default-forward-token)))
2167 (cond
2168 ;; ((equal tok ")") "case-)")
2169 ((and tok (string-match "\\`[a-z]" tok)
2170 (assoc tok smie-grammar)
2171 (not
2172 (save-excursion
2173 (goto-char pos)
2174 (sh-smie--keyword-p))))
2175 " word ")
2176 (t tok)))))))
2178 (defun sh-smie-rc-backward-token ()
2179 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
2180 (let ((bol (line-beginning-position)))
2181 (forward-comment (- (point)))
2182 (cond
2183 ((and (bolp) (not (bobp))
2184 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2185 (not (nth 3 (syntax-ppss))))
2186 ;; Right after a here-document.
2187 (let ((forward-sexp-function nil))
2188 (forward-sexp -1)
2189 ;; Pretend the here-document is a "newline representing a
2190 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2191 ";"))
2192 ((< (point) bol) ;We skipped over a newline.
2193 (cond
2194 ;; A continued line.
2195 ((and (eolp)
2196 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2197 (line-beginning-position)))
2198 (forward-char -1)
2199 (funcall smie-backward-token-function))
2200 ((sh-smie--rc-newline-semi-p) ";")
2201 (t (funcall smie-backward-token-function))))
2202 ;; ((looking-back sh-smie--sh-operators-back-re
2203 ;; (line-beginning-position) 'greedy)
2204 ;; (goto-char (match-beginning 1))
2205 ;; (match-string-no-properties 1))
2206 (t
2207 (let ((tok (sh-smie--default-backward-token)))
2208 (cond
2209 ;; ((equal tok ")") "case-)")
2210 ((and tok (string-match "\\`[a-z]" tok)
2211 (assoc tok smie-grammar)
2212 (not (save-excursion (sh-smie--keyword-p))))
2213 " word ")
2214 (t tok)))))))
2216 (defun sh-smie-rc-rules (kind token)
2217 (pcase (cons kind token)
2218 (`(:elem . basic) sh-indentation)
2219 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
2220 (`(:after . ";")
2221 (if (smie-rule-parent-p "case")
2222 (smie-rule-parent (sh-var-value 'sh-indent-after-case))))
2223 (`(:before . "{")
2224 (save-excursion
2225 (when (sh-smie--rc-after-special-arg-p)
2226 `(column . ,(current-column)))))
2227 (`(:before . ,(or `"(" `"{" `"["))
2228 (if (smie-rule-hanging-p) (smie-rule-parent)))
2229 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2230 ;; treated as an arg to (exp) by default, which indents it all wrong.
2231 ;; To handle it right, we should extend smie-indent-exps so that the
2232 ;; preceding keyword can give special rules. Currently the only special
2233 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2234 ;; with "(exp)", which is rarely the right thing to do, but is better
2235 ;; than nothing.
2236 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
2237 ;; sh-indent-after-switch: handled implicitly by the default { rule.
2238 ))
2240 ;;; End of SMIE code.
2242 (defvar sh-regexp-for-done nil
2243 "A buffer-local regexp to match opening keyword for done.")
2245 (defvar sh-kw-alist nil
2246 "A buffer-local, since it is shell-type dependent, list of keywords.")
2248 ;; ( key-word first-on-this on-prev-line )
2249 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2250 ;; having 3 elements:
2251 ;; a keyword
2252 ;; a rule to check when the keyword appears on "this" line
2253 ;; a rule to check when the keyword appears on "the previous" line
2254 ;; The keyword is usually a string and is the first word on a line.
2255 ;; If this keyword appears on the line whose indentation is to be
2256 ;; calculated, the rule in element 2 is called. If this returns
2257 ;; non-zero, the resulting point (which may be changed by the rule)
2258 ;; is used as the default indentation.
2259 ;; If it returned false or the keyword was not found in the table,
2260 ;; then the keyword from the previous line is looked up and the rule
2261 ;; in element 3 is called. In this case, however,
2262 ;; `sh-get-indent-info' does not stop but may keep going and test
2263 ;; other keywords against rules in element 3. This is because the
2264 ;; preceding line could have, for example, an opening "if" and an
2265 ;; opening "while" keyword and we need to add the indentation offsets
2266 ;; for both.
2267 ;;
2268 (defconst sh-kw
2269 '((sh
2270 ("if" nil sh-handle-prev-if)
2271 ("elif" sh-handle-this-else sh-handle-prev-else)
2272 ("else" sh-handle-this-else sh-handle-prev-else)
2273 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2274 ("then" sh-handle-this-then sh-handle-prev-then)
2275 ("(" nil sh-handle-prev-open)
2276 ("{" nil sh-handle-prev-open)
2277 ("[" nil sh-handle-prev-open)
2278 ("}" sh-handle-this-close nil)
2279 (")" sh-handle-this-close nil)
2280 ("]" sh-handle-this-close nil)
2281 ("case" nil sh-handle-prev-case)
2282 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2283 (case-label nil sh-handle-after-case-label) ;; ???
2284 (";;" nil sh-handle-prev-case-alt-end) ;; ???
2285 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2286 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2287 ("done" sh-handle-this-done sh-handle-prev-done)
2288 ("do" sh-handle-this-do sh-handle-prev-do))
2290 ;; Note: we don't need specific stuff for bash and zsh shells;
2291 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2292 ;; these shells use.
2293 (rc
2294 ("{" nil sh-handle-prev-open)
2295 ("}" sh-handle-this-close nil)
2296 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
2300 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
2301 "Set this buffer's shell to SHELL (a string).
2302 When used interactively, insert the proper starting #!-line,
2303 and make the visited file executable via `executable-set-magic',
2304 perhaps querying depending on the value of `executable-query'.
2306 When this function is called noninteractively, INSERT-FLAG (the third
2307 argument) controls whether to insert a #!-line and think about making
2308 the visited file executable, and NO-QUERY-FLAG (the second argument)
2309 controls whether to query about making the visited file executable.
2311 Calls the value of `sh-set-shell-hook' if set."
2312 (interactive (list (completing-read
2313 (format "Shell \(default %s\): "
2314 sh-shell-file)
2315 ;; This used to use interpreter-mode-alist, but that is
2316 ;; no longer appropriate now that uses regexps.
2317 ;; Maybe there could be a separate variable that lists
2318 ;; the shells, used here and to construct i-mode-alist.
2319 ;; But the following is probably good enough:
2320 (append (mapcar (lambda (e) (symbol-name (car e)))
2321 sh-ancestor-alist)
2322 '("csh" "rc" "sh"))
2323 nil nil nil nil sh-shell-file)
2324 (eq executable-query 'function)
2325 t))
2326 (if (string-match "\\.exe\\'" shell)
2327 (setq shell (substring shell 0 (match-beginning 0))))
2328 (setq sh-shell (sh-canonicalize-shell shell))
2329 (if insert-flag
2330 (setq sh-shell-file
2331 (executable-set-magic shell (sh-feature sh-shell-arg)
2332 no-query-flag insert-flag)))
2333 (setq mode-line-process (format "[%s]" sh-shell))
2334 (setq-local sh-shell-variables nil)
2335 (setq-local sh-shell-variables-initialized nil)
2336 (setq-local imenu-generic-expression
2337 (sh-feature sh-imenu-generic-expression))
2338 (let ((tem (sh-feature sh-mode-syntax-table-input)))
2339 (when tem
2340 (setq-local sh-mode-syntax-table
2341 (apply 'sh-mode-syntax-table tem))
2342 (set-syntax-table sh-mode-syntax-table)))
2343 (dolist (var (sh-feature sh-variables))
2344 (sh-remember-variable var))
2345 (if (setq-local sh-indent-supported-here
2346 (sh-feature sh-indent-supported))
2347 (progn
2348 (message "Setting up indent for shell type %s" sh-shell)
2349 (let ((mksym (lambda (name)
2350 (intern (format "sh-smie-%s-%s"
2351 sh-indent-supported-here name)))))
2352 (add-function :around (local 'smie--hanging-eolp-function)
2353 (lambda (orig)
2354 (if (looking-at "[ \t]*\\\\\n")
2355 (goto-char (match-end 0))
2356 (funcall orig))))
2357 (smie-setup (symbol-value (funcall mksym "grammar"))
2358 (funcall mksym "rules")
2359 :forward-token (funcall mksym "forward-token")
2360 :backward-token (funcall mksym "backward-token")))
2361 (unless sh-use-smie
2362 (setq-local parse-sexp-lookup-properties t)
2363 (setq-local sh-kw-alist (sh-feature sh-kw))
2364 (let ((regexp (sh-feature sh-kws-for-done)))
2365 (if regexp
2366 (setq-local sh-regexp-for-done
2367 (sh-mkword-regexpr (regexp-opt regexp t)))))
2368 (message "setting up indent stuff")
2369 ;; sh-mode has already made indent-line-function local
2370 ;; but do it in case this is called before that.
2371 (setq-local indent-line-function 'sh-indent-line))
2372 (if sh-make-vars-local
2373 (sh-make-vars-local))
2374 (message "Indentation setup for shell type %s" sh-shell))
2375 (message "No indentation for this shell type.")
2376 (setq-local indent-line-function 'sh-basic-indent-line))
2377 (when font-lock-mode
2378 (setq font-lock-set-defaults nil)
2379 (font-lock-set-defaults)
2380 (font-lock-flush))
2381 (setq sh-shell-process nil)
2382 (run-hooks 'sh-set-shell-hook))
2385 (defun sh-feature (alist &optional function)
2386 "Index ALIST by the current shell.
2387 If ALIST isn't a list where every element is a cons, it is returned as is.
2388 Else indexing follows an inheritance logic which works in two ways:
2390 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2391 the alist contains no value for the current shell.
2392 The ultimate default is always `sh'.
2394 - If the value thus looked up is a list starting with `sh-append',
2395 we call the function `sh-append' with the rest of the list as
2396 arguments, and use the value. However, the next element of the
2397 list is not used as-is; instead, we look it up recursively
2398 in ALIST to allow the function called to define the value for
2399 one shell to be derived from another shell.
2400 The value thus determined is physically replaced into the alist.
2402 If FUNCTION is non-nil, it is called with one argument,
2403 the value thus obtained, and the result is used instead."
2404 (or (if (consp alist)
2405 ;; Check for something that isn't a valid alist.
2406 (let ((l alist))
2407 (while (and l (consp (car l)))
2408 (setq l (cdr l)))
2409 (if l alist)))
2411 (let ((orig-sh-shell sh-shell))
2412 (let ((sh-shell sh-shell)
2413 elt val)
2414 (while (and sh-shell
2415 (not (setq elt (assq sh-shell alist))))
2416 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2417 ;; If the shell is not known, treat it as sh.
2418 (unless elt
2419 (setq elt (assq 'sh alist)))
2420 (setq val (cdr elt))
2421 (if (and (consp val)
2422 (memq (car val) '(sh-append sh-modify)))
2423 (setq val
2424 (apply (car val)
2425 ;; Refer to the value for a different shell,
2426 ;; as a kind of inheritance.
2427 (let ((sh-shell (car (cdr val))))
2428 (sh-feature alist))
2429 (cddr val))))
2430 (if function
2431 (setq sh-shell orig-sh-shell
2432 val (funcall function val)))
2433 val))))
2437 ;; I commented this out because nobody calls it -- rms.
2438 ;;(defun sh-abbrevs (ancestor &rest list)
2439 ;; "If it isn't, define the current shell as abbrev table and fill that.
2440 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2441 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2442 ;;according to the remaining arguments NAMEi EXPANSIONi ...
2443 ;;EXPANSION may be either a string or a skeleton command."
2444 ;; (or (if (boundp sh-shell)
2445 ;; (symbol-value sh-shell))
2446 ;; (progn
2447 ;; (if (listp ancestor)
2448 ;; (nconc list ancestor))
2449 ;; (define-abbrev-table sh-shell ())
2450 ;; (if (vectorp ancestor)
2451 ;; (mapatoms (lambda (atom)
2452 ;; (or (eq atom 0)
2453 ;; (define-abbrev (symbol-value sh-shell)
2454 ;; (symbol-name atom)
2455 ;; (symbol-value atom)
2456 ;; (symbol-function atom))))
2457 ;; ancestor))
2458 ;; (while list
2459 ;; (define-abbrev (symbol-value sh-shell)
2460 ;; (car list)
2461 ;; (if (stringp (car (cdr list)))
2462 ;; (car (cdr list))
2463 ;; "")
2464 ;; (if (symbolp (car (cdr list)))
2465 ;; (car (cdr list))))
2466 ;; (setq list (cdr (cdr list)))))
2467 ;; (symbol-value sh-shell)))
2470 (defun sh-append (ancestor &rest list)
2471 "Return list composed of first argument (a list) physically appended to rest."
2472 (nconc list ancestor))
2475 (defun sh-modify (skeleton &rest list)
2476 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2477 (setq skeleton (copy-sequence skeleton))
2478 (while list
2479 (setcar (or (nthcdr (car list) skeleton)
2480 (error "Index %d out of bounds" (car list)))
2481 (car (cdr list)))
2482 (setq list (nthcdr 2 list)))
2483 skeleton)
2486 (defun sh-basic-indent-line ()
2487 "Indent a line for Sh mode (shell script mode).
2488 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2489 Lines containing only comments are considered empty."
2490 (interactive)
2491 (let ((previous (save-excursion
2492 (while (and (progn (beginning-of-line)
2493 (not (bobp)))
2494 (progn
2495 (forward-line -1)
2496 (back-to-indentation)
2497 (or (eolp)
2498 (eq (following-char) ?#)))))
2499 (current-column)))
2500 current)
2501 (save-excursion
2502 (indent-to (if (or (eq this-command 'newline-and-indent)
2503 (and electric-indent-mode (eq this-command 'newline)))
2504 previous
2505 (if (< (current-column)
2506 (setq current (progn (back-to-indentation)
2507 (current-column))))
2508 (if (eolp) previous 0)
2509 (delete-region (point)
2510 (progn (beginning-of-line) (point)))
2511 (if (eolp)
2512 (max previous (* (1+ (/ current sh-indentation))
2513 sh-indentation))
2514 (* (1+ (/ current sh-indentation)) sh-indentation))))))
2515 (if (< (current-column) (current-indentation))
2516 (skip-chars-forward " \t"))))
2519 (defun sh-execute-region (start end &optional flag)
2520 "Pass optional header and region to a subshell for noninteractive execution.
2521 The working directory is that of the buffer, and only environment variables
2522 are already set which is why you can mark a header within the script.
2524 With a positive prefix ARG, instead of sending region, define header from
2525 beginning of buffer to point. With a negative prefix ARG, instead of sending
2526 region, clear header."
2527 (interactive "r\nP")
2528 (if flag
2529 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2530 (point-marker)))
2531 (if sh-header-marker
2532 (save-excursion
2533 (let (buffer-undo-list)
2534 (goto-char sh-header-marker)
2535 (append-to-buffer (current-buffer) start end)
2536 (shell-command-on-region (point-min)
2537 (setq end (+ sh-header-marker
2538 (- end start)))
2539 sh-shell-file)
2540 (delete-region sh-header-marker end)))
2541 (shell-command-on-region start end (concat sh-shell-file " -")))))
2544 (defun sh-remember-variable (var)
2545 "Make VARIABLE available for future completing reads in this buffer."
2546 (or (< (length var) sh-remember-variable-min)
2547 (getenv var)
2548 (assoc var sh-shell-variables)
2549 (push (cons var var) sh-shell-variables))
2550 var)
2554 (defun sh-quoted-p ()
2555 "Is point preceded by an odd number of backslashes?"
2556 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
2557 \f
2558 ;; Indentation stuff.
2559 (defun sh-must-support-indent ()
2560 "Signal an error if the shell type for this buffer is not supported.
2561 Also, the buffer must be in Shell-script mode."
2562 (unless sh-indent-supported-here
2563 (error "This buffer's shell does not support indentation through Emacs")))
2565 (defun sh-make-vars-local ()
2566 "Make the indentation variables local to this buffer.
2567 Normally they already are local. This command is provided in case
2568 variable `sh-make-vars-local' has been set to nil.
2570 To revert all these variables to the global values, use
2571 command `sh-reset-indent-vars-to-global-values'."
2572 (interactive)
2573 (mapc 'make-local-variable sh-var-list)
2574 (message "Indentation variables are now local."))
2576 (defun sh-reset-indent-vars-to-global-values ()
2577 "Reset local indentation variables to the global values.
2578 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2579 (interactive)
2580 (mapc 'kill-local-variable sh-var-list)
2581 (if sh-make-vars-local
2582 (mapcar 'make-local-variable sh-var-list)))
2585 ;; Theoretically these are only needed in shell and derived modes.
2586 ;; However, the routines which use them are only called in those modes.
2587 (defconst sh-special-keywords "then\\|do")
2589 (defun sh-help-string-for-variable (var)
2590 "Construct a string for `sh-read-variable' when changing variable VAR ."
2591 (let ((msg (documentation-property var 'variable-documentation))
2592 (msg2 ""))
2593 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
2594 (setq msg2
2595 (format "\n
2596 You can enter a number (positive to increase indentation,
2597 negative to decrease indentation, zero for no change to indentation).
2599 Or, you can enter one of the following symbols which are relative to
2600 the value of variable `sh-basic-offset'
2601 which in this buffer is currently %s.
2603 \t%s."
2604 sh-basic-offset
2605 (mapconcat (lambda (x)
2606 (nth (1- (length x)) x))
2607 sh-symbol-list "\n\t"))))
2608 (concat
2609 ;; The following shows the global not the local value!
2610 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2611 msg msg2)))
2613 (defun sh-read-variable (var)
2614 "Read a new value for indentation variable VAR."
2615 (let ((minibuffer-help-form `(sh-help-string-for-variable
2616 (quote ,var)))
2617 val)
2618 (setq val (read-from-minibuffer
2619 (format "New value for %s (press %s for help): "
2620 var (single-key-description help-char))
2621 (format "%s" (symbol-value var))
2622 nil t))
2623 val))
2627 (defun sh-in-comment-or-string (start)
2628 "Return non-nil if START is in a comment or string."
2629 (save-excursion
2630 (let ((state (syntax-ppss start)))
2631 (or (nth 3 state) (nth 4 state)))))
2633 (defun sh-goto-matching-if ()
2634 "Go to the matching if for a fi.
2635 This handles nested if..fi pairs."
2636 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2637 (if found
2638 (goto-char found))))
2641 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2642 ;; line whose indentation is being handled contain XXX;
2643 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2645 (defun sh-handle-prev-if ()
2646 (list '(+ sh-indent-after-if)))
2648 (defun sh-handle-this-else ()
2649 (if (sh-goto-matching-if)
2650 ;; (list "aligned to if")
2651 (list "aligned to if" '(+ sh-indent-for-else))
2652 nil
2653 ))
2655 (defun sh-handle-prev-else ()
2656 (if (sh-goto-matching-if)
2657 (list '(+ sh-indent-after-if))
2658 ))
2660 (defun sh-handle-this-fi ()
2661 (if (sh-goto-matching-if)
2662 (list "aligned to if" '(+ sh-indent-for-fi))
2663 nil
2664 ))
2666 (defun sh-handle-prev-fi ()
2667 ;; Why do we have this rule? Because we must go back to the if
2668 ;; to get its indent. We may continue back from there.
2669 ;; We return nil because we don't have anything to add to result,
2670 ;; the side affect of setting align-point is all that matters.
2671 ;; we could return a comment (a string) but I can't think of a good one...
2672 (sh-goto-matching-if)
2673 nil)
2675 (defun sh-handle-this-then ()
2676 (let ((p (sh-goto-matching-if)))
2677 (if p
2678 (list '(+ sh-indent-for-then))
2679 )))
2681 (defun sh-handle-prev-then ()
2682 (let ((p (sh-goto-matching-if)))
2683 (if p
2684 (list '(+ sh-indent-after-if))
2685 )))
2687 (defun sh-handle-prev-open ()
2688 (save-excursion
2689 (let ((x (sh-prev-stmt)))
2690 (if (and x
2691 (progn
2692 (goto-char x)
2693 (or
2694 (looking-at "function\\b")
2695 (looking-at "\\s-*\\S-+\\s-*()")
2696 )))
2697 (list '(+ sh-indent-after-function))
2698 (list '(+ sh-indent-after-open)))
2699 )))
2701 (defun sh-handle-this-close ()
2702 (forward-char 1) ;; move over ")"
2703 (if (sh-safe-forward-sexp -1)
2704 (list "aligned to opening paren")))
2706 (defun sh-goto-matching-case ()
2707 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2708 (if found (goto-char found))))
2710 (defun sh-handle-prev-case ()
2711 ;; This is typically called when point is on same line as a case
2712 ;; we shouldn't -- and can't find prev-case
2713 (if (looking-at ".*\\<case\\>")
2714 (list '(+ sh-indent-for-case-label))
2715 (error "We don't seem to be on a line with a case"))) ;; debug
2717 (defun sh-handle-this-esac ()
2718 (if (sh-goto-matching-case)
2719 (list "aligned to matching case")))
2721 (defun sh-handle-prev-esac ()
2722 (if (sh-goto-matching-case)
2723 (list "matching case")))
2725 (defun sh-handle-after-case-label ()
2726 (if (sh-goto-matching-case)
2727 (list '(+ sh-indent-for-case-alt))))
2729 (defun sh-handle-prev-case-alt-end ()
2730 (if (sh-goto-matching-case)
2731 (list '(+ sh-indent-for-case-label))))
2733 (defun sh-safe-forward-sexp (&optional arg)
2734 "Try and do a `forward-sexp', but do not error.
2735 Return new point if successful, nil if an error occurred."
2736 (condition-case nil
2737 (progn
2738 (forward-sexp (or arg 1))
2739 (point)) ;; return point if successful
2740 (error
2741 (sh-debug "oops!(1) %d" (point))
2742 nil))) ;; return nil if fail
2744 (defun sh-goto-match-for-done ()
2745 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2746 (if found
2747 (goto-char found))))
2749 (defun sh-handle-this-done ()
2750 (if (sh-goto-match-for-done)
2751 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2753 (defun sh-handle-prev-done ()
2754 (if (sh-goto-match-for-done)
2755 (list "previous done")))
2757 (defun sh-handle-this-do ()
2758 (if (sh-goto-match-for-done)
2759 (list '(+ sh-indent-for-do))))
2761 (defun sh-handle-prev-do ()
2762 (cond
2763 ((save-restriction
2764 (narrow-to-region (point) (line-beginning-position))
2765 (sh-goto-match-for-done))
2766 (sh-debug "match for done found on THIS line")
2767 (list '(+ sh-indent-after-loop-construct)))
2768 ((sh-goto-match-for-done)
2769 (sh-debug "match for done found on PREV line")
2770 (list '(+ sh-indent-after-do)))
2771 (t
2772 (message "match for done NOT found")
2773 nil)))
2775 ;; for rc:
2776 (defun sh-find-prev-switch ()
2777 "Find the line for the switch keyword matching this line's case keyword."
2778 (re-search-backward "\\<switch\\>" nil t))
2780 (defun sh-handle-this-rc-case ()
2781 (if (sh-find-prev-switch)
2782 (list '(+ sh-indent-after-switch))
2783 ;; (list '(+ sh-indent-for-case-label))
2784 nil))
2786 (defun sh-handle-prev-rc-case ()
2787 (list '(+ sh-indent-after-case)))
2789 (defun sh-check-rule (n thing)
2790 (let ((rule (nth n (assoc thing sh-kw-alist)))
2791 (val nil))
2792 (if rule
2793 (progn
2794 (setq val (funcall rule))
2795 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2796 n thing (point) rule val)))
2797 val))
2800 (defun sh-get-indent-info ()
2801 "Return indent-info for this line.
2802 This is a list. nil means the line is to be left as is.
2803 Otherwise it contains one or more of the following sublists:
2804 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2805 relative to. If present, this is always the first of the
2806 sublists. The indentation of the line in question is
2807 derived from the indentation of this point, possibly
2808 modified by subsequent sublists.
2809 \(+ VAR\)
2810 \(- VAR\) Get the value of variable VAR and add to or subtract from
2811 the indentation calculated so far.
2812 \(= VAR\) Get the value of variable VAR and *replace* the
2813 indentation with its value. This only occurs for
2814 special variables such as `sh-indent-comment'.
2815 STRING This is ignored for the purposes of calculating
2816 indentation, it is printed in certain cases to help show
2817 what the indentation is based on."
2818 ;; See comments before `sh-kw'.
2819 (save-excursion
2820 (let ((have-result nil)
2821 this-kw
2822 val
2823 (result nil)
2824 (align-point nil)
2825 prev-line-end x)
2826 (beginning-of-line)
2827 ;; Note: setting result to t means we are done and will return nil.
2828 ;;(This function never returns just t.)
2829 (cond
2830 ((or (nth 3 (syntax-ppss (point)))
2831 (eq (get-text-property (point) 'face) sh-heredoc-face))
2832 ;; String continuation -- don't indent
2833 (setq result t)
2834 (setq have-result t))
2835 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2836 (if (bobp)
2837 (setq result t) ;; return nil if 1st line!
2838 (setq result (list '(= sh-indent-comment)))
2839 ;; we still need to get previous line in case
2840 ;; sh-indent-comment is t (indent as normal)
2841 (setq align-point (sh-prev-line nil))
2842 (setq have-result nil)
2843 ))
2844 ) ;; cond
2846 (unless have-result
2847 ;; Continuation lines are handled specially
2848 (if (sh-this-is-a-continuation)
2849 (progn
2850 (setq result
2851 (if (save-excursion
2852 (beginning-of-line)
2853 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2854 ;; By convention, if the continuation \ is not
2855 ;; preceded by a SPC or a TAB it means that the line
2856 ;; is cut at a place where spaces cannot be freely
2857 ;; added/removed. I.e. do not indent the line.
2858 (list '(= nil))
2859 ;; We assume the line being continued is already
2860 ;; properly indented...
2861 ;; (setq prev-line-end (sh-prev-line))
2862 (setq align-point (sh-prev-line nil))
2863 (list '(+ sh-indent-for-continuation))))
2864 (setq have-result t))
2865 (beginning-of-line)
2866 (skip-chars-forward " \t")
2867 (setq this-kw (sh-get-kw)))
2869 ;; Handle "this" keyword: first word on the line we're
2870 ;; calculating indentation info for.
2871 (if this-kw
2872 (if (setq val (sh-check-rule 1 this-kw))
2873 (progn
2874 (setq align-point (point))
2875 (sh-debug
2876 "this - setting align-point to %d" align-point)
2877 (setq result (append result val))
2878 (setq have-result t)
2879 ;; set prev-line to continue processing remainder
2880 ;; of this line as a previous line
2881 (setq prev-line-end (point))
2882 ))))
2884 (unless have-result
2885 (setq prev-line-end (sh-prev-line 'end)))
2887 (if prev-line-end
2888 (save-excursion
2889 ;; We start off at beginning of this line.
2890 ;; Scan previous statements while this is <=
2891 ;; start of previous line.
2892 (goto-char prev-line-end)
2893 (setq x t)
2894 (while (and x (setq x (sh-prev-thing)))
2895 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2896 (cond
2897 ((and (equal x ")")
2898 (equal (get-text-property (1- (point)) 'syntax-table)
2899 sh-st-punc))
2900 (sh-debug "Case label) here")
2901 (setq x 'case-label)
2902 (if (setq val (sh-check-rule 2 x))
2903 (progn
2904 (setq result (append result val))
2905 (setq align-point (point))))
2906 (or (bobp)
2907 (forward-char -1))
2908 ;; FIXME: This charset looks too much like a regexp. --Stef
2909 (skip-chars-forward "[a-z0-9]*?")
2911 ((string-match "[])}]" x)
2912 (setq x (sh-safe-forward-sexp -1))
2913 (if x
2914 (progn
2915 (setq align-point (point))
2916 (setq result (append result
2917 (list "aligned to opening paren")))
2918 )))
2919 ((string-match "[[({]" x)
2920 (sh-debug "Checking special thing: %s" x)
2921 (if (setq val (sh-check-rule 2 x))
2922 (setq result (append result val)))
2923 (forward-char -1)
2924 (setq align-point (point)))
2925 ((string-match "[\"'`]" x)
2926 (sh-debug "Skipping back for %s" x)
2927 ;; this was oops-2
2928 (setq x (sh-safe-forward-sexp -1)))
2929 ((stringp x)
2930 (sh-debug "Checking string %s at %s" x (point))
2931 (if (setq val (sh-check-rule 2 x))
2932 ;; (or (eq t (car val))
2933 ;; (eq t (car (car val))))
2934 (setq result (append result val)))
2935 ;; not sure about this test Wed Jan 27 23:48:35 1999
2936 (setq align-point (point))
2937 (unless (bolp)
2938 (forward-char -1)))
2939 (t
2940 (error "Don't know what to do with %s" x))
2942 ) ;; while
2943 (sh-debug "result is %s" result)
2945 (sh-debug "No prev line!")
2946 (sh-debug "result: %s align-point: %s" result align-point)
2949 (if align-point
2950 ;; was: (setq result (append result (list (list t align-point))))
2951 (setq result (append (list (list t align-point)) result))
2953 (sh-debug "result is now: %s" result)
2955 (or result
2956 (setq result (list (if prev-line-end
2957 (list t prev-line-end)
2958 (list '= 'sh-first-lines-indent)))))
2960 (if (eq result t)
2961 (setq result nil))
2962 (sh-debug "result is: %s" result)
2963 result
2964 ) ;; let
2965 ))
2968 (defun sh-get-indent-var-for-line (&optional info)
2969 "Return the variable controlling indentation for this line.
2970 If there is not [just] one such variable, return a string
2971 indicating the problem.
2972 If INFO is supplied it is used, else it is calculated."
2973 (let ((var nil)
2974 (result nil)
2975 (reason nil)
2976 sym elt)
2977 (or info
2978 (setq info (sh-get-indent-info)))
2979 (if (null info)
2980 (setq result "this line to be left as is")
2981 (while (and info (null result))
2982 (setq elt (car info))
2983 (cond
2984 ((stringp elt)
2985 (setq reason elt)
2987 ((not (listp elt))
2988 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2989 ;; so it is a list
2990 ((eq t (car elt))
2991 ) ;; nothing
2992 ((symbolp (setq sym (nth 1 elt)))
2993 ;; A bit of a kludge - when we see the sh-indent-comment
2994 ;; ignore other variables. Otherwise it is tricky to
2995 ;; "learn" the comment indentation.
2996 (if (eq var 'sh-indent-comment)
2997 (setq result var)
2998 (if var
2999 (setq result
3000 "this line is controlled by more than 1 variable.")
3001 (setq var sym))))
3002 (t
3003 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
3004 (setq info (cdr info))
3005 ))
3006 (or result
3007 (setq result var))
3008 (or result
3009 (setq result reason))
3010 (if (null result)
3011 ;; e.g. just had (t POS)
3012 (setq result "line has default indentation"))
3013 result))
3017 ;; Finding the previous line isn't trivial.
3018 ;; We must *always* go back one more and see if that is a continuation
3019 ;; line -- it is the PREVIOUS line which is continued, not the one
3020 ;; we are going to!
3021 ;; Also, we want to treat a whole "here document" as one big line,
3022 ;; because we may want to a align to the beginning of it.
3023 ;;
3024 ;; What we do:
3025 ;; - go back to previous non-empty line
3026 ;; - if this is in a here-document, go to the beginning of it
3027 ;; - while previous line is continued, go back one line
3028 (defun sh-prev-line (&optional end)
3029 "Back to end of previous non-comment non-empty line.
3030 Go to beginning of logical line unless END is non-nil, in which case
3031 we go to the end of the previous line and do not check for continuations."
3032 (save-excursion
3033 (beginning-of-line)
3034 (forward-comment (- (point-max)))
3035 (unless end (beginning-of-line))
3036 (when (and (not (bobp))
3037 (equal (get-text-property (1- (point)) 'face)
3038 sh-heredoc-face))
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))
3078 ))
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)
3118 ))
3119 (buffer-substring start (point))
3120 ))
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.
3129 ;;
3130 ;; Added a kludge for ";;"
3131 ;; Possible return values:
3132 ;; nil - nothing
3133 ;; a string - possibly a keyword
3134 ;;
3135 (if (bolp)
3136 nil
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))
3172 t)
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))
3226 (t
3227 ))))
3228 (error nil))
3229 (if (eq depth 0)
3230 prev ;; (point)
3231 nil)
3232 )))
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))
3260 (t
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 '/))
3284 (t
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
3322 (t
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)))
3328 (t
3329 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3330 (t
3331 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
3332 (t
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
3347 (t
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 the 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)))
3406 ))
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))
3416 )))
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))
3515 (t
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
3571 ;;
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 ;; )))
3583 ;;
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 Output in buffer \"*indent*\" shows any lines which have conflicting
3594 values of a variable, and the final value of all variables learned.
3595 When called interactively, pop to this buffer automatically if
3596 there are any discrepancies.
3598 If no prefix ARG is given, then variables are set to numbers.
3599 If a prefix arg is given, then variables are set to symbols when
3600 applicable -- e.g. to symbol `+' if the value is that of the
3601 basic indent.
3602 If a positive numerical prefix is given, then `sh-basic-offset'
3603 is set to the prefix's numerical value.
3604 Otherwise, sh-basic-offset may or may not be changed, according
3605 to the value of variable `sh-learn-basic-offset'.
3607 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3608 function completes. The function is abnormal because it is called
3609 with an alist of variables learned. This feature may be changed or
3610 removed in the future.
3612 This command can often take a long time to run."
3613 (interactive "P")
3614 (sh-must-support-indent)
3615 (if sh-use-smie
3616 (smie-config-guess)
3617 (save-excursion
3618 (goto-char (point-min))
3619 (let ((learned-var-list nil)
3620 (out-buffer "*indent*")
3621 (num-diffs 0)
3622 previous-set-info
3623 (max 17)
3624 vec
3625 msg
3626 (comment-col nil) ;; number if all same, t if seen diff values
3627 (comments-always-default t) ;; nil if we see one not default
3628 initial-msg
3629 (specified-basic-offset (and arg (numberp arg)
3630 (> arg 0)))
3631 (linenum 0)
3632 suggested)
3633 (setq vec (make-vector max 0))
3634 (sh-mark-init out-buffer)
3636 (if specified-basic-offset
3637 (progn
3638 (setq sh-basic-offset arg)
3639 (setq initial-msg
3640 (format "Using specified sh-basic-offset of %d"
3641 sh-basic-offset)))
3642 (setq initial-msg
3643 (format "Initial value of sh-basic-offset: %s"
3644 sh-basic-offset)))
3646 (while (< (point) (point-max))
3647 (setq linenum (1+ linenum))
3648 ;; (if (zerop (% linenum 10))
3649 (message "line %d" linenum)
3650 ;; )
3651 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3652 (let* ((sh-indent-comment t) ;; info must return default indent
3653 (info (sh-get-indent-info))
3654 (var (sh-get-indent-var-for-line info))
3655 sval ival diff new-val
3656 (curr-indent (current-indentation)))
3657 (cond
3658 ((null var)
3659 nil)
3660 ((stringp var)
3661 nil)
3662 ((numberp (setq sval (sh-var-value var 'no-error)))
3663 ;; the numberp excludes comments since sval will be t.
3664 (setq ival (sh-calculate-indent))
3665 (setq diff (- curr-indent ival))
3666 (setq new-val (+ sval diff))
3667 (sh-set-var-value var new-val 'no-symbol)
3668 (unless (looking-at "\\s-*#") ;; don't learn from comments
3669 (if (setq previous-set-info (assoc var learned-var-list))
3670 (progn
3671 ;; it was already there, is it same value ?
3672 (unless (eq (symbol-value var)
3673 (nth 1 previous-set-info))
3674 (sh-mark-line
3675 (format "Variable %s was set to %s"
3676 var (symbol-value var))
3677 (point) out-buffer t t)
3678 (sh-mark-line
3679 (format " but was previously set to %s"
3680 (nth 1 previous-set-info))
3681 (nth 2 previous-set-info) out-buffer t)
3682 (setq num-diffs (1+ num-diffs))
3683 ;; (delete previous-set-info learned-var-list)
3684 (setcdr previous-set-info
3685 (list (symbol-value var) (point)))
3688 (setq learned-var-list
3689 (append (list (list var (symbol-value var)
3690 (point)))
3691 learned-var-list)))
3692 (if (numberp new-val)
3693 (progn
3694 (sh-debug
3695 "This line's indent value: %d" new-val)
3696 (if (< new-val 0)
3697 (setq new-val (- new-val)))
3698 (if (< new-val max)
3699 (aset vec new-val (1+ (aref vec new-val))))))
3700 ))
3701 ((eq var 'sh-indent-comment)
3702 (unless (= curr-indent (sh-calculate-indent info))
3703 ;; this is not the default indentation
3704 (setq comments-always-default nil)
3705 (if comment-col ;; then we have see one before
3706 (or (eq comment-col curr-indent)
3707 (setq comment-col t)) ;; seen a different one
3708 (setq comment-col curr-indent))
3709 ))
3710 (t
3711 (sh-debug "Cannot learn this line!!!")
3712 ))
3713 (sh-debug
3714 "at %s learned-var-list is %s" (point) learned-var-list)
3715 ))
3716 (forward-line 1)
3717 ) ;; while
3718 (if sh-debug
3719 (progn
3720 (setq msg (format
3721 "comment-col = %s comments-always-default = %s"
3722 comment-col comments-always-default))
3723 ;; (message msg)
3724 (sh-mark-line msg nil out-buffer)))
3725 (cond
3726 ((eq comment-col 0)
3727 (setq msg "\nComments are all in 1st column.\n"))
3728 (comments-always-default
3729 (setq msg "\nComments follow default indentation.\n")
3730 (setq comment-col t))
3731 ((numberp comment-col)
3732 (setq msg (format "\nComments are in col %d." comment-col)))
3733 (t
3734 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3735 (setq comment-col nil)
3736 ))
3737 (sh-debug msg)
3738 (sh-mark-line msg nil out-buffer)
3740 (sh-mark-line initial-msg nil out-buffer t t)
3742 (setq suggested (sh-guess-basic-offset vec))
3744 (if (and suggested (not specified-basic-offset))
3745 (let ((new-value
3746 (cond
3747 ;; t => set it if we have a single value as a number
3748 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3749 suggested)
3750 ;; other non-nil => set it if only one value was found
3751 (sh-learn-basic-offset
3752 (if (numberp suggested)
3753 suggested
3754 (if (= (length suggested) 1)
3755 (car suggested))))
3756 (t
3757 nil))))
3758 (if new-value
3759 (progn
3760 (setq learned-var-list
3761 (append (list (list 'sh-basic-offset
3762 (setq sh-basic-offset new-value)
3763 (point-max)))
3764 learned-var-list))
3765 ;; Not sure if we need to put this line in, since
3766 ;; it will appear in the "Learned variable settings".
3767 (sh-mark-line
3768 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3769 nil out-buffer))
3770 (sh-mark-line
3771 (if (listp suggested)
3772 (format "Possible value(s) for sh-basic-offset: %s"
3773 (mapconcat 'int-to-string suggested " "))
3774 (format "Suggested sh-basic-offset: %d" suggested))
3775 nil out-buffer))))
3778 (setq learned-var-list
3779 (append (list (list 'sh-indent-comment comment-col (point-max)))
3780 learned-var-list))
3781 (setq sh-indent-comment comment-col)
3782 (let ((name (buffer-name)))
3783 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3784 (if arg
3785 ;; Set learned variables to symbolic rather than numeric
3786 ;; values where possible.
3787 (dolist (learned-var (reverse learned-var-list))
3788 (let ((var (car learned-var))
3789 (val (nth 1 learned-var)))
3790 (when (and (not (eq var 'sh-basic-offset))
3791 (numberp val))
3792 (sh-set-var-value var val)))))
3793 (dolist (learned-var (reverse learned-var-list))
3794 (let ((var (car learned-var)))
3795 (sh-mark-line (format " %s %s" var (symbol-value var))
3796 (nth 2 learned-var) out-buffer)))
3797 (with-current-buffer out-buffer
3798 (goto-char (point-min))
3799 (let ((inhibit-read-only t))
3800 (insert
3801 (format "Indentation values for buffer %s.\n" name)
3802 (format "%d indentation variable%s different values%s\n\n"
3803 num-diffs
3804 (if (= num-diffs 1)
3805 " has" "s have")
3806 (if (zerop num-diffs)
3807 "." ":"))))))
3808 ;; Are abnormal hooks considered bad form?
3809 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3810 (and (called-interactively-p 'any)
3811 (or sh-popup-occur-buffer (> num-diffs 0))
3812 (pop-to-buffer out-buffer))))))
3814 (defun sh-guess-basic-offset (vec)
3815 "See if we can determine a reasonable value for `sh-basic-offset'.
3816 This is experimental, heuristic and arbitrary!
3817 Argument VEC is a vector of information collected by
3818 `sh-learn-buffer-indent'.
3819 Return values:
3820 number - there appears to be a good single value
3821 list of numbers - no obvious one, here is a list of one or more
3822 reasonable choices
3823 nil - we couldn't find a reasonable one."
3824 (let* ((max (1- (length vec)))
3825 (i 1)
3826 (totals (make-vector max 0)))
3827 (while (< i max)
3828 (cl-incf (aref totals i) (* 4 (aref vec i)))
3829 (if (zerop (% i 2))
3830 (cl-incf (aref totals i) (aref vec (/ i 2))))
3831 (if (< (* i 2) max)
3832 (cl-incf (aref totals i) (aref vec (* i 2))))
3833 (setq i (1+ i)))
3835 (let ((x nil)
3836 (result nil)
3837 tot sum p)
3838 (setq i 1)
3839 (while (< i max)
3840 (if (/= (aref totals i) 0)
3841 (push (cons i (aref totals i)) x))
3842 (setq i (1+ i)))
3844 (setq x (sort (nreverse x) (lambda (a b) (> (cdr a) (cdr b)))))
3845 (setq tot (apply '+ (append totals nil)))
3846 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3847 vec totals tot))
3848 (cond
3849 ((zerop (length x))
3850 (message "no values!")) ;; we return nil
3851 ((= (length x) 1)
3852 (message "only value is %d" (car (car x)))
3853 (setq result (car (car x)))) ;; return single value
3854 ((> (cdr (car x)) (/ tot 2))
3855 ;; 1st is > 50%
3856 (message "basic-offset is probably %d" (car (car x)))
3857 (setq result (car (car x)))) ;; again, return a single value
3858 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3859 ;; 1st is >= 2 * 2nd
3860 (message "basic-offset could be %d" (car (car x)))
3861 (setq result (car (car x))))
3862 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3863 ;; 1st & 2nd together >= 50% - return a list
3864 (setq p x sum 0 result nil)
3865 (while (and p
3866 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3867 (setq result (append result (list (car (car p)))))
3868 (setq p (cdr p)))
3869 (message "Possible choices for sh-basic-offset: %s"
3870 (mapconcat 'int-to-string result " ")))
3871 (t
3872 (message "No obvious value for sh-basic-offset. Perhaps %d"
3873 (car (car x)))
3874 ;; result is nil here
3875 ))
3876 result)))
3878 ;; ========================================================================
3880 ;; Styles -- a quick and dirty way of saving the indentation settings.
3882 (defvar sh-styles-alist nil
3883 "A list of all known shell indentation styles.")
3885 (defun sh-name-style (name &optional confirm-overwrite)
3886 "Name the current indentation settings as a style called NAME.
3887 If this name exists, the command will prompt whether it should be
3888 overwritten if
3889 - - it was called interactively with a prefix argument, or
3890 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3891 ;; (interactive "sName for this style: ")
3892 (interactive
3893 (list
3894 (read-from-minibuffer "Name for this style? " )
3895 (not current-prefix-arg)))
3896 (let ((slist (cons name
3897 (mapcar (lambda (var) (cons var (symbol-value var)))
3898 sh-var-list)))
3899 (style (assoc name sh-styles-alist)))
3900 (if style
3901 (if (and confirm-overwrite
3902 (not (y-or-n-p "This style exists. Overwrite it? ")))
3903 (message "Not changing style %s" name)
3904 (message "Updating style %s" name)
3905 (setcdr style (cdr slist)))
3906 (message "Creating new style %s" name)
3907 (push slist sh-styles-alist))))
3909 (defun sh-load-style (name)
3910 "Set shell indentation values for this buffer from those in style NAME."
3911 (interactive (list (completing-read
3912 "Which style to use for this buffer? "
3913 sh-styles-alist nil t)))
3914 (let ((sl (assoc name sh-styles-alist)))
3915 (if (null sl)
3916 (error "sh-load-style - style %s not known" name)
3917 (dolist (var (cdr sl))
3918 (set (car var) (cdr var))))))
3920 (defun sh-save-styles-to-buffer (buff)
3921 "Save all current styles in elisp to buffer BUFF.
3922 This is always added to the end of the buffer."
3923 (interactive
3924 (list
3925 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3926 (with-current-buffer (get-buffer-create buff)
3927 (goto-char (point-max))
3928 (insert "\n")
3929 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3932 \f
3933 ;; statement syntax-commands for various shells
3935 ;; You are welcome to add the syntax or even completely new statements as
3936 ;; appropriate for your favorite shell.
3938 (defconst sh-non-closing-paren
3939 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3940 ;; that inherits this property, which then confuses the indentation.
3941 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3943 (define-skeleton sh-case
3944 "Insert a case/switch statement. See `sh-feature'."
3945 (csh "expression: "
3946 "switch( " str " )" \n
3947 > "case " (read-string "pattern: ") ?: \n
3948 > _ \n
3949 "breaksw" \n
3950 ( "other pattern, %s: "
3951 < "case " str ?: \n
3952 > _ \n
3953 "breaksw" \n)
3954 < "default:" \n
3955 > _ \n
3956 resume:
3957 < < "endsw" \n)
3958 (es)
3959 (rc "expression: "
3960 > "switch( " str " ) {" \n
3961 > "case " (read-string "pattern: ") \n
3962 > _ \n
3963 ( "other pattern, %s: "
3964 "case " str > \n
3965 > _ \n)
3966 "case *" > \n
3967 > _ \n
3968 resume:
3969 ?\} > \n)
3970 (sh "expression: "
3971 > "case " str " in" \n
3972 ( "pattern, %s: "
3973 > str sh-non-closing-paren \n
3974 > _ \n
3975 ";;" \n)
3976 > "*" sh-non-closing-paren \n
3977 > _ \n
3978 resume:
3979 "esac" > \n))
3981 (define-skeleton sh-for
3982 "Insert a for loop. See `sh-feature'."
3983 (csh sh-modify sh
3984 1 ""
3985 2 "foreach "
3986 4 " ( "
3987 6 " )"
3988 15 '<
3989 16 "end")
3990 (es sh-modify rc
3991 4 " = ")
3992 (rc sh-modify sh
3993 2 "for( "
3994 6 " ) {"
3995 15 ?\} )
3996 (sh "Index variable: "
3997 > "for " str " in " _ "; do" \n
3998 > _ | ?$ & (sh-remember-variable str) \n
3999 "done" > \n))
4003 (define-skeleton sh-indexed-loop
4004 "Insert an indexed loop from 1 to n. See `sh-feature'."
4005 (bash sh-modify posix)
4006 (csh "Index variable: "
4007 "@ " str " = 1" \n
4008 "while( $" str " <= " (read-string "upper limit: ") " )" \n
4009 > _ ?$ str \n
4010 "@ " str "++" \n
4011 < "end" \n)
4012 (es sh-modify rc
4013 4 " =")
4014 (ksh88 "Index variable: "
4015 > "integer " str "=0" \n
4016 > "while (( ( " str " += 1 ) <= "
4017 (read-string "upper limit: ")
4018 " )); do" \n
4019 > _ ?$ (sh-remember-variable str) > \n
4020 "done" > \n)
4021 (posix "Index variable: "
4022 > str "=1" \n
4023 "while [ $" str " -le "
4024 (read-string "upper limit: ")
4025 " ]; do" \n
4026 > _ ?$ str \n
4027 str ?= (sh-add (sh-remember-variable str) 1) \n
4028 "done" > \n)
4029 (rc "Index variable: "
4030 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
4031 (read-string "upper limit: ")
4032 "; i++ ) print i }'`}) {" \n
4033 > _ ?$ (sh-remember-variable str) \n
4034 ?\} > \n)
4035 (sh "Index variable: "
4036 > "for " str " in `awk 'BEGIN { for( i=1; i<="
4037 (read-string "upper limit: ")
4038 "; i++ ) print i }'`; do" \n
4039 > _ ?$ (sh-remember-variable str) \n
4040 "done" > \n))
4043 (defun sh-shell-initialize-variables ()
4044 "Scan the buffer for variable assignments.
4045 Add these variables to `sh-shell-variables'."
4046 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
4047 (save-excursion
4048 (goto-char (point-min))
4049 (setq sh-shell-variables-initialized t)
4050 (while (search-forward "=" nil t)
4051 (sh-assignment 0)))
4052 (message "Scanning buffer `%s' for variable assignments...done"
4053 (buffer-name)))
4055 (defvar sh-add-buffer)
4057 (defun sh-add-completer (string predicate code)
4058 "Do completion using `sh-shell-variables', but initialize it first.
4059 This function is designed for use as the \"completion table\",
4060 so it takes three arguments:
4061 STRING, the current buffer contents;
4062 PREDICATE, the predicate for filtering possible matches;
4063 CODE, which says what kind of things to do.
4064 CODE can be nil, t or `lambda'.
4065 nil means to return the best completion of STRING, or nil if there is none.
4066 t means to return a list of all possible completions of STRING.
4067 `lambda' means to return t if STRING is a valid completion as it stands."
4068 (let ((vars
4069 (with-current-buffer sh-add-buffer
4070 (or sh-shell-variables-initialized
4071 (sh-shell-initialize-variables))
4072 (nconc (mapcar (lambda (var)
4073 (substring var 0 (string-match "=" var)))
4074 process-environment)
4075 sh-shell-variables))))
4076 (complete-with-action code vars string predicate)))
4078 (defun sh-add (var delta)
4079 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
4080 (interactive
4081 (let ((sh-add-buffer (current-buffer)))
4082 (list (completing-read "Variable: " 'sh-add-completer)
4083 (prefix-numeric-value current-prefix-arg))))
4084 (insert (sh-feature '((bash . "$(( ")
4085 (ksh88 . "$(( ")
4086 (posix . "$(( ")
4087 (rc . "`{expr $")
4088 (sh . "`expr $")
4089 (zsh . "$[ ")))
4090 (sh-remember-variable var)
4091 (if (< delta 0) " - " " + ")
4092 (number-to-string (abs delta))
4093 (sh-feature '((bash . " ))")
4094 (ksh88 . " ))")
4095 (posix . " ))")
4096 (rc . "}")
4097 (sh . "`")
4098 (zsh . " ]")))))
4102 (define-skeleton sh-function
4103 "Insert a function definition. See `sh-feature'."
4104 (bash sh-modify ksh88
4105 3 "() {")
4106 (ksh88 "name: "
4107 "function " str " {" \n
4108 > _ \n
4109 < "}" \n)
4110 (rc sh-modify ksh88