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