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