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