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