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