]> code.delx.au - gnu-emacs/blob - lisp/progmodes/sh-script.el
; Merge branch 'fix/no-undo-boundary-on-secondary-buffer-change'
[gnu-emacs] / lisp / progmodes / sh-script.el
1 ;;; sh-script.el --- shell-script editing commands for Emacs -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1993-1997, 1999, 2001-2015 Free Software Foundation, Inc.
4
5 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
6 ;; Version: 2.0f
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: languages, unix
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
28 ;; as various derivatives are supported and easily derived from. Structured
29 ;; statements can be inserted with one command or abbrev. Completion is
30 ;; available for filenames, variables known from the script, the shell and
31 ;; the environment as well as commands.
32
33 ;;; Known Bugs:
34
35 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
36 ;; - Variables in `"' strings aren't fontified because there's no way of
37 ;; syntactically distinguishing those from `'' strings.
38
39 ;; Indentation
40 ;; ===========
41 ;; Indentation for rc and es modes is very limited, but for Bourne shells
42 ;; and its derivatives it is quite customizable.
43 ;;
44 ;; The following description applies to sh and derived shells (bash,
45 ;; zsh, ...).
46 ;;
47 ;; There are various customization variables which allow tailoring to
48 ;; a wide variety of styles. Most of these variables are named
49 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
50 ;; sh-indent-after-if controls the indenting of a line following
51 ;; an if statement, and sh-indent-for-fi controls the indentation
52 ;; of the line containing the fi.
53 ;;
54 ;; You can set each to a numeric value, but it is often more convenient
55 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
56 ;; By changing this one variable you can increase or decrease how much
57 ;; indentation there is. Valid symbols:
58 ;;
59 ;; + Indent right by sh-basic-offset
60 ;; - Indent left by sh-basic-offset
61 ;; ++ Indent right twice sh-basic-offset
62 ;; -- Indent left twice sh-basic-offset
63 ;; * Indent right half sh-basic-offset
64 ;; / Indent left half sh-basic-offset.
65 ;;
66 ;; There are 4 commands to help set the indentation variables:
67 ;;
68 ;; `sh-show-indent'
69 ;; This shows what variable controls the indentation of the current
70 ;; line and its value.
71 ;;
72 ;; `sh-set-indent'
73 ;; This allows you to set the value of the variable controlling the
74 ;; current line's indentation. You can enter a number or one of a
75 ;; number of special symbols to denote the value of sh-basic-offset,
76 ;; or its negative, or half it, or twice it, etc. If you've used
77 ;; cc-mode this should be familiar. If you forget which symbols are
78 ;; valid simply press C-h at the prompt.
79 ;;
80 ;; `sh-learn-line-indent'
81 ;; Simply make the line look the way you want it, then invoke this
82 ;; command. It will set the variable to the value that makes the line
83 ;; indent like that. If called with a prefix argument then it will set
84 ;; the value to one of the symbols if applicable.
85 ;;
86 ;; `sh-learn-buffer-indent'
87 ;; This is the deluxe function! It "learns" the whole buffer (use
88 ;; narrowing if you want it to process only part). It outputs to a
89 ;; buffer *indent* any conflicts it finds, and all the variables it has
90 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
91 ;; easily find where something was set. It is popped to automatically
92 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
93 ;; non-nil.
94 ;; `sh-indent-comment' will be set if all comments follow the same
95 ;; pattern; if they don't it will be set to nil.
96 ;; Whether `sh-basic-offset' is set is determined by variable
97 ;; `sh-learn-basic-offset'.
98 ;;
99 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
100 ;; (e.g. if there are large case statements). Perhaps it does not make
101 ;; sense to run it on large buffers: if lots of lines have different
102 ;; indentation styles it will produce a lot of diagnostics in the
103 ;; *indent* buffer; if there is a consistent style then running
104 ;; `sh-learn-buffer-indent' on a small region of the buffer should
105 ;; suffice.
106 ;;
107 ;; Saving indentation values
108 ;; -------------------------
109 ;; After you've learned the values in a buffer, how to you remember
110 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
111 ;; would make this unnecessary; simply learn the values when you visit
112 ;; the buffer.
113 ;; You can do this automatically like this:
114 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
115 ;;
116 ;; However... `sh-learn-buffer-indent' is extremely slow,
117 ;; especially on large-ish buffer. Also, if there are conflicts the
118 ;; "last one wins" which may not produce the desired setting.
119 ;;
120 ;; So...There is a minimal way of being able to save indentation values and
121 ;; to reload them in another buffer or at another point in time.
122 ;;
123 ;; Use `sh-name-style' to give a name to the indentation settings of
124 ;; the current buffer.
125 ;; Use `sh-load-style' to load indentation settings for the current
126 ;; buffer from a specific style.
127 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
128 ;; in lisp code. You can then store it in a file and later use
129 ;; `load-file' to load it.
130 ;;
131 ;; Indentation variables - buffer local or global?
132 ;; ----------------------------------------------
133 ;; I think that often having them buffer-local makes sense,
134 ;; especially if one is using `sh-learn-buffer-indent'. However, if
135 ;; a user sets values using customization, these changes won't appear
136 ;; to work if the variables are already local!
137 ;;
138 ;; To get round this, there is a variable `sh-make-vars-local' and 2
139 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
140 ;;
141 ;; If `sh-make-vars-local' is non-nil, then these variables become
142 ;; buffer local when the mode is established.
143 ;; If this is nil, then the variables are global. At any time you
144 ;; can make them local with the command `sh-make-vars-local'.
145 ;; Conversely, to update with the global values you can use the
146 ;; command `sh-reset-indent-vars-to-global-values'.
147 ;;
148 ;; This may be awkward, but the intent is to cover all cases.
149 ;;
150 ;; Awkward things, pitfalls
151 ;; ------------------------
152 ;; Indentation for a sh script is complicated for a number of reasons:
153 ;;
154 ;; 1. You can't format by simply looking at symbols, you need to look
155 ;; at keywords. [This is not the case for rc and es shells.]
156 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
157 ;; as a stand-alone symbol (in a case alternative). This makes
158 ;; things quite tricky!
159 ;; 3. Here-documents in a script should be treated "as is", and when
160 ;; they terminate we want to revert to the indentation of the line
161 ;; containing the "<<" symbol.
162 ;; 4. A line may be continued using the "\".
163 ;; 5. The character "#" (outside a string) normally starts a comment,
164 ;; but it doesn't in the sequence "$#"!
165 ;;
166 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
167 ;; uses, that of a text's syntax property. This, however, has 2
168 ;; disadvantages:
169 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
170 ;; case alternative, to find any here documents, and handle "$#".
171 ;;
172 ;; Bugs
173 ;; ----
174 ;; - Indenting many lines is slow. It currently does each line
175 ;; independently, rather than saving state information.
176 ;;
177 ;; - `sh-learn-buffer-indent' is extremely slow.
178 ;;
179 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
180 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
181 ;; coerce sh-script into doing the right thing.
182 ;;
183 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
184 ;; a case-pattern. You need to put the "in" between quotes to coerce
185 ;; sh-script into doing the right thing.
186 ;;
187 ;; - A line starting with "}>foo" is not indented like "} >foo".
188 ;;
189 ;; Richard Sharman <rsharman@pobox.com> June 1999.
190
191 ;;; Code:
192
193 ;; page 1: variables and settings
194 ;; page 2: indentation stuff
195 ;; page 3: mode-command and utility functions
196 ;; page 4: statement syntax-commands for various shells
197 ;; page 5: various other commands
198
199 (eval-when-compile
200 (require 'skeleton)
201 (require 'cl-lib)
202 (require 'comint))
203 (require 'executable)
204
205 (autoload 'comint-completion-at-point "comint")
206 (autoload 'comint-filename-completion "comint")
207 (autoload '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 \\=`blabla\\=`."
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 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1055 ;; bingo we have a $( or a ` inside a ""
1056 (let (;; `state' can be: double-quote, backquote, code.
1057 (state (if (eq (char-before) ?`) 'backquote 'code))
1058 (startpos (point))
1059 ;; Stacked states in the context.
1060 (states '(double-quote)))
1061 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1062 (< (point) limit)))
1063 ;; unescape " inside a $( ... ) construct.
1064 (pcase (char-after)
1065 (?\' (pcase state
1066 (`double-quote nil)
1067 (_ (forward-char 1)
1068 ;; FIXME: mark skipped double quotes as punctuation syntax.
1069 (let ((spos (point)))
1070 (skip-chars-forward "^'" limit)
1071 (save-excursion
1072 (let ((epos (point)))
1073 (goto-char spos)
1074 (while (search-forward "\"" epos t)
1075 (put-text-property (point) (1- (point))
1076 'syntax-table '(1)))))))))
1077 (?\\ (forward-char 1))
1078 (?\" (pcase state
1079 (`double-quote (setq state (pop states)))
1080 (_ (push state states) (setq state 'double-quote)))
1081 (if state (put-text-property (point) (1+ (point))
1082 'syntax-table '(1))))
1083 (?\` (pcase state
1084 (`backquote (setq state (pop states)))
1085 (_ (push state states) (setq state 'backquote))))
1086 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1087 nil
1088 (forward-char 1)
1089 (pcase state
1090 (_ (push state states) (setq state 'code)))))
1091 (?\( (pcase state
1092 (`double-quote nil)
1093 (_ (push state states) (setq state 'code))))
1094 (?\) (pcase state
1095 (`double-quote nil)
1096 (_ (setq state (pop states)))))
1097 (_ (error "Internal error in sh-font-lock-quoted-subshell")))
1098 (forward-char 1))
1099 (when (< startpos (line-beginning-position))
1100 (put-text-property startpos (point) 'syntax-multiline t)
1101 (add-hook 'syntax-propertize-extend-region-functions
1102 'syntax-propertize-multiline nil t))
1103 )))
1104
1105
1106 (defun sh-is-quoted-p (pos)
1107 (and (eq (char-before pos) ?\\)
1108 (not (sh-is-quoted-p (1- pos)))))
1109
1110 (defun sh-font-lock-paren (start)
1111 (unless (nth 8 (syntax-ppss))
1112 (save-excursion
1113 (let ((open nil))
1114 (goto-char start)
1115 ;; Skip through all patterns
1116 (while
1117 (progn
1118 (while
1119 (progn
1120 (forward-comment (- (point-max)))
1121 (when (and (eolp) (sh-is-quoted-p (point)))
1122 (forward-char -1)
1123 t)))
1124 ;; Skip through one pattern
1125 (while
1126 (or (/= 0 (skip-syntax-backward "w_"))
1127 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1128 (and (sh-is-quoted-p (1- (point)))
1129 (goto-char (- (point) 2)))
1130 (when (memq (char-before) '(?\" ?\' ?\}))
1131 (condition-case nil (progn (backward-sexp 1) t)
1132 (error nil)))))
1133 ;; Patterns can be preceded by an open-paren (bug#1320).
1134 (when (eq (char-before (point)) ?\()
1135 (backward-char 1)
1136 (setq open (point)))
1137 (while (progn
1138 (forward-comment (- (point-max)))
1139 ;; Maybe we've bumped into an escaped newline.
1140 (sh-is-quoted-p (point)))
1141 (backward-char 1))
1142 (when (eq (char-before) ?|)
1143 (backward-char 1) t)))
1144 (and (> (point) (1+ (point-min)))
1145 (progn (backward-char 2)
1146 (if (> start (line-end-position))
1147 (put-text-property (point) (1+ start)
1148 'syntax-multiline t))
1149 ;; FIXME: The `in' may just be a random argument to
1150 ;; a normal command rather than the real `in' keyword.
1151 ;; I.e. we should look back to try and find the
1152 ;; corresponding `case'.
1153 (and (looking-at ";[;&]\\|\\_<in")
1154 ;; ";; esac )" is a case that looks
1155 ;; like a case-pattern but it's really just a close
1156 ;; paren after a case statement. I.e. if we skipped
1157 ;; over `esac' just now, we're not looking
1158 ;; at a case-pattern.
1159 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1160 (progn
1161 (when open
1162 (put-text-property open (1+ open) 'syntax-table sh-st-punc))
1163 sh-st-punc))))))
1164
1165 (defun sh-font-lock-backslash-quote ()
1166 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1167 ;; In a '...' the backslash is not escaping.
1168 sh-st-punc
1169 nil))
1170
1171 (defun sh-syntax-propertize-function (start end)
1172 (goto-char start)
1173 (sh-syntax-propertize-here-doc end)
1174 (funcall
1175 (syntax-propertize-rules
1176 (sh-here-doc-open-re
1177 (2 (sh-font-lock-open-heredoc
1178 (match-beginning 0) (match-string 1) (match-beginning 2))))
1179 ("\\s|" (0 (prog1 nil (sh-syntax-propertize-here-doc end))))
1180 ;; A `#' begins a comment when it is unquoted and at the
1181 ;; beginning of a word. In the shell, words are separated by
1182 ;; metacharacters. The list of special chars is taken from
1183 ;; the single-unix spec of the shell command language (under
1184 ;; `quoting') but with `$' removed.
1185 ("\\(?:[^|&;<>()`\\\"' \t\n]\\|\\${\\)\\(#+\\)" (1 "_"))
1186 ;; In a '...' the backslash is not escaping.
1187 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1188 ;; Make sure $@ and $? are correctly recognized as sexps.
1189 ("\\$\\([?@]\\)" (1 "_"))
1190 ;; Distinguish the special close-paren in `case'.
1191 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1192 ;; Highlight (possibly nested) subshells inside "" quoted
1193 ;; regions correctly.
1194 ("\"\\(?:\\(?:[^\\\"]\\|\\\\.\\)*?\\)??\\(\\$(\\|`\\)"
1195 (1 (ignore
1196 (if (nth 8 (save-excursion (syntax-ppss (match-beginning 0))))
1197 (goto-char (1+ (match-beginning 0)))
1198 ;; Save excursion because we want to also apply other
1199 ;; syntax-propertize rules within the affected region.
1200 (save-excursion
1201 (sh-font-lock-quoted-subshell end)))))))
1202 (point) end))
1203 (defun sh-font-lock-syntactic-face-function (state)
1204 (let ((q (nth 3 state)))
1205 (if q
1206 (if (characterp q)
1207 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1208 sh-heredoc-face)
1209 font-lock-comment-face)))
1210
1211 (defgroup sh-indentation nil
1212 "Variables controlling indentation in shell scripts.
1213
1214 Note: customizing these variables will not affect existing buffers if
1215 `sh-make-vars-local' is non-nil. See the documentation for
1216 variable `sh-make-vars-local', command `sh-make-vars-local'
1217 and command `sh-reset-indent-vars-to-global-values'."
1218 :group 'sh-script)
1219
1220
1221 (defcustom sh-set-shell-hook nil
1222 "Hook run by `sh-set-shell'."
1223 :type 'hook
1224 :group 'sh-script)
1225
1226 (defcustom sh-mode-hook nil
1227 "Hook run by `sh-mode'."
1228 :type 'hook
1229 :group 'sh-script)
1230
1231 (defcustom sh-learn-basic-offset nil
1232 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1233
1234 nil mean: never.
1235 t means: only if there seems to be an obvious value.
1236 Anything else means: whenever we have a \"good guess\" as to the value."
1237 :type '(choice
1238 (const :tag "Never" nil)
1239 (const :tag "Only if sure" t)
1240 (const :tag "If have a good guess" usually))
1241 :group 'sh-indentation)
1242
1243 (defcustom sh-popup-occur-buffer nil
1244 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1245 If t it is always shown. If nil, it is shown only when there
1246 are conflicts."
1247 :type '(choice
1248 (const :tag "Only when there are conflicts." nil)
1249 (const :tag "Always" t))
1250 :group 'sh-indentation)
1251
1252 (defcustom sh-blink t
1253 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1254 The position on the line is not necessarily meaningful.
1255 In some cases the line will be the matching keyword, but this is not
1256 always the case."
1257 :type 'boolean
1258 :group 'sh-indentation)
1259
1260 (defcustom sh-first-lines-indent 0
1261 "The indentation of the first non-blank non-comment line.
1262 Usually 0 meaning first column.
1263 Can be set to a number, or to nil which means leave it as is."
1264 :type '(choice
1265 (const :tag "Leave as is" nil)
1266 (integer :tag "Column number"
1267 :menu-tag "Indent to this col (0 means first col)" ))
1268 :group 'sh-indentation)
1269
1270
1271 (defcustom sh-basic-offset 4
1272 "The default indentation increment.
1273 This value is used for the `+' and `-' symbols in an indentation variable."
1274 :type 'integer
1275 :group 'sh-indentation)
1276 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1277
1278 (defcustom sh-indent-comment t
1279 "How a comment line is to be indented.
1280 nil means leave it as it is;
1281 t means indent it as a normal line, aligning it to previous non-blank
1282 non-comment line;
1283 a number means align to that column, e.g. 0 means first column."
1284 :type '(choice
1285 (const :tag "Leave as is." nil)
1286 (const :tag "Indent as a normal line." t)
1287 (integer :menu-tag "Indent to this col (0 means first col)."
1288 :tag "Indent to column number.") )
1289 :version "24.3"
1290 :group 'sh-indentation)
1291
1292
1293 (defvar sh-debug nil
1294 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1295
1296
1297 ;; Uncomment this defun and comment the defmacro for debugging.
1298 ;; (defun sh-debug (&rest args)
1299 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1300 ;; (if sh-debug
1301 ;; (apply 'message args)))
1302 (defmacro sh-debug (&rest _args))
1303
1304 (defconst sh-symbol-list
1305 '((const :tag "+ " :value +
1306 :menu-tag "+ Indent right by sh-basic-offset")
1307 (const :tag "- " :value -
1308 :menu-tag "- Indent left by sh-basic-offset")
1309 (const :tag "++" :value ++
1310 :menu-tag "++ Indent right twice sh-basic-offset")
1311 (const :tag "--" :value --
1312 :menu-tag "-- Indent left twice sh-basic-offset")
1313 (const :tag "* " :value *
1314 :menu-tag "* Indent right half sh-basic-offset")
1315 (const :tag "/ " :value /
1316 :menu-tag "/ Indent left half sh-basic-offset")))
1317
1318 (defcustom sh-indent-for-else 0
1319 "How much to indent an `else' relative to its `if'. Usually 0."
1320 :type `(choice
1321 (integer :menu-tag "A number (positive=>indent right)"
1322 :tag "A number")
1323 (const :tag "--") ;; separator!
1324 ,@ sh-symbol-list
1325 )
1326 :group 'sh-indentation)
1327
1328 (defconst sh-number-or-symbol-list
1329 (append '((integer :menu-tag "A number (positive=>indent right)"
1330 :tag "A number")
1331 (const :tag "--")) ; separator
1332 sh-symbol-list))
1333
1334 (defcustom sh-indent-for-fi 0
1335 "How much to indent a `fi' relative to its `if'. Usually 0."
1336 :type `(choice ,@ sh-number-or-symbol-list )
1337 :group 'sh-indentation)
1338
1339 (defcustom sh-indent-for-done 0
1340 "How much to indent a `done' relative to its matching stmt. Usually 0."
1341 :type `(choice ,@ sh-number-or-symbol-list )
1342 :group 'sh-indentation)
1343
1344 (defcustom sh-indent-after-else '+
1345 "How much to indent a statement after an `else' statement."
1346 :type `(choice ,@ sh-number-or-symbol-list )
1347 :group 'sh-indentation)
1348
1349 (defcustom sh-indent-after-if '+
1350 "How much to indent a statement after an `if' statement.
1351 This includes lines after `else' and `elif' statements, too, but
1352 does not affect the `else', `elif' or `fi' statements themselves."
1353 :type `(choice ,@ sh-number-or-symbol-list )
1354 :group 'sh-indentation)
1355
1356 (defcustom sh-indent-for-then 0
1357 "How much to indent a `then' relative to its `if'."
1358 :type `(choice ,@ sh-number-or-symbol-list )
1359 :group 'sh-indentation)
1360
1361 (defcustom sh-indent-for-do 0
1362 "How much to indent a `do' statement.
1363 This is relative to the statement before the `do', typically a
1364 `while', `until', `for', `repeat' or `select' statement."
1365 :type `(choice ,@ sh-number-or-symbol-list)
1366 :group 'sh-indentation)
1367
1368 (defcustom sh-indent-after-do '+
1369 "How much to indent a line after a `do' statement.
1370 This is used when the `do' is the first word of the line.
1371 This is relative to the statement before the `do', typically a
1372 `while', `until', `for', `repeat' or `select' statement."
1373 :type `(choice ,@ sh-number-or-symbol-list)
1374 :group 'sh-indentation)
1375
1376 (defcustom sh-indent-after-loop-construct '+
1377 "How much to indent a statement after a loop construct.
1378
1379 This variable is used when the keyword `do' is on the same line as the
1380 loop statement (e.g., `until', `while' or `for').
1381 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1382 :type `(choice ,@ sh-number-or-symbol-list)
1383 :group 'sh-indentation)
1384
1385
1386 (defcustom sh-indent-after-done 0
1387 "How much to indent a statement after a `done' keyword.
1388 Normally this is 0, which aligns the `done' to the matching
1389 looping construct line.
1390 Setting it non-zero allows you to have the `do' statement on a line
1391 by itself and align the done under to do."
1392 :type `(choice ,@ sh-number-or-symbol-list)
1393 :group 'sh-indentation)
1394
1395 (defcustom sh-indent-for-case-label '+
1396 "How much to indent a case label statement.
1397 This is relative to the line containing the `case' statement."
1398 :type `(choice ,@ sh-number-or-symbol-list)
1399 :group 'sh-indentation)
1400
1401 (defcustom sh-indent-for-case-alt '++
1402 "How much to indent statements after the case label.
1403 This is relative to the line containing the `case' statement."
1404 :type `(choice ,@ sh-number-or-symbol-list)
1405 :group 'sh-indentation)
1406
1407
1408 (defcustom sh-indent-for-continuation '+
1409 "How much to indent for a continuation statement."
1410 :type `(choice ,@ sh-number-or-symbol-list)
1411 :group 'sh-indentation)
1412
1413 (defcustom sh-indent-after-open '+
1414 "How much to indent after a line with an opening parenthesis or brace.
1415 For an open paren after a function, `sh-indent-after-function' is used."
1416 :type `(choice ,@ sh-number-or-symbol-list)
1417 :group 'sh-indentation)
1418
1419 (defcustom sh-indent-after-function '+
1420 "How much to indent after a function line."
1421 :type `(choice ,@ sh-number-or-symbol-list)
1422 :group 'sh-indentation)
1423
1424 ;; These 2 are for the rc shell:
1425
1426 (defcustom sh-indent-after-switch '+
1427 "How much to indent a `case' statement relative to the `switch' statement.
1428 This is for the rc shell."
1429 :type `(choice ,@ sh-number-or-symbol-list)
1430 :group 'sh-indentation)
1431
1432 (defcustom sh-indent-after-case '+
1433 "How much to indent a statement relative to the `case' statement.
1434 This is for the rc shell."
1435 :type `(choice ,@ sh-number-or-symbol-list)
1436 :group 'sh-indentation)
1437
1438 (defcustom sh-backslash-column 48
1439 "Column in which `sh-backslash-region' inserts backslashes."
1440 :type 'integer
1441 :group 'sh)
1442
1443 (defcustom sh-backslash-align t
1444 "If non-nil, `sh-backslash-region' will align backslashes."
1445 :type 'boolean
1446 :group 'sh)
1447
1448 ;; Internal use - not designed to be changed by the user:
1449
1450 (defun sh-mkword-regexpr (word)
1451 "Make a regexp which matches WORD as a word.
1452 This specifically excludes an occurrence of WORD followed by
1453 punctuation characters like '-'."
1454 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1455
1456 (defconst sh-re-done (sh-mkword-regexpr "done"))
1457
1458
1459 (defconst sh-kws-for-done
1460 '((sh . ( "while" "until" "for" ) )
1461 (bash . ( "while" "until" "for" "select" ) )
1462 (ksh88 . ( "while" "until" "for" "select" ) )
1463 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1464 "Which keywords can match the word `done' in this shell.")
1465
1466
1467 (defconst sh-indent-supported
1468 '((sh . sh)
1469 (csh . nil)
1470 (rc . rc))
1471 "Indentation rule set to use for each shell type.")
1472
1473 (defvar sh-indent-supported-here nil
1474 "Non-nil if we support indentation for the current buffer's shell type.")
1475
1476 (defconst sh-var-list
1477 '(
1478 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1479 sh-indent-after-do sh-indent-after-done
1480 sh-indent-after-else
1481 sh-indent-after-if
1482 sh-indent-after-loop-construct
1483 sh-indent-after-open
1484 sh-indent-comment
1485 sh-indent-for-case-alt
1486 sh-indent-for-case-label
1487 sh-indent-for-continuation
1488 sh-indent-for-do
1489 sh-indent-for-done
1490 sh-indent-for-else
1491 sh-indent-for-fi
1492 sh-indent-for-then
1493 )
1494 "A list of variables used by script mode to control indentation.
1495 This list is used when switching between buffer-local and global
1496 values of variables, and for the commands using indentation styles.")
1497
1498 (defvar sh-make-vars-local t
1499 "Controls whether indentation variables are local to the buffer.
1500 If non-nil, indentation variables are made local initially.
1501 If nil, you can later make the variables local by invoking
1502 command `sh-make-vars-local'.
1503 The default is t because I assume that in one Emacs session one is
1504 frequently editing existing scripts with different styles.")
1505
1506 \f
1507 ;; inferior shell interaction
1508 ;; TODO: support multiple interactive shells
1509 (defvar-local sh-shell-process nil
1510 "The inferior shell process for interaction.")
1511
1512 (defvar explicit-shell-file-name)
1513
1514 (defun sh-shell-process (force)
1515 "Get a shell process for interaction.
1516 If FORCE is non-nil and no process found, create one."
1517 (if (process-live-p sh-shell-process)
1518 sh-shell-process
1519 (setq sh-shell-process
1520 (let ((found nil) proc
1521 (procs (process-list)))
1522 (while (and (not found) procs
1523 (process-live-p (setq proc (pop procs)))
1524 (process-command proc))
1525 (when (string-equal sh-shell (file-name-nondirectory
1526 (car (process-command proc))))
1527 (setq found proc)))
1528 (or found
1529 (and force
1530 (get-buffer-process
1531 (let ((explicit-shell-file-name sh-shell-file))
1532 (shell)))))))))
1533
1534 (defun sh-show-shell ()
1535 "Pop the shell interaction buffer."
1536 (interactive)
1537 (pop-to-buffer (process-buffer (sh-shell-process t))))
1538
1539 (defun sh-send-text (text)
1540 "Send the text to the `sh-shell-process'."
1541 (comint-send-string (sh-shell-process t) (concat text "\n")))
1542
1543 (defun sh-cd-here ()
1544 "Change directory in the current interaction shell to the current one."
1545 (interactive)
1546 (sh-send-text (concat "cd " default-directory)))
1547
1548 (defun sh-send-line-or-region-and-step ()
1549 "Send the current line to the inferior shell and step to the next line.
1550 When the region is active, send the region instead."
1551 (interactive)
1552 (let (from to end)
1553 (if (use-region-p)
1554 (setq from (region-beginning)
1555 to (region-end)
1556 end to)
1557 (setq from (line-beginning-position)
1558 to (line-end-position)
1559 end (1+ to)))
1560 (sh-send-text (buffer-substring-no-properties from to))
1561 (goto-char end)))
1562
1563 \f
1564 ;; mode-command and utility functions
1565
1566 (defun sh-after-hack-local-variables ()
1567 (when (assq 'sh-shell file-local-variables-alist)
1568 (sh-set-shell (if (symbolp sh-shell)
1569 (symbol-name sh-shell)
1570 sh-shell))))
1571
1572 ;;;###autoload
1573 (define-derived-mode sh-mode prog-mode "Shell-script"
1574 "Major mode for editing shell scripts.
1575 This mode works for many shells, since they all have roughly the same syntax,
1576 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1577 Unless the file's magic number indicates the shell, your usual shell is
1578 assumed. Since filenames rarely give a clue, they are not further analyzed.
1579
1580 This mode adapts to the variations between shells (see `sh-set-shell') by
1581 means of an inheritance based feature lookup (see `sh-feature'). This
1582 mechanism applies to all variables (including skeletons) that pertain to
1583 shell-specific features.
1584
1585 The default style of this mode is that of Rosenblatt's Korn shell book.
1586 The syntax of the statements varies with the shell being used. The
1587 following commands are available, based on the current shell's syntax:
1588 \\<sh-mode-map>
1589 \\[sh-case] case statement
1590 \\[sh-for] for loop
1591 \\[sh-function] function definition
1592 \\[sh-if] if statement
1593 \\[sh-indexed-loop] indexed loop from 1 to n
1594 \\[sh-while-getopts] while getopts loop
1595 \\[sh-repeat] repeat loop
1596 \\[sh-select] select loop
1597 \\[sh-until] until loop
1598 \\[sh-while] while loop
1599
1600 For sh and rc shells indentation commands are:
1601 \\[sh-show-indent] Show the variable controlling this line's indentation.
1602 \\[sh-set-indent] Set then variable controlling this line's indentation.
1603 \\[sh-learn-line-indent] Change the indentation variable so this line
1604 would indent to the way it currently is.
1605 \\[sh-learn-buffer-indent] Set the indentation variables so the
1606 buffer indents as it currently is indented.
1607
1608
1609 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1610 \\[sh-end-of-command] Go to end of successive commands.
1611 \\[sh-beginning-of-command] Go to beginning of successive commands.
1612 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1613 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1614
1615 `sh-electric-here-document-mode' controls whether insertion of two
1616 unquoted < insert a here document.
1617
1618 If you generally program a shell different from your login shell you can
1619 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1620 indicate what shell it is use `sh-alias-alist' to translate.
1621
1622 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1623 with your script for an edit-interpret-debug cycle."
1624 (make-local-variable 'sh-shell-file)
1625 (make-local-variable 'sh-shell)
1626
1627 (setq-local skeleton-pair-default-alist
1628 sh-skeleton-pair-default-alist)
1629 (setq-local skeleton-end-hook
1630 (lambda () (or (eolp) (newline) (indent-relative))))
1631
1632 (setq-local paragraph-start (concat page-delimiter "\\|$"))
1633 (setq-local paragraph-separate (concat paragraph-start "\\|#!/"))
1634 (setq-local comment-start "# ")
1635 (setq-local comment-start-skip "#+[\t ]*")
1636 (setq-local local-abbrev-table sh-mode-abbrev-table)
1637 (setq-local comint-dynamic-complete-functions
1638 sh-dynamic-complete-functions)
1639 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t)
1640 ;; we can't look if previous line ended with `\'
1641 (setq-local comint-prompt-regexp "^[ \t]*")
1642 (setq-local imenu-case-fold-search nil)
1643 (setq font-lock-defaults
1644 `((sh-font-lock-keywords
1645 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1646 nil nil
1647 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1648 (font-lock-syntactic-face-function
1649 . sh-font-lock-syntactic-face-function)))
1650 (setq-local syntax-propertize-function #'sh-syntax-propertize-function)
1651 (add-hook 'syntax-propertize-extend-region-functions
1652 #'syntax-propertize-multiline 'append 'local)
1653 (sh-electric-here-document-mode 1)
1654 (setq-local skeleton-pair-alist '((?` _ ?`)))
1655 (setq-local skeleton-pair-filter-function 'sh-quoted-p)
1656 (setq-local skeleton-further-elements
1657 '((< '(- (min sh-indentation (current-column))))))
1658 (setq-local skeleton-filter-function 'sh-feature)
1659 (setq-local skeleton-newline-indent-rigidly t)
1660 (setq-local defun-prompt-regexp
1661 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1662 (setq-local add-log-current-defun-function #'sh-current-defun-name)
1663 (add-hook 'completion-at-point-functions
1664 #'sh-completion-at-point-function nil t)
1665 ;; Parse or insert magic number for exec, and set all variables depending
1666 ;; on the shell thus determined.
1667 (sh-set-shell
1668 (cond ((save-excursion
1669 (goto-char (point-min))
1670 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1671 (match-string 2))
1672 ((not buffer-file-name) sh-shell-file)
1673 ;; Checks that use `buffer-file-name' follow.
1674 ((string-match "\\.m?spec\\'" buffer-file-name) "rpm")
1675 ((string-match "[.]sh\\>" buffer-file-name) "sh")
1676 ((string-match "[.]bash\\>" buffer-file-name) "bash")
1677 ((string-match "[.]ksh\\>" buffer-file-name) "ksh")
1678 ((string-match "[.]t?csh\\(rc\\)?\\>" buffer-file-name) "csh")
1679 ((equal (file-name-nondirectory buffer-file-name) ".profile") "sh")
1680 (t sh-shell-file))
1681 nil nil)
1682 (add-hook 'hack-local-variables-hook
1683 #'sh-after-hack-local-variables nil t))
1684
1685 ;;;###autoload
1686 (defalias 'shell-script-mode 'sh-mode)
1687
1688
1689 (defun sh-font-lock-keywords (&optional keywords)
1690 "Function to get simple fontification based on `sh-font-lock-keywords'.
1691 This adds rules for comments and assignments."
1692 (sh-feature sh-font-lock-keywords-var
1693 (when (stringp (sh-feature sh-assignment-regexp))
1694 (lambda (list)
1695 `((,(sh-feature sh-assignment-regexp)
1696 1 font-lock-variable-name-face)
1697 ,@keywords
1698 ,@list
1699 ,@executable-font-lock-keywords)))))
1700
1701 (defun sh-font-lock-keywords-1 (&optional builtins)
1702 "Function to get better fontification including keywords."
1703 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1704 (regexp-opt (sh-feature sh-leading-keywords) t)
1705 "[ \t]+\\)?"
1706 (regexp-opt (append (sh-feature sh-leading-keywords)
1707 (sh-feature sh-other-keywords))
1708 t))))
1709 (sh-font-lock-keywords
1710 `(,@(if builtins
1711 `((,(concat keywords "[ \t]+\\)?"
1712 (regexp-opt (sh-feature sh-builtins) t)
1713 "\\>")
1714 (2 font-lock-keyword-face nil t)
1715 (6 font-lock-builtin-face))
1716 ,@(sh-feature sh-font-lock-keywords-var-2)))
1717 (,(concat keywords "\\)\\>")
1718 2 font-lock-keyword-face)
1719 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1720
1721 (defun sh-font-lock-keywords-2 ()
1722 "Function to get better fontification including keywords and builtins."
1723 (sh-font-lock-keywords-1 t))
1724
1725 ;;; Completion
1726
1727 (defun sh--vars-before-point ()
1728 (save-excursion
1729 (let ((vars ()))
1730 (while (re-search-backward "^[ \t]*\\([[:alnum:]_]+\\)=" nil t)
1731 (push (match-string 1) vars))
1732 vars)))
1733
1734 ;; (defun sh--var-completion-table (string pred action)
1735 ;; (complete-with-action action (sh--vars-before-point) string pred))
1736
1737 (defun sh--cmd-completion-table (string pred action)
1738 (let ((cmds
1739 (append (when (fboundp 'imenu--make-index-alist)
1740 (mapcar #'car (imenu--make-index-alist)))
1741 (mapcar (lambda (v) (concat v "="))
1742 (sh--vars-before-point))
1743 (locate-file-completion-table
1744 exec-path exec-suffixes string pred t)
1745 '("if" "while" "until" "for"))))
1746 (complete-with-action action cmds string pred)))
1747
1748 (defun sh-completion-at-point-function ()
1749 (save-excursion
1750 (skip-chars-forward "[:alnum:]_")
1751 (let ((end (point))
1752 (_ (skip-chars-backward "[:alnum:]_"))
1753 (start (point)))
1754 (cond
1755 ((eq (char-before) ?$)
1756 (list start end (sh--vars-before-point)))
1757 ((sh-smie--keyword-p)
1758 (list start end #'sh--cmd-completion-table))))))
1759
1760 ;;; Indentation and navigation with SMIE.
1761
1762 (require 'smie)
1763
1764 ;; The SMIE code should generally be preferred, but it currently does not obey
1765 ;; the various indentation custom-vars, and it misses some important features
1766 ;; of the old code, mostly: sh-learn-line/buffer-indent, sh-show-indent,
1767 ;; sh-name/save/load-style.
1768 (defvar sh-use-smie t
1769 "Whether to use the SMIE code for navigation and indentation.")
1770
1771 (defun sh-smie--keyword-p ()
1772 "Non-nil if we're at a keyword position.
1773 A keyword position is one where if we're looking at something that looks
1774 like a keyword, then it is a keyword."
1775 (let ((prev (funcall smie-backward-token-function)))
1776 (if (zerop (length prev))
1777 (looking-back "\\`\\|\\s(" (1- (point)))
1778 (assoc prev smie-grammar))))
1779
1780 (defun sh-smie--newline-semi-p (&optional tok)
1781 "Return non-nil if a newline should be treated as a semi-colon.
1782 Here we assume that a newline should be treated as a semi-colon unless it
1783 comes right after a special keyword.
1784 This function does not pay attention to line-continuations.
1785 If TOK is nil, point should be before the newline; otherwise, TOK is the token
1786 before the newline and in that case point should be just before the token."
1787 (save-excursion
1788 (unless tok
1789 (setq tok (funcall smie-backward-token-function)))
1790 (if (and (zerop (length tok))
1791 (looking-back "\\s(" (1- (point))))
1792 nil
1793 (not (numberp (nth 2 (assoc tok smie-grammar)))))))
1794
1795 ;;;; SMIE support for `sh'.
1796
1797 (defconst sh-smie-sh-grammar
1798 (smie-prec2->grammar
1799 (smie-bnf->prec2
1800 '((exp) ;A constant, or a $var, or a sequence of them...
1801 (cmd ("case" exp "in" branches "esac")
1802 ("if" cmd "then" cmd "fi")
1803 ("if" cmd "then" cmd "else" cmd "fi")
1804 ("if" cmd "then" cmd "elif" cmd "then" cmd "fi")
1805 ("if" cmd "then" cmd "elif" cmd "then" cmd "else" cmd "fi")
1806 ("if" cmd "then" cmd "elif" cmd "then" cmd
1807 "elif" cmd "then" cmd "else" cmd "fi")
1808 ("while" cmd "do" cmd "done")
1809 ("until" cmd "do" cmd "done")
1810 ("for" exp "in" cmd "do" cmd "done")
1811 ("for" exp "do" cmd "done")
1812 ("select" exp "in" cmd "do" cmd "done") ;bash&zsh&ksh88.
1813 ("repeat" exp "do" cmd "done") ;zsh.
1814 (exp "always" exp) ;zsh.
1815 (cmd "|" cmd) (cmd "|&" cmd)
1816 (cmd "&&" cmd) (cmd "||" cmd)
1817 (cmd ";" cmd) (cmd "&" cmd))
1818 (rpattern (rpattern "|" rpattern))
1819 (pattern (rpattern) ("case-(" rpattern))
1820 (branches (branches ";;" branches)
1821 (branches ";&" branches) (branches ";;&" branches) ;bash.
1822 (pattern "case-)" cmd)))
1823 '((assoc ";;" ";&" ";;&"))
1824 '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1825
1826 (defconst sh-smie--sh-operators
1827 (delq nil (mapcar (lambda (x)
1828 (setq x (car x))
1829 (and (stringp x)
1830 (not (string-match "\\`[a-z]" x))
1831 x))
1832 sh-smie-sh-grammar)))
1833
1834 (defconst sh-smie--sh-operators-re (regexp-opt sh-smie--sh-operators))
1835 (defconst sh-smie--sh-operators-back-re
1836 (concat "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*"
1837 "\\(" sh-smie--sh-operators-re "\\)"))
1838
1839 (defun sh-smie--sh-keyword-in-p ()
1840 "Assuming we're looking at \"in\", return non-nil if it's a keyword.
1841 Does not preserve point."
1842 (let ((forward-sexp-function nil)
1843 (words nil) ;We've seen words.
1844 (newline nil) ;We've seen newlines after the words.
1845 (res nil)
1846 prev)
1847 (while (not res)
1848 (setq prev (funcall smie-backward-token-function))
1849 (cond
1850 ((zerop (length prev))
1851 (cond
1852 (newline (cl-assert words) (setq res 'word))
1853 ((bobp) (setq res 'word))
1854 (t
1855 (setq words t)
1856 (condition-case nil
1857 (forward-sexp -1)
1858 (scan-error (setq res 'unknown))))))
1859 ((equal prev ";")
1860 (if words (setq newline t)
1861 (setq res 'keyword)))
1862 ((member prev '("case" "for" "select")) (setq res 'keyword))
1863 ((assoc prev smie-grammar) (setq res 'word))
1864 (t
1865 (if newline
1866 (progn (cl-assert words) (setq res 'word))
1867 (setq words t)))))
1868 (eq res 'keyword)))
1869
1870 (defun sh-smie--sh-keyword-p (tok)
1871 "Non-nil if TOK (at which we're looking) really is a keyword."
1872 (cond
1873 ((looking-at "[[:alnum:]_]+=") nil)
1874 ((equal tok "in") (sh-smie--sh-keyword-in-p))
1875 (t (sh-smie--keyword-p))))
1876
1877 (defun sh-smie--default-forward-token ()
1878 (forward-comment (point-max))
1879 (buffer-substring-no-properties
1880 (point)
1881 (progn (if (zerop (skip-syntax-forward "."))
1882 (while (progn (skip-syntax-forward "w_'")
1883 (looking-at "\\\\"))
1884 (forward-char 2)))
1885 (point))))
1886
1887 (defun sh-smie--default-backward-token ()
1888 (forward-comment (- (point)))
1889 (let ((pos (point))
1890 (n (skip-syntax-backward ".")))
1891 (if (or (zerop n)
1892 (and (eq n -1)
1893 (let ((p (point)))
1894 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1895 t
1896 (goto-char p)
1897 nil))))
1898 (while
1899 (progn (skip-syntax-backward "w_'")
1900 (or (not (zerop (skip-syntax-backward "\\")))
1901 (when (eq ?\\ (char-before (1- (point))))
1902 (let ((p (point)))
1903 (forward-char -1)
1904 (if (eq -1 (% (skip-syntax-backward "\\") 2))
1905 t
1906 (goto-char p)
1907 nil))))))
1908 (goto-char (- (point) (% (skip-syntax-backward "\\") 2))))
1909 (buffer-substring-no-properties (point) pos)))
1910
1911 (defun sh-smie-sh-forward-token ()
1912 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1913 (save-excursion
1914 (skip-chars-backward " \t")
1915 (not (bolp))))
1916 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1917 ;; Right before a here-doc.
1918 (let ((forward-sexp-function nil))
1919 (forward-sexp 1)
1920 ;; Pretend the here-document is a "newline representing a
1921 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1922 ";")
1923 (unless (eobp)
1924 (let ((semi (sh-smie--newline-semi-p)))
1925 (forward-line 1)
1926 (if (or semi (eobp)) ";"
1927 (sh-smie-sh-forward-token)))))
1928 (forward-comment (point-max))
1929 (cond
1930 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1931 ((looking-at sh-smie--sh-operators-re)
1932 (goto-char (match-end 0))
1933 (let ((tok (match-string-no-properties 0)))
1934 (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1935 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1936 (forward-line 1))
1937 tok))
1938 (t
1939 (let* ((pos (point))
1940 (tok (sh-smie--default-forward-token)))
1941 (cond
1942 ((equal tok ")") "case-)")
1943 ((equal tok "(") "case-(")
1944 ((and tok (string-match "\\`[a-z]" tok)
1945 (assoc tok smie-grammar)
1946 (not
1947 (save-excursion
1948 (goto-char pos)
1949 (sh-smie--sh-keyword-p tok))))
1950 " word ")
1951 (t tok)))))))
1952
1953 (defun sh-smie--looking-back-at-continuation-p ()
1954 (save-excursion
1955 (and (if (eq (char-before) ?\n) (progn (forward-char -1) t) (eolp))
1956 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1957 (line-beginning-position)))))
1958
1959 (defun sh-smie-sh-backward-token ()
1960 (let ((bol (line-beginning-position)))
1961 (forward-comment (- (point)))
1962 (cond
1963 ((and (bolp) (not (bobp))
1964 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1965 (not (nth 3 (syntax-ppss))))
1966 ;; Right after a here-document.
1967 (let ((forward-sexp-function nil))
1968 (forward-sexp -1)
1969 ;; Pretend the here-document is a "newline representing a
1970 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1971 ";"))
1972 ((< (point) bol)
1973 (cond
1974 ((sh-smie--looking-back-at-continuation-p)
1975 (forward-char -1)
1976 (funcall smie-backward-token-function))
1977 ((sh-smie--newline-semi-p) ";")
1978 (t (funcall smie-backward-token-function))))
1979 ((looking-back sh-smie--sh-operators-back-re
1980 (line-beginning-position) 'greedy)
1981 (goto-char (match-beginning 1))
1982 (match-string-no-properties 1))
1983 (t
1984 (let ((tok (sh-smie--default-backward-token)))
1985 (cond
1986 ((equal tok ")") "case-)")
1987 ((equal tok "(") "case-(")
1988 ((and tok (string-match "\\`[a-z]" tok)
1989 (assoc tok smie-grammar)
1990 (not (save-excursion (sh-smie--sh-keyword-p tok))))
1991 " word ")
1992 (t tok)))))))
1993
1994 (defcustom sh-indent-after-continuation t
1995 "If non-nil, indent relative to the continued line's beginning.
1996 Continued lines can either be indented as \"one long wrapped line\" without
1997 paying attention to the actual syntactic structure, as in:
1998
1999 for f \
2000 in a; do \
2001 toto; \
2002 done
2003
2004 or as lines that just don't have implicit semi-colons between them, as in:
2005
2006 for f \
2007 in a; do \
2008 toto; \
2009 done
2010
2011 With `always' you get the former behavior whereas with nil you get the latter.
2012 With t, you get the latter as long as that would indent the continuation line
2013 deeper than the initial line."
2014 :version "25.1"
2015 :type '(choice
2016 (const nil :tag "Never")
2017 (const t :tag "Only if needed to make it deeper")
2018 (const always :tag "Always"))
2019 :group 'sh-indentation)
2020
2021 (defun sh-smie--continuation-start-indent ()
2022 "Return the initial indentation of a continued line.
2023 May return nil if the line should not be treated as continued."
2024 (save-excursion
2025 (forward-line -1)
2026 (unless (sh-smie--looking-back-at-continuation-p)
2027 (current-indentation))))
2028
2029 (defun sh-smie--indent-continuation ()
2030 (cond
2031 ((not (and sh-indent-after-continuation
2032 (save-excursion
2033 (ignore-errors
2034 (skip-chars-backward " \t")
2035 (sh-smie--looking-back-at-continuation-p)))))
2036 nil)
2037 ((eq sh-indent-after-continuation 'always)
2038 (save-excursion
2039 (forward-line -1)
2040 (if (sh-smie--looking-back-at-continuation-p)
2041 (current-indentation)
2042 (+ (current-indentation) sh-indentation))))
2043 (t
2044 ;; Just make sure a line-continuation is indented deeper.
2045 (save-excursion
2046 (let ((indent (let ((sh-indent-after-continuation nil))
2047 (smie-indent-calculate)))
2048 (max most-positive-fixnum))
2049 (if (not (numberp indent)) indent
2050 (while (progn
2051 (forward-line -1)
2052 (let ((ci (current-indentation)))
2053 (cond
2054 ;; Previous line is less indented, we're good.
2055 ((< ci indent) nil)
2056 ((sh-smie--looking-back-at-continuation-p)
2057 (setq max (min max ci))
2058 ;; Previous line is itself a continuation.
2059 ;; If it's indented like us, we're good, otherwise
2060 ;; check the line before that one.
2061 (> ci indent))
2062 (t ;Previous line is the beginning of the continued line.
2063 (setq indent (min (+ ci sh-indentation) max))
2064 nil)))))
2065 indent))))))
2066
2067 (defun sh-smie-sh-rules (kind token)
2068 (pcase (cons kind token)
2069 (`(:elem . basic) sh-indentation)
2070 (`(:after . "case-)") (- (sh-var-value 'sh-indent-for-case-alt)
2071 (sh-var-value 'sh-indent-for-case-label)))
2072 (`(:before . ,(or `"(" `"{" `"[" "while" "if" "for" "case"))
2073 (if (not (smie-rule-prev-p "&&" "||" "|"))
2074 (when (smie-rule-hanging-p)
2075 (smie-rule-parent))
2076 (unless (smie-rule-bolp)
2077 (while (equal "|" (nth 2 (smie-backward-sexp 'halfexp))))
2078 `(column . ,(smie-indent-virtual)))))
2079 ;; FIXME: Maybe this handling of ;; should be made into
2080 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
2081 (`(:before . ,(or `";;" `";&" `";;&"))
2082 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
2083 (cons 'column (smie-indent-keyword ";"))
2084 (smie-rule-separator kind)))
2085 (`(:after . ,(or `";;" `";&" `";;&"))
2086 (with-demoted-errors
2087 (smie-backward-sexp token)
2088 (cons 'column
2089 (if (or (smie-rule-bolp)
2090 (save-excursion
2091 (and (member (funcall smie-backward-token-function)
2092 '("in" ";;"))
2093 (smie-rule-bolp))))
2094 (current-column)
2095 (smie-indent-calculate)))))
2096 (`(:before . ,(or `"|" `"&&" `"||"))
2097 (unless (smie-rule-parent-p token)
2098 (smie-backward-sexp token)
2099 `(column . ,(+ (funcall smie-rules-function :elem 'basic)
2100 (smie-indent-virtual)))))
2101
2102 ;; Attempt at backward compatibility with the old config variables.
2103 (`(:before . "fi") (sh-var-value 'sh-indent-for-fi))
2104 (`(:before . "done") (sh-var-value 'sh-indent-for-done))
2105 (`(:after . "else") (sh-var-value 'sh-indent-after-else))
2106 (`(:after . "if") (sh-var-value 'sh-indent-after-if))
2107 (`(:before . "then") (sh-var-value 'sh-indent-for-then))
2108 (`(:before . "do") (sh-var-value 'sh-indent-for-do))
2109 (`(:after . "do")
2110 (sh-var-value (if (smie-rule-hanging-p)
2111 'sh-indent-after-loop-construct 'sh-indent-after-do)))
2112 ;; sh-indent-after-done: aligned completely differently.
2113 (`(:after . "in") (sh-var-value 'sh-indent-for-case-label))
2114 ;; sh-indent-for-continuation: Line continuations are handled differently.
2115 (`(:after . ,(or `"(" `"{" `"[")) (sh-var-value 'sh-indent-after-open))
2116 ;; sh-indent-after-function: we don't handle it differently.
2117 ))
2118
2119 ;; (defconst sh-smie-csh-grammar
2120 ;; (smie-prec2->grammar
2121 ;; (smie-bnf->prec2
2122 ;; '((exp) ;A constant, or a $var, or a sequence of them...
2123 ;; (elseifcmd (cmd)
2124 ;; (cmd "else" "else-if" exp "then" elseifcmd))
2125 ;; (cmd ("switch" branches "endsw")
2126 ;; ("if" exp)
2127 ;; ("if" exp "then" cmd "endif")
2128 ;; ("if" exp "then" cmd "else" cmd "endif")
2129 ;; ("if" exp "then" elseifcmd "endif")
2130 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
2131 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2132 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2133 ;; ;; "else" cmd "endif")
2134 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2135 ;; ;; "else" "if" exp "then" cmd "endif")
2136 ;; ("while" cmd "end")
2137 ;; ("foreach" cmd "end")
2138 ;; (cmd "|" cmd) (cmd "|&" cmd)
2139 ;; (cmd "&&" cmd) (cmd "||" cmd)
2140 ;; (cmd ";" cmd) (cmd "&" cmd))
2141 ;; ;; This is a lie, but (combined with the corresponding disambiguation
2142 ;; ;; rule) it makes it more clear that `case' and `default' are the key
2143 ;; ;; separators and the `:' is a secondary tokens.
2144 ;; (branches (branches "case" branches)
2145 ;; (branches "default" branches)
2146 ;; (exp ":" branches)))
2147 ;; '((assoc "else" "then" "endif"))
2148 ;; '((assoc "case" "default") (nonassoc ":"))
2149 ;; '((assoc ";;" ";&" ";;&"))
2150 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2151
2152 ;;;; SMIE support for `rc'.
2153
2154 (defconst sh-smie-rc-grammar
2155 (smie-prec2->grammar
2156 (smie-bnf->prec2
2157 '((exp) ;A constant, or a $var, or a sequence of them...
2158 (cmd (cmd "case" cmd)
2159 ("if" exp)
2160 ("switch" exp)
2161 ("for" exp) ("while" exp)
2162 (cmd "|" cmd) (cmd "|&" cmd)
2163 (cmd "&&" cmd) (cmd "||" cmd)
2164 (cmd ";" cmd) (cmd "&" cmd))
2165 (pattern (pattern "|" pattern))
2166 (branches (branches ";;" branches)
2167 (branches ";&" branches) (branches ";;&" branches) ;bash.
2168 (pattern "case-)" cmd)))
2169 '((assoc ";;" ";&" ";;&"))
2170 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2171
2172 (defun sh-smie--rc-after-special-arg-p ()
2173 "Check if we're after the first arg of an if/while/for/... construct.
2174 Returns the construct's token and moves point before it, if so."
2175 (forward-comment (- (point)))
2176 (when (looking-back ")\\|\\_<not" (- (point) 3))
2177 (ignore-errors
2178 (let ((forward-sexp-function nil))
2179 (forward-sexp -1)
2180 (car (member (funcall smie-backward-token-function)
2181 '("if" "for" "switch" "while")))))))
2182
2183 (defun sh-smie--rc-newline-semi-p ()
2184 "Return non-nil if a newline should be treated as a semi-colon.
2185 Point should be before the newline."
2186 (save-excursion
2187 (let ((tok (funcall smie-backward-token-function)))
2188 (if (or (when (equal tok "not") (forward-word 1) t)
2189 (and (zerop (length tok)) (eq (char-before) ?\))))
2190 (not (sh-smie--rc-after-special-arg-p))
2191 (sh-smie--newline-semi-p tok)))))
2192
2193 (defun sh-smie-rc-forward-token ()
2194 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2195 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2196 (save-excursion
2197 (skip-chars-backward " \t")
2198 (not (bolp))))
2199 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2200 ;; Right before a here-doc.
2201 (let ((forward-sexp-function nil))
2202 (forward-sexp 1)
2203 ;; Pretend the here-document is a "newline representing a
2204 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2205 ";")
2206 (let ((semi (sh-smie--rc-newline-semi-p)))
2207 (forward-line 1)
2208 (if (or semi (eobp)) ";"
2209 (sh-smie-rc-forward-token))))
2210 (forward-comment (point-max))
2211 (cond
2212 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2213 ;; ((looking-at sh-smie--rc-operators-re)
2214 ;; (goto-char (match-end 0))
2215 ;; (let ((tok (match-string-no-properties 0)))
2216 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2217 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2218 ;; (forward-line 1))
2219 ;; tok))
2220 (t
2221 (let* ((pos (point))
2222 (tok (sh-smie--default-forward-token)))
2223 (cond
2224 ;; ((equal tok ")") "case-)")
2225 ((and tok (string-match "\\`[a-z]" tok)
2226 (assoc tok smie-grammar)
2227 (not
2228 (save-excursion
2229 (goto-char pos)
2230 (sh-smie--keyword-p))))
2231 " word ")
2232 (t tok)))))))
2233
2234 (defun sh-smie-rc-backward-token ()
2235 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
2236 (let ((bol (line-beginning-position)))
2237 (forward-comment (- (point)))
2238 (cond
2239 ((and (bolp) (not (bobp))
2240 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2241 (not (nth 3 (syntax-ppss))))
2242 ;; Right after a here-document.
2243 (let ((forward-sexp-function nil))
2244 (forward-sexp -1)
2245 ;; Pretend the here-document is a "newline representing a
2246 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2247 ";"))
2248 ((< (point) bol) ;We skipped over a newline.
2249 (cond
2250 ;; A continued line.
2251 ((and (eolp)
2252 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2253 (line-beginning-position)))
2254 (forward-char -1)
2255 (funcall smie-backward-token-function))
2256 ((sh-smie--rc-newline-semi-p) ";")
2257 (t (funcall smie-backward-token-function))))
2258 ;; ((looking-back sh-smie--sh-operators-back-re
2259 ;; (line-beginning-position) 'greedy)
2260 ;; (goto-char (match-beginning 1))
2261 ;; (match-string-no-properties 1))
2262 (t
2263 (let ((tok (sh-smie--default-backward-token)))
2264 (cond
2265 ;; ((equal tok ")") "case-)")
2266 ((and tok (string-match "\\`[a-z]" tok)
2267 (assoc tok smie-grammar)
2268 (not (save-excursion (sh-smie--keyword-p))))
2269 " word ")
2270 (t tok)))))))
2271
2272 (defun sh-smie-rc-rules (kind token)
2273 (pcase (cons kind token)
2274 (`(:elem . basic) sh-indentation)
2275 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
2276 (`(:after . ";")
2277 (if (smie-rule-parent-p "case")
2278 (smie-rule-parent (sh-var-value 'sh-indent-after-case))))
2279 (`(:before . "{")
2280 (save-excursion
2281 (when (sh-smie--rc-after-special-arg-p)
2282 `(column . ,(current-column)))))
2283 (`(:before . ,(or `"(" `"{" `"["))
2284 (if (smie-rule-hanging-p) (smie-rule-parent)))
2285 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2286 ;; treated as an arg to (exp) by default, which indents it all wrong.
2287 ;; To handle it right, we should extend smie-indent-exps so that the
2288 ;; preceding keyword can give special rules. Currently the only special
2289 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2290 ;; with "(exp)", which is rarely the right thing to do, but is better
2291 ;; than nothing.
2292 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
2293 ;; sh-indent-after-switch: handled implicitly by the default { rule.
2294 ))
2295
2296 ;;; End of SMIE code.
2297
2298 (defvar sh-regexp-for-done nil
2299 "A buffer-local regexp to match opening keyword for done.")
2300
2301 (defvar sh-kw-alist nil
2302 "A buffer-local, since it is shell-type dependent, list of keywords.")
2303
2304 ;; ( key-word first-on-this on-prev-line )
2305 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2306 ;; having 3 elements:
2307 ;; a keyword
2308 ;; a rule to check when the keyword appears on "this" line
2309 ;; a rule to check when the keyword appears on "the previous" line
2310 ;; The keyword is usually a string and is the first word on a line.
2311 ;; If this keyword appears on the line whose indentation is to be
2312 ;; calculated, the rule in element 2 is called. If this returns
2313 ;; non-zero, the resulting point (which may be changed by the rule)
2314 ;; is used as the default indentation.
2315 ;; If it returned false or the keyword was not found in the table,
2316 ;; then the keyword from the previous line is looked up and the rule
2317 ;; in element 3 is called. In this case, however,
2318 ;; `sh-get-indent-info' does not stop but may keep going and test
2319 ;; other keywords against rules in element 3. This is because the
2320 ;; preceding line could have, for example, an opening "if" and an
2321 ;; opening "while" keyword and we need to add the indentation offsets
2322 ;; for both.
2323 ;;
2324 (defconst sh-kw
2325 '((sh
2326 ("if" nil sh-handle-prev-if)
2327 ("elif" sh-handle-this-else sh-handle-prev-else)
2328 ("else" sh-handle-this-else sh-handle-prev-else)
2329 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2330 ("then" sh-handle-this-then sh-handle-prev-then)
2331 ("(" nil sh-handle-prev-open)
2332 ("{" nil sh-handle-prev-open)
2333 ("[" nil sh-handle-prev-open)
2334 ("}" sh-handle-this-close nil)
2335 (")" sh-handle-this-close nil)
2336 ("]" sh-handle-this-close nil)
2337 ("case" nil sh-handle-prev-case)
2338 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2339 (case-label nil sh-handle-after-case-label) ;; ???
2340 (";;" nil sh-handle-prev-case-alt-end) ;; ???
2341 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2342 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2343 ("done" sh-handle-this-done sh-handle-prev-done)
2344 ("do" sh-handle-this-do sh-handle-prev-do))
2345
2346 ;; Note: we don't need specific stuff for bash and zsh shells;
2347 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2348 ;; these shells use.
2349 (rc
2350 ("{" nil sh-handle-prev-open)
2351 ("}" sh-handle-this-close nil)
2352 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
2353
2354
2355
2356 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
2357 "Set this buffer's shell to SHELL (a string).
2358 When used interactively, insert the proper starting #!-line,
2359 and make the visited file executable via `executable-set-magic',
2360 perhaps querying depending on the value of `executable-query'.
2361
2362 When this function is called noninteractively, INSERT-FLAG (the third
2363 argument) controls whether to insert a #!-line and think about making
2364 the visited file executable, and NO-QUERY-FLAG (the second argument)
2365 controls whether to query about making the visited file executable.
2366
2367 Calls the value of `sh-set-shell-hook' if set."
2368 (interactive (list (completing-read
2369 (format "Shell (default %s): "
2370 sh-shell-file)
2371 ;; This used to use interpreter-mode-alist, but that is
2372 ;; no longer appropriate now that uses regexps.
2373 ;; Maybe there could be a separate variable that lists
2374 ;; the shells, used here and to construct i-mode-alist.
2375 ;; But the following is probably good enough:
2376 (append (mapcar (lambda (e) (symbol-name (car e)))
2377 sh-ancestor-alist)
2378 '("csh" "rc" "sh"))
2379 nil nil nil nil sh-shell-file)
2380 (eq executable-query 'function)
2381 t))
2382 (if (string-match "\\.exe\\'" shell)
2383 (setq shell (substring shell 0 (match-beginning 0))))
2384 (setq sh-shell (sh-canonicalize-shell shell))
2385 (if insert-flag
2386 (setq sh-shell-file
2387 (executable-set-magic shell (sh-feature sh-shell-arg)
2388 no-query-flag insert-flag)))
2389 (setq mode-line-process (format "[%s]" sh-shell))
2390 (setq-local sh-shell-variables nil)
2391 (setq-local sh-shell-variables-initialized nil)
2392 (setq-local imenu-generic-expression
2393 (sh-feature sh-imenu-generic-expression))
2394 (let ((tem (sh-feature sh-mode-syntax-table-input)))
2395 (when tem
2396 (setq-local sh-mode-syntax-table
2397 (apply 'sh-mode-syntax-table tem))
2398 (set-syntax-table sh-mode-syntax-table)))
2399 (dolist (var (sh-feature sh-variables))
2400 (sh-remember-variable var))
2401 (if (setq-local sh-indent-supported-here
2402 (sh-feature sh-indent-supported))
2403 (progn
2404 (message "Setting up indent for shell type %s" sh-shell)
2405 (let ((mksym (lambda (name)
2406 (intern (format "sh-smie-%s-%s"
2407 sh-indent-supported-here name)))))
2408 (add-function :around (local 'smie--hanging-eolp-function)
2409 (lambda (orig)
2410 (if (looking-at "[ \t]*\\\\\n")
2411 (goto-char (match-end 0))
2412 (funcall orig))))
2413 (add-hook 'smie-indent-functions #'sh-smie--indent-continuation nil t)
2414 (smie-setup (symbol-value (funcall mksym "grammar"))
2415 (funcall mksym "rules")
2416 :forward-token (funcall mksym "forward-token")
2417 :backward-token (funcall mksym "backward-token")))
2418 (unless sh-use-smie
2419 (setq-local parse-sexp-lookup-properties t)
2420 (setq-local sh-kw-alist (sh-feature sh-kw))
2421 (let ((regexp (sh-feature sh-kws-for-done)))
2422 (if regexp
2423 (setq-local sh-regexp-for-done
2424 (sh-mkword-regexpr (regexp-opt regexp t)))))
2425 (message "setting up indent stuff")
2426 ;; sh-mode has already made indent-line-function local
2427 ;; but do it in case this is called before that.
2428 (setq-local indent-line-function 'sh-indent-line))
2429 (if sh-make-vars-local
2430 (sh-make-vars-local))
2431 (message "Indentation setup for shell type %s" sh-shell))
2432 (message "No indentation for this shell type.")
2433 (setq-local indent-line-function 'sh-basic-indent-line))
2434 (when font-lock-mode
2435 (setq font-lock-set-defaults nil)
2436 (font-lock-set-defaults)
2437 (font-lock-flush))
2438 (setq sh-shell-process nil)
2439 (run-hooks 'sh-set-shell-hook))
2440
2441
2442 (defun sh-feature (alist &optional function)
2443 "Index ALIST by the current shell.
2444 If ALIST isn't a list where every element is a cons, it is returned as is.
2445 Else indexing follows an inheritance logic which works in two ways:
2446
2447 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2448 the alist contains no value for the current shell.
2449 The ultimate default is always `sh'.
2450
2451 - If the value thus looked up is a list starting with `sh-append',
2452 we call the function `sh-append' with the rest of the list as
2453 arguments, and use the value. However, the next element of the
2454 list is not used as-is; instead, we look it up recursively
2455 in ALIST to allow the function called to define the value for
2456 one shell to be derived from another shell.
2457 The value thus determined is physically replaced into the alist.
2458
2459 If FUNCTION is non-nil, it is called with one argument,
2460 the value thus obtained, and the result is used instead."
2461 (or (if (consp alist)
2462 ;; Check for something that isn't a valid alist.
2463 (let ((l alist))
2464 (while (and l (consp (car l)))
2465 (setq l (cdr l)))
2466 (if l alist)))
2467
2468 (let ((orig-sh-shell sh-shell))
2469 (let ((sh-shell sh-shell)
2470 elt val)
2471 (while (and sh-shell
2472 (not (setq elt (assq sh-shell alist))))
2473 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2474 ;; If the shell is not known, treat it as sh.
2475 (unless elt
2476 (setq elt (assq 'sh alist)))
2477 (setq val (cdr elt))
2478 (if (and (consp val)
2479 (memq (car val) '(sh-append sh-modify)))
2480 (setq val
2481 (apply (car val)
2482 ;; Refer to the value for a different shell,
2483 ;; as a kind of inheritance.
2484 (let ((sh-shell (car (cdr val))))
2485 (sh-feature alist))
2486 (cddr val))))
2487 (if function
2488 (setq sh-shell orig-sh-shell
2489 val (funcall function val)))
2490 val))))
2491
2492
2493
2494 ;; I commented this out because nobody calls it -- rms.
2495 ;;(defun sh-abbrevs (ancestor &rest list)
2496 ;; "If it isn't, define the current shell as abbrev table and fill that.
2497 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2498 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2499 ;;according to the remaining arguments NAMEi EXPANSIONi ...
2500 ;;EXPANSION may be either a string or a skeleton command."
2501 ;; (or (if (boundp sh-shell)
2502 ;; (symbol-value sh-shell))
2503 ;; (progn
2504 ;; (if (listp ancestor)
2505 ;; (nconc list ancestor))
2506 ;; (define-abbrev-table sh-shell ())
2507 ;; (if (vectorp ancestor)
2508 ;; (mapatoms (lambda (atom)
2509 ;; (or (eq atom 0)
2510 ;; (define-abbrev (symbol-value sh-shell)
2511 ;; (symbol-name atom)
2512 ;; (symbol-value atom)
2513 ;; (symbol-function atom))))
2514 ;; ancestor))
2515 ;; (while list
2516 ;; (define-abbrev (symbol-value sh-shell)
2517 ;; (car list)
2518 ;; (if (stringp (car (cdr list)))
2519 ;; (car (cdr list))
2520 ;; "")
2521 ;; (if (symbolp (car (cdr list)))
2522 ;; (car (cdr list))))
2523 ;; (setq list (cdr (cdr list)))))
2524 ;; (symbol-value sh-shell)))
2525
2526
2527 (defun sh-append (ancestor &rest list)
2528 "Return list composed of first argument (a list) physically appended to rest."
2529 (nconc list ancestor))
2530
2531
2532 (defun sh-modify (skeleton &rest list)
2533 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2534 (setq skeleton (copy-sequence skeleton))
2535 (while list
2536 (setcar (or (nthcdr (car list) skeleton)
2537 (error "Index %d out of bounds" (car list)))
2538 (car (cdr list)))
2539 (setq list (nthcdr 2 list)))
2540 skeleton)
2541
2542
2543 (defun sh-basic-indent-line ()
2544 "Indent a line for Sh mode (shell script mode).
2545 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2546 Lines containing only comments are considered empty."
2547 (interactive)
2548 (let ((previous (save-excursion
2549 (while (and (progn (beginning-of-line)
2550 (not (bobp)))
2551 (progn
2552 (forward-line -1)
2553 (back-to-indentation)
2554 (or (eolp)
2555 (eq (following-char) ?#)))))
2556 (current-column)))
2557 current)
2558 (save-excursion
2559 (indent-to (if (or (eq this-command 'newline-and-indent)
2560 (and electric-indent-mode (eq this-command 'newline)))
2561 previous
2562 (if (< (current-column)
2563 (setq current (progn (back-to-indentation)
2564 (current-column))))
2565 (if (eolp) previous 0)
2566 (delete-region (point)
2567 (progn (beginning-of-line) (point)))
2568 (if (eolp)
2569 (max previous (* (1+ (/ current sh-indentation))
2570 sh-indentation))
2571 (* (1+ (/ current sh-indentation)) sh-indentation))))))
2572 (if (< (current-column) (current-indentation))
2573 (skip-chars-forward " \t"))))
2574
2575
2576 (defun sh-execute-region (start end &optional flag)
2577 "Pass optional header and region to a subshell for noninteractive execution.
2578 The working directory is that of the buffer, and only environment variables
2579 are already set which is why you can mark a header within the script.
2580
2581 With a positive prefix ARG, instead of sending region, define header from
2582 beginning of buffer to point. With a negative prefix ARG, instead of sending
2583 region, clear header."
2584 (interactive "r\nP")
2585 (if flag
2586 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2587 (point-marker)))
2588 (if sh-header-marker
2589 (save-excursion
2590 (let (buffer-undo-list)
2591 (goto-char sh-header-marker)
2592 (append-to-buffer (current-buffer) start end)
2593 (shell-command-on-region (point-min)
2594 (setq end (+ sh-header-marker
2595 (- end start)))
2596 sh-shell-file)
2597 (delete-region sh-header-marker end)))
2598 (shell-command-on-region start end (concat sh-shell-file " -")))))
2599
2600
2601 (defun sh-remember-variable (var)
2602 "Make VARIABLE available for future completing reads in this buffer."
2603 (or (< (length var) sh-remember-variable-min)
2604 (getenv var)
2605 (assoc var sh-shell-variables)
2606 (push (cons var var) sh-shell-variables))
2607 var)
2608
2609
2610
2611 (defun sh-quoted-p ()
2612 "Is point preceded by an odd number of backslashes?"
2613 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
2614 \f
2615 ;; Indentation stuff.
2616 (defun sh-must-support-indent ()
2617 "Signal an error if the shell type for this buffer is not supported.
2618 Also, the buffer must be in Shell-script mode."
2619 (unless sh-indent-supported-here
2620 (error "This buffer's shell does not support indentation through Emacs")))
2621
2622 (defun sh-make-vars-local ()
2623 "Make the indentation variables local to this buffer.
2624 Normally they already are local. This command is provided in case
2625 variable `sh-make-vars-local' has been set to nil.
2626
2627 To revert all these variables to the global values, use
2628 command `sh-reset-indent-vars-to-global-values'."
2629 (interactive)
2630 (mapc 'make-local-variable sh-var-list)
2631 (message "Indentation variables are now local."))
2632
2633 (defun sh-reset-indent-vars-to-global-values ()
2634 "Reset local indentation variables to the global values.
2635 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2636 (interactive)
2637 (mapc 'kill-local-variable sh-var-list)
2638 (if sh-make-vars-local
2639 (mapcar 'make-local-variable sh-var-list)))
2640
2641
2642 ;; Theoretically these are only needed in shell and derived modes.
2643 ;; However, the routines which use them are only called in those modes.
2644 (defconst sh-special-keywords "then\\|do")
2645
2646 (defun sh-help-string-for-variable (var)
2647 "Construct a string for `sh-read-variable' when changing variable VAR ."
2648 (let ((msg (documentation-property var 'variable-documentation))
2649 (msg2 ""))
2650 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
2651 (setq msg2
2652 (format "\n
2653 You can enter a number (positive to increase indentation,
2654 negative to decrease indentation, zero for no change to indentation).
2655
2656 Or, you can enter one of the following symbols which are relative to
2657 the value of variable `sh-basic-offset'
2658 which in this buffer is currently %s.
2659
2660 \t%s."
2661 sh-basic-offset
2662 (mapconcat (lambda (x)
2663 (nth (1- (length x)) x))
2664 sh-symbol-list "\n\t"))))
2665 (concat
2666 ;; The following shows the global not the local value!
2667 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2668 msg msg2)))
2669
2670 (defun sh-read-variable (var)
2671 "Read a new value for indentation variable VAR."
2672 (let ((minibuffer-help-form `(sh-help-string-for-variable
2673 (quote ,var)))
2674 val)
2675 (setq val (read-from-minibuffer
2676 (format "New value for %s (press %s for help): "
2677 var (single-key-description help-char))
2678 (format "%s" (symbol-value var))
2679 nil t))
2680 val))
2681
2682
2683
2684 (defun sh-in-comment-or-string (start)
2685 "Return non-nil if START is in a comment or string."
2686 (save-excursion
2687 (let ((state (syntax-ppss start)))
2688 (or (nth 3 state) (nth 4 state)))))
2689
2690 (defun sh-goto-matching-if ()
2691 "Go to the matching if for a fi.
2692 This handles nested if..fi pairs."
2693 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2694 (if found
2695 (goto-char found))))
2696
2697
2698 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2699 ;; line whose indentation is being handled contain XXX;
2700 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2701
2702 (defun sh-handle-prev-if ()
2703 (list '(+ sh-indent-after-if)))
2704
2705 (defun sh-handle-this-else ()
2706 (if (sh-goto-matching-if)
2707 ;; (list "aligned to if")
2708 (list "aligned to if" '(+ sh-indent-for-else))
2709 nil
2710 ))
2711
2712 (defun sh-handle-prev-else ()
2713 (if (sh-goto-matching-if)
2714 (list '(+ sh-indent-after-if))
2715 ))
2716
2717 (defun sh-handle-this-fi ()
2718 (if (sh-goto-matching-if)
2719 (list "aligned to if" '(+ sh-indent-for-fi))
2720 nil
2721 ))
2722
2723 (defun sh-handle-prev-fi ()
2724 ;; Why do we have this rule? Because we must go back to the if
2725 ;; to get its indent. We may continue back from there.
2726 ;; We return nil because we don't have anything to add to result,
2727 ;; the side affect of setting align-point is all that matters.
2728 ;; we could return a comment (a string) but I can't think of a good one...
2729 (sh-goto-matching-if)
2730 nil)
2731
2732 (defun sh-handle-this-then ()
2733 (let ((p (sh-goto-matching-if)))
2734 (if p
2735 (list '(+ sh-indent-for-then))
2736 )))
2737
2738 (defun sh-handle-prev-then ()
2739 (let ((p (sh-goto-matching-if)))
2740 (if p
2741 (list '(+ sh-indent-after-if))
2742 )))
2743
2744 (defun sh-handle-prev-open ()
2745 (save-excursion
2746 (let ((x (sh-prev-stmt)))
2747 (if (and x
2748 (progn
2749 (goto-char x)
2750 (or
2751 (looking-at "function\\b")
2752 (looking-at "\\s-*\\S-+\\s-*()")
2753 )))
2754 (list '(+ sh-indent-after-function))
2755 (list '(+ sh-indent-after-open)))
2756 )))
2757
2758 (defun sh-handle-this-close ()
2759 (forward-char 1) ;; move over ")"
2760 (if (sh-safe-forward-sexp -1)
2761 (list "aligned to opening paren")))
2762
2763 (defun sh-goto-matching-case ()
2764 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2765 (if found (goto-char found))))
2766
2767 (defun sh-handle-prev-case ()
2768 ;; This is typically called when point is on same line as a case
2769 ;; we shouldn't -- and can't find prev-case
2770 (if (looking-at ".*\\<case\\>")
2771 (list '(+ sh-indent-for-case-label))
2772 (error "We don't seem to be on a line with a case"))) ;; debug
2773
2774 (defun sh-handle-this-esac ()
2775 (if (sh-goto-matching-case)
2776 (list "aligned to matching case")))
2777
2778 (defun sh-handle-prev-esac ()
2779 (if (sh-goto-matching-case)
2780 (list "matching case")))
2781
2782 (defun sh-handle-after-case-label ()
2783 (if (sh-goto-matching-case)
2784 (list '(+ sh-indent-for-case-alt))))
2785
2786 (defun sh-handle-prev-case-alt-end ()
2787 (if (sh-goto-matching-case)
2788 (list '(+ sh-indent-for-case-label))))
2789
2790 (defun sh-safe-forward-sexp (&optional arg)
2791 "Try and do a `forward-sexp', but do not error.
2792 Return new point if successful, nil if an error occurred."
2793 (condition-case nil
2794 (progn
2795 (forward-sexp (or arg 1))
2796 (point)) ;; return point if successful
2797 (error
2798 (sh-debug "oops!(1) %d" (point))
2799 nil))) ;; return nil if fail
2800
2801 (defun sh-goto-match-for-done ()
2802 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2803 (if found
2804 (goto-char found))))
2805
2806 (defun sh-handle-this-done ()
2807 (if (sh-goto-match-for-done)
2808 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2809
2810 (defun sh-handle-prev-done ()
2811 (if (sh-goto-match-for-done)
2812 (list "previous done")))
2813
2814 (defun sh-handle-this-do ()
2815 (if (sh-goto-match-for-done)
2816 (list '(+ sh-indent-for-do))))
2817
2818 (defun sh-handle-prev-do ()
2819 (cond
2820 ((save-restriction
2821 (narrow-to-region (point) (line-beginning-position))
2822 (sh-goto-match-for-done))
2823 (sh-debug "match for done found on THIS line")
2824 (list '(+ sh-indent-after-loop-construct)))
2825 ((sh-goto-match-for-done)
2826 (sh-debug "match for done found on PREV line")
2827 (list '(+ sh-indent-after-do)))
2828 (t
2829 (message "match for done NOT found")
2830 nil)))
2831
2832 ;; for rc:
2833 (defun sh-find-prev-switch ()
2834 "Find the line for the switch keyword matching this line's case keyword."
2835 (re-search-backward "\\<switch\\>" nil t))
2836
2837 (defun sh-handle-this-rc-case ()
2838 (if (sh-find-prev-switch)
2839 (list '(+ sh-indent-after-switch))
2840 ;; (list '(+ sh-indent-for-case-label))
2841 nil))
2842
2843 (defun sh-handle-prev-rc-case ()
2844 (list '(+ sh-indent-after-case)))
2845
2846 (defun sh-check-rule (n thing)
2847 (let ((rule (nth n (assoc thing sh-kw-alist)))
2848 (val nil))
2849 (if rule
2850 (progn
2851 (setq val (funcall rule))
2852 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2853 n thing (point) rule val)))
2854 val))
2855
2856
2857 (defun sh-get-indent-info ()
2858 "Return indent-info for this line.
2859 This is a list. nil means the line is to be left as is.
2860 Otherwise it contains one or more of the following sublists:
2861 \(t NUMBER) NUMBER is the base location in the buffer that indentation is
2862 relative to. If present, this is always the first of the
2863 sublists. The indentation of the line in question is
2864 derived from the indentation of this point, possibly
2865 modified by subsequent sublists.
2866 \(+ VAR)
2867 \(- VAR) Get the value of variable VAR and add to or subtract from
2868 the indentation calculated so far.
2869 \(= VAR) Get the value of variable VAR and *replace* the
2870 indentation with its value. This only occurs for
2871 special variables such as `sh-indent-comment'.
2872 STRING This is ignored for the purposes of calculating
2873 indentation, it is printed in certain cases to help show
2874 what the indentation is based on."
2875 ;; See comments before `sh-kw'.
2876 (save-excursion
2877 (let ((have-result nil)
2878 this-kw
2879 val
2880 (result nil)
2881 (align-point nil)
2882 prev-line-end x)
2883 (beginning-of-line)
2884 ;; Note: setting result to t means we are done and will return nil.
2885 ;;(This function never returns just t.)
2886 (cond
2887 ((or (nth 3 (syntax-ppss (point)))
2888 (eq (get-text-property (point) 'face) sh-heredoc-face))
2889 ;; String continuation -- don't indent
2890 (setq result t)
2891 (setq have-result t))
2892 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2893 (if (bobp)
2894 (setq result t) ;; return nil if 1st line!
2895 (setq result (list '(= sh-indent-comment)))
2896 ;; we still need to get previous line in case
2897 ;; sh-indent-comment is t (indent as normal)
2898 (setq align-point (sh-prev-line nil))
2899 (setq have-result nil)
2900 ))
2901 ) ;; cond
2902
2903 (unless have-result
2904 ;; Continuation lines are handled specially
2905 (if (sh-this-is-a-continuation)
2906 (progn
2907 (setq result
2908 (if (save-excursion
2909 (beginning-of-line)
2910 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2911 ;; By convention, if the continuation \ is not
2912 ;; preceded by a SPC or a TAB it means that the line
2913 ;; is cut at a place where spaces cannot be freely
2914 ;; added/removed. I.e. do not indent the line.
2915 (list '(= nil))
2916 ;; We assume the line being continued is already
2917 ;; properly indented...
2918 ;; (setq prev-line-end (sh-prev-line))
2919 (setq align-point (sh-prev-line nil))
2920 (list '(+ sh-indent-for-continuation))))
2921 (setq have-result t))
2922 (beginning-of-line)
2923 (skip-chars-forward " \t")
2924 (setq this-kw (sh-get-kw)))
2925
2926 ;; Handle "this" keyword: first word on the line we're
2927 ;; calculating indentation info for.
2928 (if this-kw
2929 (if (setq val (sh-check-rule 1 this-kw))
2930 (progn
2931 (setq align-point (point))
2932 (sh-debug
2933 "this - setting align-point to %d" align-point)
2934 (setq result (append result val))
2935 (setq have-result t)
2936 ;; set prev-line to continue processing remainder
2937 ;; of this line as a previous line
2938 (setq prev-line-end (point))
2939 ))))
2940
2941 (unless have-result
2942 (setq prev-line-end (sh-prev-line 'end)))
2943
2944 (if prev-line-end
2945 (save-excursion
2946 ;; We start off at beginning of this line.
2947 ;; Scan previous statements while this is <=
2948 ;; start of previous line.
2949 (goto-char prev-line-end)
2950 (setq x t)
2951 (while (and x (setq x (sh-prev-thing)))
2952 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2953 (cond
2954 ((and (equal x ")")
2955 (equal (get-text-property (1- (point)) 'syntax-table)
2956 sh-st-punc))
2957 (sh-debug "Case label) here")
2958 (setq x 'case-label)
2959 (if (setq val (sh-check-rule 2 x))
2960 (progn
2961 (setq result (append result val))
2962 (setq align-point (point))))
2963 (or (bobp)
2964 (forward-char -1))
2965 ;; FIXME: This charset looks too much like a regexp. --Stef
2966 (skip-chars-forward "[a-z0-9]*?")
2967 )
2968 ((string-match "[])}]" x)
2969 (setq x (sh-safe-forward-sexp -1))
2970 (if x
2971 (progn
2972 (setq align-point (point))
2973 (setq result (append result
2974 (list "aligned to opening paren")))
2975 )))
2976 ((string-match "[[({]" x)
2977 (sh-debug "Checking special thing: %s" x)
2978 (if (setq val (sh-check-rule 2 x))
2979 (setq result (append result val)))
2980 (forward-char -1)
2981 (setq align-point (point)))
2982 ((string-match "[\"'`]" x)
2983 (sh-debug "Skipping back for %s" x)
2984 ;; this was oops-2
2985 (setq x (sh-safe-forward-sexp -1)))
2986 ((stringp x)
2987 (sh-debug "Checking string %s at %s" x (point))
2988 (if (setq val (sh-check-rule 2 x))
2989 ;; (or (eq t (car val))
2990 ;; (eq t (car (car val))))
2991 (setq result (append result val)))
2992 ;; not sure about this test Wed Jan 27 23:48:35 1999
2993 (setq align-point (point))
2994 (unless (bolp)
2995 (forward-char -1)))
2996 (t
2997 (error "Don't know what to do with %s" x))
2998 )
2999 ) ;; while
3000 (sh-debug "result is %s" result)
3001 )
3002 (sh-debug "No prev line!")
3003 (sh-debug "result: %s align-point: %s" result align-point)
3004 )
3005
3006 (if align-point
3007 ;; was: (setq result (append result (list (list t align-point))))
3008 (setq result (append (list (list t align-point)) result))
3009 )
3010 (sh-debug "result is now: %s" result)
3011
3012 (or result
3013 (setq result (list (if prev-line-end
3014 (list t prev-line-end)
3015 (list '= 'sh-first-lines-indent)))))
3016
3017 (if (eq result t)
3018 (setq result nil))
3019 (sh-debug "result is: %s" result)
3020 result
3021 ) ;; let
3022 ))
3023
3024
3025 (defun sh-get-indent-var-for-line (&optional info)
3026 "Return the variable controlling indentation for this line.
3027 If there is not [just] one such variable, return a string
3028 indicating the problem.
3029 If INFO is supplied it is used, else it is calculated."
3030 (let ((var nil)
3031 (result nil)
3032 (reason nil)
3033 sym elt)
3034 (or info
3035 (setq info (sh-get-indent-info)))
3036 (if (null info)
3037 (setq result "this line to be left as is")
3038 (while (and info (null result))
3039 (setq elt (car info))
3040 (cond
3041 ((stringp elt)
3042 (setq reason elt)
3043 )
3044 ((not (listp elt))
3045 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
3046 ;; so it is a list
3047 ((eq t (car elt))
3048 ) ;; nothing
3049 ((symbolp (setq sym (nth 1 elt)))
3050 ;; A bit of a kludge - when we see the sh-indent-comment
3051 ;; ignore other variables. Otherwise it is tricky to
3052 ;; "learn" the comment indentation.
3053 (if (eq var 'sh-indent-comment)
3054 (setq result var)
3055 (if var
3056 (setq result
3057 "this line is controlled by more than 1 variable.")
3058 (setq var sym))))
3059 (t
3060 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
3061 (setq info (cdr info))
3062 ))
3063 (or result
3064 (setq result var))
3065 (or result
3066 (setq result reason))
3067 (if (null result)
3068 ;; e.g. just had (t POS)
3069 (setq result "line has default indentation"))
3070 result))
3071
3072
3073
3074 ;; Finding the previous line isn't trivial.
3075 ;; We must *always* go back one more and see if that is a continuation
3076 ;; line -- it is the PREVIOUS line which is continued, not the one
3077 ;; we are going to!
3078 ;; Also, we want to treat a whole "here document" as one big line,
3079 ;; because we may want to a align to the beginning of it.
3080 ;;
3081 ;; What we do:
3082 ;; - go back to previous non-empty line
3083 ;; - if this is in a here-document, go to the beginning of it
3084 ;; - while previous line is continued, go back one line
3085 (defun sh-prev-line (&optional end)
3086 "Back to end of previous non-comment non-empty line.
3087 Go to beginning of logical line unless END is non-nil, in which case
3088 we go to the end of the previous line and do not check for continuations."
3089 (save-excursion
3090 (beginning-of-line)
3091 (forward-comment (- (point-max)))
3092 (unless end (beginning-of-line))
3093 (when (and (not (bobp))
3094 (equal (get-text-property (1- (point)) 'face)
3095 sh-heredoc-face))
3096 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
3097 (when p1
3098 (goto-char p1)
3099 (if end
3100 (end-of-line)
3101 (beginning-of-line)))))
3102 (unless end
3103 ;; we must check previous lines to see if they are continuation lines
3104 ;; if so, we must return position of first of them
3105 (while (and (sh-this-is-a-continuation)
3106 (>= 0 (forward-line -1))))
3107 (beginning-of-line)
3108 (skip-chars-forward " \t"))
3109 (point)))
3110
3111
3112 (defun sh-prev-stmt ()
3113 "Return the address of the previous stmt or nil."
3114 ;; This is used when we are trying to find a matching keyword.
3115 ;; Searching backward for the keyword would certainly be quicker, but
3116 ;; it is hard to remove "false matches" -- such as if the keyword
3117 ;; appears in a string or quote. This way is slower, but (I think) safer.
3118 (interactive)
3119 (save-excursion
3120 (let ((going t)
3121 (start (point))
3122 (found nil)
3123 (prev nil))
3124 (skip-chars-backward " \t;|&({[")
3125 (while (and (not found)
3126 (not (bobp))
3127 going)
3128 ;; Do a backward-sexp if possible, else backup bit by bit...
3129 (if (sh-safe-forward-sexp -1)
3130 (progn
3131 (if (looking-at sh-special-keywords)
3132 (progn
3133 (setq found prev))
3134 (setq prev (point))
3135 ))
3136 ;; backward-sexp failed
3137 (if (zerop (skip-chars-backward " \t()[]{};`'"))
3138 (forward-char -1))
3139 (if (bolp)
3140 (let ((back (sh-prev-line nil)))
3141 (if back
3142 (goto-char back)
3143 (setq going nil)))))
3144 (unless found
3145 (skip-chars-backward " \t")
3146 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
3147 (eq (char-before) ?\;)
3148 (looking-at "\\s-*[|&]"))
3149 (setq found (point)))))
3150 (if found
3151 (goto-char found))
3152 (if found
3153 (progn
3154 (skip-chars-forward " \t|&({[")
3155 (setq found (point))))
3156 (if (>= (point) start)
3157 (progn
3158 (debug "We didn't move!")
3159 (setq found nil))
3160 (or found
3161 (sh-debug "Did not find prev stmt.")))
3162 found)))
3163
3164
3165 (defun sh-get-word ()
3166 "Get a shell word skipping whitespace from point."
3167 (interactive)
3168 (skip-chars-forward "\t ")
3169 (let ((start (point)))
3170 (while
3171 (if (looking-at "[\"'`]")
3172 (sh-safe-forward-sexp)
3173 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
3174 (> (skip-chars-forward "-_$[:alnum:]") 0)
3175 ))
3176 (buffer-substring start (point))
3177 ))
3178
3179 (defun sh-prev-thing ()
3180 "Return the previous thing this logical line."
3181 ;; This is called when `sh-get-indent-info' is working backwards on
3182 ;; the previous line(s) finding what keywords may be relevant for
3183 ;; indenting. It moves over sexps if possible, and will stop
3184 ;; on a ; and at the beginning of a line if it is not a continuation
3185 ;; line.
3186 ;;
3187 ;; Added a kludge for ";;"
3188 ;; Possible return values:
3189 ;; nil - nothing
3190 ;; a string - possibly a keyword
3191 ;;
3192 (if (bolp)
3193 nil
3194 (let ((start (point))
3195 (min-point (if (sh-this-is-a-continuation)
3196 (sh-prev-line nil)
3197 (line-beginning-position))))
3198 (skip-chars-backward " \t;" min-point)
3199 (if (looking-at "\\s-*;[;&]")
3200 ;; (message "Found ;; !")
3201 ";;"
3202 (skip-chars-backward "^)}];\"'`({[" min-point)
3203 (let ((c (if (> (point) min-point) (char-before))))
3204 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
3205 (point) c start min-point)
3206 (if (not (memq c '(?\n nil ?\;)))
3207 ;; c -- return a string
3208 (char-to-string c)
3209 ;; Return the leading keyword of the "command" we supposedly
3210 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
3211 ;; `then' that precedes the actual command), so check whether
3212 ;; we're looking at such a keyword and if so, move back forward.
3213 (let ((boundary (point))
3214 kwd next)
3215 (while
3216 (progn
3217 ;; Skip forward over white space newline and \ at eol.
3218 (skip-chars-forward " \t\n\\\\" start)
3219 (if (>= (point) start)
3220 (progn
3221 (sh-debug "point: %d >= start: %d" (point) start)
3222 nil)
3223 (if next (setq boundary next))
3224 (sh-debug "Now at %d start=%d" (point) start)
3225 (setq kwd (sh-get-word))
3226 (if (member kwd (sh-feature sh-leading-keywords))
3227 (progn
3228 (setq next (point))
3229 t)
3230 nil))))
3231 (goto-char boundary)
3232 kwd)))))))
3233
3234
3235 (defun sh-this-is-a-continuation ()
3236 "Return non-nil if current line is a continuation of previous line."
3237 (save-excursion
3238 (and (zerop (forward-line -1))
3239 (looking-at ".*\\\\$")
3240 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
3241 nil nil nil t))))))
3242
3243 (defun sh-get-kw (&optional where and-move)
3244 "Return first word of line from WHERE.
3245 If AND-MOVE is non-nil then move to end of word."
3246 (let ((start (point)))
3247 (if where
3248 (goto-char where))
3249 (prog1
3250 (buffer-substring (point)
3251 (progn (skip-chars-forward "^ \t\n;&|")(point)))
3252 (unless and-move
3253 (goto-char start)))))
3254
3255 (defun sh-find-prev-matching (open close &optional depth)
3256 "Find a matching token for a set of opening and closing keywords.
3257 This takes into account that there may be nested open..close pairings.
3258 OPEN and CLOSE are regexps denoting the tokens to be matched.
3259 Optional parameter DEPTH (usually 1) says how many to look for."
3260 (let ((parse-sexp-ignore-comments t)
3261 (forward-sexp-function nil)
3262 prev)
3263 (setq depth (or depth 1))
3264 (save-excursion
3265 (condition-case nil
3266 (while (and
3267 (/= 0 depth)
3268 (not (bobp))
3269 (setq prev (sh-prev-stmt)))
3270 (goto-char prev)
3271 (save-excursion
3272 (if (looking-at "\\\\\n")
3273 (progn
3274 (forward-char 2)
3275 (skip-chars-forward " \t")))
3276 (cond
3277 ((looking-at open)
3278 (setq depth (1- depth))
3279 (sh-debug "found open at %d - depth = %d" (point) depth))
3280 ((looking-at close)
3281 (setq depth (1+ depth))
3282 (sh-debug "found close - depth = %d" depth))
3283 (t
3284 ))))
3285 (error nil))
3286 (if (eq depth 0)
3287 prev ;; (point)
3288 nil)
3289 )))
3290
3291
3292 (defun sh-var-value (var &optional ignore-error)
3293 "Return the value of variable VAR, interpreting symbols.
3294 It can also return t or nil.
3295 If an invalid value is found, throw an error unless Optional argument
3296 IGNORE-ERROR is non-nil."
3297 (let ((val (symbol-value var)))
3298 (cond
3299 ((numberp val)
3300 val)
3301 ((eq val t)
3302 val)
3303 ((null val)
3304 val)
3305 ((eq val '+)
3306 sh-basic-offset)
3307 ((eq val '-)
3308 (- sh-basic-offset))
3309 ((eq val '++)
3310 (* 2 sh-basic-offset))
3311 ((eq val '--)
3312 (* 2 (- sh-basic-offset)))
3313 ((eq val '*)
3314 (/ sh-basic-offset 2))
3315 ((eq val '/)
3316 (/ (- sh-basic-offset) 2))
3317 (t
3318 (funcall (if ignore-error #'message #'error)
3319 "Don't know how to handle %s's value of %s" var val)
3320 0))))
3321
3322 (defun sh-set-var-value (var value &optional no-symbol)
3323 "Set variable VAR to VALUE.
3324 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3325 can be represented by a symbol then do so."
3326 (cond
3327 (no-symbol
3328 (set var value))
3329 ((= value sh-basic-offset)
3330 (set var '+))
3331 ((= value (- sh-basic-offset))
3332 (set var '-))
3333 ((eq value (* 2 sh-basic-offset))
3334 (set var '++))
3335 ((eq value (* 2 (- sh-basic-offset)))
3336 (set var '--))
3337 ((eq value (/ sh-basic-offset 2))
3338 (set var '*))
3339 ((eq value (/ (- sh-basic-offset) 2))
3340 (set var '/))
3341 (t
3342 (set var value)))
3343 )
3344
3345
3346 (defun sh-calculate-indent (&optional info)
3347 "Return the indentation for the current line.
3348 If INFO is supplied it is used, else it is calculated from current line."
3349 (let ((ofs 0)
3350 (base-value 0)
3351 elt a b val)
3352 (or info
3353 (setq info (sh-get-indent-info)))
3354 (when info
3355 (while info
3356 (sh-debug "info: %s ofs=%s" info ofs)
3357 (setq elt (car info))
3358 (cond
3359 ((stringp elt)) ;; do nothing?
3360 ((listp elt)
3361 (setq a (car (car info)))
3362 (setq b (nth 1 (car info)))
3363 (cond
3364 ((eq a t)
3365 (save-excursion
3366 (goto-char b)
3367 (setq val (current-indentation)))
3368 (setq base-value val))
3369 ((symbolp b)
3370 (setq val (sh-var-value b))
3371 (cond
3372 ((eq a '=)
3373 (cond
3374 ((null val)
3375 ;; no indentation
3376 ;; set info to nil so we stop immediately
3377 (setq base-value nil ofs nil info nil))
3378 ((eq val t) (setq ofs 0)) ;; indent as normal line
3379 (t
3380 ;; The following assume the (t POS) come first!
3381 (setq ofs val base-value 0)
3382 (setq info nil)))) ;; ? stop now
3383 ((eq a '+) (setq ofs (+ ofs val)))
3384 ((eq a '-) (setq ofs (- ofs val)))
3385 (t
3386 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3387 (t
3388 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
3389 (t
3390 (error "sh-calculate-indent invalid elt %s" elt)))
3391 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3392 a b val base-value ofs)
3393 (setq info (cdr info)))
3394 ;; return value:
3395 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
3396
3397 (cond
3398 ((or (null base-value)(null ofs))
3399 nil)
3400 ((and (numberp base-value)(numberp ofs))
3401 (sh-debug "base (%d) + ofs (%d) = %d"
3402 base-value ofs (+ base-value ofs))
3403 (+ base-value ofs)) ;; return value
3404 (t
3405 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3406 base-value ofs)
3407 nil)))))
3408
3409
3410 (defun sh-indent-line ()
3411 "Indent the current line."
3412 (interactive)
3413 (let ((indent (sh-calculate-indent))
3414 (pos (- (point-max) (point))))
3415 (when indent
3416 (beginning-of-line)
3417 (skip-chars-forward " \t")
3418 (indent-line-to indent)
3419 ;; If initial point was within line's indentation,
3420 ;; position after the indentation. Else stay at same point in text.
3421 (if (> (- (point-max) pos) (point))
3422 (goto-char (- (point-max) pos))))))
3423
3424
3425 (defun sh-blink (blinkpos &optional msg)
3426 "Move cursor momentarily to BLINKPOS and display MSG."
3427 ;; We can get here without it being a number on first line
3428 (if (numberp blinkpos)
3429 (save-excursion
3430 (goto-char blinkpos)
3431 (if msg (message "%s" msg) (message nil))
3432 (sit-for blink-matching-delay))
3433 (if msg (message "%s" msg) (message nil))))
3434
3435 (defun sh-show-indent (arg)
3436 "Show the how the current line would be indented.
3437 This tells you which variable, if any, controls the indentation of
3438 this line.
3439 If optional arg ARG is non-null (called interactively with a prefix),
3440 a pop up window describes this variable.
3441 If variable `sh-blink' is non-nil then momentarily go to the line
3442 we are indenting relative to, if applicable."
3443 (interactive "P")
3444 (sh-must-support-indent)
3445 (if sh-use-smie
3446 (smie-config-show-indent)
3447 (let* ((info (sh-get-indent-info))
3448 (var (sh-get-indent-var-for-line info))
3449 (curr-indent (current-indentation))
3450 val msg)
3451 (if (stringp var)
3452 (message "%s" (setq msg var))
3453 (setq val (sh-calculate-indent info))
3454
3455 (if (eq curr-indent val)
3456 (setq msg (format "%s is %s" var (symbol-value var)))
3457 (setq msg
3458 (if val
3459 (format "%s (%s) would change indent from %d to: %d"
3460 var (symbol-value var) curr-indent val)
3461 (format "%s (%s) would leave line as is"
3462 var (symbol-value var)))
3463 ))
3464 (if (and arg var)
3465 (describe-variable var)))
3466 (if sh-blink
3467 (let ((info (sh-get-indent-info)))
3468 (if (and info (listp (car info))
3469 (eq (car (car info)) t))
3470 (sh-blink (nth 1 (car info)) msg)
3471 (message "%s" msg)))
3472 (message "%s" msg))
3473 )))
3474
3475 (defun sh-set-indent ()
3476 "Set the indentation for the current line.
3477 If the current line is controlled by an indentation variable, prompt
3478 for a new value for it."
3479 (interactive)
3480 (sh-must-support-indent)
3481 (if sh-use-smie
3482 (smie-config-set-indent)
3483 (let* ((info (sh-get-indent-info))
3484 (var (sh-get-indent-var-for-line info))
3485 val old-val indent-val)
3486 (if (stringp var)
3487 (message "Cannot set indent - %s" var)
3488 (setq old-val (symbol-value var))
3489 (setq val (sh-read-variable var))
3490 (condition-case nil
3491 (progn
3492 (set var val)
3493 (setq indent-val (sh-calculate-indent info))
3494 (if indent-val
3495 (message "Variable: %s Value: %s would indent to: %d"
3496 var (symbol-value var) indent-val)
3497 (message "Variable: %s Value: %s would leave line as is."
3498 var (symbol-value var)))
3499 ;; I'm not sure about this, indenting it now?
3500 ;; No. Because it would give the impression that an undo would
3501 ;; restore thing, but the value has been altered.
3502 ;; (sh-indent-line)
3503 )
3504 (error
3505 (set var old-val)
3506 (message "Bad value for %s, restoring to previous value %s"
3507 var old-val)
3508 (sit-for 1)
3509 nil))
3510 ))))
3511
3512
3513 (defun sh-learn-line-indent (arg)
3514 "Learn how to indent a line as it currently is indented.
3515
3516 If there is an indentation variable which controls this line's indentation,
3517 then set it to a value which would indent the line the way it
3518 presently is.
3519
3520 If the value can be represented by one of the symbols then do so
3521 unless optional argument ARG (the prefix when interactive) is non-nil."
3522 (interactive "*P")
3523 (sh-must-support-indent)
3524 (if sh-use-smie
3525 (smie-config-set-indent)
3526 ;; I'm not sure if we show allow learning on an empty line.
3527 ;; Though it might occasionally be useful I think it usually
3528 ;; would just be confusing.
3529 (if (save-excursion
3530 (beginning-of-line)
3531 (looking-at "\\s-*$"))
3532 (message "sh-learn-line-indent ignores empty lines.")
3533 (let* ((info (sh-get-indent-info))
3534 (var (sh-get-indent-var-for-line info))
3535 ival sval diff new-val
3536 (no-symbol arg)
3537 (curr-indent (current-indentation)))
3538 (cond
3539 ((stringp var)
3540 (message "Cannot learn line - %s" var))
3541 ((eq var 'sh-indent-comment)
3542 ;; This is arbitrary...
3543 ;; - if curr-indent is 0, set to curr-indent
3544 ;; - else if it has the indentation of a "normal" line,
3545 ;; then set to t
3546 ;; - else set to curr-indent.
3547 (setq sh-indent-comment
3548 (if (= curr-indent 0)
3549 0
3550 (let* ((sh-indent-comment t)
3551 (val2 (sh-calculate-indent info)))
3552 (if (= val2 curr-indent)
3553 t
3554 curr-indent))))
3555 (message "%s set to %s" var (symbol-value var))
3556 )
3557 ((numberp (setq sval (sh-var-value var)))
3558 (setq ival (sh-calculate-indent info))
3559 (setq diff (- curr-indent ival))
3560
3561 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3562 curr-indent ival diff var sval)
3563 (setq new-val (+ sval diff))
3564 ;; I commented out this because someone might want to replace
3565 ;; a value of `+' with the current value of sh-basic-offset
3566 ;; or vice-versa.
3567 ;;(if (= 0 diff)
3568 ;; (message "No change needed!")
3569 (sh-set-var-value var new-val no-symbol)
3570 (message "%s set to %s" var (symbol-value var))
3571 )
3572 (t
3573 (debug)
3574 (message "Cannot change %s" var)))))))
3575
3576
3577
3578 (defun sh-mark-init (buffer)
3579 "Initialize a BUFFER to be used by `sh-mark-line'."
3580 (with-current-buffer (get-buffer-create buffer)
3581 (erase-buffer)
3582 (occur-mode)))
3583
3584
3585 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
3586 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3587 Buffer BUFFER is in `occur-mode'.
3588 If ADD-LINENUM is non-nil the message is preceded by the line number.
3589 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3590 so that `occur-next' and `occur-prev' will work."
3591 (let ((m1 (make-marker))
3592 start
3593 (line ""))
3594 (when point
3595 (set-marker m1 point (current-buffer))
3596 (if add-linenum
3597 (setq line (format "%d: " (1+ (count-lines 1 point))))))
3598 (save-excursion
3599 (if (get-buffer buffer)
3600 (set-buffer (get-buffer buffer))
3601 (set-buffer (get-buffer-create buffer))
3602 (occur-mode)
3603 )
3604 (goto-char (point-max))
3605 (setq start (point))
3606 (let ((inhibit-read-only t))
3607 (insert line)
3608 (if occur-point
3609 (setq occur-point (point)))
3610 (insert message)
3611 (if point
3612 (add-text-properties
3613 start (point)
3614 '(mouse-face highlight
3615 help-echo "mouse-2: go to the line where I learned this")))
3616 (insert "\n")
3617 (when point
3618 (put-text-property start (point) 'occur-target m1)
3619 (if occur-point
3620 (put-text-property start occur-point
3621 'occur-match t))
3622 )))))
3623
3624 ;; Is this really worth having?
3625 (defvar sh-learned-buffer-hook nil
3626 "An abnormal hook, called with an alist of learned variables.")
3627 ;; Example of how to use sh-learned-buffer-hook
3628 ;;
3629 ;; (defun what-i-learned (list)
3630 ;; (let ((p list))
3631 ;; (with-current-buffer "*scratch*"
3632 ;; (goto-char (point-max))
3633 ;; (insert "(setq\n")
3634 ;; (while p
3635 ;; (insert (format " %s %s \n"
3636 ;; (nth 0 (car p)) (nth 1 (car p))))
3637 ;; (setq p (cdr p)))
3638 ;; (insert ")\n")
3639 ;; )))
3640 ;;
3641 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3642
3643
3644 ;; Originally this was sh-learn-region-indent (beg end)
3645 ;; However, in practice this was awkward so I changed it to
3646 ;; use the whole buffer. Use narrowing if need be.
3647 (defun sh-learn-buffer-indent (&optional arg)
3648 "Learn how to indent the buffer the way it currently is.
3649
3650 Output in buffer \"*indent*\" shows any lines which have conflicting
3651 values of a variable, and the final value of all variables learned.
3652 When called interactively, pop to this buffer automatically if
3653 there are any discrepancies.
3654
3655 If no prefix ARG is given, then variables are set to numbers.
3656 If a prefix arg is given, then variables are set to symbols when
3657 applicable -- e.g. to symbol `+' if the value is that of the
3658 basic indent.
3659 If a positive numerical prefix is given, then `sh-basic-offset'
3660 is set to the prefix's numerical value.
3661 Otherwise, sh-basic-offset may or may not be changed, according
3662 to the value of variable `sh-learn-basic-offset'.
3663
3664 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3665 function completes. The function is abnormal because it is called
3666 with an alist of variables learned. This feature may be changed or
3667 removed in the future.
3668
3669 This command can often take a long time to run."
3670 (interactive "P")
3671 (sh-must-support-indent)
3672 (if sh-use-smie
3673 (smie-config-guess)
3674 (save-excursion
3675 (goto-char (point-min))
3676 (let ((learned-var-list nil)
3677 (out-buffer "*indent*")
3678 (num-diffs 0)
3679 previous-set-info
3680 (max 17)
3681 vec
3682 msg
3683 (comment-col nil) ;; number if all same, t if seen diff values
3684 (comments-always-default t) ;; nil if we see one not default
3685 initial-msg
3686 (specified-basic-offset (and arg (numberp arg)
3687 (> arg 0)))
3688 (linenum 0)
3689 suggested)
3690 (setq vec (make-vector max 0))
3691 (sh-mark-init out-buffer)
3692
3693 (if specified-basic-offset
3694 (progn
3695 (setq sh-basic-offset arg)
3696 (setq initial-msg
3697 (format "Using specified sh-basic-offset of %d"
3698 sh-basic-offset)))
3699 (setq initial-msg
3700 (format "Initial value of sh-basic-offset: %s"
3701 sh-basic-offset)))
3702
3703 (while (< (point) (point-max))
3704 (setq linenum (1+ linenum))
3705 ;; (if (zerop (% linenum 10))
3706 (message "line %d" linenum)
3707 ;; )
3708 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3709 (let* ((sh-indent-comment t) ;; info must return default indent
3710 (info (sh-get-indent-info))
3711 (var (sh-get-indent-var-for-line info))
3712 sval ival diff new-val
3713 (curr-indent (current-indentation)))
3714 (cond
3715 ((null var)
3716 nil)
3717 ((stringp var)
3718 nil)
3719 ((numberp (setq sval (sh-var-value var 'no-error)))
3720 ;; the numberp excludes comments since sval will be t.
3721 (setq ival (sh-calculate-indent))
3722 (setq diff (- curr-indent ival))
3723 (setq new-val (+ sval diff))
3724 (sh-set-var-value var new-val 'no-symbol)
3725 (unless (looking-at "\\s-*#") ;; don't learn from comments
3726 (if (setq previous-set-info (assoc var learned-var-list))
3727 (progn
3728 ;; it was already there, is it same value ?
3729 (unless (eq (symbol-value var)
3730 (nth 1 previous-set-info))
3731 (sh-mark-line
3732 (format "Variable %s was set to %s"
3733 var (symbol-value var))
3734 (point) out-buffer t t)
3735 (sh-mark-line
3736 (format " but was previously set to %s"
3737 (nth 1 previous-set-info))
3738 (nth 2 previous-set-info) out-buffer t)
3739 (setq num-diffs (1+ num-diffs))
3740 ;; (delete previous-set-info learned-var-list)
3741 (setcdr previous-set-info
3742 (list (symbol-value var) (point)))
3743 )
3744 )
3745 (setq learned-var-list
3746 (append (list (list var (symbol-value var)
3747 (point)))
3748 learned-var-list)))
3749 (if (numberp new-val)
3750 (progn
3751 (sh-debug
3752 "This line's indent value: %d" new-val)
3753 (if (< new-val 0)
3754 (setq new-val (- new-val)))
3755 (if (< new-val max)
3756 (aset vec new-val (1+ (aref vec new-val))))))
3757 ))
3758 ((eq var 'sh-indent-comment)
3759 (unless (= curr-indent (sh-calculate-indent info))
3760 ;; this is not the default indentation
3761 (setq comments-always-default nil)
3762 (if comment-col ;; then we have see one before
3763 (or (eq comment-col curr-indent)
3764 (setq comment-col t)) ;; seen a different one
3765 (setq comment-col curr-indent))
3766 ))
3767 (t
3768 (sh-debug "Cannot learn this line!!!")
3769 ))
3770 (sh-debug
3771 "at %s learned-var-list is %s" (point) learned-var-list)
3772 ))
3773 (forward-line 1)
3774 ) ;; while
3775 (if sh-debug
3776 (progn
3777 (setq msg (format
3778 "comment-col = %s comments-always-default = %s"
3779 comment-col comments-always-default))
3780 ;; (message msg)
3781 (sh-mark-line msg nil out-buffer)))
3782 (cond
3783 ((eq comment-col 0)
3784 (setq msg "\nComments are all in 1st column.\n"))
3785 (comments-always-default
3786 (setq msg "\nComments follow default indentation.\n")
3787 (setq comment-col t))
3788 ((numberp comment-col)
3789 (setq msg (format "\nComments are in col %d." comment-col)))
3790 (t
3791 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3792 (setq comment-col nil)
3793 ))
3794 (sh-debug msg)
3795 (sh-mark-line msg nil out-buffer)
3796
3797 (sh-mark-line initial-msg nil out-buffer t t)
3798
3799 (setq suggested (sh-guess-basic-offset vec))
3800
3801 (if (and suggested (not specified-basic-offset))
3802 (let ((new-value
3803 (cond
3804 ;; t => set it if we have a single value as a number
3805 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3806 suggested)
3807 ;; other non-nil => set it if only one value was found
3808 (sh-learn-basic-offset
3809 (if (numberp suggested)
3810 suggested
3811 (if (= (length suggested) 1)
3812 (car suggested))))
3813 (t
3814 nil))))
3815 (if new-value
3816 (progn
3817 (setq learned-var-list
3818 (append (list (list 'sh-basic-offset
3819 (setq sh-basic-offset new-value)
3820 (point-max)))
3821 learned-var-list))
3822 ;; Not sure if we need to put this line in, since
3823 ;; it will appear in the "Learned variable settings".
3824 (sh-mark-line
3825 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3826 nil out-buffer))
3827 (sh-mark-line
3828 (if (listp suggested)
3829 (format "Possible value(s) for sh-basic-offset: %s"
3830 (mapconcat 'int-to-string suggested " "))
3831 (format "Suggested sh-basic-offset: %d" suggested))
3832 nil out-buffer))))
3833
3834
3835 (setq learned-var-list
3836 (append (list (list 'sh-indent-comment comment-col (point-max)))
3837 learned-var-list))
3838 (setq sh-indent-comment comment-col)
3839 (let ((name (buffer-name)))
3840 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3841 (if arg
3842 ;; Set learned variables to symbolic rather than numeric
3843 ;; values where possible.
3844 (dolist (learned-var (reverse learned-var-list))
3845 (let ((var (car learned-var))
3846 (val (nth 1 learned-var)))
3847 (when (and (not (eq var 'sh-basic-offset))
3848 (numberp val))
3849 (sh-set-var-value var val)))))
3850 (dolist (learned-var (reverse learned-var-list))
3851 (let ((var (car learned-var)))
3852 (sh-mark-line (format " %s %s" var (symbol-value var))
3853 (nth 2 learned-var) out-buffer)))
3854 (with-current-buffer out-buffer
3855 (goto-char (point-min))
3856 (let ((inhibit-read-only t))
3857 (insert
3858 (format "Indentation values for buffer %s.\n" name)
3859 (format "%d indentation variable%s different values%s\n\n"
3860 num-diffs
3861 (if (= num-diffs 1)
3862 " has" "s have")
3863 (if (zerop num-diffs)
3864 "." ":"))))))
3865 ;; Are abnormal hooks considered bad form?
3866 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3867 (and (called-interactively-p 'any)
3868 (or sh-popup-occur-buffer (> num-diffs 0))
3869 (pop-to-buffer out-buffer))))))
3870
3871 (defun sh-guess-basic-offset (vec)
3872 "See if we can determine a reasonable value for `sh-basic-offset'.
3873 This is experimental, heuristic and arbitrary!
3874 Argument VEC is a vector of information collected by
3875 `sh-learn-buffer-indent'.
3876 Return values:
3877 number - there appears to be a good single value
3878 list of numbers - no obvious one, here is a list of one or more
3879 reasonable choices
3880 nil - we couldn't find a reasonable one."
3881 (let* ((max (1- (length vec)))
3882 (i 1)
3883 (totals (make-vector max 0)))
3884 (while (< i max)
3885 (cl-incf (aref totals i) (* 4 (aref vec i)))
3886 (if (zerop (% i 2))
3887 (cl-incf (aref totals i) (aref vec (/ i 2))))
3888 (if (< (* i 2) max)
3889 (cl-incf (aref totals i) (aref vec (* i 2))))
3890 (setq i (1+ i)))
3891
3892 (let ((x nil)
3893 (result nil)
3894 tot sum p)
3895 (setq i 1)
3896 (while (< i max)
3897 (if (/= (aref totals i) 0)
3898 (push (cons i (aref totals i)) x))
3899 (setq i (1+ i)))
3900
3901 (setq x (sort (nreverse x) (lambda (a b) (> (cdr a) (cdr b)))))
3902 (setq tot (apply '+ (append totals nil)))
3903 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3904 vec totals tot))
3905 (cond
3906 ((zerop (length x))
3907 (message "no values!")) ;; we return nil
3908 ((= (length x) 1)
3909 (message "only value is %d" (car (car x)))
3910 (setq result (car (car x)))) ;; return single value
3911 ((> (cdr (car x)) (/ tot 2))
3912 ;; 1st is > 50%
3913 (message "basic-offset is probably %d" (car (car x)))
3914 (setq result (car (car x)))) ;; again, return a single value
3915 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3916 ;; 1st is >= 2 * 2nd
3917 (message "basic-offset could be %d" (car (car x)))
3918 (setq result (car (car x))))
3919 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3920 ;; 1st & 2nd together >= 50% - return a list
3921 (setq p x sum 0 result nil)
3922 (while (and p
3923 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3924 (setq result (append result (list (car (car p)))))
3925 (setq p (cdr p)))
3926 (message "Possible choices for sh-basic-offset: %s"
3927 (mapconcat 'int-to-string result " ")))
3928 (t
3929 (message "No obvious value for sh-basic-offset. Perhaps %d"
3930 (car (car x)))
3931 ;; result is nil here
3932 ))
3933 result)))
3934
3935 ;; ========================================================================
3936
3937 ;; Styles -- a quick and dirty way of saving the indentation settings.
3938
3939 (defvar sh-styles-alist nil
3940 "A list of all known shell indentation styles.")
3941
3942 (defun sh-name-style (name &optional confirm-overwrite)
3943 "Name the current indentation settings as a style called NAME.
3944 If this name exists, the command will prompt whether it should be
3945 overwritten if
3946 - - it was called interactively with a prefix argument, or
3947 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3948 ;; (interactive "sName for this style: ")
3949 (interactive
3950 (list
3951 (read-from-minibuffer "Name for this style? " )
3952 (not current-prefix-arg)))
3953 (let ((slist (cons name
3954 (mapcar (lambda (var) (cons var (symbol-value var)))
3955 sh-var-list)))
3956 (style (assoc name sh-styles-alist)))
3957 (if style
3958 (if (and confirm-overwrite
3959 (not (y-or-n-p "This style exists. Overwrite it? ")))
3960 (message "Not changing style %s" name)
3961 (message "Updating style %s" name)
3962 (setcdr style (cdr slist)))
3963 (message "Creating new style %s" name)
3964 (push slist sh-styles-alist))))
3965
3966 (defun sh-load-style (name)
3967 "Set shell indentation values for this buffer from those in style NAME."
3968 (interactive (list (completing-read
3969 "Which style to use for this buffer? "
3970 sh-styles-alist nil t)))
3971 (let ((sl (assoc name sh-styles-alist)))
3972 (if (null sl)
3973 (error "sh-load-style - style %s not known" name)
3974 (dolist (var (cdr sl))
3975 (set (car var) (cdr var))))))
3976
3977 (defun sh-save-styles-to-buffer (buff)
3978 "Save all current styles in elisp to buffer BUFF.
3979 This is always added to the end of the buffer."
3980 (interactive
3981 (list
3982 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3983 (with-current-buffer (get-buffer-create buff)
3984 (goto-char (point-max))
3985 (insert "\n")
3986 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3987
3988
3989 \f
3990 ;; statement syntax-commands for various shells
3991
3992 ;; You are welcome to add the syntax or even completely new statements as
3993 ;; appropriate for your favorite shell.
3994
3995 (defconst sh-non-closing-paren
3996 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3997 ;; that inherits this property, which then confuses the indentation.
3998 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3999
4000 (define-skeleton sh-case
4001 "Insert a case/switch statement. See `sh-feature'."
4002 (csh "expression: "
4003 "switch( " str " )" \n
4004 > "case " (read-string "pattern: ") ?: \n
4005 > _ \n
4006 "breaksw" \n
4007 ( "other pattern, %s: "
4008 < "case " str ?: \n
4009 > _ \n
4010 "breaksw" \n)
4011 < "default:" \n
4012 > _ \n
4013 resume:
4014 < < "endsw" \n)
4015 (es)
4016 (rc "expression: "
4017 > "switch( " str " ) {" \n
4018 > "case " (read-string "pattern: ") \n
4019 > _ \n
4020 ( "other pattern, %s: "
4021 "case " str > \n
4022 > _ \n)
4023 "case *" > \n
4024 > _ \n
4025 resume:
4026 ?\} > \n)
4027 (sh "expression: "
4028 > "case " str " in" \n
4029 ( "pattern, %s: "
4030 > str sh-non-closing-paren \n
4031 > _ \n
4032 ";;" \n)
4033 > "*" sh-non-closing-paren \n
4034 > _ \n
4035 resume:
4036 "esac" > \n))
4037
4038 (define-skeleton sh-for
4039 "Insert a for loop. See `sh-feature'."
4040 (csh sh-modify sh
4041 1 ""
4042 2 "foreach "
4043 4 " ( "
4044 6 " )"
4045 15 '<
4046 16 "end")
4047 (es sh-modify rc
4048 4 " = ")
4049 (rc sh-modify sh
4050 2 "for( "
4051 6 " ) {"
4052 15 ?\} )
4053 (sh "Index variable: "
4054 > "for " str " in " _ "; do" \n
4055 > _ | ?$ & (sh-remember-variable str) \n
4056 "done" > \n))
4057
4058
4059
4060 (define-skeleton sh-indexed-loop
4061 "Insert an indexed loop from 1 to n. See `sh-feature'."
4062 (bash sh-modify posix)
4063 (csh "Index variable: "
4064 "@ " str " = 1" \n
4065 "while( $" str " <= " (read-string "upper limit: ") " )" \n
4066 > _ ?$ str \n
4067 "@ " str "++" \n
4068 < "end" \n)
4069 (es sh-modify rc
4070 4 " =")
4071 (ksh88 "Index variable: "
4072 > "integer " str "=0" \n
4073 > "while (( ( " str " += 1 ) <= "
4074 (read-string "upper limit: ")
4075 " )); do" \n
4076 > _ ?$ (sh-remember-variable str) > \n
4077 "done" > \n)
4078 (posix "Index variable: "
4079 > str "=1" \n
4080 "while [ $" str " -le "
4081 (read-string "upper limit: ")
4082 " ]; do" \n
4083 > _ ?$ str \n
4084 str ?= (sh-add (sh-remember-variable str) 1) \n
4085 "done" > \n)
4086 (rc "Index variable: "
4087 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
4088 (read-string "upper limit: ")
4089 "; i++ ) print i }'`}) {" \n
4090 > _ ?$ (sh-remember-variable str) \n
4091 ?\} > \n)
4092 (sh "Index variable: "
4093 > "for " str " in `awk 'BEGIN { for( i=1; i<="
4094 (read-string "upper limit: ")
4095 "; i++ ) print i }'`; do" \n
4096 > _ ?$ (sh-remember-variable str) \n
4097 "done" > \n))
4098
4099
4100 (defun sh-shell-initialize-variables ()
4101 "Scan the buffer for variable assignments.
4102 Add these variables to `sh-shell-variables'."
4103 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
4104 (save-excursion
4105 (goto-char (point-min))
4106 (setq sh-shell-variables-initialized t)
4107 (while (search-forward "=" nil t)
4108 (sh-assignment 0)))
4109 (message "Scanning buffer `%s' for variable assignments...done"
4110 (buffer-name)))
4111
4112 (defvar sh-add-buffer)
4113
4114 (defun sh-add-completer (string predicate code)
4115 "Do completion using `sh-shell-variables', but initialize it first.
4116 This function is designed for use as the \"completion table\",
4117 so it takes three arguments:
4118 STRING, the current buffer contents;
4119 PREDICATE, the predicate for filtering possible matches;
4120 CODE, which says what kind of things to do.
4121 CODE can be nil, t or `lambda'.
4122 nil means to return the best completion of STRING, or nil if there is none.
4123 t means to return a list of all possible completions of STRING.
4124 `lambda' means to return t if STRING is a valid completion as it stands."
4125 (let ((vars
4126 (with-current-buffer sh-add-buffer
4127 (or sh-shell-variables-initialized
4128 (sh-shell-initialize-variables))
4129 (nconc (mapcar (lambda (var)
4130 (substring var 0 (string-match "=" var)))
4131 process-environment)
4132 sh-shell-variables))))
4133 (complete-with-action code vars string predicate)))
4134
4135 (defun sh-add (var delta)
4136 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
4137 (interactive
4138 (let ((sh-add-buffer (current-buffer)))
4139 (list (completing-read "Variable: " 'sh-add-completer)
4140 (prefix-numeric-value current-prefix-arg))))
4141 (insert (sh-feature '((bash . "$(( ")
4142 (ksh88 . "$(( ")
4143 (posix . "$(( ")
4144 (rc . "`{expr $")
4145 (sh . "`expr $")
4146 (zsh . "$[ ")))
4147 (sh-remember-variable var)
4148 (if (< delta 0) " - " " + ")
4149 (number-to-string (abs delta))
4150 (sh-feature '((bash . " ))")
4151 (ksh88 . " ))")
4152 (posix . " ))")
4153 (rc . "}")
4154 (sh . "`")
4155 (zsh . " ]")))))
4156
4157
4158
4159 (define-skeleton sh-function
4160 "Insert a function definition. See `sh-feature'."
4161 (bash sh-modify ksh88
4162 3 "() {")
4163 (ksh88 "name: "
4164 "function " str " {" \n
4165 > _ \n
4166 < "}" \n)
4167 (rc sh-modify ksh88
4168 1 "fn ")
4169 (sh ()
4170 "() {" \n
4171 > _ \n
4172 < "}" \n))
4173
4174
4175
4176 (define-skeleton sh-if
4177 "Insert an if statement. See `sh-feature'."
4178 (csh "condition: "
4179 "if( " str " ) then" \n
4180 > _ \n
4181 ( "other condition, %s: "
4182 < "else if( " str " ) then" \n
4183 > _ \n)
4184 < "else" \n
4185 > _ \n
4186 resume:
4187 < "endif" \n)
4188 (es "condition: "
4189 > "if { " str " } {" \n
4190 > _ \n
4191 ( "other condition, %s: "
4192 "} { " str " } {" > \n
4193 > _ \n)
4194 "} {" > \n
4195 > _ \n
4196 resume:
4197 ?\} > \n)
4198 (rc "condition: "
4199 > "if( " str " ) {" \n
4200 > _ \n
4201 ( "other condition, %s: "
4202 "} else if( " str " ) {" > \n
4203 > _ \n)
4204 "} else {" > \n
4205 > _ \n
4206 resume:
4207 ?\} > \n)
4208 (sh "condition: "
4209 '(setq input (sh-feature sh-test))
4210 > "if " str "; then" \n
4211 > _ \n
4212 ( "other condition, %s: "
4213 > "elif " str "; then" > \n
4214 > \n)
4215 "else" > \n
4216 > \n
4217 resume:
4218 "fi" > \n))
4219
4220
4221
4222 (define-skeleton sh-repeat
4223 "Insert a repeat loop definition. See `sh-feature'."
4224 (es nil
4225 > "forever {" \n
4226 > _ \n
4227 ?\} > \n)
4228 (zsh "factor: "
4229 > "repeat " str "; do" > \n
4230 > \n
4231 "done" > \n))
4232
4233 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
4234
4235
4236
4237 (define-skeleton sh-select
4238 "Insert a select statement. See `sh-feature'."
4239 (ksh88 "Index variable: "
4240 > "select " str " in " _ "; do" \n
4241 > ?$ str \n
4242 "done" > \n)
4243 (bash sh-append ksh88))
4244 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
4245
4246
4247
4248 (define-skeleton sh-tmp-file
4249 "Insert code to setup temporary file handling. See `sh-feature'."
4250 (bash sh-append ksh88)
4251 (csh (file-name-nondirectory (buffer-file-name))
4252 "set tmp = `mktemp -t " str ".XXXXXX`" \n
4253 "onintr exit" \n _
4254 (and (goto-char (point-max))
4255 (not (bolp))
4256 ?\n)
4257 "exit:\n"
4258 "rm $tmp* >&/dev/null" > \n)
4259 (es (file-name-nondirectory (buffer-file-name))
4260 > "local( signals = $signals sighup sigint;" \n
4261 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
4262 > "catch @ e {" \n
4263 > "rm $tmp^* >[2]/dev/null" \n
4264 "throw $e" \n
4265 "} {" > \n
4266 _ \n
4267 ?\} > \n
4268 ?\} > \n)
4269 (ksh88 sh-modify sh
4270 7 "EXIT")
4271 (rc (file-name-nondirectory (buffer-file-name))
4272 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
4273 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
4274 (sh (file-name-nondirectory (buffer-file-name))
4275 > "TMP=`mktemp -t " str ".XXXXXX`" \n
4276 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
4277
4278
4279
4280 (define-skeleton sh-until
4281 "Insert an until loop. See `sh-feature'."
4282 (sh "condition: "
4283 '(setq input (sh-feature sh-test))
4284 > "until " str "; do" \n
4285 > _ \n
4286 "done" > \n))
4287 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
4288
4289
4290
4291 (define-skeleton sh-while
4292 "Insert a while loop. See `sh-feature'."
4293 (csh sh-modify sh
4294 2 ""
4295 3 "while( "
4296 5 " )"
4297 10 '<
4298 11 "end")
4299 (es sh-modify sh
4300 3 "while { "
4301 5 " } {"
4302 10 ?\} )
4303 (rc sh-modify sh
4304 3 "while( "
4305 5 " ) {"
4306 10 ?\} )
4307 (sh "condition: "
4308 '(setq input (sh-feature sh-test))
4309 > "while " str "; do" \n
4310 > _ \n
4311 "done" > \n))
4312
4313
4314
4315 (define-skeleton sh-while-getopts
4316 "Insert a while getopts loop. See `sh-feature'.
4317 Prompts for an options string which consists of letters for each recognized
4318 option followed by a colon `:' if the option accepts an argument."
4319 (bash sh-modify sh
4320 18 "${0##*/}")
4321 (csh nil
4322 "while( 1 )" \n
4323 > "switch( \"$1\" )" \n
4324 '(setq input '("- x" . 2))
4325 > >
4326 ( "option, %s: "
4327 < "case " '(eval str)
4328 '(if (string-match " +" str)
4329 (setq v1 (substring str (match-end 0))
4330 str (substring str 0 (match-beginning 0)))
4331 (setq v1 nil))
4332 str ?: \n
4333 > "set " v1 & " = $2" | -4 & _ \n
4334 (if v1 "shift") & \n
4335 "breaksw" \n)
4336 < "case --:" \n
4337 > "shift" \n
4338 < "default:" \n
4339 > "break" \n
4340 resume:
4341 < < "endsw" \n
4342 "shift" \n
4343 < "end" \n)
4344 (ksh88 sh-modify sh
4345 16 "print"
4346 18 "${0##*/}"
4347 37 "OPTIND-1")
4348 (posix sh-modify sh
4349 18 "$(basename $0)")
4350 (sh "optstring: "
4351 > "while getopts :" str " OPT; do" \n
4352 > "case $OPT in" \n
4353 '(setq v1 (append (vconcat str) nil))
4354 ( (prog1 (if v1 (char-to-string (car v1)))
4355 (if (eq (nth 1 v1) ?:)
4356 (setq v1 (nthcdr 2 v1)
4357 v2 "\"$OPTARG\"")
4358 (setq v1 (cdr v1)
4359 v2 nil)))
4360 > str "|+" str sh-non-closing-paren \n
4361 > _ v2 \n
4362 > ";;" \n)
4363 > "*" sh-non-closing-paren \n
4364 > "echo" " \"usage: " "`basename $0`"
4365 " [+-" '(setq v1 (point)) str
4366 '(save-excursion
4367 (while (search-backward ":" v1 t)
4368 (replace-match " ARG] [+-" t t)))
4369 (if (eq (preceding-char) ?-) -5)
4370 (if (and (sequencep v1) (length v1)) "] " "} ")
4371 "[--] ARGS...\"" \n
4372 "exit 2" > \n
4373 "esac" >
4374 \n "done"
4375 > \n
4376 "shift " (sh-add "OPTIND" -1) \n
4377 "OPTIND=1" \n))
4378
4379
4380
4381 (defun sh-assignment (arg)
4382 "Remember preceding identifier for future completion and do self-insert."
4383 (interactive "p")
4384 (self-insert-command arg)
4385 (if (<= arg 1)
4386 (sh-remember-variable
4387 (save-excursion
4388 (if (re-search-forward (sh-feature sh-assignment-regexp)
4389 (prog1 (point)
4390 (beginning-of-line 1))
4391 t)
4392 (match-string 1))))))
4393
4394
4395 (defun sh-maybe-here-document (arg)
4396 "Insert self. Without prefix, following unquoted `<' inserts here document.
4397 The document is bounded by `sh-here-document-word'."
4398 (declare (obsolete sh-electric-here-document-mode "24.3"))
4399 (interactive "*P")
4400 (self-insert-command (prefix-numeric-value arg))
4401 (or arg (sh--maybe-here-document)))
4402
4403 (defun sh--maybe-here-document ()
4404 (or (not (looking-back "[^<]<<" (line-beginning-position)))
4405 (save-excursion
4406 (backward-char 2)
4407 (or (sh-quoted-p)
4408 (sh--inside-noncommand-expression (point))))
4409 (nth 8 (syntax-ppss))
4410 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
4411 (make-string (/ (current-indentation) tab-width) ?\t)
4412 ""))
4413 (delim (replace-regexp-in-string "['\"]" ""
4414 sh-here-document-word)))
4415 (insert sh-here-document-word)
4416 (or (eolp) (looking-at "[ \t]") (insert ?\s))
4417 (end-of-line 1)
4418 (while
4419 (sh-quoted-p)
4420 (end-of-line 2))
4421 (insert ?\n tabs)
4422 (save-excursion
4423 (insert ?\n tabs (replace-regexp-in-string
4424 "\\`-?[ \t]*" "" delim))))))
4425
4426 (define-minor-mode sh-electric-here-document-mode
4427 "Make << insert a here document skeleton."
4428 nil nil nil
4429 (if sh-electric-here-document-mode
4430 (add-hook 'post-self-insert-hook #'sh--maybe-here-document nil t)
4431 (remove-hook 'post-self-insert-hook #'sh--maybe-here-document t)))
4432 \f
4433 ;; various other commands
4434
4435 (defun sh-beginning-of-command ()
4436 ;; FIXME: Redefine using SMIE.
4437 "Move point to successive beginnings of commands."
4438 (interactive)
4439 (if (re-search-backward sh-beginning-of-command nil t)
4440 (goto-char (match-beginning 2))))
4441
4442 (defun sh-end-of-command ()
4443 ;; FIXME: Redefine using SMIE.
4444 "Move point to successive ends of commands."
4445 (interactive)
4446 (if (re-search-forward sh-end-of-command nil t)
4447 (goto-char (match-end 1))))
4448
4449 ;; Backslashification. Stolen from make-mode.el.
4450
4451 (defun sh-backslash-region (from to delete-flag)
4452 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4453 With no argument, inserts backslashes and aligns existing backslashes.
4454 With an argument, deletes the backslashes.
4455
4456 This function does not modify the last line of the region if the region ends
4457 right at the start of the following line; it does not modify blank lines
4458 at the start of the region. So you can put the region around an entire
4459 shell command and conveniently use this command."
4460 (interactive "r\nP")
4461 (save-excursion
4462 (goto-char from)
4463 (let ((column sh-backslash-column)
4464 (endmark (make-marker)))
4465 (move-marker endmark to)
4466 ;; Compute the smallest column number past the ends of all the lines.
4467 (if sh-backslash-align
4468 (progn
4469 (if (not delete-flag)
4470 (while (< (point) to)
4471 (end-of-line)
4472 (if (= (preceding-char) ?\\)
4473 (progn (forward-char -1)
4474 (skip-chars-backward " \t")))
4475 (setq column (max column (1+ (current-column))))
4476 (forward-line 1)))
4477 ;; Adjust upward to a tab column, if that doesn't push
4478 ;; past the margin.
4479 (if (> (% column tab-width) 0)
4480 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
4481 tab-width)))
4482 (if (< adjusted (window-width))
4483 (setq column adjusted))))))
4484 ;; Don't modify blank lines at start of region.
4485 (goto-char from)
4486 (while (and (< (point) endmark) (eolp))
4487 (forward-line 1))
4488 ;; Add or remove backslashes on all the lines.
4489 (while (and (< (point) endmark)
4490 ;; Don't backslashify the last line
4491 ;; if the region ends right at the start of the next line.
4492 (save-excursion
4493 (forward-line 1)
4494 (< (point) endmark)))
4495 (if (not delete-flag)
4496 (sh-append-backslash column)
4497 (sh-delete-backslash))
4498 (forward-line 1))
4499 (move-marker endmark nil))))
4500
4501 (defun sh-append-backslash (column)
4502 (end-of-line)
4503 ;; Note that "\\\\" is needed to get one backslash.
4504 (if (= (preceding-char) ?\\)
4505 (progn (forward-char -1)
4506 (delete-horizontal-space)
4507 (indent-to column (if sh-backslash-align nil 1)))
4508 (indent-to column (if sh-backslash-align nil 1))
4509 (insert "\\")))
4510
4511 (defun sh-delete-backslash ()
4512 (end-of-line)
4513 (or (bolp)
4514 (progn
4515 (forward-char -1)
4516 (if (looking-at "\\\\")
4517 (delete-region (1+ (point))
4518 (progn (skip-chars-backward " \t") (point)))))))
4519
4520 (provide 'sh-script)
4521
4522 ;;; sh-script.el ends here