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