]> code.delx.au - gnu-emacs/blob - lisp/progmodes/sh-script.el
Merge from emacs-24; up to 2014-06-11T19:33:14Z!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 (when (smie-rule-hanging-p)
2016 (if (not (smie-rule-prev-p "&&" "||" "|"))
2017 (smie-rule-parent)
2018 (smie-backward-sexp 'halfexp)
2019 `(column . ,(smie-indent-virtual)))))
2020 ;; FIXME: Maybe this handling of ;; should be made into
2021 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
2022 (`(:before . ,(or `";;" `";&" `";;&"))
2023 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
2024 (cons 'column (smie-indent-keyword ";"))
2025 (smie-rule-separator kind)))
2026 (`(:after . ,(or `";;" `";&" `";;&"))
2027 (with-demoted-errors
2028 (smie-backward-sexp token)
2029 (cons 'column
2030 (if (or (smie-rule-bolp)
2031 (save-excursion
2032 (and (member (funcall smie-backward-token-function)
2033 '("in" ";;"))
2034 (smie-rule-bolp))))
2035 (current-column)
2036 (smie-indent-calculate)))))
2037 (`(:before . ,(or `"|" `"&&" `"||"))
2038 (unless (smie-rule-parent-p token)
2039 (smie-backward-sexp token)
2040 `(column . ,(+ (funcall smie-rules-function :elem 'basic)
2041 (smie-indent-virtual)))))
2042
2043 ;; Attempt at backward compatibility with the old config variables.
2044 (`(:before . "fi") (sh-var-value 'sh-indent-for-fi))
2045 (`(:before . "done") (sh-var-value 'sh-indent-for-done))
2046 (`(:after . "else") (sh-var-value 'sh-indent-after-else))
2047 (`(:after . "if") (sh-var-value 'sh-indent-after-if))
2048 (`(:before . "then") (sh-var-value 'sh-indent-for-then))
2049 (`(:before . "do") (sh-var-value 'sh-indent-for-do))
2050 (`(:after . "do")
2051 (sh-var-value (if (smie-rule-hanging-p)
2052 'sh-indent-after-loop-construct 'sh-indent-after-do)))
2053 ;; sh-indent-after-done: aligned completely differently.
2054 (`(:after . "in") (sh-var-value 'sh-indent-for-case-label))
2055 ;; sh-indent-for-continuation: Line continuations are handled differently.
2056 (`(:after . ,(or `"(" `"{" `"[")) (sh-var-value 'sh-indent-after-open))
2057 ;; sh-indent-after-function: we don't handle it differently.
2058 ))
2059
2060 ;; (defconst sh-smie-csh-grammar
2061 ;; (smie-prec2->grammar
2062 ;; (smie-bnf->prec2
2063 ;; '((exp) ;A constant, or a $var, or a sequence of them...
2064 ;; (elseifcmd (cmd)
2065 ;; (cmd "else" "else-if" exp "then" elseifcmd))
2066 ;; (cmd ("switch" branches "endsw")
2067 ;; ("if" exp)
2068 ;; ("if" exp "then" cmd "endif")
2069 ;; ("if" exp "then" cmd "else" cmd "endif")
2070 ;; ("if" exp "then" elseifcmd "endif")
2071 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
2072 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2073 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2074 ;; ;; "else" cmd "endif")
2075 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2076 ;; ;; "else" "if" exp "then" cmd "endif")
2077 ;; ("while" cmd "end")
2078 ;; ("foreach" cmd "end")
2079 ;; (cmd "|" cmd) (cmd "|&" cmd)
2080 ;; (cmd "&&" cmd) (cmd "||" cmd)
2081 ;; (cmd ";" cmd) (cmd "&" cmd))
2082 ;; ;; This is a lie, but (combined with the corresponding disambiguation
2083 ;; ;; rule) it makes it more clear that `case' and `default' are the key
2084 ;; ;; separators and the `:' is a secondary tokens.
2085 ;; (branches (branches "case" branches)
2086 ;; (branches "default" branches)
2087 ;; (exp ":" branches)))
2088 ;; '((assoc "else" "then" "endif"))
2089 ;; '((assoc "case" "default") (nonassoc ":"))
2090 ;; '((assoc ";;" ";&" ";;&"))
2091 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2092
2093 ;;;; SMIE support for `rc'.
2094
2095 (defconst sh-smie-rc-grammar
2096 (smie-prec2->grammar
2097 (smie-bnf->prec2
2098 '((exp) ;A constant, or a $var, or a sequence of them...
2099 (cmd (cmd "case" cmd)
2100 ("if" exp)
2101 ("switch" exp)
2102 ("for" exp) ("while" exp)
2103 (cmd "|" cmd) (cmd "|&" cmd)
2104 (cmd "&&" cmd) (cmd "||" cmd)
2105 (cmd ";" cmd) (cmd "&" cmd))
2106 (pattern (pattern "|" pattern))
2107 (branches (branches ";;" branches)
2108 (branches ";&" branches) (branches ";;&" branches) ;bash.
2109 (pattern "case-)" cmd)))
2110 '((assoc ";;" ";&" ";;&"))
2111 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2112
2113 (defun sh-smie--rc-after-special-arg-p ()
2114 "Check if we're after the first arg of an if/while/for/... construct.
2115 Returns the construct's token and moves point before it, if so."
2116 (forward-comment (- (point)))
2117 (when (looking-back ")\\|\\_<not" (- (point) 3))
2118 (ignore-errors
2119 (let ((forward-sexp-function nil))
2120 (forward-sexp -1)
2121 (car (member (funcall smie-backward-token-function)
2122 '("if" "for" "switch" "while")))))))
2123
2124 (defun sh-smie--rc-newline-semi-p ()
2125 "Return non-nil if a newline should be treated as a semi-colon.
2126 Point should be before the newline."
2127 (save-excursion
2128 (let ((tok (funcall smie-backward-token-function)))
2129 (if (or (when (equal tok "not") (forward-word 1) t)
2130 (and (zerop (length tok)) (eq (char-before) ?\))))
2131 (not (sh-smie--rc-after-special-arg-p))
2132 (sh-smie--newline-semi-p tok)))))
2133
2134 (defun sh-smie-rc-forward-token ()
2135 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2136 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2137 (save-excursion
2138 (skip-chars-backward " \t")
2139 (not (bolp))))
2140 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2141 ;; Right before a here-doc.
2142 (let ((forward-sexp-function nil))
2143 (forward-sexp 1)
2144 ;; Pretend the here-document is a "newline representing a
2145 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2146 ";")
2147 (let ((semi (sh-smie--rc-newline-semi-p)))
2148 (forward-line 1)
2149 (if (or semi (eobp)) ";"
2150 (sh-smie-rc-forward-token))))
2151 (forward-comment (point-max))
2152 (cond
2153 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2154 ;; ((looking-at sh-smie--rc-operators-re)
2155 ;; (goto-char (match-end 0))
2156 ;; (let ((tok (match-string-no-properties 0)))
2157 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2158 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2159 ;; (forward-line 1))
2160 ;; tok))
2161 (t
2162 (let* ((pos (point))
2163 (tok (sh-smie--default-forward-token)))
2164 (cond
2165 ;; ((equal tok ")") "case-)")
2166 ((and tok (string-match "\\`[a-z]" tok)
2167 (assoc tok smie-grammar)
2168 (not
2169 (save-excursion
2170 (goto-char pos)
2171 (sh-smie--keyword-p))))
2172 " word ")
2173 (t tok)))))))
2174
2175 (defun sh-smie-rc-backward-token ()
2176 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
2177 (let ((bol (line-beginning-position)))
2178 (forward-comment (- (point)))
2179 (cond
2180 ((and (bolp) (not (bobp))
2181 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2182 (not (nth 3 (syntax-ppss))))
2183 ;; Right after a here-document.
2184 (let ((forward-sexp-function nil))
2185 (forward-sexp -1)
2186 ;; Pretend the here-document is a "newline representing a
2187 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2188 ";"))
2189 ((< (point) bol) ;We skipped over a newline.
2190 (cond
2191 ;; A continued line.
2192 ((and (eolp)
2193 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2194 (line-beginning-position)))
2195 (forward-char -1)
2196 (funcall smie-backward-token-function))
2197 ((sh-smie--rc-newline-semi-p) ";")
2198 (t (funcall smie-backward-token-function))))
2199 ;; ((looking-back sh-smie--sh-operators-back-re
2200 ;; (line-beginning-position) 'greedy)
2201 ;; (goto-char (match-beginning 1))
2202 ;; (match-string-no-properties 1))
2203 (t
2204 (let ((tok (sh-smie--default-backward-token)))
2205 (cond
2206 ;; ((equal tok ")") "case-)")
2207 ((and tok (string-match "\\`[a-z]" tok)
2208 (assoc tok smie-grammar)
2209 (not (save-excursion (sh-smie--keyword-p))))
2210 " word ")
2211 (t tok)))))))
2212
2213 (defun sh-smie-rc-rules (kind token)
2214 (pcase (cons kind token)
2215 (`(:elem . basic) sh-indentation)
2216 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
2217 (`(:after . ";")
2218 (if (smie-rule-parent-p "case")
2219 (smie-rule-parent (sh-var-value 'sh-indent-after-case))))
2220 (`(:before . "{")
2221 (save-excursion
2222 (when (sh-smie--rc-after-special-arg-p)
2223 `(column . ,(current-column)))))
2224 (`(:before . ,(or `"(" `"{" `"["))
2225 (if (smie-rule-hanging-p) (smie-rule-parent)))
2226 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2227 ;; treated as an arg to (exp) by default, which indents it all wrong.
2228 ;; To handle it right, we should extend smie-indent-exps so that the
2229 ;; preceding keyword can give special rules. Currently the only special
2230 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2231 ;; with "(exp)", which is rarely the right thing to do, but is better
2232 ;; than nothing.
2233 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
2234 ;; sh-indent-after-switch: handled implicitly by the default { rule.
2235 ))
2236
2237 ;;; End of SMIE code.
2238
2239 (defvar sh-regexp-for-done nil
2240 "A buffer-local regexp to match opening keyword for done.")
2241
2242 (defvar sh-kw-alist nil
2243 "A buffer-local, since it is shell-type dependent, list of keywords.")
2244
2245 ;; ( key-word first-on-this on-prev-line )
2246 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2247 ;; having 3 elements:
2248 ;; a keyword
2249 ;; a rule to check when the keyword appears on "this" line
2250 ;; a rule to check when the keyword appears on "the previous" line
2251 ;; The keyword is usually a string and is the first word on a line.
2252 ;; If this keyword appears on the line whose indentation is to be
2253 ;; calculated, the rule in element 2 is called. If this returns
2254 ;; non-zero, the resulting point (which may be changed by the rule)
2255 ;; is used as the default indentation.
2256 ;; If it returned false or the keyword was not found in the table,
2257 ;; then the keyword from the previous line is looked up and the rule
2258 ;; in element 3 is called. In this case, however,
2259 ;; `sh-get-indent-info' does not stop but may keep going and test
2260 ;; other keywords against rules in element 3. This is because the
2261 ;; preceding line could have, for example, an opening "if" and an
2262 ;; opening "while" keyword and we need to add the indentation offsets
2263 ;; for both.
2264 ;;
2265 (defconst sh-kw
2266 '((sh
2267 ("if" nil sh-handle-prev-if)
2268 ("elif" sh-handle-this-else sh-handle-prev-else)
2269 ("else" sh-handle-this-else sh-handle-prev-else)
2270 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2271 ("then" sh-handle-this-then sh-handle-prev-then)
2272 ("(" nil sh-handle-prev-open)
2273 ("{" nil sh-handle-prev-open)
2274 ("[" nil sh-handle-prev-open)
2275 ("}" sh-handle-this-close nil)
2276 (")" sh-handle-this-close nil)
2277 ("]" sh-handle-this-close nil)
2278 ("case" nil sh-handle-prev-case)
2279 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2280 (case-label nil sh-handle-after-case-label) ;; ???
2281 (";;" nil sh-handle-prev-case-alt-end) ;; ???
2282 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2283 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2284 ("done" sh-handle-this-done sh-handle-prev-done)
2285 ("do" sh-handle-this-do sh-handle-prev-do))
2286
2287 ;; Note: we don't need specific stuff for bash and zsh shells;
2288 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2289 ;; these shells use.
2290 (rc
2291 ("{" nil sh-handle-prev-open)
2292 ("}" sh-handle-this-close nil)
2293 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
2294
2295
2296
2297 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
2298 "Set this buffer's shell to SHELL (a string).
2299 When used interactively, insert the proper starting #!-line,
2300 and make the visited file executable via `executable-set-magic',
2301 perhaps querying depending on the value of `executable-query'.
2302
2303 When this function is called noninteractively, INSERT-FLAG (the third
2304 argument) controls whether to insert a #!-line and think about making
2305 the visited file executable, and NO-QUERY-FLAG (the second argument)
2306 controls whether to query about making the visited file executable.
2307
2308 Calls the value of `sh-set-shell-hook' if set."
2309 (interactive (list (completing-read
2310 (format "Shell \(default %s\): "
2311 sh-shell-file)
2312 ;; This used to use interpreter-mode-alist, but that is
2313 ;; no longer appropriate now that uses regexps.
2314 ;; Maybe there could be a separate variable that lists
2315 ;; the shells, used here and to construct i-mode-alist.
2316 ;; But the following is probably good enough:
2317 (append (mapcar (lambda (e) (symbol-name (car e)))
2318 sh-ancestor-alist)
2319 '("csh" "rc" "sh"))
2320 nil nil nil nil sh-shell-file)
2321 (eq executable-query 'function)
2322 t))
2323 (if (string-match "\\.exe\\'" shell)
2324 (setq shell (substring shell 0 (match-beginning 0))))
2325 (setq sh-shell (sh-canonicalize-shell shell))
2326 (if insert-flag
2327 (setq sh-shell-file
2328 (executable-set-magic shell (sh-feature sh-shell-arg)
2329 no-query-flag insert-flag)))
2330 (setq mode-line-process (format "[%s]" sh-shell))
2331 (setq-local sh-shell-variables nil)
2332 (setq-local sh-shell-variables-initialized nil)
2333 (setq-local imenu-generic-expression
2334 (sh-feature sh-imenu-generic-expression))
2335 (let ((tem (sh-feature sh-mode-syntax-table-input)))
2336 (when tem
2337 (setq-local sh-mode-syntax-table
2338 (apply 'sh-mode-syntax-table tem))
2339 (set-syntax-table sh-mode-syntax-table)))
2340 (dolist (var (sh-feature sh-variables))
2341 (sh-remember-variable var))
2342 (if (setq-local sh-indent-supported-here
2343 (sh-feature sh-indent-supported))
2344 (progn
2345 (message "Setting up indent for shell type %s" sh-shell)
2346 (let ((mksym (lambda (name)
2347 (intern (format "sh-smie-%s-%s"
2348 sh-indent-supported-here name)))))
2349 (add-function :around (local 'smie--hanging-eolp-function)
2350 (lambda (orig)
2351 (if (looking-at "[ \t]*\\\\\n")
2352 (goto-char (match-end 0))
2353 (funcall orig))))
2354 (smie-setup (symbol-value (funcall mksym "grammar"))
2355 (funcall mksym "rules")
2356 :forward-token (funcall mksym "forward-token")
2357 :backward-token (funcall mksym "backward-token")))
2358 (unless sh-use-smie
2359 (setq-local parse-sexp-lookup-properties t)
2360 (setq-local sh-kw-alist (sh-feature sh-kw))
2361 (let ((regexp (sh-feature sh-kws-for-done)))
2362 (if regexp
2363 (setq-local sh-regexp-for-done
2364 (sh-mkword-regexpr (regexp-opt regexp t)))))
2365 (message "setting up indent stuff")
2366 ;; sh-mode has already made indent-line-function local
2367 ;; but do it in case this is called before that.
2368 (setq-local indent-line-function 'sh-indent-line))
2369 (if sh-make-vars-local
2370 (sh-make-vars-local))
2371 (message "Indentation setup for shell type %s" sh-shell))
2372 (message "No indentation for this shell type.")
2373 (setq indent-line-function 'sh-basic-indent-line))
2374 (when font-lock-mode
2375 (setq font-lock-set-defaults nil)
2376 (font-lock-set-defaults)
2377 (font-lock-flush))
2378 (setq sh-shell-process nil)
2379 (run-hooks 'sh-set-shell-hook))
2380
2381
2382 (defun sh-feature (alist &optional function)
2383 "Index ALIST by the current shell.
2384 If ALIST isn't a list where every element is a cons, it is returned as is.
2385 Else indexing follows an inheritance logic which works in two ways:
2386
2387 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2388 the alist contains no value for the current shell.
2389 The ultimate default is always `sh'.
2390
2391 - If the value thus looked up is a list starting with `sh-append',
2392 we call the function `sh-append' with the rest of the list as
2393 arguments, and use the value. However, the next element of the
2394 list is not used as-is; instead, we look it up recursively
2395 in ALIST to allow the function called to define the value for
2396 one shell to be derived from another shell.
2397 The value thus determined is physically replaced into the alist.
2398
2399 If FUNCTION is non-nil, it is called with one argument,
2400 the value thus obtained, and the result is used instead."
2401 (or (if (consp alist)
2402 ;; Check for something that isn't a valid alist.
2403 (let ((l alist))
2404 (while (and l (consp (car l)))
2405 (setq l (cdr l)))
2406 (if l alist)))
2407
2408 (let ((orig-sh-shell sh-shell))
2409 (let ((sh-shell sh-shell)
2410 elt val)
2411 (while (and sh-shell
2412 (not (setq elt (assq sh-shell alist))))
2413 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2414 ;; If the shell is not known, treat it as sh.
2415 (unless elt
2416 (setq elt (assq 'sh alist)))
2417 (setq val (cdr elt))
2418 (if (and (consp val)
2419 (memq (car val) '(sh-append sh-modify)))
2420 (setq val
2421 (apply (car val)
2422 ;; Refer to the value for a different shell,
2423 ;; as a kind of inheritance.
2424 (let ((sh-shell (car (cdr val))))
2425 (sh-feature alist))
2426 (cddr val))))
2427 (if function
2428 (setq sh-shell orig-sh-shell
2429 val (funcall function val)))
2430 val))))
2431
2432
2433
2434 ;; I commented this out because nobody calls it -- rms.
2435 ;;(defun sh-abbrevs (ancestor &rest list)
2436 ;; "If it isn't, define the current shell as abbrev table and fill that.
2437 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2438 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2439 ;;according to the remaining arguments NAMEi EXPANSIONi ...
2440 ;;EXPANSION may be either a string or a skeleton command."
2441 ;; (or (if (boundp sh-shell)
2442 ;; (symbol-value sh-shell))
2443 ;; (progn
2444 ;; (if (listp ancestor)
2445 ;; (nconc list ancestor))
2446 ;; (define-abbrev-table sh-shell ())
2447 ;; (if (vectorp ancestor)
2448 ;; (mapatoms (lambda (atom)
2449 ;; (or (eq atom 0)
2450 ;; (define-abbrev (symbol-value sh-shell)
2451 ;; (symbol-name atom)
2452 ;; (symbol-value atom)
2453 ;; (symbol-function atom))))
2454 ;; ancestor))
2455 ;; (while list
2456 ;; (define-abbrev (symbol-value sh-shell)
2457 ;; (car list)
2458 ;; (if (stringp (car (cdr list)))
2459 ;; (car (cdr list))
2460 ;; "")
2461 ;; (if (symbolp (car (cdr list)))
2462 ;; (car (cdr list))))
2463 ;; (setq list (cdr (cdr list)))))
2464 ;; (symbol-value sh-shell)))
2465
2466
2467 (defun sh-append (ancestor &rest list)
2468 "Return list composed of first argument (a list) physically appended to rest."
2469 (nconc list ancestor))
2470
2471
2472 (defun sh-modify (skeleton &rest list)
2473 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2474 (setq skeleton (copy-sequence skeleton))
2475 (while list
2476 (setcar (or (nthcdr (car list) skeleton)
2477 (error "Index %d out of bounds" (car list)))
2478 (car (cdr list)))
2479 (setq list (nthcdr 2 list)))
2480 skeleton)
2481
2482
2483 (defun sh-basic-indent-line ()
2484 "Indent a line for Sh mode (shell script mode).
2485 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2486 Lines containing only comments are considered empty."
2487 (interactive)
2488 (let ((previous (save-excursion
2489 (while (and (progn (beginning-of-line)
2490 (not (bobp)))
2491 (progn
2492 (forward-line -1)
2493 (back-to-indentation)
2494 (or (eolp)
2495 (eq (following-char) ?#)))))
2496 (current-column)))
2497 current)
2498 (save-excursion
2499 (indent-to (if (eq this-command 'newline-and-indent)
2500 previous
2501 (if (< (current-column)
2502 (setq current (progn (back-to-indentation)
2503 (current-column))))
2504 (if (eolp) previous 0)
2505 (delete-region (point)
2506 (progn (beginning-of-line) (point)))
2507 (if (eolp)
2508 (max previous (* (1+ (/ current sh-indentation))
2509 sh-indentation))
2510 (* (1+ (/ current sh-indentation)) sh-indentation))))))
2511 (if (< (current-column) (current-indentation))
2512 (skip-chars-forward " \t"))))
2513
2514
2515 (defun sh-execute-region (start end &optional flag)
2516 "Pass optional header and region to a subshell for noninteractive execution.
2517 The working directory is that of the buffer, and only environment variables
2518 are already set which is why you can mark a header within the script.
2519
2520 With a positive prefix ARG, instead of sending region, define header from
2521 beginning of buffer to point. With a negative prefix ARG, instead of sending
2522 region, clear header."
2523 (interactive "r\nP")
2524 (if flag
2525 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2526 (point-marker)))
2527 (if sh-header-marker
2528 (save-excursion
2529 (let (buffer-undo-list)
2530 (goto-char sh-header-marker)
2531 (append-to-buffer (current-buffer) start end)
2532 (shell-command-on-region (point-min)
2533 (setq end (+ sh-header-marker
2534 (- end start)))
2535 sh-shell-file)
2536 (delete-region sh-header-marker end)))
2537 (shell-command-on-region start end (concat sh-shell-file " -")))))
2538
2539
2540 (defun sh-remember-variable (var)
2541 "Make VARIABLE available for future completing reads in this buffer."
2542 (or (< (length var) sh-remember-variable-min)
2543 (getenv var)
2544 (assoc var sh-shell-variables)
2545 (push (cons var var) sh-shell-variables))
2546 var)
2547
2548
2549
2550 (defun sh-quoted-p ()
2551 "Is point preceded by an odd number of backslashes?"
2552 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
2553 \f
2554 ;; Indentation stuff.
2555 (defun sh-must-support-indent ()
2556 "Signal an error if the shell type for this buffer is not supported.
2557 Also, the buffer must be in Shell-script mode."
2558 (unless sh-indent-supported-here
2559 (error "This buffer's shell does not support indentation through Emacs")))
2560
2561 (defun sh-make-vars-local ()
2562 "Make the indentation variables local to this buffer.
2563 Normally they already are local. This command is provided in case
2564 variable `sh-make-vars-local' has been set to nil.
2565
2566 To revert all these variables to the global values, use
2567 command `sh-reset-indent-vars-to-global-values'."
2568 (interactive)
2569 (mapc 'make-local-variable sh-var-list)
2570 (message "Indentation variables are now local."))
2571
2572 (defun sh-reset-indent-vars-to-global-values ()
2573 "Reset local indentation variables to the global values.
2574 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2575 (interactive)
2576 (mapc 'kill-local-variable sh-var-list)
2577 (if sh-make-vars-local
2578 (mapcar 'make-local-variable sh-var-list)))
2579
2580
2581 ;; Theoretically these are only needed in shell and derived modes.
2582 ;; However, the routines which use them are only called in those modes.
2583 (defconst sh-special-keywords "then\\|do")
2584
2585 (defun sh-help-string-for-variable (var)
2586 "Construct a string for `sh-read-variable' when changing variable VAR ."
2587 (let ((msg (documentation-property var 'variable-documentation))
2588 (msg2 ""))
2589 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
2590 (setq msg2
2591 (format "\n
2592 You can enter a number (positive to increase indentation,
2593 negative to decrease indentation, zero for no change to indentation).
2594
2595 Or, you can enter one of the following symbols which are relative to
2596 the value of variable `sh-basic-offset'
2597 which in this buffer is currently %s.
2598
2599 \t%s."
2600 sh-basic-offset
2601 (mapconcat (lambda (x)
2602 (nth (1- (length x)) x))
2603 sh-symbol-list "\n\t"))))
2604 (concat
2605 ;; The following shows the global not the local value!
2606 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2607 msg msg2)))
2608
2609 (defun sh-read-variable (var)
2610 "Read a new value for indentation variable VAR."
2611 (let ((minibuffer-help-form `(sh-help-string-for-variable
2612 (quote ,var)))
2613 val)
2614 (setq val (read-from-minibuffer
2615 (format "New value for %s (press %s for help): "
2616 var (single-key-description help-char))
2617 (format "%s" (symbol-value var))
2618 nil t))
2619 val))
2620
2621
2622
2623 (defun sh-in-comment-or-string (start)
2624 "Return non-nil if START is in a comment or string."
2625 (save-excursion
2626 (let ((state (syntax-ppss start)))
2627 (or (nth 3 state) (nth 4 state)))))
2628
2629 (defun sh-goto-matching-if ()
2630 "Go to the matching if for a fi.
2631 This handles nested if..fi pairs."
2632 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2633 (if found
2634 (goto-char found))))
2635
2636
2637 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2638 ;; line whose indentation is being handled contain XXX;
2639 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2640
2641 (defun sh-handle-prev-if ()
2642 (list '(+ sh-indent-after-if)))
2643
2644 (defun sh-handle-this-else ()
2645 (if (sh-goto-matching-if)
2646 ;; (list "aligned to if")
2647 (list "aligned to if" '(+ sh-indent-for-else))
2648 nil
2649 ))
2650
2651 (defun sh-handle-prev-else ()
2652 (if (sh-goto-matching-if)
2653 (list '(+ sh-indent-after-if))
2654 ))
2655
2656 (defun sh-handle-this-fi ()
2657 (if (sh-goto-matching-if)
2658 (list "aligned to if" '(+ sh-indent-for-fi))
2659 nil
2660 ))
2661
2662 (defun sh-handle-prev-fi ()
2663 ;; Why do we have this rule? Because we must go back to the if
2664 ;; to get its indent. We may continue back from there.
2665 ;; We return nil because we don't have anything to add to result,
2666 ;; the side affect of setting align-point is all that matters.
2667 ;; we could return a comment (a string) but I can't think of a good one...
2668 (sh-goto-matching-if)
2669 nil)
2670
2671 (defun sh-handle-this-then ()
2672 (let ((p (sh-goto-matching-if)))
2673 (if p
2674 (list '(+ sh-indent-for-then))
2675 )))
2676
2677 (defun sh-handle-prev-then ()
2678 (let ((p (sh-goto-matching-if)))
2679 (if p
2680 (list '(+ sh-indent-after-if))
2681 )))
2682
2683 (defun sh-handle-prev-open ()
2684 (save-excursion
2685 (let ((x (sh-prev-stmt)))
2686 (if (and x
2687 (progn
2688 (goto-char x)
2689 (or
2690 (looking-at "function\\b")
2691 (looking-at "\\s-*\\S-+\\s-*()")
2692 )))
2693 (list '(+ sh-indent-after-function))
2694 (list '(+ sh-indent-after-open)))
2695 )))
2696
2697 (defun sh-handle-this-close ()
2698 (forward-char 1) ;; move over ")"
2699 (if (sh-safe-forward-sexp -1)
2700 (list "aligned to opening paren")))
2701
2702 (defun sh-goto-matching-case ()
2703 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2704 (if found (goto-char found))))
2705
2706 (defun sh-handle-prev-case ()
2707 ;; This is typically called when point is on same line as a case
2708 ;; we shouldn't -- and can't find prev-case
2709 (if (looking-at ".*\\<case\\>")
2710 (list '(+ sh-indent-for-case-label))
2711 (error "We don't seem to be on a line with a case"))) ;; debug
2712
2713 (defun sh-handle-this-esac ()
2714 (if (sh-goto-matching-case)
2715 (list "aligned to matching case")))
2716
2717 (defun sh-handle-prev-esac ()
2718 (if (sh-goto-matching-case)
2719 (list "matching case")))
2720
2721 (defun sh-handle-after-case-label ()
2722 (if (sh-goto-matching-case)
2723 (list '(+ sh-indent-for-case-alt))))
2724
2725 (defun sh-handle-prev-case-alt-end ()
2726 (if (sh-goto-matching-case)
2727 (list '(+ sh-indent-for-case-label))))
2728
2729 (defun sh-safe-forward-sexp (&optional arg)
2730 "Try and do a `forward-sexp', but do not error.
2731 Return new point if successful, nil if an error occurred."
2732 (condition-case nil
2733 (progn
2734 (forward-sexp (or arg 1))
2735 (point)) ;; return point if successful
2736 (error
2737 (sh-debug "oops!(1) %d" (point))
2738 nil))) ;; return nil if fail
2739
2740 (defun sh-goto-match-for-done ()
2741 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2742 (if found
2743 (goto-char found))))
2744
2745 (defun sh-handle-this-done ()
2746 (if (sh-goto-match-for-done)
2747 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2748
2749 (defun sh-handle-prev-done ()
2750 (if (sh-goto-match-for-done)
2751 (list "previous done")))
2752
2753 (defun sh-handle-this-do ()
2754 (if (sh-goto-match-for-done)
2755 (list '(+ sh-indent-for-do))))
2756
2757 (defun sh-handle-prev-do ()
2758 (cond
2759 ((save-restriction
2760 (narrow-to-region (point) (line-beginning-position))
2761 (sh-goto-match-for-done))
2762 (sh-debug "match for done found on THIS line")
2763 (list '(+ sh-indent-after-loop-construct)))
2764 ((sh-goto-match-for-done)
2765 (sh-debug "match for done found on PREV line")
2766 (list '(+ sh-indent-after-do)))
2767 (t
2768 (message "match for done NOT found")
2769 nil)))
2770
2771 ;; for rc:
2772 (defun sh-find-prev-switch ()
2773 "Find the line for the switch keyword matching this line's case keyword."
2774 (re-search-backward "\\<switch\\>" nil t))
2775
2776 (defun sh-handle-this-rc-case ()
2777 (if (sh-find-prev-switch)
2778 (list '(+ sh-indent-after-switch))
2779 ;; (list '(+ sh-indent-for-case-label))
2780 nil))
2781
2782 (defun sh-handle-prev-rc-case ()
2783 (list '(+ sh-indent-after-case)))
2784
2785 (defun sh-check-rule (n thing)
2786 (let ((rule (nth n (assoc thing sh-kw-alist)))
2787 (val nil))
2788 (if rule
2789 (progn
2790 (setq val (funcall rule))
2791 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2792 n thing (point) rule val)))
2793 val))
2794
2795
2796 (defun sh-get-indent-info ()
2797 "Return indent-info for this line.
2798 This is a list. nil means the line is to be left as is.
2799 Otherwise it contains one or more of the following sublists:
2800 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2801 relative to. If present, this is always the first of the
2802 sublists. The indentation of the line in question is
2803 derived from the indentation of this point, possibly
2804 modified by subsequent sublists.
2805 \(+ VAR\)
2806 \(- VAR\) Get the value of variable VAR and add to or subtract from
2807 the indentation calculated so far.
2808 \(= VAR\) Get the value of variable VAR and *replace* the
2809 indentation with its value. This only occurs for
2810 special variables such as `sh-indent-comment'.
2811 STRING This is ignored for the purposes of calculating
2812 indentation, it is printed in certain cases to help show
2813 what the indentation is based on."
2814 ;; See comments before `sh-kw'.
2815 (save-excursion
2816 (let ((have-result nil)
2817 this-kw
2818 val
2819 (result nil)
2820 (align-point nil)
2821 prev-line-end x)
2822 (beginning-of-line)
2823 ;; Note: setting result to t means we are done and will return nil.
2824 ;;(This function never returns just t.)
2825 (cond
2826 ((or (nth 3 (syntax-ppss (point)))
2827 (eq (get-text-property (point) 'face) sh-heredoc-face))
2828 ;; String continuation -- don't indent
2829 (setq result t)
2830 (setq have-result t))
2831 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2832 (if (bobp)
2833 (setq result t) ;; return nil if 1st line!
2834 (setq result (list '(= sh-indent-comment)))
2835 ;; we still need to get previous line in case
2836 ;; sh-indent-comment is t (indent as normal)
2837 (setq align-point (sh-prev-line nil))
2838 (setq have-result nil)
2839 ))
2840 ) ;; cond
2841
2842 (unless have-result
2843 ;; Continuation lines are handled specially
2844 (if (sh-this-is-a-continuation)
2845 (progn
2846 (setq result
2847 (if (save-excursion
2848 (beginning-of-line)
2849 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2850 ;; By convention, if the continuation \ is not
2851 ;; preceded by a SPC or a TAB it means that the line
2852 ;; is cut at a place where spaces cannot be freely
2853 ;; added/removed. I.e. do not indent the line.
2854 (list '(= nil))
2855 ;; We assume the line being continued is already
2856 ;; properly indented...
2857 ;; (setq prev-line-end (sh-prev-line))
2858 (setq align-point (sh-prev-line nil))
2859 (list '(+ sh-indent-for-continuation))))
2860 (setq have-result t))
2861 (beginning-of-line)
2862 (skip-chars-forward " \t")
2863 (setq this-kw (sh-get-kw)))
2864
2865 ;; Handle "this" keyword: first word on the line we're
2866 ;; calculating indentation info for.
2867 (if this-kw
2868 (if (setq val (sh-check-rule 1 this-kw))
2869 (progn
2870 (setq align-point (point))
2871 (sh-debug
2872 "this - setting align-point to %d" align-point)
2873 (setq result (append result val))
2874 (setq have-result t)
2875 ;; set prev-line to continue processing remainder
2876 ;; of this line as a previous line
2877 (setq prev-line-end (point))
2878 ))))
2879
2880 (unless have-result
2881 (setq prev-line-end (sh-prev-line 'end)))
2882
2883 (if prev-line-end
2884 (save-excursion
2885 ;; We start off at beginning of this line.
2886 ;; Scan previous statements while this is <=
2887 ;; start of previous line.
2888 (goto-char prev-line-end)
2889 (setq x t)
2890 (while (and x (setq x (sh-prev-thing)))
2891 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2892 (cond
2893 ((and (equal x ")")
2894 (equal (get-text-property (1- (point)) 'syntax-table)
2895 sh-st-punc))
2896 (sh-debug "Case label) here")
2897 (setq x 'case-label)
2898 (if (setq val (sh-check-rule 2 x))
2899 (progn
2900 (setq result (append result val))
2901 (setq align-point (point))))
2902 (or (bobp)
2903 (forward-char -1))
2904 ;; FIXME: This charset looks too much like a regexp. --Stef
2905 (skip-chars-forward "[a-z0-9]*?")
2906 )
2907 ((string-match "[])}]" x)
2908 (setq x (sh-safe-forward-sexp -1))
2909 (if x
2910 (progn
2911 (setq align-point (point))
2912 (setq result (append result
2913 (list "aligned to opening paren")))
2914 )))
2915 ((string-match "[[({]" x)
2916 (sh-debug "Checking special thing: %s" x)
2917 (if (setq val (sh-check-rule 2 x))
2918 (setq result (append result val)))
2919 (forward-char -1)
2920 (setq align-point (point)))
2921 ((string-match "[\"'`]" x)
2922 (sh-debug "Skipping back for %s" x)
2923 ;; this was oops-2
2924 (setq x (sh-safe-forward-sexp -1)))
2925 ((stringp x)
2926 (sh-debug "Checking string %s at %s" x (point))
2927 (if (setq val (sh-check-rule 2 x))
2928 ;; (or (eq t (car val))
2929 ;; (eq t (car (car val))))
2930 (setq result (append result val)))
2931 ;; not sure about this test Wed Jan 27 23:48:35 1999
2932 (setq align-point (point))
2933 (unless (bolp)
2934 (forward-char -1)))
2935 (t
2936 (error "Don't know what to do with %s" x))
2937 )
2938 ) ;; while
2939 (sh-debug "result is %s" result)
2940 )
2941 (sh-debug "No prev line!")
2942 (sh-debug "result: %s align-point: %s" result align-point)
2943 )
2944
2945 (if align-point
2946 ;; was: (setq result (append result (list (list t align-point))))
2947 (setq result (append (list (list t align-point)) result))
2948 )
2949 (sh-debug "result is now: %s" result)
2950
2951 (or result
2952 (setq result (list (if prev-line-end
2953 (list t prev-line-end)
2954 (list '= 'sh-first-lines-indent)))))
2955
2956 (if (eq result t)
2957 (setq result nil))
2958 (sh-debug "result is: %s" result)
2959 result
2960 ) ;; let
2961 ))
2962
2963
2964 (defun sh-get-indent-var-for-line (&optional info)
2965 "Return the variable controlling indentation for this line.
2966 If there is not [just] one such variable, return a string
2967 indicating the problem.
2968 If INFO is supplied it is used, else it is calculated."
2969 (let ((var nil)
2970 (result nil)
2971 (reason nil)
2972 sym elt)
2973 (or info
2974 (setq info (sh-get-indent-info)))
2975 (if (null info)
2976 (setq result "this line to be left as is")
2977 (while (and info (null result))
2978 (setq elt (car info))
2979 (cond
2980 ((stringp elt)
2981 (setq reason elt)
2982 )
2983 ((not (listp elt))
2984 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2985 ;; so it is a list
2986 ((eq t (car elt))
2987 ) ;; nothing
2988 ((symbolp (setq sym (nth 1 elt)))
2989 ;; A bit of a kludge - when we see the sh-indent-comment
2990 ;; ignore other variables. Otherwise it is tricky to
2991 ;; "learn" the comment indentation.
2992 (if (eq var 'sh-indent-comment)
2993 (setq result var)
2994 (if var
2995 (setq result
2996 "this line is controlled by more than 1 variable.")
2997 (setq var sym))))
2998 (t
2999 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
3000 (setq info (cdr info))
3001 ))
3002 (or result
3003 (setq result var))
3004 (or result
3005 (setq result reason))
3006 (if (null result)
3007 ;; e.g. just had (t POS)
3008 (setq result "line has default indentation"))
3009 result))
3010
3011
3012
3013 ;; Finding the previous line isn't trivial.
3014 ;; We must *always* go back one more and see if that is a continuation
3015 ;; line -- it is the PREVIOUS line which is continued, not the one
3016 ;; we are going to!
3017 ;; Also, we want to treat a whole "here document" as one big line,
3018 ;; because we may want to a align to the beginning of it.
3019 ;;
3020 ;; What we do:
3021 ;; - go back to previous non-empty line
3022 ;; - if this is in a here-document, go to the beginning of it
3023 ;; - while previous line is continued, go back one line
3024 (defun sh-prev-line (&optional end)
3025 "Back to end of previous non-comment non-empty line.
3026 Go to beginning of logical line unless END is non-nil, in which case
3027 we go to the end of the previous line and do not check for continuations."
3028 (save-excursion
3029 (beginning-of-line)
3030 (forward-comment (- (point-max)))
3031 (unless end (beginning-of-line))
3032 (when (and (not (bobp))
3033 (equal (get-text-property (1- (point)) 'face)
3034 sh-heredoc-face))
3035 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
3036 (when p1
3037 (goto-char p1)
3038 (if end
3039 (end-of-line)
3040 (beginning-of-line)))))
3041 (unless end
3042 ;; we must check previous lines to see if they are continuation lines
3043 ;; if so, we must return position of first of them
3044 (while (and (sh-this-is-a-continuation)
3045 (>= 0 (forward-line -1))))
3046 (beginning-of-line)
3047 (skip-chars-forward " \t"))
3048 (point)))
3049
3050
3051 (defun sh-prev-stmt ()
3052 "Return the address of the previous stmt or nil."
3053 ;; This is used when we are trying to find a matching keyword.
3054 ;; Searching backward for the keyword would certainly be quicker, but
3055 ;; it is hard to remove "false matches" -- such as if the keyword
3056 ;; appears in a string or quote. This way is slower, but (I think) safer.
3057 (interactive)
3058 (save-excursion
3059 (let ((going t)
3060 (start (point))
3061 (found nil)
3062 (prev nil))
3063 (skip-chars-backward " \t;|&({[")
3064 (while (and (not found)
3065 (not (bobp))
3066 going)
3067 ;; Do a backward-sexp if possible, else backup bit by bit...
3068 (if (sh-safe-forward-sexp -1)
3069 (progn
3070 (if (looking-at sh-special-keywords)
3071 (progn
3072 (setq found prev))
3073 (setq prev (point))
3074 ))
3075 ;; backward-sexp failed
3076 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
3077 (forward-char -1))
3078 (if (bolp)
3079 (let ((back (sh-prev-line nil)))
3080 (if back
3081 (goto-char back)
3082 (setq going nil)))))
3083 (unless found
3084 (skip-chars-backward " \t")
3085 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
3086 (eq (char-before) ?\;)
3087 (looking-at "\\s-*[|&]"))
3088 (setq found (point)))))
3089 (if found
3090 (goto-char found))
3091 (if found
3092 (progn
3093 (skip-chars-forward " \t|&({[")
3094 (setq found (point))))
3095 (if (>= (point) start)
3096 (progn
3097 (debug "We didn't move!")
3098 (setq found nil))
3099 (or found
3100 (sh-debug "Did not find prev stmt.")))
3101 found)))
3102
3103
3104 (defun sh-get-word ()
3105 "Get a shell word skipping whitespace from point."
3106 (interactive)
3107 (skip-chars-forward "\t ")
3108 (let ((start (point)))
3109 (while
3110 (if (looking-at "[\"'`]")
3111 (sh-safe-forward-sexp)
3112 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
3113 (> (skip-chars-forward "-_$[:alnum:]") 0)
3114 ))
3115 (buffer-substring start (point))
3116 ))
3117
3118 (defun sh-prev-thing ()
3119 "Return the previous thing this logical line."
3120 ;; This is called when `sh-get-indent-info' is working backwards on
3121 ;; the previous line(s) finding what keywords may be relevant for
3122 ;; indenting. It moves over sexps if possible, and will stop
3123 ;; on a ; and at the beginning of a line if it is not a continuation
3124 ;; line.
3125 ;;
3126 ;; Added a kludge for ";;"
3127 ;; Possible return values:
3128 ;; nil - nothing
3129 ;; a string - possibly a keyword
3130 ;;
3131 (if (bolp)
3132 nil
3133 (let ((start (point))
3134 (min-point (if (sh-this-is-a-continuation)
3135 (sh-prev-line nil)
3136 (line-beginning-position))))
3137 (skip-chars-backward " \t;" min-point)
3138 (if (looking-at "\\s-*;[;&]")
3139 ;; (message "Found ;; !")
3140 ";;"
3141 (skip-chars-backward "^)}];\"'`({[" min-point)
3142 (let ((c (if (> (point) min-point) (char-before))))
3143 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
3144 (point) c start min-point)
3145 (if (not (memq c '(?\n nil ?\;)))
3146 ;; c -- return a string
3147 (char-to-string c)
3148 ;; Return the leading keyword of the "command" we supposedly
3149 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
3150 ;; `then' that precedes the actual command), so check whether
3151 ;; we're looking at such a keyword and if so, move back forward.
3152 (let ((boundary (point))
3153 kwd next)
3154 (while
3155 (progn
3156 ;; Skip forward over white space newline and \ at eol.
3157 (skip-chars-forward " \t\n\\\\" start)
3158 (if (>= (point) start)
3159 (progn
3160 (sh-debug "point: %d >= start: %d" (point) start)
3161 nil)
3162 (if next (setq boundary next))
3163 (sh-debug "Now at %d start=%d" (point) start)
3164 (setq kwd (sh-get-word))
3165 (if (member kwd (sh-feature sh-leading-keywords))
3166 (progn
3167 (setq next (point))
3168 t)
3169 nil))))
3170 (goto-char boundary)
3171 kwd)))))))
3172
3173
3174 (defun sh-this-is-a-continuation ()
3175 "Return non-nil if current line is a continuation of previous line."
3176 (save-excursion
3177 (and (zerop (forward-line -1))
3178 (looking-at ".*\\\\$")
3179 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
3180 nil nil nil t))))))
3181
3182 (defun sh-get-kw (&optional where and-move)
3183 "Return first word of line from WHERE.
3184 If AND-MOVE is non-nil then move to end of word."
3185 (let ((start (point)))
3186 (if where
3187 (goto-char where))
3188 (prog1
3189 (buffer-substring (point)
3190 (progn (skip-chars-forward "^ \t\n;&|")(point)))
3191 (unless and-move
3192 (goto-char start)))))
3193
3194 (defun sh-find-prev-matching (open close &optional depth)
3195 "Find a matching token for a set of opening and closing keywords.
3196 This takes into account that there may be nested open..close pairings.
3197 OPEN and CLOSE are regexps denoting the tokens to be matched.
3198 Optional parameter DEPTH (usually 1) says how many to look for."
3199 (let ((parse-sexp-ignore-comments t)
3200 (forward-sexp-function nil)
3201 prev)
3202 (setq depth (or depth 1))
3203 (save-excursion
3204 (condition-case nil
3205 (while (and
3206 (/= 0 depth)
3207 (not (bobp))
3208 (setq prev (sh-prev-stmt)))
3209 (goto-char prev)
3210 (save-excursion
3211 (if (looking-at "\\\\\n")
3212 (progn
3213 (forward-char 2)
3214 (skip-chars-forward " \t")))
3215 (cond
3216 ((looking-at open)
3217 (setq depth (1- depth))
3218 (sh-debug "found open at %d - depth = %d" (point) depth))
3219 ((looking-at close)
3220 (setq depth (1+ depth))
3221 (sh-debug "found close - depth = %d" depth))
3222 (t
3223 ))))
3224 (error nil))
3225 (if (eq depth 0)
3226 prev ;; (point)
3227 nil)
3228 )))
3229
3230
3231 (defun sh-var-value (var &optional ignore-error)
3232 "Return the value of variable VAR, interpreting symbols.
3233 It can also return t or nil.
3234 If an invalid value is found, throw an error unless Optional argument
3235 IGNORE-ERROR is non-nil."
3236 (let ((val (symbol-value var)))
3237 (cond
3238 ((numberp val)
3239 val)
3240 ((eq val t)
3241 val)
3242 ((null val)
3243 val)
3244 ((eq val '+)
3245 sh-basic-offset)
3246 ((eq val '-)
3247 (- sh-basic-offset))
3248 ((eq val '++)
3249 (* 2 sh-basic-offset))
3250 ((eq val '--)
3251 (* 2 (- sh-basic-offset)))
3252 ((eq val '*)
3253 (/ sh-basic-offset 2))
3254 ((eq val '/)
3255 (/ (- sh-basic-offset) 2))
3256 (t
3257 (funcall (if ignore-error #'message #'error)
3258 "Don't know how to handle %s's value of %s" var val)
3259 0))))
3260
3261 (defun sh-set-var-value (var value &optional no-symbol)
3262 "Set variable VAR to VALUE.
3263 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3264 can be represented by a symbol then do so."
3265 (cond
3266 (no-symbol
3267 (set var value))
3268 ((= value sh-basic-offset)
3269 (set var '+))
3270 ((= value (- sh-basic-offset))
3271 (set var '-))
3272 ((eq value (* 2 sh-basic-offset))
3273 (set var '++))
3274 ((eq value (* 2 (- sh-basic-offset)))
3275 (set var '--))
3276 ((eq value (/ sh-basic-offset 2))
3277 (set var '*))
3278 ((eq value (/ (- sh-basic-offset) 2))
3279 (set var '/))
3280 (t
3281 (set var value)))
3282 )
3283
3284
3285 (defun sh-calculate-indent (&optional info)
3286 "Return the indentation for the current line.
3287 If INFO is supplied it is used, else it is calculated from current line."
3288 (let ((ofs 0)
3289 (base-value 0)
3290 elt a b val)
3291 (or info
3292 (setq info (sh-get-indent-info)))
3293 (when info
3294 (while info
3295 (sh-debug "info: %s ofs=%s" info ofs)
3296 (setq elt (car info))
3297 (cond
3298 ((stringp elt)) ;; do nothing?
3299 ((listp elt)
3300 (setq a (car (car info)))
3301 (setq b (nth 1 (car info)))
3302 (cond
3303 ((eq a t)
3304 (save-excursion
3305 (goto-char b)
3306 (setq val (current-indentation)))
3307 (setq base-value val))
3308 ((symbolp b)
3309 (setq val (sh-var-value b))
3310 (cond
3311 ((eq a '=)
3312 (cond
3313 ((null val)
3314 ;; no indentation
3315 ;; set info to nil so we stop immediately
3316 (setq base-value nil ofs nil info nil))
3317 ((eq val t) (setq ofs 0)) ;; indent as normal line
3318 (t
3319 ;; The following assume the (t POS) come first!
3320 (setq ofs val base-value 0)
3321 (setq info nil)))) ;; ? stop now
3322 ((eq a '+) (setq ofs (+ ofs val)))
3323 ((eq a '-) (setq ofs (- ofs val)))
3324 (t
3325 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3326 (t
3327 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
3328 (t
3329 (error "sh-calculate-indent invalid elt %s" elt)))
3330 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3331 a b val base-value ofs)
3332 (setq info (cdr info)))
3333 ;; return value:
3334 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
3335
3336 (cond
3337 ((or (null base-value)(null ofs))
3338 nil)
3339 ((and (numberp base-value)(numberp ofs))
3340 (sh-debug "base (%d) + ofs (%d) = %d"
3341 base-value ofs (+ base-value ofs))
3342 (+ base-value ofs)) ;; return value
3343 (t
3344 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3345 base-value ofs)
3346 nil)))))
3347
3348
3349 (defun sh-indent-line ()
3350 "Indent the current line."
3351 (interactive)
3352 (let ((indent (sh-calculate-indent))
3353 (pos (- (point-max) (point))))
3354 (when indent
3355 (beginning-of-line)
3356 (skip-chars-forward " \t")
3357 (indent-line-to indent)
3358 ;; If initial point was within line's indentation,
3359 ;; position after the indentation. Else stay at same point in text.
3360 (if (> (- (point-max) pos) (point))
3361 (goto-char (- (point-max) pos))))))
3362
3363
3364 (defun sh-blink (blinkpos &optional msg)
3365 "Move cursor momentarily to BLINKPOS and display MSG."
3366 ;; We can get here without it being a number on first line
3367 (if (numberp blinkpos)
3368 (save-excursion
3369 (goto-char blinkpos)
3370 (if msg (message "%s" msg) (message nil))
3371 (sit-for blink-matching-delay))
3372 (if msg (message "%s" msg) (message nil))))
3373
3374 (defun sh-show-indent (arg)
3375 "Show the how the current line would be indented.
3376 This tells you which variable, if any, controls the indentation of
3377 this line.
3378 If optional arg ARG is non-null (called interactively with a prefix),
3379 a pop up window describes this variable.
3380 If variable `sh-blink' is non-nil then momentarily go to the line
3381 we are indenting relative to, if applicable."
3382 (interactive "P")
3383 (sh-must-support-indent)
3384 (if sh-use-smie
3385 (smie-config-show-indent)
3386 (let* ((info (sh-get-indent-info))
3387 (var (sh-get-indent-var-for-line info))
3388 (curr-indent (current-indentation))
3389 val msg)
3390 (if (stringp var)
3391 (message "%s" (setq msg var))
3392 (setq val (sh-calculate-indent info))
3393
3394 (if (eq curr-indent val)
3395 (setq msg (format "%s is %s" var (symbol-value var)))
3396 (setq msg
3397 (if val
3398 (format "%s (%s) would change indent from %d to: %d"
3399 var (symbol-value var) curr-indent val)
3400 (format "%s (%s) would leave line as is"
3401 var (symbol-value var)))
3402 ))
3403 (if (and arg var)
3404 (describe-variable var)))
3405 (if sh-blink
3406 (let ((info (sh-get-indent-info)))
3407 (if (and info (listp (car info))
3408 (eq (car (car info)) t))
3409 (sh-blink (nth 1 (car info)) msg)
3410 (message "%s" msg)))
3411 (message "%s" msg))
3412 )))
3413
3414 (defun sh-set-indent ()
3415 "Set the indentation for the current line.
3416 If the current line is controlled by an indentation variable, prompt
3417 for a new value for it."
3418 (interactive)
3419 (sh-must-support-indent)
3420 (if sh-use-smie
3421 (smie-config-set-indent)
3422 (let* ((info (sh-get-indent-info))
3423 (var (sh-get-indent-var-for-line info))
3424 val old-val indent-val)
3425 (if (stringp var)
3426 (message "Cannot set indent - %s" var)
3427 (setq old-val (symbol-value var))
3428 (setq val (sh-read-variable var))
3429 (condition-case nil
3430 (progn
3431 (set var val)
3432 (setq indent-val (sh-calculate-indent info))
3433 (if indent-val
3434 (message "Variable: %s Value: %s would indent to: %d"
3435 var (symbol-value var) indent-val)
3436 (message "Variable: %s Value: %s would leave line as is."
3437 var (symbol-value var)))
3438 ;; I'm not sure about this, indenting it now?
3439 ;; No. Because it would give the impression that an undo would
3440 ;; restore thing, but the value has been altered.
3441 ;; (sh-indent-line)
3442 )
3443 (error
3444 (set var old-val)
3445 (message "Bad value for %s, restoring to previous value %s"
3446 var old-val)
3447 (sit-for 1)
3448 nil))
3449 ))))
3450
3451
3452 (defun sh-learn-line-indent (arg)
3453 "Learn how to indent a line as it currently is indented.
3454
3455 If there is an indentation variable which controls this line's indentation,
3456 then set it to a value which would indent the line the way it
3457 presently is.
3458
3459 If the value can be represented by one of the symbols then do so
3460 unless optional argument ARG (the prefix when interactive) is non-nil."
3461 (interactive "*P")
3462 (sh-must-support-indent)
3463 (if sh-use-smie
3464 (smie-config-set-indent)
3465 ;; I'm not sure if we show allow learning on an empty line.
3466 ;; Though it might occasionally be useful I think it usually
3467 ;; would just be confusing.
3468 (if (save-excursion
3469 (beginning-of-line)
3470 (looking-at "\\s-*$"))
3471 (message "sh-learn-line-indent ignores empty lines.")
3472 (let* ((info (sh-get-indent-info))
3473 (var (sh-get-indent-var-for-line info))
3474 ival sval diff new-val
3475 (no-symbol arg)
3476 (curr-indent (current-indentation)))
3477 (cond
3478 ((stringp var)
3479 (message "Cannot learn line - %s" var))
3480 ((eq var 'sh-indent-comment)
3481 ;; This is arbitrary...
3482 ;; - if curr-indent is 0, set to curr-indent
3483 ;; - else if it has the indentation of a "normal" line,
3484 ;; then set to t
3485 ;; - else set to curr-indent.
3486 (setq sh-indent-comment
3487 (if (= curr-indent 0)
3488 0
3489 (let* ((sh-indent-comment t)
3490 (val2 (sh-calculate-indent info)))
3491 (if (= val2 curr-indent)
3492 t
3493 curr-indent))))
3494 (message "%s set to %s" var (symbol-value var))
3495 )
3496 ((numberp (setq sval (sh-var-value var)))
3497 (setq ival (sh-calculate-indent info))
3498 (setq diff (- curr-indent ival))
3499
3500 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3501 curr-indent ival diff var sval)
3502 (setq new-val (+ sval diff))
3503 ;; I commented out this because someone might want to replace
3504 ;; a value of `+' with the current value of sh-basic-offset
3505 ;; or vice-versa.
3506 ;;(if (= 0 diff)
3507 ;; (message "No change needed!")
3508 (sh-set-var-value var new-val no-symbol)
3509 (message "%s set to %s" var (symbol-value var))
3510 )
3511 (t
3512 (debug)
3513 (message "Cannot change %s" var)))))))
3514
3515
3516
3517 (defun sh-mark-init (buffer)
3518 "Initialize a BUFFER to be used by `sh-mark-line'."
3519 (with-current-buffer (get-buffer-create buffer)
3520 (erase-buffer)
3521 (occur-mode)))
3522
3523
3524 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
3525 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3526 Buffer BUFFER is in `occur-mode'.
3527 If ADD-LINENUM is non-nil the message is preceded by the line number.
3528 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3529 so that `occur-next' and `occur-prev' will work."
3530 (let ((m1 (make-marker))
3531 start
3532 (line ""))
3533 (when point
3534 (set-marker m1 point (current-buffer))
3535 (if add-linenum
3536 (setq line (format "%d: " (1+ (count-lines 1 point))))))
3537 (save-excursion
3538 (if (get-buffer buffer)
3539 (set-buffer (get-buffer buffer))
3540 (set-buffer (get-buffer-create buffer))
3541 (occur-mode)
3542 )
3543 (goto-char (point-max))
3544 (setq start (point))
3545 (let ((inhibit-read-only t))
3546 (insert line)
3547 (if occur-point
3548 (setq occur-point (point)))
3549 (insert message)
3550 (if point
3551 (add-text-properties
3552 start (point)
3553 '(mouse-face highlight
3554 help-echo "mouse-2: go to the line where I learned this")))
3555 (insert "\n")
3556 (when point
3557 (put-text-property start (point) 'occur-target m1)
3558 (if occur-point
3559 (put-text-property start occur-point
3560 'occur-match t))
3561 )))))
3562
3563 ;; Is this really worth having?
3564 (defvar sh-learned-buffer-hook nil
3565 "An abnormal hook, called with an alist of learned variables.")
3566 ;; Example of how to use sh-learned-buffer-hook
3567 ;;
3568 ;; (defun what-i-learned (list)
3569 ;; (let ((p list))
3570 ;; (with-current-buffer "*scratch*"
3571 ;; (goto-char (point-max))
3572 ;; (insert "(setq\n")
3573 ;; (while p
3574 ;; (insert (format " %s %s \n"
3575 ;; (nth 0 (car p)) (nth 1 (car p))))
3576 ;; (setq p (cdr p)))
3577 ;; (insert ")\n")
3578 ;; )))
3579 ;;
3580 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3581
3582
3583 ;; Originally this was sh-learn-region-indent (beg end)
3584 ;; However, in practice this was awkward so I changed it to
3585 ;; use the whole buffer. Use narrowing if need be.
3586 (defun sh-learn-buffer-indent (&optional arg)
3587 "Learn how to indent the buffer the way it currently is.
3588
3589 Output in buffer \"*indent*\" shows any lines which have conflicting
3590 values of a variable, and the final value of all variables learned.
3591 When called interactively, pop to this buffer automatically if
3592 there are any discrepancies.
3593
3594 If no prefix ARG is given, then variables are set to numbers.
3595 If a prefix arg is given, then variables are set to symbols when
3596 applicable -- e.g. to symbol `+' if the value is that of the
3597 basic indent.
3598 If a positive numerical prefix is given, then `sh-basic-offset'
3599 is set to the prefix's numerical value.
3600 Otherwise, sh-basic-offset may or may not be changed, according
3601 to the value of variable `sh-learn-basic-offset'.
3602
3603 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3604 function completes. The function is abnormal because it is called
3605 with an alist of variables learned. This feature may be changed or
3606 removed in the future.
3607
3608 This command can often take a long time to run."
3609 (interactive "P")
3610 (sh-must-support-indent)
3611 (if sh-use-smie
3612 (smie-config-guess)
3613 (save-excursion
3614 (goto-char (point-min))
3615 (let ((learned-var-list nil)
3616 (out-buffer "*indent*")
3617 (num-diffs 0)
3618 previous-set-info
3619 (max 17)
3620 vec
3621 msg
3622 (comment-col nil) ;; number if all same, t if seen diff values
3623 (comments-always-default t) ;; nil if we see one not default
3624 initial-msg
3625 (specified-basic-offset (and arg (numberp arg)
3626 (> arg 0)))
3627 (linenum 0)
3628 suggested)
3629 (setq vec (make-vector max 0))
3630 (sh-mark-init out-buffer)
3631
3632 (if specified-basic-offset
3633 (progn
3634 (setq sh-basic-offset arg)
3635 (setq initial-msg
3636 (format "Using specified sh-basic-offset of %d"
3637 sh-basic-offset)))
3638 (setq initial-msg
3639 (format "Initial value of sh-basic-offset: %s"
3640 sh-basic-offset)))
3641
3642 (while (< (point) (point-max))
3643 (setq linenum (1+ linenum))
3644 ;; (if (zerop (% linenum 10))
3645 (message "line %d" linenum)
3646 ;; )
3647 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3648 (let* ((sh-indent-comment t) ;; info must return default indent
3649 (info (sh-get-indent-info))
3650 (var (sh-get-indent-var-for-line info))
3651 sval ival diff new-val
3652 (curr-indent (current-indentation)))
3653 (cond
3654 ((null var)
3655 nil)
3656 ((stringp var)
3657 nil)
3658 ((numberp (setq sval (sh-var-value var 'no-error)))
3659 ;; the numberp excludes comments since sval will be t.
3660 (setq ival (sh-calculate-indent))
3661 (setq diff (- curr-indent ival))
3662 (setq new-val (+ sval diff))
3663 (sh-set-var-value var new-val 'no-symbol)
3664 (unless (looking-at "\\s-*#") ;; don't learn from comments
3665 (if (setq previous-set-info (assoc var learned-var-list))
3666 (progn
3667 ;; it was already there, is it same value ?
3668 (unless (eq (symbol-value var)
3669 (nth 1 previous-set-info))
3670 (sh-mark-line
3671 (format "Variable %s was set to %s"
3672 var (symbol-value var))
3673 (point) out-buffer t t)
3674 (sh-mark-line
3675 (format " but was previously set to %s"
3676 (nth 1 previous-set-info))
3677 (nth 2 previous-set-info) out-buffer t)
3678 (setq num-diffs (1+ num-diffs))
3679 ;; (delete previous-set-info learned-var-list)
3680 (setcdr previous-set-info
3681 (list (symbol-value var) (point)))
3682 )
3683 )
3684 (setq learned-var-list
3685 (append (list (list var (symbol-value var)
3686 (point)))
3687 learned-var-list)))
3688 (if (numberp new-val)
3689 (progn
3690 (sh-debug
3691 "This line's indent value: %d" new-val)
3692 (if (< new-val 0)
3693 (setq new-val (- new-val)))
3694 (if (< new-val max)
3695 (aset vec new-val (1+ (aref vec new-val))))))
3696 ))
3697 ((eq var 'sh-indent-comment)
3698 (unless (= curr-indent (sh-calculate-indent info))
3699 ;; this is not the default indentation
3700 (setq comments-always-default nil)
3701 (if comment-col ;; then we have see one before
3702 (or (eq comment-col curr-indent)
3703 (setq comment-col t)) ;; seen a different one
3704 (setq comment-col curr-indent))
3705 ))
3706 (t
3707 (sh-debug "Cannot learn this line!!!")
3708 ))
3709 (sh-debug
3710 "at %s learned-var-list is %s" (point) learned-var-list)
3711 ))
3712 (forward-line 1)
3713 ) ;; while
3714 (if sh-debug
3715 (progn
3716 (setq msg (format
3717 "comment-col = %s comments-always-default = %s"
3718 comment-col comments-always-default))
3719 ;; (message msg)
3720 (sh-mark-line msg nil out-buffer)))
3721 (cond
3722 ((eq comment-col 0)
3723 (setq msg "\nComments are all in 1st column.\n"))
3724 (comments-always-default
3725 (setq msg "\nComments follow default indentation.\n")
3726 (setq comment-col t))
3727 ((numberp comment-col)
3728 (setq msg (format "\nComments are in col %d." comment-col)))
3729 (t
3730 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3731 (setq comment-col nil)
3732 ))
3733 (sh-debug msg)
3734 (sh-mark-line msg nil out-buffer)
3735
3736 (sh-mark-line initial-msg nil out-buffer t t)
3737
3738 (setq suggested (sh-guess-basic-offset vec))
3739
3740 (if (and suggested (not specified-basic-offset))
3741 (let ((new-value
3742 (cond
3743 ;; t => set it if we have a single value as a number
3744 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3745 suggested)
3746 ;; other non-nil => set it if only one value was found
3747 (sh-learn-basic-offset
3748 (if (numberp suggested)
3749 suggested
3750 (if (= (length suggested) 1)
3751 (car suggested))))
3752 (t
3753 nil))))
3754 (if new-value
3755 (progn
3756 (setq learned-var-list
3757 (append (list (list 'sh-basic-offset
3758 (setq sh-basic-offset new-value)
3759 (point-max)))
3760 learned-var-list))
3761 ;; Not sure if we need to put this line in, since
3762 ;; it will appear in the "Learned variable settings".
3763 (sh-mark-line
3764 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3765 nil out-buffer))
3766 (sh-mark-line
3767 (if (listp suggested)
3768 (format "Possible value(s) for sh-basic-offset: %s"
3769 (mapconcat 'int-to-string suggested " "))
3770 (format "Suggested sh-basic-offset: %d" suggested))
3771 nil out-buffer))))
3772
3773
3774 (setq learned-var-list
3775 (append (list (list 'sh-indent-comment comment-col (point-max)))
3776 learned-var-list))
3777 (setq sh-indent-comment comment-col)
3778 (let ((name (buffer-name)))
3779 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3780 (if arg
3781 ;; Set learned variables to symbolic rather than numeric
3782 ;; values where possible.
3783 (dolist (learned-var (reverse learned-var-list))
3784 (let ((var (car learned-var))
3785 (val (nth 1 learned-var)))
3786 (when (and (not (eq var 'sh-basic-offset))
3787 (numberp val))
3788 (sh-set-var-value var val)))))
3789 (dolist (learned-var (reverse learned-var-list))
3790 (let ((var (car learned-var)))
3791 (sh-mark-line (format " %s %s" var (symbol-value var))
3792 (nth 2 learned-var) out-buffer)))
3793 (with-current-buffer out-buffer
3794 (goto-char (point-min))
3795 (let ((inhibit-read-only t))
3796 (insert
3797 (format "Indentation values for buffer %s.\n" name)
3798 (format "%d indentation variable%s different values%s\n\n"
3799 num-diffs
3800 (if (= num-diffs 1)
3801 " has" "s have")
3802 (if (zerop num-diffs)
3803 "." ":"))))))
3804 ;; Are abnormal hooks considered bad form?
3805 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3806 (and (called-interactively-p 'any)
3807 (or sh-popup-occur-buffer (> num-diffs 0))
3808 (pop-to-buffer out-buffer))))))
3809
3810 (defun sh-guess-basic-offset (vec)
3811 "See if we can determine a reasonable value for `sh-basic-offset'.
3812 This is experimental, heuristic and arbitrary!
3813 Argument VEC is a vector of information collected by
3814 `sh-learn-buffer-indent'.
3815 Return values:
3816 number - there appears to be a good single value
3817 list of numbers - no obvious one, here is a list of one or more
3818 reasonable choices
3819 nil - we couldn't find a reasonable one."
3820 (let* ((max (1- (length vec)))
3821 (i 1)
3822 (totals (make-vector max 0)))
3823 (while (< i max)
3824 (cl-incf (aref totals i) (* 4 (aref vec i)))
3825 (if (zerop (% i 2))
3826 (cl-incf (aref totals i) (aref vec (/ i 2))))
3827 (if (< (* i 2) max)
3828 (cl-incf (aref totals i) (aref vec (* i 2))))
3829 (setq i (1+ i)))
3830
3831 (let ((x nil)
3832 (result nil)
3833 tot sum p)
3834 (setq i 1)
3835 (while (< i max)
3836 (if (/= (aref totals i) 0)
3837 (push (cons i (aref totals i)) x))
3838 (setq i (1+ i)))
3839
3840 (setq x (sort (nreverse x) (lambda (a b) (> (cdr a) (cdr b)))))
3841 (setq tot (apply '+ (append totals nil)))
3842 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3843 vec totals tot))
3844 (cond
3845 ((zerop (length x))
3846 (message "no values!")) ;; we return nil
3847 ((= (length x) 1)
3848 (message "only value is %d" (car (car x)))
3849 (setq result (car (car x)))) ;; return single value
3850 ((> (cdr (car x)) (/ tot 2))
3851 ;; 1st is > 50%
3852 (message "basic-offset is probably %d" (car (car x)))
3853 (setq result (car (car x)))) ;; again, return a single value
3854 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3855 ;; 1st is >= 2 * 2nd
3856 (message "basic-offset could be %d" (car (car x)))
3857 (setq result (car (car x))))
3858 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3859 ;; 1st & 2nd together >= 50% - return a list
3860 (setq p x sum 0 result nil)
3861 (while (and p
3862 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3863 (setq result (append result (list (car (car p)))))
3864 (setq p (cdr p)))
3865 (message "Possible choices for sh-basic-offset: %s"
3866 (mapconcat 'int-to-string result " ")))
3867 (t
3868 (message "No obvious value for sh-basic-offset. Perhaps %d"
3869 (car (car x)))
3870 ;; result is nil here
3871 ))
3872 result)))
3873
3874 ;; ========================================================================
3875
3876 ;; Styles -- a quick and dirty way of saving the indentation settings.
3877
3878 (defvar sh-styles-alist nil
3879 "A list of all known shell indentation styles.")
3880
3881 (defun sh-name-style (name &optional confirm-overwrite)
3882 "Name the current indentation settings as a style called NAME.
3883 If this name exists, the command will prompt whether it should be
3884 overwritten if
3885 - - it was called interactively with a prefix argument, or
3886 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3887 ;; (interactive "sName for this style: ")
3888 (interactive
3889 (list
3890 (read-from-minibuffer "Name for this style? " )
3891 (not current-prefix-arg)))
3892 (let ((slist (cons name
3893 (mapcar (lambda (var) (cons var (symbol-value var)))
3894 sh-var-list)))
3895 (style (assoc name sh-styles-alist)))
3896 (if style
3897 (if (and confirm-overwrite
3898 (not (y-or-n-p "This style exists. Overwrite it? ")))
3899 (message "Not changing style %s" name)
3900 (message "Updating style %s" name)
3901 (setcdr style (cdr slist)))
3902 (message "Creating new style %s" name)
3903 (push slist sh-styles-alist))))
3904
3905 (defun sh-load-style (name)
3906 "Set shell indentation values for this buffer from those in style NAME."
3907 (interactive (list (completing-read
3908 "Which style to use for this buffer? "
3909 sh-styles-alist nil t)))
3910 (let ((sl (assoc name sh-styles-alist)))
3911 (if (null sl)
3912 (error "sh-load-style - style %s not known" name)
3913 (dolist (var (cdr sl))
3914 (set (car var) (cdr var))))))
3915
3916 (defun sh-save-styles-to-buffer (buff)
3917 "Save all current styles in elisp to buffer BUFF.
3918 This is always added to the end of the buffer."
3919 (interactive
3920 (list
3921 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3922 (with-current-buffer (get-buffer-create buff)
3923 (goto-char (point-max))
3924 (insert "\n")
3925 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3926
3927
3928 \f
3929 ;; statement syntax-commands for various shells
3930
3931 ;; You are welcome to add the syntax or even completely new statements as
3932 ;; appropriate for your favorite shell.
3933
3934 (defconst sh-non-closing-paren
3935 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3936 ;; that inherits this property, which then confuses the indentation.
3937 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3938
3939 (define-skeleton sh-case
3940 "Insert a case/switch statement. See `sh-feature'."
3941 (csh "expression: "
3942 "switch( " str " )" \n
3943 > "case " (read-string "pattern: ") ?: \n
3944 > _ \n
3945 "breaksw" \n
3946 ( "other pattern, %s: "
3947 < "case " str ?: \n
3948 > _ \n
3949 "breaksw" \n)
3950 < "default:" \n
3951 > _ \n
3952 resume:
3953 < < "endsw" \n)
3954 (es)
3955 (rc "expression: "
3956 > "switch( " str " ) {" \n
3957 > "case " (read-string "pattern: ") \n
3958 > _ \n
3959 ( "other pattern, %s: "
3960 "case " str > \n
3961 > _ \n)
3962 "case *" > \n
3963 > _ \n
3964 resume:
3965 ?\} > \n)
3966 (sh "expression: "
3967 > "case " str " in" \n
3968 ( "pattern, %s: "
3969 > str sh-non-closing-paren \n
3970 > _ \n
3971 ";;" \n)
3972 > "*" sh-non-closing-paren \n
3973 > _ \n
3974 resume:
3975 "esac" > \n))
3976
3977 (define-skeleton sh-for
3978 "Insert a for loop. See `sh-feature'."
3979 (csh sh-modify sh
3980 1 ""
3981 2 "foreach "
3982 4 " ( "
3983 6 " )"
3984 15 '<
3985 16 "end")
3986 (es sh-modify rc
3987 4 " = ")
3988 (rc sh-modify sh
3989 2 "for( "
3990 6 " ) {"
3991 15 ?\} )
3992 (sh "Index variable: "
3993 > "for " str " in " _ "; do" \n
3994 > _ | ?$ & (sh-remember-variable str) \n
3995 "done" > \n))
3996
3997
3998
3999 (define-skeleton sh-indexed-loop
4000 "Insert an indexed loop from 1 to n. See `sh-feature'."
4001 (bash sh-modify posix)
4002 (csh "Index variable: "
4003 "@ " str " = 1" \n
4004 "while( $" str " <= " (read-string "upper limit: ") " )" \n
4005 > _ ?$ str \n
4006 "@ " str "++" \n
4007 < "end" \n)
4008 (es sh-modify rc
4009 4 " =")
4010 (ksh88 "Index variable: "
4011 > "integer " str "=0" \n
4012 > "while (( ( " str " += 1 ) <= "
4013 (read-string "upper limit: ")
4014 " )); do" \n
4015 > _ ?$ (sh-remember-variable str) > \n
4016 "done" > \n)
4017 (posix "Index variable: "
4018 > str "=1" \n
4019 "while [ $" str " -le "
4020 (read-string "upper limit: ")
4021 " ]; do" \n
4022 > _ ?$ str \n
4023 str ?= (sh-add (sh-remember-variable str) 1) \n
4024 "done" > \n)
4025 (rc "Index variable: "
4026 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
4027 (read-string "upper limit: ")
4028 "; i++ ) print i }'`}) {" \n
4029 > _ ?$ (sh-remember-variable str) \n
4030 ?\} > \n)
4031 (sh "Index variable: "
4032 > "for " str " in `awk 'BEGIN { for( i=1; i<="
4033 (read-string "upper limit: ")
4034 "; i++ ) print i }'`; do" \n
4035 > _ ?$ (sh-remember-variable str) \n
4036 "done" > \n))
4037
4038
4039 (defun sh-shell-initialize-variables ()
4040 "Scan the buffer for variable assignments.
4041 Add these variables to `sh-shell-variables'."
4042 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
4043 (save-excursion
4044 (goto-char (point-min))
4045 (setq sh-shell-variables-initialized t)
4046 (while (search-forward "=" nil t)
4047 (sh-assignment 0)))
4048 (message "Scanning buffer `%s' for variable assignments...done"
4049 (buffer-name)))
4050
4051 (defvar sh-add-buffer)
4052
4053 (defun sh-add-completer (string predicate code)
4054 "Do completion using `sh-shell-variables', but initialize it first.
4055 This function is designed for use as the \"completion table\",
4056 so it takes three arguments:
4057 STRING, the current buffer contents;
4058 PREDICATE, the predicate for filtering possible matches;
4059 CODE, which says what kind of things to do.
4060 CODE can be nil, t or `lambda'.
4061 nil means to return the best completion of STRING, or nil if there is none.
4062 t means to return a list of all possible completions of STRING.
4063 `lambda' means to return t if STRING is a valid completion as it stands."
4064 (let ((vars
4065 (with-current-buffer sh-add-buffer
4066 (or sh-shell-variables-initialized
4067 (sh-shell-initialize-variables))
4068 (nconc (mapcar (lambda (var)
4069 (substring var 0 (string-match "=" var)))
4070 process-environment)
4071 sh-shell-variables))))
4072 (complete-with-action code vars string predicate)))
4073
4074 (defun sh-add (var delta)
4075 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
4076 (interactive
4077 (let ((sh-add-buffer (current-buffer)))
4078 (list (completing-read "Variable: " 'sh-add-completer)
4079 (prefix-numeric-value current-prefix-arg))))
4080 (insert (sh-feature '((bash . "$(( ")
4081 (ksh88 . "$(( ")
4082 (posix . "$(( ")
4083 (rc . "`{expr $")
4084 (sh . "`expr $")
4085 (zsh . "$[ ")))
4086 (sh-remember-variable var)
4087 (if (< delta 0) " - " " + ")
4088 (number-to-string (abs delta))
4089 (sh-feature '((bash . " ))")
4090 (ksh88 . " ))")
4091 (posix . " ))")
4092 (rc . "}")
4093 (sh . "`")
4094 (zsh . " ]")))))
4095
4096
4097
4098 (define-skeleton sh-function
4099 "Insert a function definition. See `sh-feature'."
4100 (bash sh-modify ksh88
4101 3 "() {")
4102 (ksh88 "name: "
4103 "function " str " {" \n
4104 > _ \n
4105 < "}" \n)
4106 (rc sh-modify ksh88
4107 1 "fn ")
4108 (sh ()
4109 "() {" \n
4110 > _ \n
4111 < "}" \n))
4112
4113
4114
4115 (define-skeleton sh-if
4116 "Insert an if statement. See `sh-feature'."
4117 (csh "condition: "
4118 "if( " str " ) then" \n
4119 > _ \n
4120 ( "other condition, %s: "
4121 < "else if( " str " ) then" \n
4122 > _ \n)
4123 < "else" \n
4124 > _ \n
4125 resume:
4126 < "endif" \n)
4127 (es "condition: "
4128 > "if { " str " } {" \n
4129 > _ \n
4130 ( "other condition, %s: "
4131 "} { " str " } {" > \n
4132 > _ \n)
4133 "} {" > \n
4134 > _ \n
4135 resume:
4136 ?\} > \n)
4137 (rc "condition: "
4138 > "if( " str " ) {" \n
4139 > _ \n
4140 ( "other condition, %s: "
4141 "} else if( " str " ) {" > \n
4142 > _ \n)
4143 "} else {" > \n
4144 > _ \n
4145 resume:
4146 ?\} > \n)
4147 (sh "condition: "
4148 '(setq input (sh-feature sh-test))
4149 > "if " str "; then" \n
4150 > _ \n
4151 ( "other condition, %s: "
4152 > "elif " str "; then" > \n
4153 > \n)
4154 "else" > \n
4155 > \n
4156 resume:
4157 "fi" > \n))
4158
4159
4160
4161 (define-skeleton sh-repeat
4162 "Insert a repeat loop definition. See `sh-feature'."
4163 (es nil
4164 > "forever {" \n
4165 > _ \n
4166 ?\} > \n)
4167 (zsh "factor: "
4168 > "repeat " str "; do" > \n
4169 > \n
4170 "done" > \n))
4171
4172 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
4173
4174
4175
4176 (define-skeleton sh-select
4177 "Insert a select statement. See `sh-feature'."
4178 (ksh88 "Index variable: "
4179 > "select " str " in " _ "; do" \n
4180 > ?$ str \n
4181 "done" > \n)
4182 (bash sh-append ksh88))
4183 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
4184
4185
4186
4187 (define-skeleton sh-tmp-file
4188 "Insert code to setup temporary file handling. See `sh-feature'."
4189 (bash sh-append ksh88)
4190 (csh (file-name-nondirectory (buffer-file-name))
4191 "set tmp = `mktemp -t " str ".XXXXXX`" \n
4192 "onintr exit" \n _
4193 (and (goto-char (point-max))
4194 (not (bolp))
4195 ?\n)
4196 "exit:\n"
4197 "rm $tmp* >&/dev/null" > \n)
4198 (es (file-name-nondirectory (buffer-file-name))
4199 > "local( signals = $signals sighup sigint;" \n
4200 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
4201 > "catch @ e {" \n
4202 > "rm $tmp^* >[2]/dev/null" \n
4203 "throw $e" \n
4204 "} {" > \n
4205 _ \n
4206 ?\} > \n
4207 ?\} > \n)
4208 (ksh88 sh-modify sh
4209 7 "EXIT")
4210 (rc (file-name-nondirectory (buffer-file-name))
4211 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
4212 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
4213 (sh (file-name-nondirectory (buffer-file-name))
4214 > "TMP=`mktemp -t " str ".XXXXXX`" \n
4215 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
4216
4217
4218
4219 (define-skeleton sh-until
4220 "Insert an until loop. See `sh-feature'."
4221 (sh "condition: "
4222 '(setq input (sh-feature sh-test))
4223 > "until " str "; do" \n
4224 > _ \n
4225 "done" > \n))
4226 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
4227
4228
4229
4230 (define-skeleton sh-while
4231 "Insert a while loop. See `sh-feature'."
4232 (csh sh-modify sh
4233 2 ""
4234 3 "while( "
4235 5 " )"
4236 10 '<
4237 11 "end")
4238 (es sh-modify sh
4239 3 "while { "
4240 5 " } {"
4241 10 ?\} )
4242 (rc sh-modify sh
4243 3 "while( "
4244 5 " ) {"
4245 10 ?\} )
4246 (sh "condition: "
4247 '(setq input (sh-feature sh-test))
4248 > "while " str "; do" \n
4249 > _ \n
4250 "done" > \n))
4251
4252
4253
4254 (define-skeleton sh-while-getopts
4255 "Insert a while getopts loop. See `sh-feature'.
4256 Prompts for an options string which consists of letters for each recognized
4257 option followed by a colon `:' if the option accepts an argument."
4258 (bash sh-modify sh
4259 18 "${0##*/}")
4260 (csh nil
4261 "while( 1 )" \n
4262 > "switch( \"$1\" )" \n
4263 '(setq input '("- x" . 2))
4264 > >
4265 ( "option, %s: "
4266 < "case " '(eval str)
4267 '(if (string-match " +" str)
4268 (setq v1 (substring str (match-end 0))
4269 str (substring str 0 (match-beginning 0)))
4270 (setq v1 nil))
4271 str ?: \n
4272 > "set " v1 & " = $2" | -4 & _ \n
4273 (if v1 "shift") & \n
4274 "breaksw" \n)
4275 < "case --:" \n
4276 > "shift" \n
4277 < "default:" \n
4278 > "break" \n
4279 resume:
4280 < < "endsw" \n
4281 "shift" \n
4282 < "end" \n)
4283 (ksh88 sh-modify sh
4284 16 "print"
4285 18 "${0##*/}"
4286 37 "OPTIND-1")
4287 (posix sh-modify sh
4288 18 "$(basename $0)")
4289 (sh "optstring: "
4290 > "while getopts :" str " OPT; do" \n
4291 > "case $OPT in" \n
4292 '(setq v1 (append (vconcat str) nil))
4293 ( (prog1 (if v1 (char-to-string (car v1)))
4294 (if (eq (nth 1 v1) ?:)
4295 (setq v1 (nthcdr 2 v1)
4296 v2 "\"$OPTARG\"")
4297 (setq v1 (cdr v1)
4298 v2 nil)))
4299 > str "|+" str sh-non-closing-paren \n
4300 > _ v2 \n
4301 > ";;" \n)
4302 > "*" sh-non-closing-paren \n
4303 > "echo" " \"usage: " "`basename $0`"
4304 " [+-" '(setq v1 (point)) str
4305 '(save-excursion
4306 (while (search-backward ":" v1 t)
4307 (replace-match " ARG] [+-" t t)))
4308 (if (eq (preceding-char) ?-) -5)
4309 (if (and (sequencep v1) (length v1)) "] " "} ")
4310 "[--] ARGS...\"" \n
4311 "exit 2" > \n
4312 "esac" >
4313 \n "done"
4314 > \n
4315 "shift " (sh-add "OPTIND" -1) \n
4316 "OPTIND=1" \n))
4317
4318
4319
4320 (defun sh-assignment (arg)
4321 "Remember preceding identifier for future completion and do self-insert."
4322 (interactive "p")
4323 (self-insert-command arg)
4324 (if (<= arg 1)
4325 (sh-remember-variable
4326 (save-excursion
4327 (if (re-search-forward (sh-feature sh-assignment-regexp)
4328 (prog1 (point)
4329 (beginning-of-line 1))
4330 t)
4331 (match-string 1))))))
4332
4333
4334 (defun sh-maybe-here-document (arg)
4335 "Insert self. Without prefix, following unquoted `<' inserts here document.
4336 The document is bounded by `sh-here-document-word'."
4337 (declare (obsolete sh-electric-here-document-mode "24.3"))
4338 (interactive "*P")
4339 (self-insert-command (prefix-numeric-value arg))
4340 (or arg (sh--maybe-here-document)))
4341
4342 (defun sh--maybe-here-document ()
4343 (or (not (looking-back "[^<]<<"))
4344 (save-excursion
4345 (backward-char 2)
4346 (or (sh-quoted-p)
4347 (sh--inside-noncommand-expression (point))))
4348 (nth 8 (syntax-ppss))
4349 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
4350 (make-string (/ (current-indentation) tab-width) ?\t)
4351 ""))
4352 (delim (replace-regexp-in-string "['\"]" ""
4353 sh-here-document-word)))
4354 (insert sh-here-document-word)
4355 (or (eolp) (looking-at "[ \t]") (insert ?\s))
4356 (end-of-line 1)
4357 (while
4358 (sh-quoted-p)
4359 (end-of-line 2))
4360 (insert ?\n tabs)
4361 (save-excursion
4362 (insert ?\n tabs (replace-regexp-in-string
4363 "\\`-?[ \t]*" "" delim))))))
4364
4365 (define-minor-mode sh-electric-here-document-mode
4366 "Make << insert a here document skeleton."
4367 nil nil nil
4368 (if sh-electric-here-document-mode
4369 (add-hook 'post-self-insert-hook #'sh--maybe-here-document nil t)
4370 (remove-hook 'post-self-insert-hook #'sh--maybe-here-document t)))
4371 \f
4372 ;; various other commands
4373
4374 (defun sh-beginning-of-command ()
4375 ;; FIXME: Redefine using SMIE.
4376 "Move point to successive beginnings of commands."
4377 (interactive)
4378 (if (re-search-backward sh-beginning-of-command nil t)
4379 (goto-char (match-beginning 2))))
4380
4381 (defun sh-end-of-command ()
4382 ;; FIXME: Redefine using SMIE.
4383 "Move point to successive ends of commands."
4384 (interactive)
4385 (if (re-search-forward sh-end-of-command nil t)
4386 (goto-char (match-end 1))))
4387
4388 ;; Backslashification. Stolen from make-mode.el.
4389
4390 (defun sh-backslash-region (from to delete-flag)
4391 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4392 With no argument, inserts backslashes and aligns existing backslashes.
4393 With an argument, deletes the backslashes.
4394
4395 This function does not modify the last line of the region if the region ends
4396 right at the start of the following line; it does not modify blank lines
4397 at the start of the region. So you can put the region around an entire
4398 shell command and conveniently use this command."
4399 (interactive "r\nP")
4400 (save-excursion
4401 (goto-char from)
4402 (let ((column sh-backslash-column)
4403 (endmark (make-marker)))
4404 (move-marker endmark to)
4405 ;; Compute the smallest column number past the ends of all the lines.
4406 (if sh-backslash-align
4407 (progn
4408 (if (not delete-flag)
4409 (while (< (point) to)
4410 (end-of-line)
4411 (if (= (preceding-char) ?\\)
4412 (progn (forward-char -1)
4413 (skip-chars-backward " \t")))
4414 (setq column (max column (1+ (current-column))))
4415 (forward-line 1)))
4416 ;; Adjust upward to a tab column, if that doesn't push
4417 ;; past the margin.
4418 (if (> (% column tab-width) 0)
4419 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
4420 tab-width)))
4421 (if (< adjusted (window-width))
4422 (setq column adjusted))))))
4423 ;; Don't modify blank lines at start of region.
4424 (goto-char from)
4425 (while (and (< (point) endmark) (eolp))
4426 (forward-line 1))
4427 ;; Add or remove backslashes on all the lines.
4428 (while (and (< (point) endmark)
4429 ;; Don't backslashify the last line
4430 ;; if the region ends right at the start of the next line.
4431 (save-excursion
4432 (forward-line 1)
4433 (< (point) endmark)))
4434 (if (not delete-flag)
4435 (sh-append-backslash column)
4436 (sh-delete-backslash))
4437 (forward-line 1))
4438 (move-marker endmark nil))))
4439
4440 (defun sh-append-backslash (column)
4441 (end-of-line)
4442 ;; Note that "\\\\" is needed to get one backslash.
4443 (if (= (preceding-char) ?\\)
4444 (progn (forward-char -1)
4445 (delete-horizontal-space)
4446 (indent-to column (if sh-backslash-align nil 1)))
4447 (indent-to column (if sh-backslash-align nil 1))
4448 (insert "\\")))
4449
4450 (defun sh-delete-backslash ()
4451 (end-of-line)
4452 (or (bolp)
4453 (progn
4454 (forward-char -1)
4455 (if (looking-at "\\\\")
4456 (delete-region (1+ (point))
4457 (progn (skip-chars-backward " \t") (point)))))))
4458
4459 (provide 'sh-script)
4460
4461 ;;; sh-script.el ends here