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