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