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