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