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