Derive from prog-mode, use derived-mode-p, and fix up various
[emacs.git] / lisp / progmodes / sh-script.el
blobee7e4c3b1b6c430d3d26a6d3c72f4d75d176ad93
1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 1994, 1995, 1996, 1997, 1999, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 ;; Free Software Foundation, Inc.
7 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
8 ;; Version: 2.0f
9 ;; Maintainer: FSF
10 ;; Keywords: languages, unix
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30 ;; as various derivatives are supported and easily derived from. Structured
31 ;; statements can be inserted with one command or abbrev. Completion is
32 ;; available for filenames, variables known from the script, the shell and
33 ;; the environment as well as commands.
35 ;;; Known Bugs:
37 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 ;; - Variables in `"' strings aren't fontified because there's no way of
39 ;; syntactically distinguishing those from `'' strings.
41 ;; Indentation
42 ;; ===========
43 ;; Indentation for rc and es modes is very limited, but for Bourne shells
44 ;; and its derivatives it is quite customizable.
46 ;; The following description applies to sh and derived shells (bash,
47 ;; zsh, ...).
49 ;; There are various customization variables which allow tailoring to
50 ;; a wide variety of styles. Most of these variables are named
51 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
52 ;; sh-indent-after-if controls the indenting of a line following
53 ;; an if statement, and sh-indent-for-fi controls the indentation
54 ;; of the line containing the fi.
56 ;; You can set each to a numeric value, but it is often more convenient
57 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
58 ;; By changing this one variable you can increase or decrease how much
59 ;; indentation there is. Valid symbols:
61 ;; + Indent right by sh-basic-offset
62 ;; - Indent left by sh-basic-offset
63 ;; ++ Indent right twice sh-basic-offset
64 ;; -- Indent left twice sh-basic-offset
65 ;; * Indent right half sh-basic-offset
66 ;; / Indent left half sh-basic-offset.
68 ;; There are 4 commands to help set the indentation variables:
70 ;; `sh-show-indent'
71 ;; This shows what variable controls the indentation of the current
72 ;; line and its value.
74 ;; `sh-set-indent'
75 ;; This allows you to set the value of the variable controlling the
76 ;; current line's indentation. You can enter a number or one of a
77 ;; number of special symbols to denote the value of sh-basic-offset,
78 ;; or its negative, or half it, or twice it, etc. If you've used
79 ;; cc-mode this should be familiar. If you forget which symbols are
80 ;; valid simply press C-h at the prompt.
82 ;; `sh-learn-line-indent'
83 ;; Simply make the line look the way you want it, then invoke this
84 ;; command. It will set the variable to the value that makes the line
85 ;; indent like that. If called with a prefix argument then it will set
86 ;; the value to one of the symbols if applicable.
88 ;; `sh-learn-buffer-indent'
89 ;; This is the deluxe function! It "learns" the whole buffer (use
90 ;; narrowing if you want it to process only part). It outputs to a
91 ;; buffer *indent* any conflicts it finds, and all the variables it has
92 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
93 ;; easily find where something was set. It is popped to automatically
94 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
95 ;; non-nil.
96 ;; `sh-indent-comment' will be set if all comments follow the same
97 ;; pattern; if they don't it will be set to nil.
98 ;; Whether `sh-basic-offset' is set is determined by variable
99 ;; `sh-learn-basic-offset'.
101 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
102 ;; (e.g. if there are large case statements). Perhaps it does not make
103 ;; sense to run it on large buffers: if lots of lines have different
104 ;; indentation styles it will produce a lot of diagnostics in the
105 ;; *indent* buffer; if there is a consistent style then running
106 ;; `sh-learn-buffer-indent' on a small region of the buffer should
107 ;; suffice.
109 ;; Saving indentation values
110 ;; -------------------------
111 ;; After you've learned the values in a buffer, how to you remember
112 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
113 ;; would make this unnecessary; simply learn the values when you visit
114 ;; the buffer.
115 ;; You can do this automatically like this:
116 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
118 ;; However... `sh-learn-buffer-indent' is extremely slow,
119 ;; especially on large-ish buffer. Also, if there are conflicts the
120 ;; "last one wins" which may not produce the desired setting.
122 ;; So...There is a minimal way of being able to save indentation values and
123 ;; to reload them in another buffer or at another point in time.
125 ;; Use `sh-name-style' to give a name to the indentation settings of
126 ;; the current buffer.
127 ;; Use `sh-load-style' to load indentation settings for the current
128 ;; buffer from a specific style.
129 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
130 ;; in lisp code. You can then store it in a file and later use
131 ;; `load-file' to load it.
133 ;; Indentation variables - buffer local or global?
134 ;; ----------------------------------------------
135 ;; I think that often having them buffer-local makes sense,
136 ;; especially if one is using `sh-learn-buffer-indent'. However, if
137 ;; a user sets values using customization, these changes won't appear
138 ;; to work if the variables are already local!
140 ;; To get round this, there is a variable `sh-make-vars-local' and 2
141 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
143 ;; If `sh-make-vars-local' is non-nil, then these variables become
144 ;; buffer local when the mode is established.
145 ;; If this is nil, then the variables are global. At any time you
146 ;; can make them local with the command `sh-make-vars-local'.
147 ;; Conversely, to update with the global values you can use the
148 ;; command `sh-reset-indent-vars-to-global-values'.
150 ;; This may be awkward, but the intent is to cover all cases.
152 ;; Awkward things, pitfalls
153 ;; ------------------------
154 ;; Indentation for a sh script is complicated for a number of reasons:
156 ;; 1. You can't format by simply looking at symbols, you need to look
157 ;; at keywords. [This is not the case for rc and es shells.]
158 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
159 ;; as a stand-alone symbol (in a case alternative). This makes
160 ;; things quite tricky!
161 ;; 3. Here-documents in a script should be treated "as is", and when
162 ;; they terminate we want to revert to the indentation of the line
163 ;; containing the "<<" symbol.
164 ;; 4. A line may be continued using the "\".
165 ;; 5. The character "#" (outside a string) normally starts a comment,
166 ;; but it doesn't in the sequence "$#"!
168 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
169 ;; uses, that of a text's syntax property. This, however, has 2
170 ;; disadvantages:
171 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
172 ;; case alternative, to find any here documents, and handle "$#".
174 ;; Bugs
175 ;; ----
176 ;; - Indenting many lines is slow. It currently does each line
177 ;; independently, rather than saving state information.
179 ;; - `sh-learn-buffer-indent' is extremely slow.
181 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
182 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
183 ;; coerce sh-script into doing the right thing.
185 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
186 ;; a case-pattern. You need to put the "in" between quotes to coerce
187 ;; sh-script into doing the right thing.
189 ;; - A line starting with "}>foo" is not indented like "} >foo".
191 ;; Richard Sharman <rsharman@pobox.com> June 1999.
193 ;;; Code:
195 ;; page 1: variables and settings
196 ;; page 2: indentation stuff
197 ;; page 3: mode-command and utility functions
198 ;; page 4: statement syntax-commands for various shells
199 ;; page 5: various other commands
201 (eval-when-compile
202 (require 'skeleton)
203 (require 'cl)
204 (require 'comint))
205 (require 'executable)
207 (defvar font-lock-comment-face)
208 (defvar font-lock-set-defaults)
209 (defvar font-lock-string-face)
212 (defgroup sh nil
213 "Shell programming utilities."
214 :group 'languages)
216 (defgroup sh-script nil
217 "Shell script mode."
218 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
219 :group 'sh
220 :prefix "sh-")
223 (defcustom sh-ancestor-alist
224 '((ash . sh)
225 (bash . jsh)
226 (bash2 . jsh)
227 (dtksh . ksh)
228 (es . rc)
229 (itcsh . tcsh)
230 (jcsh . csh)
231 (jsh . sh)
232 (ksh . ksh88)
233 (ksh88 . jsh)
234 (oash . sh)
235 (pdksh . ksh88)
236 (posix . sh)
237 (tcsh . csh)
238 (wksh . ksh88)
239 (wsh . sh)
240 (zsh . ksh88)
241 (rpm . sh))
242 "Alist showing the direct ancestor of various shells.
243 This is the basis for `sh-feature'. See also `sh-alias-alist'.
244 By default we have the following three hierarchies:
246 csh C Shell
247 jcsh C Shell with Job Control
248 tcsh TENEX C Shell
249 itcsh Ian's TENEX C Shell
250 rc Plan 9 Shell
251 es Extensible Shell
252 sh Bourne Shell
253 ash Almquist Shell
254 jsh Bourne Shell with Job Control
255 bash GNU Bourne Again Shell
256 ksh88 Korn Shell '88
257 ksh Korn Shell '93
258 dtksh CDE Desktop Korn Shell
259 pdksh Public Domain Korn Shell
260 wksh Window Korn Shell
261 zsh Z Shell
262 oash SCO OA (curses) Shell
263 posix IEEE 1003.2 Shell Standard
264 wsh ? Shell"
265 :type '(repeat (cons symbol symbol))
266 :group 'sh-script)
269 (defcustom sh-alias-alist
270 (append (if (eq system-type 'gnu/linux)
271 '((csh . tcsh)
272 (ksh . pdksh)))
273 ;; for the time being
274 '((ksh . ksh88)
275 (bash2 . bash)
276 (sh5 . sh)))
277 "Alist for transforming shell names to what they really are.
278 Use this where the name of the executable doesn't correspond to the type of
279 shell it really is."
280 :type '(repeat (cons symbol symbol))
281 :group 'sh-script)
284 (defcustom sh-shell-file
286 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
287 ;; the executable extension, so comparisons with the list of
288 ;; known shells work.
289 (and (memq system-type '(ms-dos windows-nt))
290 (let* ((shell (getenv "SHELL"))
291 (shell-base
292 (and shell (file-name-nondirectory shell))))
293 ;; shell-script mode doesn't support DOS/Windows shells,
294 ;; so use the default instead.
295 (if (or (null shell)
296 (member (downcase shell-base)
297 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
298 "cmdproxy.exe")))
299 "/bin/sh"
300 (file-name-sans-extension (downcase shell)))))
301 (getenv "SHELL")
302 "/bin/sh")
303 "The executable file name for the shell being programmed."
304 :type 'string
305 :group 'sh-script)
308 (defcustom sh-shell-arg
309 ;; bash does not need any options when run in a shell script,
310 '((bash)
311 (csh . "-f")
312 (pdksh)
313 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
314 (ksh88)
315 ;; -p means don't initialize functions from the environment.
316 (rc . "-p")
317 ;; Someone proposed -motif, but we don't want to encourage
318 ;; use of a non-free widget set.
319 (wksh)
320 ;; -f means don't run .zshrc.
321 (zsh . "-f"))
322 "Single argument string for the magic number. See `sh-feature'."
323 :type '(repeat (cons (symbol :tag "Shell")
324 (choice (const :tag "No Arguments" nil)
325 (string :tag "Arguments")
326 (sexp :format "Evaluate: %v"))))
327 :group 'sh-script)
329 (defcustom sh-imenu-generic-expression
330 `((sh
331 . ((nil "^\\s-*\\(function\\s-+\\)?\\([[:alpha:]_][[:alnum:]_]+\\)\\s-*()" 2))))
332 "Alist of regular expressions for recognizing shell function definitions.
333 See `sh-feature' and `imenu-generic-expression'."
334 :type '(alist :key-type (symbol :tag "Shell")
335 :value-type (alist :key-type (choice :tag "Title"
336 string
337 (const :tag "None" nil))
338 :value-type
339 (repeat :tag "Regexp, index..." sexp)))
340 :group 'sh-script
341 :version "20.4")
343 (defvar sh-shell-variables nil
344 "Alist of shell variable names that should be included in completion.
345 These are used for completion in addition to all the variables named
346 in `process-environment'. Each element looks like (VAR . VAR), where
347 the car and cdr are the same symbol.")
349 (defvar sh-shell-variables-initialized nil
350 "Non-nil if `sh-shell-variables' is initialized.")
352 (defun sh-canonicalize-shell (shell)
353 "Convert a shell name SHELL to the one we should handle it as."
354 (if (string-match "\\.exe\\'" shell)
355 (setq shell (substring shell 0 (match-beginning 0))))
356 (or (symbolp shell)
357 (setq shell (intern shell)))
358 (or (cdr (assq shell sh-alias-alist))
359 shell))
361 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
362 "The shell being programmed. This is set by \\[sh-set-shell].")
363 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
365 (define-abbrev-table 'sh-mode-abbrev-table ())
368 ;; I turned off this feature because it doesn't permit typing commands
369 ;; in the usual way without help.
370 ;;(defvar sh-abbrevs
371 ;; '((csh sh-abbrevs shell
372 ;; "switch" 'sh-case
373 ;; "getopts" 'sh-while-getopts)
375 ;; (es sh-abbrevs shell
376 ;; "function" 'sh-function)
378 ;; (ksh88 sh-abbrevs sh
379 ;; "select" 'sh-select)
381 ;; (rc sh-abbrevs shell
382 ;; "case" 'sh-case
383 ;; "function" 'sh-function)
385 ;; (sh sh-abbrevs shell
386 ;; "case" 'sh-case
387 ;; "function" 'sh-function
388 ;; "until" 'sh-until
389 ;; "getopts" 'sh-while-getopts)
391 ;; ;; The next entry is only used for defining the others
392 ;; (shell "for" sh-for
393 ;; "loop" sh-indexed-loop
394 ;; "if" sh-if
395 ;; "tmpfile" sh-tmp-file
396 ;; "while" sh-while)
398 ;; (zsh sh-abbrevs ksh88
399 ;; "repeat" 'sh-repeat))
400 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
401 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
402 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
406 (defun sh-mode-syntax-table (table &rest list)
407 "Copy TABLE and set syntax for successive CHARs according to strings S."
408 (setq table (copy-syntax-table table))
409 (while list
410 (modify-syntax-entry (pop list) (pop list) table))
411 table)
413 (defvar sh-mode-syntax-table
414 (sh-mode-syntax-table ()
415 ?\# "<"
416 ?\n ">#"
417 ?\" "\"\""
418 ?\' "\"'"
419 ?\` "\"`"
420 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
421 ;; to work fine. This is needed so that dabbrev-expand
422 ;; $VARNAME works.
423 ?$ "'"
424 ?! "_"
425 ?% "_"
426 ?: "_"
427 ?. "_"
428 ?^ "_"
429 ?~ "_"
430 ?, "_"
431 ?= "."
432 ?< "."
433 ?> ".")
434 "The syntax table to use for Shell-Script mode.
435 This is buffer-local in every such buffer.")
437 (defvar sh-mode-syntax-table-input
438 '((sh . nil))
439 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
441 (defvar sh-mode-map
442 (let ((map (make-sparse-keymap))
443 (menu-map (make-sparse-keymap)))
444 (define-key map "\C-c(" 'sh-function)
445 (define-key map "\C-c\C-w" 'sh-while)
446 (define-key map "\C-c\C-u" 'sh-until)
447 (define-key map "\C-c\C-t" 'sh-tmp-file)
448 (define-key map "\C-c\C-s" 'sh-select)
449 (define-key map "\C-c\C-r" 'sh-repeat)
450 (define-key map "\C-c\C-o" 'sh-while-getopts)
451 (define-key map "\C-c\C-l" 'sh-indexed-loop)
452 (define-key map "\C-c\C-i" 'sh-if)
453 (define-key map "\C-c\C-f" 'sh-for)
454 (define-key map "\C-c\C-c" 'sh-case)
455 (define-key map "\C-c?" 'sh-show-indent)
456 (define-key map "\C-c=" 'sh-set-indent)
457 (define-key map "\C-c<" 'sh-learn-line-indent)
458 (define-key map "\C-c>" 'sh-learn-buffer-indent)
459 (define-key map "\C-c\C-\\" 'sh-backslash-region)
461 (define-key map "=" 'sh-assignment)
462 (define-key map "\C-c+" 'sh-add)
463 (define-key map "\C-\M-x" 'sh-execute-region)
464 (define-key map "\C-c\C-x" 'executable-interpret)
465 (define-key map "<" 'sh-maybe-here-document)
466 (define-key map "(" 'skeleton-pair-insert-maybe)
467 (define-key map "{" 'skeleton-pair-insert-maybe)
468 (define-key map "[" 'skeleton-pair-insert-maybe)
469 (define-key map "'" 'skeleton-pair-insert-maybe)
470 (define-key map "`" 'skeleton-pair-insert-maybe)
471 (define-key map "\"" 'skeleton-pair-insert-maybe)
473 (define-key map [remap complete-tag] 'comint-dynamic-complete)
474 (define-key map [remap delete-backward-char]
475 'backward-delete-char-untabify)
476 (define-key map "\C-c:" 'sh-set-shell)
477 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
478 (define-key map [remap forward-sentence] 'sh-end-of-command)
479 (define-key map [menu-bar sh-script] (cons "Sh-Script" menu-map))
480 (define-key menu-map [sh-learn-buffer-indent]
481 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
482 :help "Learn how to indent the buffer the way it currently is."))
483 (define-key menu-map [sh-learn-line-indent]
484 '(menu-item "Learn line indentation" sh-learn-line-indent
485 :help "Learn how to indent a line as it currently is indented"))
486 (define-key menu-map [sh-show-indent]
487 '(menu-item "Show indentation" sh-show-indent
488 :help "Show the how the current line would be indented"))
489 (define-key menu-map [sh-set-indent]
490 '(menu-item "Set indentation" sh-set-indent
491 :help "Set the indentation for the current line"))
493 (define-key menu-map [sh-pair]
494 '(menu-item "Insert braces and quotes in pairs"
495 (lambda ()
496 (interactive)
497 (require 'skeleton)
498 (setq skeleton-pair (not skeleton-pair)))
499 :button (:toggle . (and (boundp 'skeleton-pair)
500 skeleton-pair))
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-dynamic-complete-environment-variable
561 shell-dynamic-complete-command
562 comint-dynamic-complete-filename)
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 . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
571 (rc . "\\<\\([[:alnum:]_*]+\\)[ \t]*=")
572 (sh . "\\<\\([[:alnum:]_]+\\)="))
573 "Regexp for the variable name and what may follow in an assignment.
574 First grouping matches the variable name. This is upto and including the `='
575 sign. See `sh-feature'."
576 :type '(repeat (cons (symbol :tag "Shell")
577 (choice regexp
578 (sexp :format "Evaluate: %v"))))
579 :group 'sh-script)
582 (defcustom sh-indentation 4
583 "The width for further indentation in Shell-Script mode."
584 :type 'integer
585 :group 'sh-script)
586 (put 'sh-indentation 'safe-local-variable 'integerp)
588 (defcustom sh-remember-variable-min 3
589 "Don't remember variables less than this length for completing reads."
590 :type 'integer
591 :group 'sh-script)
594 (defvar sh-header-marker nil
595 "When non-nil is the end of header for prepending by \\[sh-execute-region].
596 That command is also used for setting this variable.")
597 (make-variable-buffer-local 'sh-header-marker)
599 (defcustom sh-beginning-of-command
600 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
601 "Regexp to determine the beginning of a shell command.
602 The actual command starts at the beginning of the second \\(grouping\\)."
603 :type 'regexp
604 :group 'sh-script)
607 (defcustom sh-end-of-command
608 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
609 "Regexp to determine the end of a shell command.
610 The actual command ends at the end of the first \\(grouping\\)."
611 :type 'regexp
612 :group 'sh-script)
616 (defcustom sh-here-document-word "EOF"
617 "Word to delimit here documents.
618 If the first character of this string is \"-\", this is taken as
619 part of the redirection operator, rather than part of the
620 word (that is, \"<<-\" instead of \"<<\"). This is a feature
621 used by some shells (for example Bash) to indicate that leading
622 tabs inside the here document should be ignored. In this case,
623 Emacs indents the initial body and end of the here document with
624 tabs, to the same level as the start (note that apart from this
625 there is no support for indentation of here documents). This
626 will only work correctly if `sh-basic-offset' is a multiple of
627 `tab-width'.
629 Any quote characters or leading whitespace in the word are
630 removed when closing the here document."
631 :type 'string
632 :group 'sh-script)
635 (defvar sh-test
636 '((sh "[ ]" . 3)
637 (ksh88 "[[ ]]" . 4))
638 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
641 ;; customized this out of sheer bravado. not for the faint of heart.
642 ;; but it *did* have an asterisk in the docstring!
643 (defcustom sh-builtins
644 '((bash sh-append posix
645 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
646 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
647 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
648 "source" "suspend" "typeset" "unalias")
650 ;; The next entry is only used for defining the others
651 (bourne sh-append shell
652 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
653 "times" "ulimit")
655 (csh sh-append shell
656 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
657 "setenv" "source" "time" "unalias" "unhash")
659 (dtksh sh-append wksh)
661 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
662 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
664 (jsh sh-append sh
665 "bg" "fg" "jobs" "kill" "stop" "suspend")
667 (jcsh sh-append csh
668 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
670 (ksh88 sh-append bourne
671 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
672 "typeset" "unalias" "whence")
674 (oash sh-append sh
675 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
676 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
677 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
678 "wmtitle" "wrefresh")
680 (pdksh sh-append ksh88
681 "bind")
683 (posix sh-append sh
684 "command")
686 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
687 "whatis")
689 (sh sh-append bourne
690 "hash" "test" "type")
692 ;; The next entry is only used for defining the others
693 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
695 (wksh sh-append ksh88
696 ;; FIXME: This looks too much like a regexp. --Stef
697 "Xt[A-Z][A-Za-z]*")
699 (zsh sh-append ksh88
700 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
701 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
702 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
703 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
704 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
705 "which"))
706 "List of all shell builtins for completing read and fontification.
707 Note that on some systems not all builtins are available or some are
708 implemented as aliases. See `sh-feature'."
709 :type '(repeat (cons (symbol :tag "Shell")
710 (choice (repeat string)
711 (sexp :format "Evaluate: %v"))))
712 :group 'sh-script)
716 (defcustom sh-leading-keywords
717 '((bash sh-append sh
718 "time")
720 (csh "else")
722 (es "true" "unwind-protect" "whatis")
724 (rc "else")
726 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
727 "List of keywords that may be immediately followed by a builtin or keyword.
728 Given some confusion between keywords and builtins depending on shell and
729 system, the distinction here has been based on whether they influence the
730 flow of control or syntax. See `sh-feature'."
731 :type '(repeat (cons (symbol :tag "Shell")
732 (choice (repeat string)
733 (sexp :format "Evaluate: %v"))))
734 :group 'sh-script)
737 (defcustom sh-other-keywords
738 '((bash sh-append bourne
739 "bye" "logout" "select")
741 ;; The next entry is only used for defining the others
742 (bourne sh-append sh
743 "function")
745 (csh sh-append shell
746 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
747 "if" "logout" "onintr" "repeat" "switch" "then" "while")
749 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
750 "return" "throw" "while")
752 (ksh88 sh-append bourne
753 "select")
755 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
756 "while")
758 (sh sh-append shell
759 "done" "esac" "fi" "for" "in" "return")
761 ;; The next entry is only used for defining the others
762 (shell "break" "case" "continue" "exec" "exit")
764 (zsh sh-append bash
765 "select"))
766 "List of keywords not in `sh-leading-keywords'.
767 See `sh-feature'."
768 :type '(repeat (cons (symbol :tag "Shell")
769 (choice (repeat string)
770 (sexp :format "Evaluate: %v"))))
771 :group 'sh-script)
775 (defvar sh-variables
776 '((bash sh-append sh
777 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
778 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
779 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
780 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
781 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
782 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
783 "HISTIGNORE" "history_control" "HISTSIZE"
784 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
785 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
786 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
787 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
788 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
789 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
790 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
792 (csh sh-append shell
793 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
794 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
795 "shell" "status" "time" "verbose")
797 (es sh-append shell
798 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
799 "pid" "prompt" "signals")
801 (jcsh sh-append csh
802 "notify")
804 (ksh88 sh-append sh
805 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
806 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
807 "TMOUT")
809 (oash sh-append sh
810 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
812 (rc sh-append shell
813 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
814 "prompt" "status")
816 (sh sh-append shell
817 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
819 ;; The next entry is only used for defining the others
820 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
821 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
822 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
823 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
825 (tcsh sh-append csh
826 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
827 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
828 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
829 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
830 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
831 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
832 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
833 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
834 "wordchars")
836 (zsh sh-append ksh88
837 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
838 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
839 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
840 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
841 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
842 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
843 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
844 "List of all shell variables available for completing read.
845 See `sh-feature'.")
848 ;; Font-Lock support
850 (defface sh-heredoc
851 '((((min-colors 88) (class color)
852 (background dark))
853 (:foreground "yellow1" :weight bold))
854 (((class color)
855 (background dark))
856 (:foreground "yellow" :weight bold))
857 (((class color)
858 (background light))
859 (:foreground "tan1" ))
861 (:weight bold)))
862 "Face to show a here-document"
863 :group 'sh-indentation)
865 ;; These colors are probably icky. It's just a placeholder though.
866 (defface sh-quoted-exec
867 '((((class color) (background dark))
868 (:foreground "salmon"))
869 (((class color) (background light))
870 (:foreground "magenta"))
872 (:weight bold)))
873 "Face to show quoted execs like ``"
874 :group 'sh-indentation)
875 (define-obsolete-face-alias 'sh-heredoc-face 'sh-heredoc "22.1")
876 (defvar sh-heredoc-face 'sh-heredoc)
878 (defface sh-escaped-newline '((t :inherit font-lock-string-face))
879 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
880 :group 'sh-script
881 :version "22.1")
883 (defvar sh-font-lock-keywords-var
884 '((csh sh-append shell
885 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
886 font-lock-variable-name-face))
888 (es sh-append executable-font-lock-keywords
889 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
890 font-lock-variable-name-face))
892 (rc sh-append es)
893 (bash sh-append shell ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
894 (sh sh-append shell
895 ;; Variable names.
896 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
897 font-lock-variable-name-face)
898 ;; Function names.
899 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
900 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
901 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
902 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
903 1 font-lock-negation-char-face))
905 ;; The next entry is only used for defining the others
906 (shell
907 ;; Using font-lock-string-face here confuses sh-get-indent-info.
908 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
909 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
910 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
911 font-lock-variable-name-face))
912 (rpm sh-append rpm2
913 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
914 (rpm2 sh-append shell
915 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
916 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
918 (defvar sh-font-lock-keywords-var-1
919 '((sh "[ \t]in\\>"))
920 "Subdued level highlighting for Shell Script modes.")
922 (defvar sh-font-lock-keywords-var-2 ()
923 "Gaudy level highlighting for Shell Script modes.")
925 ;; These are used for the syntax table stuff (derived from cperl-mode).
926 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
927 (defconst sh-st-punc (string-to-syntax "."))
928 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
930 (defconst sh-escaped-line-re
931 ;; Should match until the real end-of-continued-line, but if that is not
932 ;; possible (because we bump into EOB or the search bound), then we should
933 ;; match until the search bound.
934 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
936 (defconst sh-here-doc-open-re
937 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\)+\\)"
938 sh-escaped-line-re "\\(\n\\)"))
940 (defvar sh-here-doc-markers nil)
941 (make-variable-buffer-local 'sh-here-doc-markers)
942 (defvar sh-here-doc-re sh-here-doc-open-re)
943 (make-variable-buffer-local 'sh-here-doc-re)
945 (defun sh-font-lock-close-heredoc (bol eof indented eol)
946 "Determine the syntax of the \\n after an EOF.
947 If non-nil INDENTED indicates that the EOF was indented."
948 (let* ((eof-re (if eof (regexp-quote eof) ""))
949 ;; A rough regexp that should find the opening <<EOF back.
950 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
951 ;; Use \s| to cheaply check it's an open-heredoc.
952 eof-re "['\"]?\\([ \t|;&)<>]"
953 sh-escaped-line-re
954 "\\)?\\s|"))
955 ;; A regexp that will find other EOFs.
956 (ere (concat "^" (if indented "[ \t]*") eof-re "\n"))
957 (start (save-excursion
958 (goto-char bol)
959 ;; FIXME: will incorrectly find a <<EOF embedded inside
960 ;; the heredoc.
961 (re-search-backward (concat sre "\\|" ere) nil t))))
962 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
963 ;; found a close-heredoc which makes the current close-heredoc inoperant.
964 (cond
965 ((when (and start (match-end 1)
966 (not (and indented (= (match-beginning 1) (match-end 1))))
967 (not (sh-in-comment-or-string (match-beginning 0))))
968 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
969 (save-excursion
970 (goto-char start)
971 (setq start (line-beginning-position 2))
972 (while
973 (progn
974 (re-search-forward "<<") ; Skip ourselves.
975 (and (re-search-forward sh-here-doc-open-re start 'move)
976 (goto-char (match-beginning 0))
977 (sh-in-comment-or-string (point)))))
978 ;; No <<EOF2 found after our <<.
979 (= (point) start)))
980 (put-text-property eol (1+ eol) 'syntax-table sh-here-doc-syntax))
981 ((not (or start (save-excursion (re-search-forward sre nil t))))
982 ;; There's no <<EOF either before or after us,
983 ;; so we should remove ourselves from font-lock's keywords.
984 (setq sh-here-doc-markers (delete eof sh-here-doc-markers))
985 (setq sh-here-doc-re
986 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
987 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))
988 nil))))
990 (defun sh-font-lock-open-heredoc (start string eol)
991 "Determine the syntax of the \\n after a <<EOF.
992 START is the position of <<.
993 STRING is the actual word used as delimiter (e.g. \"EOF\").
994 INDENTED is non-nil if the here document's content (and the EOF mark) can
995 be indented (i.e. a <<- was used rather than just <<).
996 Point is at the beginning of the next line."
997 (unless (or (memq (char-before start) '(?< ?>))
998 (sh-in-comment-or-string start))
999 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
1000 ;; font-lock keywords to detect the end of this here document.
1001 (let ((str (replace-regexp-in-string "['\"]" "" string)))
1002 (unless (member str sh-here-doc-markers)
1003 (push str sh-here-doc-markers)
1004 (setq sh-here-doc-re
1005 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
1006 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))))
1007 (let ((ppss (save-excursion (syntax-ppss (1- (point))))))
1008 (if (nth 4 ppss)
1009 ;; The \n not only starts the heredoc but also closes a comment.
1010 ;; Let's close the comment just before the \n.
1011 (put-text-property (1- (point)) (point) 'syntax-table '(12))) ;">"
1012 (if (or (nth 5 ppss) (> (count-lines start (point)) 1))
1013 ;; If the sh-escaped-line-re part of sh-here-doc-re has matched
1014 ;; several lines, make sure we refontify them together.
1015 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
1016 ;; escaped), it means the right \n is actually further down.
1017 ;; Don't bother fixing it now, but place a multiline property so
1018 ;; that when jit-lock-context-* refontifies the rest of the
1019 ;; buffer, it also refontifies the current line with it.
1020 (put-text-property start (point) 'syntax-multiline t)))
1021 (put-text-property eol (1+ eol) 'syntax-table sh-here-doc-syntax)))
1023 (defun sh-font-lock-quoted-subshell (limit)
1024 "Search for a subshell embedded in a string.
1025 Find all the unescaped \" characters within said subshell, remembering that
1026 subshells can nest."
1027 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
1028 ;; effort to handle multiline cases correctly, so it ends up being
1029 ;; rather flakey.
1030 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1031 ;; bingo we have a $( or a ` inside a ""
1032 (let ((char (char-after (point)))
1033 ;; `state' can be: double-quote, backquote, code.
1034 (state (if (eq (char-before) ?`) 'backquote 'code))
1035 ;; Stacked states in the context.
1036 (states '(double-quote)))
1037 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1038 (< (point) limit)))
1039 ;; unescape " inside a $( ... ) construct.
1040 (case (char-after)
1041 (?\' (case state
1042 (double-quote nil)
1043 (t (forward-char 1) (skip-chars-forward "^'" limit))))
1044 (?\\ (forward-char 1))
1045 (?\" (case state
1046 (double-quote (setq state (pop states)))
1047 (t (push state states) (setq state 'double-quote)))
1048 (if state (put-text-property (point) (1+ (point))
1049 'syntax-table '(1))))
1050 (?\` (case state
1051 (backquote (setq state (pop states)))
1052 (t (push state states) (setq state 'backquote))))
1053 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1055 (forward-char 1)
1056 (case state
1057 (t (push state states) (setq state 'code)))))
1058 (?\( (case state
1059 (double-quote nil)
1060 (t (push state states) (setq state 'code))))
1061 (?\) (case state
1062 (double-quote nil)
1063 (t (setq state (pop states)))))
1064 (t (error "Internal error in sh-font-lock-quoted-subshell")))
1065 (forward-char 1)))))
1068 (defun sh-is-quoted-p (pos)
1069 (and (eq (char-before pos) ?\\)
1070 (not (sh-is-quoted-p (1- pos)))))
1072 (defun sh-font-lock-paren (start)
1073 (save-excursion
1074 (goto-char start)
1075 ;; Skip through all patterns
1076 (while
1077 (progn
1078 (forward-comment (- (point-max)))
1079 ;; Skip through one pattern
1080 (while
1081 (or (/= 0 (skip-syntax-backward "w_"))
1082 (/= 0 (skip-chars-backward "?[]*@/\\"))
1083 (and (sh-is-quoted-p (1- (point)))
1084 (goto-char (- (point) 2)))
1085 (when (memq (char-before) '(?\" ?\'))
1086 (condition-case nil (progn (backward-sexp 1) t)
1087 (error nil)))))
1088 ;; Patterns can be preceded by an open-paren (Bug#1320).
1089 (if (eq (char-before (point)) ?\()
1090 (backward-char 1))
1091 (while (progn
1092 (forward-comment (- (point-max)))
1093 ;; Maybe we've bumped into an escaped newline.
1094 (sh-is-quoted-p (point)))
1095 (backward-char 1))
1096 (when (eq (char-before) ?|)
1097 (backward-char 1) t)))
1098 ;; FIXME: ";; esac )" is a case that looks like a case-pattern but it's
1099 ;; really just a close paren after a case statement. I.e. if we skipped
1100 ;; over `esac' just now, we're not looking at a case-pattern.
1101 (when (progn (backward-char 2)
1102 (if (> start (line-end-position))
1103 (put-text-property (point) (1+ start)
1104 'syntax-multiline t))
1105 ;; FIXME: The `in' may just be a random argument to
1106 ;; a normal command rather than the real `in' keyword.
1107 ;; I.e. we should look back to try and find the
1108 ;; corresponding `case'.
1109 (looking-at ";;\\|in"))
1110 sh-st-punc)))
1112 (defun sh-font-lock-backslash-quote ()
1113 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1114 ;; In a '...' the backslash is not escaping.
1115 sh-st-punc
1116 nil))
1118 (defun sh-syntax-propertize-function (start end)
1119 (goto-char start)
1120 (while (prog1
1121 (re-search-forward sh-here-doc-re end 'move)
1122 (save-excursion
1123 (save-match-data
1124 (funcall
1125 (syntax-propertize-rules
1126 ;; A `#' begins a comment when it is unquoted and at the
1127 ;; beginning of a word. In the shell, words are separated by
1128 ;; metacharacters. The list of special chars is taken from
1129 ;; the single-unix spec of the shell command language (under
1130 ;; `quoting') but with `$' removed.
1131 ("[^|&;<>()`\\\"' \t\n]\\(#+\\)" (1 "_"))
1132 ;; In a '...' the backslash is not escaping.
1133 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1134 ;; Make sure $@ and $? are correctly recognized as sexps.
1135 ("\\$\\([?@]\\)" (1 "_"))
1136 ;; Distinguish the special close-paren in `case'.
1137 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1138 ;; Highlight (possibly nested) subshells inside "" quoted
1139 ;; regions correctly.
1140 ("\"\\(?:\\(?:.\\|\n\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)"
1141 (1 (ignore
1142 ;; Save excursion because we want to also apply other
1143 ;; syntax-propertize rules within the affected region.
1144 (save-excursion
1145 (sh-font-lock-quoted-subshell end))))))
1146 (prog1 start (setq start (point))) (point)))))
1147 (if (match-beginning 2)
1148 ;; FIXME: actually, once we see an heredoc opener, we should just
1149 ;; search for its ender without propertizing anything in it.
1150 (sh-font-lock-open-heredoc
1151 (match-beginning 0) (match-string 1) (match-beginning 2))
1152 (sh-font-lock-close-heredoc
1153 (match-beginning 0) (match-string 4)
1154 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3)))
1155 (match-beginning 5)))))
1157 (defun sh-font-lock-syntactic-face-function (state)
1158 (let ((q (nth 3 state)))
1159 (if q
1160 (if (characterp q)
1161 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1162 sh-heredoc-face)
1163 font-lock-comment-face)))
1165 (defgroup sh-indentation nil
1166 "Variables controlling indentation in shell scripts.
1168 Note: customizing these variables will not affect existing buffers if
1169 `sh-make-vars-local' is non-nil. See the documentation for
1170 variable `sh-make-vars-local', command `sh-make-vars-local'
1171 and command `sh-reset-indent-vars-to-global-values'."
1172 :group 'sh-script)
1175 (defcustom sh-set-shell-hook nil
1176 "Hook run by `sh-set-shell'."
1177 :type 'hook
1178 :group 'sh-script)
1180 (defcustom sh-mode-hook nil
1181 "Hook run by `sh-mode'."
1182 :type 'hook
1183 :group 'sh-script)
1185 (defcustom sh-learn-basic-offset nil
1186 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1188 nil mean: never.
1189 t means: only if there seems to be an obvious value.
1190 Anything else means: whenever we have a \"good guess\" as to the value."
1191 :type '(choice
1192 (const :tag "Never" nil)
1193 (const :tag "Only if sure" t)
1194 (const :tag "If have a good guess" usually))
1195 :group 'sh-indentation)
1197 (defcustom sh-popup-occur-buffer nil
1198 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1199 If t it is always shown. If nil, it is shown only when there
1200 are conflicts."
1201 :type '(choice
1202 (const :tag "Only when there are conflicts." nil)
1203 (const :tag "Always" t))
1204 :group 'sh-indentation)
1206 (defcustom sh-blink t
1207 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1208 The position on the line is not necessarily meaningful.
1209 In some cases the line will be the matching keyword, but this is not
1210 always the case."
1211 :type 'boolean
1212 :group 'sh-indentation)
1214 (defcustom sh-first-lines-indent 0
1215 "The indentation of the first non-blank non-comment line.
1216 Usually 0 meaning first column.
1217 Can be set to a number, or to nil which means leave it as is."
1218 :type '(choice
1219 (const :tag "Leave as is" nil)
1220 (integer :tag "Column number"
1221 :menu-tag "Indent to this col (0 means first col)" ))
1222 :group 'sh-indentation)
1225 (defcustom sh-basic-offset 4
1226 "The default indentation increment.
1227 This value is used for the `+' and `-' symbols in an indentation variable."
1228 :type 'integer
1229 :group 'sh-indentation)
1230 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1232 (defcustom sh-indent-comment nil
1233 "How a comment line is to be indented.
1234 nil means leave it as it is;
1235 t means indent it as a normal line, aligning it to previous non-blank
1236 non-comment line;
1237 a number means align to that column, e.g. 0 means first column."
1238 :type '(choice
1239 (const :tag "Leave as is." nil)
1240 (const :tag "Indent as a normal line." t)
1241 (integer :menu-tag "Indent to this col (0 means first col)."
1242 :tag "Indent to column number.") )
1243 :group 'sh-indentation)
1246 (defvar sh-debug nil
1247 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1250 ;; Uncomment this defun and comment the defmacro for debugging.
1251 ;; (defun sh-debug (&rest args)
1252 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1253 ;; (if sh-debug
1254 ;; (apply 'message args)))
1255 (defmacro sh-debug (&rest args))
1257 (defconst sh-symbol-list
1258 '((const :tag "+ " :value +
1259 :menu-tag "+ Indent right by sh-basic-offset")
1260 (const :tag "- " :value -
1261 :menu-tag "- Indent left by sh-basic-offset")
1262 (const :tag "++" :value ++
1263 :menu-tag "++ Indent right twice sh-basic-offset")
1264 (const :tag "--" :value --
1265 :menu-tag "-- Indent left twice sh-basic-offset")
1266 (const :tag "* " :value *
1267 :menu-tag "* Indent right half sh-basic-offset")
1268 (const :tag "/ " :value /
1269 :menu-tag "/ Indent left half sh-basic-offset")))
1271 (defcustom sh-indent-for-else 0
1272 "How much to indent an `else' relative to its `if'. Usually 0."
1273 :type `(choice
1274 (integer :menu-tag "A number (positive=>indent right)"
1275 :tag "A number")
1276 (const :tag "--") ;; separator!
1277 ,@ sh-symbol-list
1279 :group 'sh-indentation)
1281 (defconst sh-number-or-symbol-list
1282 (append '((integer :menu-tag "A number (positive=>indent right)"
1283 :tag "A number")
1284 (const :tag "--")) ; separator
1285 sh-symbol-list))
1287 (defcustom sh-indent-for-fi 0
1288 "How much to indent a `fi' relative to its `if'. Usually 0."
1289 :type `(choice ,@ sh-number-or-symbol-list )
1290 :group 'sh-indentation)
1292 (defcustom sh-indent-for-done 0
1293 "How much to indent a `done' relative to its matching stmt. Usually 0."
1294 :type `(choice ,@ sh-number-or-symbol-list )
1295 :group 'sh-indentation)
1297 (defcustom sh-indent-after-else '+
1298 "How much to indent a statement after an `else' statement."
1299 :type `(choice ,@ sh-number-or-symbol-list )
1300 :group 'sh-indentation)
1302 (defcustom sh-indent-after-if '+
1303 "How much to indent a statement after an `if' statement.
1304 This includes lines after `else' and `elif' statements, too, but
1305 does not affect the `else', `elif' or `fi' statements themselves."
1306 :type `(choice ,@ sh-number-or-symbol-list )
1307 :group 'sh-indentation)
1309 (defcustom sh-indent-for-then 0
1310 "How much to indent a `then' relative to its `if'."
1311 :type `(choice ,@ sh-number-or-symbol-list )
1312 :group 'sh-indentation)
1314 (defcustom sh-indent-for-do 0
1315 "How much to indent a `do' statement.
1316 This is relative to the statement before the `do', typically a
1317 `while', `until', `for', `repeat' or `select' statement."
1318 :type `(choice ,@ sh-number-or-symbol-list)
1319 :group 'sh-indentation)
1321 (defcustom sh-indent-after-do '+
1322 "How much to indent a line after a `do' statement.
1323 This is used when the `do' is the first word of the line.
1324 This is relative to the statement before the `do', typically a
1325 `while', `until', `for', `repeat' or `select' statement."
1326 :type `(choice ,@ sh-number-or-symbol-list)
1327 :group 'sh-indentation)
1329 (defcustom sh-indent-after-loop-construct '+
1330 "How much to indent a statement after a loop construct.
1332 This variable is used when the keyword `do' is on the same line as the
1333 loop statement (e.g., `until', `while' or `for').
1334 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1335 :type `(choice ,@ sh-number-or-symbol-list)
1336 :group 'sh-indentation)
1339 (defcustom sh-indent-after-done 0
1340 "How much to indent a statement after a `done' keyword.
1341 Normally this is 0, which aligns the `done' to the matching
1342 looping construct line.
1343 Setting it non-zero allows you to have the `do' statement on a line
1344 by itself and align the done under to do."
1345 :type `(choice ,@ sh-number-or-symbol-list)
1346 :group 'sh-indentation)
1348 (defcustom sh-indent-for-case-label '+
1349 "How much to indent a case label statement.
1350 This is relative to the line containing the `case' statement."
1351 :type `(choice ,@ sh-number-or-symbol-list)
1352 :group 'sh-indentation)
1354 (defcustom sh-indent-for-case-alt '++
1355 "How much to indent statements after the case label.
1356 This is relative to the line containing the `case' statement."
1357 :type `(choice ,@ sh-number-or-symbol-list)
1358 :group 'sh-indentation)
1361 (defcustom sh-indent-for-continuation '+
1362 "How much to indent for a continuation statement."
1363 :type `(choice ,@ sh-number-or-symbol-list)
1364 :group 'sh-indentation)
1366 (defcustom sh-indent-after-open '+
1367 "How much to indent after a line with an opening parenthesis or brace.
1368 For an open paren after a function, `sh-indent-after-function' is used."
1369 :type `(choice ,@ sh-number-or-symbol-list)
1370 :group 'sh-indentation)
1372 (defcustom sh-indent-after-function '+
1373 "How much to indent after a function line."
1374 :type `(choice ,@ sh-number-or-symbol-list)
1375 :group 'sh-indentation)
1377 ;; These 2 are for the rc shell:
1379 (defcustom sh-indent-after-switch '+
1380 "How much to indent a `case' statement relative to the `switch' statement.
1381 This is for the rc shell."
1382 :type `(choice ,@ sh-number-or-symbol-list)
1383 :group 'sh-indentation)
1385 (defcustom sh-indent-after-case '+
1386 "How much to indent a statement relative to the `case' statement.
1387 This is for the rc shell."
1388 :type `(choice ,@ sh-number-or-symbol-list)
1389 :group 'sh-indentation)
1391 (defcustom sh-backslash-column 48
1392 "Column in which `sh-backslash-region' inserts backslashes."
1393 :type 'integer
1394 :group 'sh)
1396 (defcustom sh-backslash-align t
1397 "If non-nil, `sh-backslash-region' will align backslashes."
1398 :type 'boolean
1399 :group 'sh)
1401 ;; Internal use - not designed to be changed by the user:
1403 (defun sh-mkword-regexpr (word)
1404 "Make a regexp which matches WORD as a word.
1405 This specifically excludes an occurrence of WORD followed by
1406 punctuation characters like '-'."
1407 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1409 (defconst sh-re-done (sh-mkword-regexpr "done"))
1412 (defconst sh-kws-for-done
1413 '((sh . ( "while" "until" "for" ) )
1414 (bash . ( "while" "until" "for" "select" ) )
1415 (ksh88 . ( "while" "until" "for" "select" ) )
1416 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1417 "Which keywords can match the word `done' in this shell.")
1420 (defconst sh-indent-supported
1421 '((sh . t)
1422 (csh . nil)
1423 (rc . t))
1424 "Shell types that shell indenting can do something with.")
1426 (defvar sh-indent-supported-here nil
1427 "Non-nil if we support indentation for the current buffer's shell type.")
1429 (defconst sh-var-list
1431 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1432 sh-indent-after-do sh-indent-after-done
1433 sh-indent-after-else
1434 sh-indent-after-if
1435 sh-indent-after-loop-construct
1436 sh-indent-after-open
1437 sh-indent-comment
1438 sh-indent-for-case-alt
1439 sh-indent-for-case-label
1440 sh-indent-for-continuation
1441 sh-indent-for-do
1442 sh-indent-for-done
1443 sh-indent-for-else
1444 sh-indent-for-fi
1445 sh-indent-for-then
1447 "A list of variables used by script mode to control indentation.
1448 This list is used when switching between buffer-local and global
1449 values of variables, and for the commands using indentation styles.")
1451 (defvar sh-make-vars-local t
1452 "*Controls whether indentation variables are local to the buffer.
1453 If non-nil, indentation variables are made local initially.
1454 If nil, you can later make the variables local by invoking
1455 command `sh-make-vars-local'.
1456 The default is t because I assume that in one Emacs session one is
1457 frequently editing existing scripts with different styles.")
1460 ;; mode-command and utility functions
1462 ;;;###autoload
1463 (define-derived-mode sh-mode prog-mode "Shell-script"
1464 "Major mode for editing shell scripts.
1465 This mode works for many shells, since they all have roughly the same syntax,
1466 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1467 Unless the file's magic number indicates the shell, your usual shell is
1468 assumed. Since filenames rarely give a clue, they are not further analyzed.
1470 This mode adapts to the variations between shells (see `sh-set-shell') by
1471 means of an inheritance based feature lookup (see `sh-feature'). This
1472 mechanism applies to all variables (including skeletons) that pertain to
1473 shell-specific features.
1475 The default style of this mode is that of Rosenblatt's Korn shell book.
1476 The syntax of the statements varies with the shell being used. The
1477 following commands are available, based on the current shell's syntax:
1478 \\<sh-mode-map>
1479 \\[sh-case] case statement
1480 \\[sh-for] for loop
1481 \\[sh-function] function definition
1482 \\[sh-if] if statement
1483 \\[sh-indexed-loop] indexed loop from 1 to n
1484 \\[sh-while-getopts] while getopts loop
1485 \\[sh-repeat] repeat loop
1486 \\[sh-select] select loop
1487 \\[sh-until] until loop
1488 \\[sh-while] while loop
1490 For sh and rc shells indentation commands are:
1491 \\[sh-show-indent] Show the variable controlling this line's indentation.
1492 \\[sh-set-indent] Set then variable controlling this line's indentation.
1493 \\[sh-learn-line-indent] Change the indentation variable so this line
1494 would indent to the way it currently is.
1495 \\[sh-learn-buffer-indent] Set the indentation variables so the
1496 buffer indents as it currently is indented.
1499 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1500 \\[newline-and-indent] Delete unquoted space and indent new line same as this one.
1501 \\[sh-end-of-command] Go to end of successive commands.
1502 \\[sh-beginning-of-command] Go to beginning of successive commands.
1503 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1504 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1506 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1507 \{, (, [, ', \", `
1508 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1510 If you generally program a shell different from your login shell you can
1511 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1512 indicate what shell it is use `sh-alias-alist' to translate.
1514 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1515 with your script for an edit-interpret-debug cycle."
1516 (make-local-variable 'sh-shell-file)
1517 (make-local-variable 'sh-shell)
1519 (set (make-local-variable 'skeleton-pair-default-alist)
1520 sh-skeleton-pair-default-alist)
1521 (set (make-local-variable 'skeleton-end-hook)
1522 (lambda () (or (eolp) (newline) (indent-relative))))
1524 (set (make-local-variable 'paragraph-start) (concat page-delimiter "\\|$"))
1525 (set (make-local-variable 'paragraph-separate) paragraph-start)
1526 (set (make-local-variable 'comment-start) "# ")
1527 (set (make-local-variable 'comment-start-skip) "#+[\t ]*")
1528 (set (make-local-variable 'local-abbrev-table) sh-mode-abbrev-table)
1529 (set (make-local-variable 'comint-dynamic-complete-functions)
1530 sh-dynamic-complete-functions)
1531 ;; we can't look if previous line ended with `\'
1532 (set (make-local-variable 'comint-prompt-regexp) "^[ \t]*")
1533 (set (make-local-variable 'imenu-case-fold-search) nil)
1534 (set (make-local-variable 'font-lock-defaults)
1535 `((sh-font-lock-keywords
1536 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1537 nil nil
1538 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1539 (font-lock-syntactic-face-function
1540 . sh-font-lock-syntactic-face-function)))
1541 (set (make-local-variable 'syntax-propertize-function)
1542 #'sh-syntax-propertize-function)
1543 (add-hook 'syntax-propertize-extend-region-functions
1544 #'syntax-propertize-multiline 'append 'local)
1545 (set (make-local-variable 'skeleton-pair-alist) '((?` _ ?`)))
1546 (set (make-local-variable 'skeleton-pair-filter-function) 'sh-quoted-p)
1547 (set (make-local-variable 'skeleton-further-elements)
1548 '((< '(- (min sh-indentation (current-column))))))
1549 (set (make-local-variable 'skeleton-filter-function) 'sh-feature)
1550 (set (make-local-variable 'skeleton-newline-indent-rigidly) t)
1551 (set (make-local-variable 'sh-indent-supported-here) nil)
1552 (set (make-local-variable 'defun-prompt-regexp)
1553 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1554 ;; Parse or insert magic number for exec, and set all variables depending
1555 ;; on the shell thus determined.
1556 (sh-set-shell
1557 (cond ((save-excursion
1558 (goto-char (point-min))
1559 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1560 (match-string 2))
1561 ((not buffer-file-name)
1562 sh-shell-file)
1563 ;; Checks that use `buffer-file-name' follow.
1564 ((string-match "\\.m?spec\\'" buffer-file-name)
1565 "rpm")
1566 ((string-match "[.]sh\\>" buffer-file-name)
1567 "sh")
1568 ((string-match "[.]bash\\>" buffer-file-name)
1569 "bash")
1570 ((string-match "[.]ksh\\>" buffer-file-name)
1571 "ksh")
1572 ((string-match "[.]csh\\>" buffer-file-name)
1573 "csh")
1574 ((equal (file-name-nondirectory buffer-file-name) ".profile")
1575 "sh")
1577 sh-shell-file))
1578 nil nil))
1580 ;;;###autoload
1581 (defalias 'shell-script-mode 'sh-mode)
1584 (defun sh-font-lock-keywords (&optional keywords)
1585 "Function to get simple fontification based on `sh-font-lock-keywords'.
1586 This adds rules for comments and assignments."
1587 (sh-feature sh-font-lock-keywords-var
1588 (when (stringp (sh-feature sh-assignment-regexp))
1589 (lambda (list)
1590 `((,(sh-feature sh-assignment-regexp)
1591 1 font-lock-variable-name-face)
1592 ,@keywords
1593 ,@list
1594 ,@executable-font-lock-keywords)))))
1596 (defun sh-font-lock-keywords-1 (&optional builtins)
1597 "Function to get better fontification including keywords."
1598 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1599 (regexp-opt (sh-feature sh-leading-keywords) t)
1600 "[ \t]+\\)?"
1601 (regexp-opt (append (sh-feature sh-leading-keywords)
1602 (sh-feature sh-other-keywords))
1603 t))))
1604 (sh-font-lock-keywords
1605 `(,@(if builtins
1606 `((,(concat keywords "[ \t]+\\)?"
1607 (regexp-opt (sh-feature sh-builtins) t)
1608 "\\>")
1609 (2 font-lock-keyword-face nil t)
1610 (6 font-lock-builtin-face))
1611 ,@(sh-feature sh-font-lock-keywords-var-2)))
1612 (,(concat keywords "\\)\\>")
1613 2 font-lock-keyword-face)
1614 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1616 (defun sh-font-lock-keywords-2 ()
1617 "Function to get better fontification including keywords and builtins."
1618 (sh-font-lock-keywords-1 t))
1621 (defvar sh-regexp-for-done nil
1622 "A buffer-local regexp to match opening keyword for done.")
1624 (defvar sh-kw-alist nil
1625 "A buffer-local, since it is shell-type dependent, list of keywords.")
1627 ;; ( key-word first-on-this on-prev-line )
1628 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1629 ;; having 3 elements:
1630 ;; a keyword
1631 ;; a rule to check when the keyword appears on "this" line
1632 ;; a rule to check when the keyword appears on "the previous" line
1633 ;; The keyword is usually a string and is the first word on a line.
1634 ;; If this keyword appears on the line whose indentation is to be
1635 ;; calculated, the rule in element 2 is called. If this returns
1636 ;; non-zero, the resulting point (which may be changed by the rule)
1637 ;; is used as the default indentation.
1638 ;; If it returned false or the keyword was not found in the table,
1639 ;; then the keyword from the previous line is looked up and the rule
1640 ;; in element 3 is called. In this case, however,
1641 ;; `sh-get-indent-info' does not stop but may keep going and test
1642 ;; other keywords against rules in element 3. This is because the
1643 ;; preceding line could have, for example, an opening "if" and an
1644 ;; opening "while" keyword and we need to add the indentation offsets
1645 ;; for both.
1647 (defconst sh-kw
1648 '((sh
1649 ("if" nil sh-handle-prev-if)
1650 ("elif" sh-handle-this-else sh-handle-prev-else)
1651 ("else" sh-handle-this-else sh-handle-prev-else)
1652 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1653 ("then" sh-handle-this-then sh-handle-prev-then)
1654 ("(" nil sh-handle-prev-open)
1655 ("{" nil sh-handle-prev-open)
1656 ("[" nil sh-handle-prev-open)
1657 ("}" sh-handle-this-close nil)
1658 (")" sh-handle-this-close nil)
1659 ("]" sh-handle-this-close nil)
1660 ("case" nil sh-handle-prev-case)
1661 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1662 (case-label nil sh-handle-after-case-label) ;; ???
1663 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1664 ("done" sh-handle-this-done sh-handle-prev-done)
1665 ("do" sh-handle-this-do sh-handle-prev-do))
1667 ;; Note: we don't need specific stuff for bash and zsh shells;
1668 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1669 ;; these shells use.
1671 ("{" nil sh-handle-prev-open)
1672 ("}" sh-handle-this-close nil)
1673 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1677 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1678 "Set this buffer's shell to SHELL (a string).
1679 When used interactively, insert the proper starting #!-line,
1680 and make the visited file executable via `executable-set-magic',
1681 perhaps querying depending on the value of `executable-query'.
1683 When this function is called noninteractively, INSERT-FLAG (the third
1684 argument) controls whether to insert a #!-line and think about making
1685 the visited file executable, and NO-QUERY-FLAG (the second argument)
1686 controls whether to query about making the visited file executable.
1688 Calls the value of `sh-set-shell-hook' if set."
1689 (interactive (list (completing-read (format "Shell \(default %s\): "
1690 sh-shell-file)
1691 interpreter-mode-alist
1692 (lambda (x) (eq (cdr x) 'sh-mode))
1693 nil nil nil sh-shell-file)
1694 (eq executable-query 'function)
1696 (if (string-match "\\.exe\\'" shell)
1697 (setq shell (substring shell 0 (match-beginning 0))))
1698 (setq sh-shell (intern (file-name-nondirectory shell))
1699 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1700 sh-shell))
1701 (if insert-flag
1702 (setq sh-shell-file
1703 (executable-set-magic shell (sh-feature sh-shell-arg)
1704 no-query-flag insert-flag)))
1705 (setq mode-line-process (format "[%s]" sh-shell))
1706 (set (make-local-variable 'sh-shell-variables) nil)
1707 (set (make-local-variable 'sh-shell-variables-initialized) nil)
1708 (set (make-local-variable 'imenu-generic-expression)
1709 (sh-feature sh-imenu-generic-expression))
1710 (let ((tem (sh-feature sh-mode-syntax-table-input)))
1711 (when tem
1712 (set (make-local-variable 'sh-mode-syntax-table)
1713 (apply 'sh-mode-syntax-table tem))
1714 (set-syntax-table sh-mode-syntax-table)))
1715 (dolist (var (sh-feature sh-variables))
1716 (sh-remember-variable var))
1717 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1718 (progn
1719 (message "Setting up indent for shell type %s" sh-shell)
1720 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1721 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1722 (let ((regexp (sh-feature sh-kws-for-done)))
1723 (if regexp
1724 (set (make-local-variable 'sh-regexp-for-done)
1725 (sh-mkword-regexpr (regexp-opt regexp t)))))
1726 (message "setting up indent stuff")
1727 ;; sh-mode has already made indent-line-function local
1728 ;; but do it in case this is called before that.
1729 (set (make-local-variable 'indent-line-function) 'sh-indent-line)
1730 (if sh-make-vars-local
1731 (sh-make-vars-local))
1732 (message "Indentation setup for shell type %s" sh-shell))
1733 (message "No indentation for this shell type.")
1734 (setq indent-line-function 'sh-basic-indent-line))
1735 (when font-lock-mode
1736 (setq font-lock-set-defaults nil)
1737 (font-lock-set-defaults)
1738 (font-lock-fontify-buffer))
1739 (run-hooks 'sh-set-shell-hook))
1742 (defun sh-feature (alist &optional function)
1743 "Index ALIST by the current shell.
1744 If ALIST isn't a list where every element is a cons, it is returned as is.
1745 Else indexing follows an inheritance logic which works in two ways:
1747 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1748 the alist contains no value for the current shell.
1749 The ultimate default is always `sh'.
1751 - If the value thus looked up is a list starting with `sh-append',
1752 we call the function `sh-append' with the rest of the list as
1753 arguments, and use the value. However, the next element of the
1754 list is not used as-is; instead, we look it up recursively
1755 in ALIST to allow the function called to define the value for
1756 one shell to be derived from another shell.
1757 The value thus determined is physically replaced into the alist.
1759 If FUNCTION is non-nil, it is called with one argument,
1760 the value thus obtained, and the result is used instead."
1761 (or (if (consp alist)
1762 ;; Check for something that isn't a valid alist.
1763 (let ((l alist))
1764 (while (and l (consp (car l)))
1765 (setq l (cdr l)))
1766 (if l alist)))
1768 (let ((orig-sh-shell sh-shell))
1769 (let ((sh-shell sh-shell)
1770 elt val)
1771 (while (and sh-shell
1772 (not (setq elt (assq sh-shell alist))))
1773 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1774 ;; If the shell is not known, treat it as sh.
1775 (unless elt
1776 (setq elt (assq 'sh alist)))
1777 (setq val (cdr elt))
1778 (if (and (consp val)
1779 (memq (car val) '(sh-append sh-modify)))
1780 (setq val
1781 (apply (car val)
1782 ;; Refer to the value for a different shell,
1783 ;; as a kind of inheritance.
1784 (let ((sh-shell (car (cdr val))))
1785 (sh-feature alist))
1786 (cddr val))))
1787 (if function
1788 (setq sh-shell orig-sh-shell
1789 val (funcall function val)))
1790 val))))
1794 ;; I commented this out because nobody calls it -- rms.
1795 ;;(defun sh-abbrevs (ancestor &rest list)
1796 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1797 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1798 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1799 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1800 ;;EXPANSION may be either a string or a skeleton command."
1801 ;; (or (if (boundp sh-shell)
1802 ;; (symbol-value sh-shell))
1803 ;; (progn
1804 ;; (if (listp ancestor)
1805 ;; (nconc list ancestor))
1806 ;; (define-abbrev-table sh-shell ())
1807 ;; (if (vectorp ancestor)
1808 ;; (mapatoms (lambda (atom)
1809 ;; (or (eq atom 0)
1810 ;; (define-abbrev (symbol-value sh-shell)
1811 ;; (symbol-name atom)
1812 ;; (symbol-value atom)
1813 ;; (symbol-function atom))))
1814 ;; ancestor))
1815 ;; (while list
1816 ;; (define-abbrev (symbol-value sh-shell)
1817 ;; (car list)
1818 ;; (if (stringp (car (cdr list)))
1819 ;; (car (cdr list))
1820 ;; "")
1821 ;; (if (symbolp (car (cdr list)))
1822 ;; (car (cdr list))))
1823 ;; (setq list (cdr (cdr list)))))
1824 ;; (symbol-value sh-shell)))
1827 (defun sh-append (ancestor &rest list)
1828 "Return list composed of first argument (a list) physically appended to rest."
1829 (nconc list ancestor))
1832 (defun sh-modify (skeleton &rest list)
1833 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1834 (setq skeleton (copy-sequence skeleton))
1835 (while list
1836 (setcar (or (nthcdr (car list) skeleton)
1837 (error "Index %d out of bounds" (car list)))
1838 (car (cdr list)))
1839 (setq list (nthcdr 2 list)))
1840 skeleton)
1843 (defun sh-basic-indent-line ()
1844 "Indent a line for Sh mode (shell script mode).
1845 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1846 Lines containing only comments are considered empty."
1847 (interactive)
1848 (let ((previous (save-excursion
1849 (while (and (progn (beginning-of-line)
1850 (not (bobp)))
1851 (progn
1852 (forward-line -1)
1853 (back-to-indentation)
1854 (or (eolp)
1855 (eq (following-char) ?#)))))
1856 (current-column)))
1857 current)
1858 (save-excursion
1859 (indent-to (if (eq this-command 'newline-and-indent)
1860 previous
1861 (if (< (current-column)
1862 (setq current (progn (back-to-indentation)
1863 (current-column))))
1864 (if (eolp) previous 0)
1865 (delete-region (point)
1866 (progn (beginning-of-line) (point)))
1867 (if (eolp)
1868 (max previous (* (1+ (/ current sh-indentation))
1869 sh-indentation))
1870 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1871 (if (< (current-column) (current-indentation))
1872 (skip-chars-forward " \t"))))
1875 (defun sh-execute-region (start end &optional flag)
1876 "Pass optional header and region to a subshell for noninteractive execution.
1877 The working directory is that of the buffer, and only environment variables
1878 are already set which is why you can mark a header within the script.
1880 With a positive prefix ARG, instead of sending region, define header from
1881 beginning of buffer to point. With a negative prefix ARG, instead of sending
1882 region, clear header."
1883 (interactive "r\nP")
1884 (if flag
1885 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1886 (point-marker)))
1887 (if sh-header-marker
1888 (save-excursion
1889 (let (buffer-undo-list)
1890 (goto-char sh-header-marker)
1891 (append-to-buffer (current-buffer) start end)
1892 (shell-command-on-region (point-min)
1893 (setq end (+ sh-header-marker
1894 (- end start)))
1895 sh-shell-file)
1896 (delete-region sh-header-marker end)))
1897 (shell-command-on-region start end (concat sh-shell-file " -")))))
1900 (defun sh-remember-variable (var)
1901 "Make VARIABLE available for future completing reads in this buffer."
1902 (or (< (length var) sh-remember-variable-min)
1903 (getenv var)
1904 (assoc var sh-shell-variables)
1905 (push (cons var var) sh-shell-variables))
1906 var)
1910 (defun sh-quoted-p ()
1911 "Is point preceded by an odd number of backslashes?"
1912 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1914 ;; Indentation stuff.
1915 (defun sh-must-support-indent ()
1916 "*Signal an error if the shell type for this buffer is not supported.
1917 Also, the buffer must be in Shell-script mode."
1918 (unless sh-indent-supported-here
1919 (error "This buffer's shell does not support indentation through Emacs")))
1921 (defun sh-make-vars-local ()
1922 "Make the indentation variables local to this buffer.
1923 Normally they already are local. This command is provided in case
1924 variable `sh-make-vars-local' has been set to nil.
1926 To revert all these variables to the global values, use
1927 command `sh-reset-indent-vars-to-global-values'."
1928 (interactive)
1929 (mapc 'make-local-variable sh-var-list)
1930 (message "Indentation variables are now local."))
1932 (defun sh-reset-indent-vars-to-global-values ()
1933 "Reset local indentation variables to the global values.
1934 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1935 (interactive)
1936 (mapc 'kill-local-variable sh-var-list)
1937 (if sh-make-vars-local
1938 (mapcar 'make-local-variable sh-var-list)))
1941 ;; Theoretically these are only needed in shell and derived modes.
1942 ;; However, the routines which use them are only called in those modes.
1943 (defconst sh-special-keywords "then\\|do")
1945 (defun sh-help-string-for-variable (var)
1946 "Construct a string for `sh-read-variable' when changing variable VAR ."
1947 (let ((msg (documentation-property var 'variable-documentation))
1948 (msg2 ""))
1949 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
1950 (setq msg2
1951 (format "\n
1952 You can enter a number (positive to increase indentation,
1953 negative to decrease indentation, zero for no change to indentation).
1955 Or, you can enter one of the following symbols which are relative to
1956 the value of variable `sh-basic-offset'
1957 which in this buffer is currently %s.
1959 \t%s."
1960 sh-basic-offset
1961 (mapconcat (lambda (x)
1962 (nth (1- (length x)) x))
1963 sh-symbol-list "\n\t"))))
1964 (concat
1965 ;; The following shows the global not the local value!
1966 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1967 msg msg2)))
1969 (defun sh-read-variable (var)
1970 "Read a new value for indentation variable VAR."
1971 (interactive "*variable? ") ;; to test
1972 (let ((minibuffer-help-form `(sh-help-string-for-variable
1973 (quote ,var)))
1974 val)
1975 (setq val (read-from-minibuffer
1976 (format "New value for %s (press %s for help): "
1977 var (single-key-description help-char))
1978 (format "%s" (symbol-value var))
1979 nil t))
1980 val))
1984 (defun sh-in-comment-or-string (start)
1985 "Return non-nil if START is in a comment or string."
1986 (save-excursion
1987 (let ((state (syntax-ppss start)))
1988 (or (nth 3 state) (nth 4 state)))))
1990 (defun sh-goto-matching-if ()
1991 "Go to the matching if for a fi.
1992 This handles nested if..fi pairs."
1993 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1994 (if found
1995 (goto-char found))))
1998 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1999 ;; line whose indentation is being handled contain XXX;
2000 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2002 (defun sh-handle-prev-if ()
2003 (list '(+ sh-indent-after-if)))
2005 (defun sh-handle-this-else ()
2006 (if (sh-goto-matching-if)
2007 ;; (list "aligned to if")
2008 (list "aligned to if" '(+ sh-indent-for-else))
2012 (defun sh-handle-prev-else ()
2013 (if (sh-goto-matching-if)
2014 (list '(+ sh-indent-after-if))
2017 (defun sh-handle-this-fi ()
2018 (if (sh-goto-matching-if)
2019 (list "aligned to if" '(+ sh-indent-for-fi))
2023 (defun sh-handle-prev-fi ()
2024 ;; Why do we have this rule? Because we must go back to the if
2025 ;; to get its indent. We may continue back from there.
2026 ;; We return nil because we don't have anything to add to result,
2027 ;; the side affect of setting align-point is all that matters.
2028 ;; we could return a comment (a string) but I can't think of a good one...
2029 (sh-goto-matching-if)
2030 nil)
2032 (defun sh-handle-this-then ()
2033 (let ((p (sh-goto-matching-if)))
2034 (if p
2035 (list '(+ sh-indent-for-then))
2038 (defun sh-handle-prev-then ()
2039 (let ((p (sh-goto-matching-if)))
2040 (if p
2041 (list '(+ sh-indent-after-if))
2044 (defun sh-handle-prev-open ()
2045 (save-excursion
2046 (let ((x (sh-prev-stmt)))
2047 (if (and x
2048 (progn
2049 (goto-char x)
2051 (looking-at "function\\b")
2052 (looking-at "\\s-*\\S-+\\s-*()")
2054 (list '(+ sh-indent-after-function))
2055 (list '(+ sh-indent-after-open)))
2058 (defun sh-handle-this-close ()
2059 (forward-char 1) ;; move over ")"
2060 (if (sh-safe-forward-sexp -1)
2061 (list "aligned to opening paren")))
2063 (defun sh-goto-matching-case ()
2064 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2065 (if found (goto-char found))))
2067 (defun sh-handle-prev-case ()
2068 ;; This is typically called when point is on same line as a case
2069 ;; we shouldn't -- and can't find prev-case
2070 (if (looking-at ".*\\<case\\>")
2071 (list '(+ sh-indent-for-case-label))
2072 (error "We don't seem to be on a line with a case"))) ;; debug
2074 (defun sh-handle-this-esac ()
2075 (if (sh-goto-matching-case)
2076 (list "aligned to matching case")))
2078 (defun sh-handle-prev-esac ()
2079 (if (sh-goto-matching-case)
2080 (list "matching case")))
2082 (defun sh-handle-after-case-label ()
2083 (if (sh-goto-matching-case)
2084 (list '(+ sh-indent-for-case-alt))))
2086 (defun sh-handle-prev-case-alt-end ()
2087 (if (sh-goto-matching-case)
2088 (list '(+ sh-indent-for-case-label))))
2090 (defun sh-safe-forward-sexp (&optional arg)
2091 "Try and do a `forward-sexp', but do not error.
2092 Return new point if successful, nil if an error occurred."
2093 (condition-case nil
2094 (progn
2095 (forward-sexp (or arg 1))
2096 (point)) ;; return point if successful
2097 (error
2098 (sh-debug "oops!(1) %d" (point))
2099 nil))) ;; return nil if fail
2101 (defun sh-goto-match-for-done ()
2102 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2103 (if found
2104 (goto-char found))))
2106 (defun sh-handle-this-done ()
2107 (if (sh-goto-match-for-done)
2108 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2110 (defun sh-handle-prev-done ()
2111 (if (sh-goto-match-for-done)
2112 (list "previous done")))
2114 (defun sh-handle-this-do ()
2115 (if (sh-goto-match-for-done)
2116 (list '(+ sh-indent-for-do))))
2118 (defun sh-handle-prev-do ()
2119 (cond
2120 ((save-restriction
2121 (narrow-to-region (point) (line-beginning-position))
2122 (sh-goto-match-for-done))
2123 (sh-debug "match for done found on THIS line")
2124 (list '(+ sh-indent-after-loop-construct)))
2125 ((sh-goto-match-for-done)
2126 (sh-debug "match for done found on PREV line")
2127 (list '(+ sh-indent-after-do)))
2129 (message "match for done NOT found")
2130 nil)))
2132 ;; for rc:
2133 (defun sh-find-prev-switch ()
2134 "Find the line for the switch keyword matching this line's case keyword."
2135 (re-search-backward "\\<switch\\>" nil t))
2137 (defun sh-handle-this-rc-case ()
2138 (if (sh-find-prev-switch)
2139 (list '(+ sh-indent-after-switch))
2140 ;; (list '(+ sh-indent-for-case-label))
2141 nil))
2143 (defun sh-handle-prev-rc-case ()
2144 (list '(+ sh-indent-after-case)))
2146 (defun sh-check-rule (n thing)
2147 (let ((rule (nth n (assoc thing sh-kw-alist)))
2148 (val nil))
2149 (if rule
2150 (progn
2151 (setq val (funcall rule))
2152 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2153 n thing (point) rule val)))
2154 val))
2157 (defun sh-get-indent-info ()
2158 "Return indent-info for this line.
2159 This is a list. nil means the line is to be left as is.
2160 Otherwise it contains one or more of the following sublists:
2161 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2162 relative to. If present, this is always the first of the
2163 sublists. The indentation of the line in question is
2164 derived from the indentation of this point, possibly
2165 modified by subsequent sublists.
2166 \(+ VAR\)
2167 \(- VAR\) Get the value of variable VAR and add to or subtract from
2168 the indentation calculated so far.
2169 \(= VAR\) Get the value of variable VAR and *replace* the
2170 indentation with its value. This only occurs for
2171 special variables such as `sh-indent-comment'.
2172 STRING This is ignored for the purposes of calculating
2173 indentation, it is printed in certain cases to help show
2174 what the indentation is based on."
2175 ;; See comments before `sh-kw'.
2176 (save-excursion
2177 (let ((have-result nil)
2178 this-kw
2179 start
2181 (result nil)
2182 (align-point nil)
2183 prev-line-end x)
2184 (beginning-of-line)
2185 ;; Note: setting result to t means we are done and will return nil.
2186 ;;(This function never returns just t.)
2187 (cond
2188 ((or (nth 3 (syntax-ppss (point)))
2189 (eq (get-text-property (point) 'face) sh-heredoc-face))
2190 ;; String continuation -- don't indent
2191 (setq result t)
2192 (setq have-result t))
2193 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2194 (if (bobp)
2195 (setq result t) ;; return nil if 1st line!
2196 (setq result (list '(= sh-indent-comment)))
2197 ;; we still need to get previous line in case
2198 ;; sh-indent-comment is t (indent as normal)
2199 (setq align-point (sh-prev-line nil))
2200 (setq have-result nil)
2202 ) ;; cond
2204 (unless have-result
2205 ;; Continuation lines are handled specially
2206 (if (sh-this-is-a-continuation)
2207 (progn
2208 (setq result
2209 (if (save-excursion
2210 (beginning-of-line)
2211 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2212 ;; By convention, if the continuation \ is not
2213 ;; preceded by a SPC or a TAB it means that the line
2214 ;; is cut at a place where spaces cannot be freely
2215 ;; added/removed. I.e. do not indent the line.
2216 (list '(= nil))
2217 ;; We assume the line being continued is already
2218 ;; properly indented...
2219 ;; (setq prev-line-end (sh-prev-line))
2220 (setq align-point (sh-prev-line nil))
2221 (list '(+ sh-indent-for-continuation))))
2222 (setq have-result t))
2223 (beginning-of-line)
2224 (skip-chars-forward " \t")
2225 (setq this-kw (sh-get-kw)))
2227 ;; Handle "this" keyword: first word on the line we're
2228 ;; calculating indentation info for.
2229 (if this-kw
2230 (if (setq val (sh-check-rule 1 this-kw))
2231 (progn
2232 (setq align-point (point))
2233 (sh-debug
2234 "this - setting align-point to %d" align-point)
2235 (setq result (append result val))
2236 (setq have-result t)
2237 ;; set prev-line to continue processing remainder
2238 ;; of this line as a previous line
2239 (setq prev-line-end (point))
2240 ))))
2242 (unless have-result
2243 (setq prev-line-end (sh-prev-line 'end)))
2245 (if prev-line-end
2246 (save-excursion
2247 ;; We start off at beginning of this line.
2248 ;; Scan previous statements while this is <=
2249 ;; start of previous line.
2250 (setq start (point)) ;; for debug only
2251 (goto-char prev-line-end)
2252 (setq x t)
2253 (while (and x (setq x (sh-prev-thing)))
2254 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2255 (cond
2256 ((and (equal x ")")
2257 (equal (get-text-property (1- (point)) 'syntax-table)
2258 sh-st-punc))
2259 (sh-debug "Case label) here")
2260 (setq x 'case-label)
2261 (if (setq val (sh-check-rule 2 x))
2262 (progn
2263 (setq result (append result val))
2264 (setq align-point (point))))
2265 (or (bobp)
2266 (forward-char -1))
2267 ;; FIXME: This charset looks too much like a regexp. --Stef
2268 (skip-chars-forward "[a-z0-9]*?")
2270 ((string-match "[])}]" x)
2271 (setq x (sh-safe-forward-sexp -1))
2272 (if x
2273 (progn
2274 (setq align-point (point))
2275 (setq result (append result
2276 (list "aligned to opening paren")))
2278 ((string-match "[[({]" x)
2279 (sh-debug "Checking special thing: %s" x)
2280 (if (setq val (sh-check-rule 2 x))
2281 (setq result (append result val)))
2282 (forward-char -1)
2283 (setq align-point (point)))
2284 ((string-match "[\"'`]" x)
2285 (sh-debug "Skipping back for %s" x)
2286 ;; this was oops-2
2287 (setq x (sh-safe-forward-sexp -1)))
2288 ((stringp x)
2289 (sh-debug "Checking string %s at %s" x (point))
2290 (if (setq val (sh-check-rule 2 x))
2291 ;; (or (eq t (car val))
2292 ;; (eq t (car (car val))))
2293 (setq result (append result val)))
2294 ;; not sure about this test Wed Jan 27 23:48:35 1999
2295 (setq align-point (point))
2296 (unless (bolp)
2297 (forward-char -1)))
2299 (error "Don't know what to do with %s" x))
2301 ) ;; while
2302 (sh-debug "result is %s" result)
2304 (sh-debug "No prev line!")
2305 (sh-debug "result: %s align-point: %s" result align-point)
2308 (if align-point
2309 ;; was: (setq result (append result (list (list t align-point))))
2310 (setq result (append (list (list t align-point)) result))
2312 (sh-debug "result is now: %s" result)
2314 (or result
2315 (setq result (list (if prev-line-end
2316 (list t prev-line-end)
2317 (list '= 'sh-first-lines-indent)))))
2319 (if (eq result t)
2320 (setq result nil))
2321 (sh-debug "result is: %s" result)
2322 result
2323 ) ;; let
2327 (defun sh-get-indent-var-for-line (&optional info)
2328 "Return the variable controlling indentation for this line.
2329 If there is not [just] one such variable, return a string
2330 indicating the problem.
2331 If INFO is supplied it is used, else it is calculated."
2332 (let ((var nil)
2333 (result nil)
2334 (reason nil)
2335 sym elt)
2336 (or info
2337 (setq info (sh-get-indent-info)))
2338 (if (null info)
2339 (setq result "this line to be left as is")
2340 (while (and info (null result))
2341 (setq elt (car info))
2342 (cond
2343 ((stringp elt)
2344 (setq reason elt)
2346 ((not (listp elt))
2347 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2348 ;; so it is a list
2349 ((eq t (car elt))
2350 ) ;; nothing
2351 ((symbolp (setq sym (nth 1 elt)))
2352 ;; A bit of a kludge - when we see the sh-indent-comment
2353 ;; ignore other variables. Otherwise it is tricky to
2354 ;; "learn" the comment indentation.
2355 (if (eq var 'sh-indent-comment)
2356 (setq result var)
2357 (if var
2358 (setq result
2359 "this line is controlled by more than 1 variable.")
2360 (setq var sym))))
2362 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2363 (setq info (cdr info))
2365 (or result
2366 (setq result var))
2367 (or result
2368 (setq result reason))
2369 (if (null result)
2370 ;; e.g. just had (t POS)
2371 (setq result "line has default indentation"))
2372 result))
2376 ;; Finding the previous line isn't trivial.
2377 ;; We must *always* go back one more and see if that is a continuation
2378 ;; line -- it is the PREVIOUS line which is continued, not the one
2379 ;; we are going to!
2380 ;; Also, we want to treat a whole "here document" as one big line,
2381 ;; because we may want to a align to the beginning of it.
2383 ;; What we do:
2384 ;; - go back to previous non-empty line
2385 ;; - if this is in a here-document, go to the beginning of it
2386 ;; - while previous line is continued, go back one line
2387 (defun sh-prev-line (&optional end)
2388 "Back to end of previous non-comment non-empty line.
2389 Go to beginning of logical line unless END is non-nil, in which case
2390 we go to the end of the previous line and do not check for continuations."
2391 (save-excursion
2392 (beginning-of-line)
2393 (forward-comment (- (point-max)))
2394 (unless end (beginning-of-line))
2395 (when (and (not (bobp))
2396 (equal (get-text-property (1- (point)) 'face)
2397 sh-heredoc-face))
2398 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2399 (when p1
2400 (goto-char p1)
2401 (if end
2402 (end-of-line)
2403 (beginning-of-line)))))
2404 (unless end
2405 ;; we must check previous lines to see if they are continuation lines
2406 ;; if so, we must return position of first of them
2407 (while (and (sh-this-is-a-continuation)
2408 (>= 0 (forward-line -1))))
2409 (beginning-of-line)
2410 (skip-chars-forward " \t"))
2411 (point)))
2414 (defun sh-prev-stmt ()
2415 "Return the address of the previous stmt or nil."
2416 ;; This is used when we are trying to find a matching keyword.
2417 ;; Searching backward for the keyword would certainly be quicker, but
2418 ;; it is hard to remove "false matches" -- such as if the keyword
2419 ;; appears in a string or quote. This way is slower, but (I think) safer.
2420 (interactive)
2421 (save-excursion
2422 (let ((going t)
2423 (start (point))
2424 (found nil)
2425 (prev nil))
2426 (skip-chars-backward " \t;|&({[")
2427 (while (and (not found)
2428 (not (bobp))
2429 going)
2430 ;; Do a backward-sexp if possible, else backup bit by bit...
2431 (if (sh-safe-forward-sexp -1)
2432 (progn
2433 (if (looking-at sh-special-keywords)
2434 (progn
2435 (setq found prev))
2436 (setq prev (point))
2438 ;; backward-sexp failed
2439 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2440 (forward-char -1))
2441 (if (bolp)
2442 (let ((back (sh-prev-line nil)))
2443 (if back
2444 (goto-char back)
2445 (setq going nil)))))
2446 (unless found
2447 (skip-chars-backward " \t")
2448 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2449 (eq (char-before) ?\;)
2450 (looking-at "\\s-*[|&]"))
2451 (setq found (point)))))
2452 (if found
2453 (goto-char found))
2454 (if found
2455 (progn
2456 (skip-chars-forward " \t|&({[")
2457 (setq found (point))))
2458 (if (>= (point) start)
2459 (progn
2460 (debug "We didn't move!")
2461 (setq found nil))
2462 (or found
2463 (sh-debug "Did not find prev stmt.")))
2464 found)))
2467 (defun sh-get-word ()
2468 "Get a shell word skipping whitespace from point."
2469 (interactive)
2470 (skip-chars-forward "\t ")
2471 (let ((start (point)))
2472 (while
2473 (if (looking-at "[\"'`]")
2474 (sh-safe-forward-sexp)
2475 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2476 (> (skip-chars-forward "-_$[:alnum:]") 0)
2478 (buffer-substring start (point))
2481 (defun sh-prev-thing ()
2482 "Return the previous thing this logical line."
2483 ;; This is called when `sh-get-indent-info' is working backwards on
2484 ;; the previous line(s) finding what keywords may be relevant for
2485 ;; indenting. It moves over sexps if possible, and will stop
2486 ;; on a ; and at the beginning of a line if it is not a continuation
2487 ;; line.
2489 ;; Added a kludge for ";;"
2490 ;; Possible return values:
2491 ;; nil - nothing
2492 ;; a string - possibly a keyword
2494 (if (bolp)
2496 (let ((start (point))
2497 (min-point (if (sh-this-is-a-continuation)
2498 (sh-prev-line nil)
2499 (line-beginning-position))))
2500 (skip-chars-backward " \t;" min-point)
2501 (if (looking-at "\\s-*;;")
2502 ;; (message "Found ;; !")
2503 ";;"
2504 (skip-chars-backward "^)}];\"'`({[" min-point)
2505 (let ((c (if (> (point) min-point) (char-before))))
2506 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2507 (point) c start min-point)
2508 (if (not (memq c '(?\n nil ?\;)))
2509 ;; c -- return a string
2510 (char-to-string c)
2511 ;; Return the leading keyword of the "command" we supposedly
2512 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
2513 ;; `then' that precedes the actual command), so check whether
2514 ;; we're looking at such a keyword and if so, move back forward.
2515 (let ((boundary (point))
2516 kwd next)
2517 (while
2518 (progn
2519 ;; Skip forward over white space newline and \ at eol.
2520 (skip-chars-forward " \t\n\\\\" start)
2521 (if (>= (point) start)
2522 (progn
2523 (sh-debug "point: %d >= start: %d" (point) start)
2524 nil)
2525 (if next (setq boundary next))
2526 (sh-debug "Now at %d start=%d" (point) start)
2527 (setq kwd (sh-get-word))
2528 (if (member kwd (sh-feature sh-leading-keywords))
2529 (progn
2530 (setq next (point))
2532 nil))))
2533 (goto-char boundary)
2534 kwd)))))))
2537 (defun sh-this-is-a-continuation ()
2538 "Return non-nil if current line is a continuation of previous line."
2539 (save-excursion
2540 (and (zerop (forward-line -1))
2541 (looking-at ".*\\\\$")
2542 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2543 nil nil nil t))))))
2545 (defun sh-get-kw (&optional where and-move)
2546 "Return first word of line from WHERE.
2547 If AND-MOVE is non-nil then move to end of word."
2548 (let ((start (point)))
2549 (if where
2550 (goto-char where))
2551 (prog1
2552 (buffer-substring (point)
2553 (progn (skip-chars-forward "^ \t\n;&|")(point)))
2554 (unless and-move
2555 (goto-char start)))))
2557 (defun sh-find-prev-matching (open close &optional depth)
2558 "Find a matching token for a set of opening and closing keywords.
2559 This takes into account that there may be nested open..close pairings.
2560 OPEN and CLOSE are regexps denoting the tokens to be matched.
2561 Optional parameter DEPTH (usually 1) says how many to look for."
2562 (let ((parse-sexp-ignore-comments t)
2563 prev)
2564 (setq depth (or depth 1))
2565 (save-excursion
2566 (condition-case nil
2567 (while (and
2568 (/= 0 depth)
2569 (not (bobp))
2570 (setq prev (sh-prev-stmt)))
2571 (goto-char prev)
2572 (save-excursion
2573 (if (looking-at "\\\\\n")
2574 (progn
2575 (forward-char 2)
2576 (skip-chars-forward " \t")))
2577 (cond
2578 ((looking-at open)
2579 (setq depth (1- depth))
2580 (sh-debug "found open at %d - depth = %d" (point) depth))
2581 ((looking-at close)
2582 (setq depth (1+ depth))
2583 (sh-debug "found close - depth = %d" depth))
2585 ))))
2586 (error nil))
2587 (if (eq depth 0)
2588 prev ;; (point)
2589 nil)
2593 (defun sh-var-value (var &optional ignore-error)
2594 "Return the value of variable VAR, interpreting symbols.
2595 It can also return t or nil.
2596 If an invalid value is found, throw an error unless Optional argument
2597 IGNORE-ERROR is non-nil."
2598 (let ((val (symbol-value var)))
2599 (cond
2600 ((numberp val)
2601 val)
2602 ((eq val t)
2603 val)
2604 ((null val)
2605 val)
2606 ((eq val '+)
2607 sh-basic-offset)
2608 ((eq val '-)
2609 (- sh-basic-offset))
2610 ((eq val '++)
2611 (* 2 sh-basic-offset))
2612 ((eq val '--)
2613 (* 2 (- sh-basic-offset)))
2614 ((eq val '*)
2615 (/ sh-basic-offset 2))
2616 ((eq val '/)
2617 (/ (- sh-basic-offset) 2))
2619 (if ignore-error
2620 (progn
2621 (message "Don't know how to handle %s's value of %s" var val)
2623 (error "Don't know how to handle %s's value of %s" var val))
2624 ))))
2626 (defun sh-set-var-value (var value &optional no-symbol)
2627 "Set variable VAR to VALUE.
2628 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2629 can be represented by a symbol then do so."
2630 (cond
2631 (no-symbol
2632 (set var value))
2633 ((= value sh-basic-offset)
2634 (set var '+))
2635 ((= value (- sh-basic-offset))
2636 (set var '-))
2637 ((eq value (* 2 sh-basic-offset))
2638 (set var '++))
2639 ((eq value (* 2 (- sh-basic-offset)))
2640 (set var '--))
2641 ((eq value (/ sh-basic-offset 2))
2642 (set var '*))
2643 ((eq value (/ (- sh-basic-offset) 2))
2644 (set var '/))
2646 (set var value)))
2650 (defun sh-calculate-indent (&optional info)
2651 "Return the indentation for the current line.
2652 If INFO is supplied it is used, else it is calculated from current line."
2653 (let ((ofs 0)
2654 (base-value 0)
2655 elt a b var val)
2656 (or info
2657 (setq info (sh-get-indent-info)))
2658 (when info
2659 (while info
2660 (sh-debug "info: %s ofs=%s" info ofs)
2661 (setq elt (car info))
2662 (cond
2663 ((stringp elt)) ;; do nothing?
2664 ((listp elt)
2665 (setq a (car (car info)))
2666 (setq b (nth 1 (car info)))
2667 (cond
2668 ((eq a t)
2669 (save-excursion
2670 (goto-char b)
2671 (setq val (current-indentation)))
2672 (setq base-value val))
2673 ((symbolp b)
2674 (setq val (sh-var-value b))
2675 (cond
2676 ((eq a '=)
2677 (cond
2678 ((null val)
2679 ;; no indentation
2680 ;; set info to nil so we stop immediately
2681 (setq base-value nil ofs nil info nil))
2682 ((eq val t) (setq ofs 0)) ;; indent as normal line
2684 ;; The following assume the (t POS) come first!
2685 (setq ofs val base-value 0)
2686 (setq info nil)))) ;; ? stop now
2687 ((eq a '+) (setq ofs (+ ofs val)))
2688 ((eq a '-) (setq ofs (- ofs val)))
2690 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2692 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2694 (error "sh-calculate-indent invalid elt %s" elt)))
2695 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2696 a b val base-value ofs)
2697 (setq info (cdr info)))
2698 ;; return value:
2699 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2701 (cond
2702 ((or (null base-value)(null ofs))
2703 nil)
2704 ((and (numberp base-value)(numberp ofs))
2705 (sh-debug "base (%d) + ofs (%d) = %d"
2706 base-value ofs (+ base-value ofs))
2707 (+ base-value ofs)) ;; return value
2709 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2710 base-value ofs)
2711 nil)))))
2714 (defun sh-indent-line ()
2715 "Indent the current line."
2716 (interactive)
2717 (let ((indent (sh-calculate-indent))
2718 (pos (- (point-max) (point))))
2719 (when indent
2720 (beginning-of-line)
2721 (skip-chars-forward " \t")
2722 (indent-line-to indent)
2723 ;; If initial point was within line's indentation,
2724 ;; position after the indentation. Else stay at same point in text.
2725 (if (> (- (point-max) pos) (point))
2726 (goto-char (- (point-max) pos))))))
2729 (defun sh-blink (blinkpos &optional msg)
2730 "Move cursor momentarily to BLINKPOS and display MSG."
2731 ;; We can get here without it being a number on first line
2732 (if (numberp blinkpos)
2733 (save-excursion
2734 (goto-char blinkpos)
2735 (if msg (message "%s" msg) (message nil))
2736 (sit-for blink-matching-delay))
2737 (if msg (message "%s" msg) (message nil))))
2739 (defun sh-show-indent (arg)
2740 "Show the how the current line would be indented.
2741 This tells you which variable, if any, controls the indentation of
2742 this line.
2743 If optional arg ARG is non-null (called interactively with a prefix),
2744 a pop up window describes this variable.
2745 If variable `sh-blink' is non-nil then momentarily go to the line
2746 we are indenting relative to, if applicable."
2747 (interactive "P")
2748 (sh-must-support-indent)
2749 (let* ((info (sh-get-indent-info))
2750 (var (sh-get-indent-var-for-line info))
2751 (curr-indent (current-indentation))
2752 val msg)
2753 (if (stringp var)
2754 (message "%s" (setq msg var))
2755 (setq val (sh-calculate-indent info))
2757 (if (eq curr-indent val)
2758 (setq msg (format "%s is %s" var (symbol-value var)))
2759 (setq msg
2760 (if val
2761 (format "%s (%s) would change indent from %d to: %d"
2762 var (symbol-value var) curr-indent val)
2763 (format "%s (%s) would leave line as is"
2764 var (symbol-value var)))
2766 (if (and arg var)
2767 (describe-variable var)))
2768 (if sh-blink
2769 (let ((info (sh-get-indent-info)))
2770 (if (and info (listp (car info))
2771 (eq (car (car info)) t))
2772 (sh-blink (nth 1 (car info)) msg)
2773 (message "%s" msg)))
2774 (message "%s" msg))
2777 (defun sh-set-indent ()
2778 "Set the indentation for the current line.
2779 If the current line is controlled by an indentation variable, prompt
2780 for a new value for it."
2781 (interactive)
2782 (sh-must-support-indent)
2783 (let* ((info (sh-get-indent-info))
2784 (var (sh-get-indent-var-for-line info))
2785 val old-val indent-val)
2786 (if (stringp var)
2787 (message "Cannot set indent - %s" var)
2788 (setq old-val (symbol-value var))
2789 (setq val (sh-read-variable var))
2790 (condition-case nil
2791 (progn
2792 (set var val)
2793 (setq indent-val (sh-calculate-indent info))
2794 (if indent-val
2795 (message "Variable: %s Value: %s would indent to: %d"
2796 var (symbol-value var) indent-val)
2797 (message "Variable: %s Value: %s would leave line as is."
2798 var (symbol-value var)))
2799 ;; I'm not sure about this, indenting it now?
2800 ;; No. Because it would give the impression that an undo would
2801 ;; restore thing, but the value has been altered.
2802 ;; (sh-indent-line)
2804 (error
2805 (set var old-val)
2806 (message "Bad value for %s, restoring to previous value %s"
2807 var old-val)
2808 (sit-for 1)
2809 nil))
2813 (defun sh-learn-line-indent (arg)
2814 "Learn how to indent a line as it currently is indented.
2816 If there is an indentation variable which controls this line's indentation,
2817 then set it to a value which would indent the line the way it
2818 presently is.
2820 If the value can be represented by one of the symbols then do so
2821 unless optional argument ARG (the prefix when interactive) is non-nil."
2822 (interactive "*P")
2823 (sh-must-support-indent)
2824 ;; I'm not sure if we show allow learning on an empty line.
2825 ;; Though it might occasionally be useful I think it usually
2826 ;; would just be confusing.
2827 (if (save-excursion
2828 (beginning-of-line)
2829 (looking-at "\\s-*$"))
2830 (message "sh-learn-line-indent ignores empty lines.")
2831 (let* ((info (sh-get-indent-info))
2832 (var (sh-get-indent-var-for-line info))
2833 ival sval diff new-val
2834 (no-symbol arg)
2835 (curr-indent (current-indentation)))
2836 (cond
2837 ((stringp var)
2838 (message "Cannot learn line - %s" var))
2839 ((eq var 'sh-indent-comment)
2840 ;; This is arbitrary...
2841 ;; - if curr-indent is 0, set to curr-indent
2842 ;; - else if it has the indentation of a "normal" line,
2843 ;; then set to t
2844 ;; - else set to curr-indent.
2845 (setq sh-indent-comment
2846 (if (= curr-indent 0)
2848 (let* ((sh-indent-comment t)
2849 (val2 (sh-calculate-indent info)))
2850 (if (= val2 curr-indent)
2852 curr-indent))))
2853 (message "%s set to %s" var (symbol-value var))
2855 ((numberp (setq sval (sh-var-value var)))
2856 (setq ival (sh-calculate-indent info))
2857 (setq diff (- curr-indent ival))
2859 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2860 curr-indent ival diff var sval)
2861 (setq new-val (+ sval diff))
2862 ;;; I commented out this because someone might want to replace
2863 ;;; a value of `+' with the current value of sh-basic-offset
2864 ;;; or vice-versa.
2865 ;;; (if (= 0 diff)
2866 ;;; (message "No change needed!")
2867 (sh-set-var-value var new-val no-symbol)
2868 (message "%s set to %s" var (symbol-value var))
2871 (debug)
2872 (message "Cannot change %s" var))))))
2876 (defun sh-mark-init (buffer)
2877 "Initialize a BUFFER to be used by `sh-mark-line'."
2878 (with-current-buffer (get-buffer-create buffer)
2879 (erase-buffer)
2880 (occur-mode)))
2883 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2884 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2885 Buffer BUFFER is in `occur-mode'.
2886 If ADD-LINENUM is non-nil the message is preceded by the line number.
2887 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2888 so that `occur-next' and `occur-prev' will work."
2889 (let ((m1 (make-marker))
2890 start
2891 (line ""))
2892 (when point
2893 (set-marker m1 point (current-buffer))
2894 (if add-linenum
2895 (setq line (format "%d: " (1+ (count-lines 1 point))))))
2896 (save-excursion
2897 (if (get-buffer buffer)
2898 (set-buffer (get-buffer buffer))
2899 (set-buffer (get-buffer-create buffer))
2900 (occur-mode)
2902 (goto-char (point-max))
2903 (setq start (point))
2904 (insert line)
2905 (if occur-point
2906 (setq occur-point (point)))
2907 (insert message)
2908 (if point
2909 (add-text-properties
2910 start (point)
2911 '(mouse-face highlight
2912 help-echo "mouse-2: go to the line where I learned this")))
2913 (insert "\n")
2914 (if point
2915 (progn
2916 (put-text-property start (point) 'occur-target m1)
2917 (if occur-point
2918 (put-text-property start occur-point
2919 'occur-match t))
2925 ;; Is this really worth having?
2926 (defvar sh-learned-buffer-hook nil
2927 "*An abnormal hook, called with an alist of learned variables.")
2928 ;; Example of how to use sh-learned-buffer-hook
2930 ;; (defun what-i-learned (list)
2931 ;; (let ((p list))
2932 ;; (with-current-buffer "*scratch*"
2933 ;; (goto-char (point-max))
2934 ;; (insert "(setq\n")
2935 ;; (while p
2936 ;; (insert (format " %s %s \n"
2937 ;; (nth 0 (car p)) (nth 1 (car p))))
2938 ;; (setq p (cdr p)))
2939 ;; (insert ")\n")
2940 ;; )))
2942 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2945 ;; Originally this was sh-learn-region-indent (beg end)
2946 ;; However, in practice this was awkward so I changed it to
2947 ;; use the whole buffer. Use narrowing if needbe.
2948 (defun sh-learn-buffer-indent (&optional arg)
2949 "Learn how to indent the buffer the way it currently is.
2951 Output in buffer \"*indent*\" shows any lines which have conflicting
2952 values of a variable, and the final value of all variables learned.
2953 When called interactively, pop to this buffer automatically if
2954 there are any discrepancies.
2956 If no prefix ARG is given, then variables are set to numbers.
2957 If a prefix arg is given, then variables are set to symbols when
2958 applicable -- e.g. to symbol `+' if the value is that of the
2959 basic indent.
2960 If a positive numerical prefix is given, then `sh-basic-offset'
2961 is set to the prefix's numerical value.
2962 Otherwise, sh-basic-offset may or may not be changed, according
2963 to the value of variable `sh-learn-basic-offset'.
2965 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2966 function completes. The function is abnormal because it is called
2967 with an alist of variables learned. This feature may be changed or
2968 removed in the future.
2970 This command can often take a long time to run."
2971 (interactive "P")
2972 (sh-must-support-indent)
2973 (save-excursion
2974 (goto-char (point-min))
2975 (let ((learned-var-list nil)
2976 (out-buffer "*indent*")
2977 (num-diffs 0)
2978 previous-set-info
2979 (max 17)
2982 (comment-col nil) ;; number if all same, t if seen diff values
2983 (comments-always-default t) ;; nil if we see one not default
2984 initial-msg
2985 (specified-basic-offset (and arg (numberp arg)
2986 (> arg 0)))
2987 (linenum 0)
2988 suggested)
2989 (setq vec (make-vector max 0))
2990 (sh-mark-init out-buffer)
2992 (if specified-basic-offset
2993 (progn
2994 (setq sh-basic-offset arg)
2995 (setq initial-msg
2996 (format "Using specified sh-basic-offset of %d"
2997 sh-basic-offset)))
2998 (setq initial-msg
2999 (format "Initial value of sh-basic-offset: %s"
3000 sh-basic-offset)))
3002 (while (< (point) (point-max))
3003 (setq linenum (1+ linenum))
3004 ;; (if (zerop (% linenum 10))
3005 (message "line %d" linenum)
3006 ;; )
3007 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3008 (let* ((sh-indent-comment t) ;; info must return default indent
3009 (info (sh-get-indent-info))
3010 (var (sh-get-indent-var-for-line info))
3011 sval ival diff new-val
3012 (curr-indent (current-indentation)))
3013 (cond
3014 ((null var)
3015 nil)
3016 ((stringp var)
3017 nil)
3018 ((numberp (setq sval (sh-var-value var 'no-error)))
3019 ;; the numberp excludes comments since sval will be t.
3020 (setq ival (sh-calculate-indent))
3021 (setq diff (- curr-indent ival))
3022 (setq new-val (+ sval diff))
3023 (sh-set-var-value var new-val 'no-symbol)
3024 (unless (looking-at "\\s-*#") ;; don't learn from comments
3025 (if (setq previous-set-info (assoc var learned-var-list))
3026 (progn
3027 ;; it was already there, is it same value ?
3028 (unless (eq (symbol-value var)
3029 (nth 1 previous-set-info))
3030 (sh-mark-line
3031 (format "Variable %s was set to %s"
3032 var (symbol-value var))
3033 (point) out-buffer t t)
3034 (sh-mark-line
3035 (format " but was previously set to %s"
3036 (nth 1 previous-set-info))
3037 (nth 2 previous-set-info) out-buffer t)
3038 (setq num-diffs (1+ num-diffs))
3039 ;; (delete previous-set-info learned-var-list)
3040 (setcdr previous-set-info
3041 (list (symbol-value var) (point)))
3044 (setq learned-var-list
3045 (append (list (list var (symbol-value var)
3046 (point)))
3047 learned-var-list)))
3048 (if (numberp new-val)
3049 (progn
3050 (sh-debug
3051 "This line's indent value: %d" new-val)
3052 (if (< new-val 0)
3053 (setq new-val (- new-val)))
3054 (if (< new-val max)
3055 (aset vec new-val (1+ (aref vec new-val))))))
3057 ((eq var 'sh-indent-comment)
3058 (unless (= curr-indent (sh-calculate-indent info))
3059 ;; this is not the default indentation
3060 (setq comments-always-default nil)
3061 (if comment-col ;; then we have see one before
3062 (or (eq comment-col curr-indent)
3063 (setq comment-col t)) ;; seen a different one
3064 (setq comment-col curr-indent))
3067 (sh-debug "Cannot learn this line!!!")
3069 (sh-debug
3070 "at %s learned-var-list is %s" (point) learned-var-list)
3072 (forward-line 1)
3073 ) ;; while
3074 (if sh-debug
3075 (progn
3076 (setq msg (format
3077 "comment-col = %s comments-always-default = %s"
3078 comment-col comments-always-default))
3079 ;; (message msg)
3080 (sh-mark-line msg nil out-buffer)))
3081 (cond
3082 ((eq comment-col 0)
3083 (setq msg "\nComments are all in 1st column.\n"))
3084 (comments-always-default
3085 (setq msg "\nComments follow default indentation.\n")
3086 (setq comment-col t))
3087 ((numberp comment-col)
3088 (setq msg (format "\nComments are in col %d." comment-col)))
3090 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3091 (setq comment-col nil)
3093 (sh-debug msg)
3094 (sh-mark-line msg nil out-buffer)
3096 (sh-mark-line initial-msg nil out-buffer t t)
3098 (setq suggested (sh-guess-basic-offset vec))
3100 (if (and suggested (not specified-basic-offset))
3101 (let ((new-value
3102 (cond
3103 ;; t => set it if we have a single value as a number
3104 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3105 suggested)
3106 ;; other non-nil => set it if only one value was found
3107 (sh-learn-basic-offset
3108 (if (numberp suggested)
3109 suggested
3110 (if (= (length suggested) 1)
3111 (car suggested))))
3113 nil))))
3114 (if new-value
3115 (progn
3116 (setq learned-var-list
3117 (append (list (list 'sh-basic-offset
3118 (setq sh-basic-offset new-value)
3119 (point-max)))
3120 learned-var-list))
3121 ;; Not sure if we need to put this line in, since
3122 ;; it will appear in the "Learned variable settings".
3123 (sh-mark-line
3124 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3125 nil out-buffer))
3126 (sh-mark-line
3127 (if (listp suggested)
3128 (format "Possible value(s) for sh-basic-offset: %s"
3129 (mapconcat 'int-to-string suggested " "))
3130 (format "Suggested sh-basic-offset: %d" suggested))
3131 nil out-buffer))))
3134 (setq learned-var-list
3135 (append (list (list 'sh-indent-comment comment-col (point-max)))
3136 learned-var-list))
3137 (setq sh-indent-comment comment-col)
3138 (let ((name (buffer-name)))
3139 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3140 (if arg
3141 ;; Set learned variables to symbolic rather than numeric
3142 ;; values where possible.
3143 (dolist (learned-var (reverse learned-var-list))
3144 (let ((var (car learned-var))
3145 (val (nth 1 learned-var)))
3146 (when (and (not (eq var 'sh-basic-offset))
3147 (numberp val))
3148 (sh-set-var-value var val)))))
3149 (dolist (learned-var (reverse learned-var-list))
3150 (let ((var (car learned-var)))
3151 (sh-mark-line (format " %s %s" var (symbol-value var))
3152 (nth 2 learned-var) out-buffer)))
3153 (with-current-buffer out-buffer
3154 (goto-char (point-min))
3155 (insert
3156 (format "Indentation values for buffer %s.\n" name)
3157 (format "%d indentation variable%s different values%s\n\n"
3158 num-diffs
3159 (if (= num-diffs 1)
3160 " has" "s have")
3161 (if (zerop num-diffs)
3162 "." ":"))
3164 ;; Are abnormal hooks considered bad form?
3165 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3166 (and (called-interactively-p 'any)
3167 (or sh-popup-occur-buffer (> num-diffs 0))
3168 (pop-to-buffer out-buffer)))))
3170 (defun sh-guess-basic-offset (vec)
3171 "See if we can determine a reasonable value for `sh-basic-offset'.
3172 This is experimental, heuristic and arbitrary!
3173 Argument VEC is a vector of information collected by
3174 `sh-learn-buffer-indent'.
3175 Return values:
3176 number - there appears to be a good single value
3177 list of numbers - no obvious one, here is a list of one or more
3178 reasonable choices
3179 nil - we couldn't find a reasonable one."
3180 (let* ((max (1- (length vec)))
3181 (i 1)
3182 (totals (make-vector max 0)))
3183 (while (< i max)
3184 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
3185 (if (zerop (% i 2))
3186 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3187 (if (< (* i 2) max)
3188 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3189 (setq i (1+ i)))
3191 (let ((x nil)
3192 (result nil)
3193 tot sum p)
3194 (setq i 1)
3195 (while (< i max)
3196 (if (/= (aref totals i) 0)
3197 (setq x (append x (list (cons i (aref totals i))))))
3198 (setq i (1+ i)))
3200 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3201 (setq tot (apply '+ (append totals nil)))
3202 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3203 vec totals tot))
3204 (cond
3205 ((zerop (length x))
3206 (message "no values!")) ;; we return nil
3207 ((= (length x) 1)
3208 (message "only value is %d" (car (car x)))
3209 (setq result (car (car x)))) ;; return single value
3210 ((> (cdr (car x)) (/ tot 2))
3211 ;; 1st is > 50%
3212 (message "basic-offset is probably %d" (car (car x)))
3213 (setq result (car (car x)))) ;; again, return a single value
3214 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3215 ;; 1st is >= 2 * 2nd
3216 (message "basic-offset could be %d" (car (car x)))
3217 (setq result (car (car x))))
3218 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3219 ;; 1st & 2nd together >= 50% - return a list
3220 (setq p x sum 0 result nil)
3221 (while (and p
3222 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3223 (setq result (append result (list (car (car p)))))
3224 (setq p (cdr p)))
3225 (message "Possible choices for sh-basic-offset: %s"
3226 (mapconcat 'int-to-string result " ")))
3228 (message "No obvious value for sh-basic-offset. Perhaps %d"
3229 (car (car x)))
3230 ;; result is nil here
3232 result)))
3234 ;; ========================================================================
3236 ;; Styles -- a quick and dirty way of saving the indentation settings.
3238 (defvar sh-styles-alist nil
3239 "A list of all known shell indentation styles.")
3241 (defun sh-name-style (name &optional confirm-overwrite)
3242 "Name the current indentation settings as a style called NAME.
3243 If this name exists, the command will prompt whether it should be
3244 overwritten if
3245 - - it was called interactively with a prefix argument, or
3246 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3247 ;; (interactive "sName for this style: ")
3248 (interactive
3249 (list
3250 (read-from-minibuffer "Name for this style? " )
3251 (not current-prefix-arg)))
3252 (let ((slist (cons name
3253 (mapcar (lambda (var) (cons var (symbol-value var)))
3254 sh-var-list)))
3255 (style (assoc name sh-styles-alist)))
3256 (if style
3257 (if (and confirm-overwrite
3258 (not (y-or-n-p "This style exists. Overwrite it? ")))
3259 (message "Not changing style %s" name)
3260 (message "Updating style %s" name)
3261 (setcdr style (cdr slist)))
3262 (message "Creating new style %s" name)
3263 (push slist sh-styles-alist))))
3265 (defun sh-load-style (name)
3266 "Set shell indentation values for this buffer from those in style NAME."
3267 (interactive (list (completing-read
3268 "Which style to use for this buffer? "
3269 sh-styles-alist nil t)))
3270 (let ((sl (assoc name sh-styles-alist)))
3271 (if (null sl)
3272 (error "sh-load-style - style %s not known" name)
3273 (dolist (var (cdr sl))
3274 (set (car var) (cdr var))))))
3276 (defun sh-save-styles-to-buffer (buff)
3277 "Save all current styles in elisp to buffer BUFF.
3278 This is always added to the end of the buffer."
3279 (interactive (list
3280 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3281 (with-current-buffer (get-buffer-create buff)
3282 (goto-char (point-max))
3283 (insert "\n")
3284 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3288 ;; statement syntax-commands for various shells
3290 ;; You are welcome to add the syntax or even completely new statements as
3291 ;; appropriate for your favorite shell.
3293 (defconst sh-non-closing-paren
3294 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3295 ;; that inherits this property, which then confuses the indentation.
3296 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3298 (define-skeleton sh-case
3299 "Insert a case/switch statement. See `sh-feature'."
3300 (csh "expression: "
3301 "switch( " str " )" \n
3302 > "case " (read-string "pattern: ") ?: \n
3303 > _ \n
3304 "breaksw" \n
3305 ( "other pattern, %s: "
3306 < "case " str ?: \n
3307 > _ \n
3308 "breaksw" \n)
3309 < "default:" \n
3310 > _ \n
3311 resume:
3312 < < "endsw" \n)
3313 (es)
3314 (rc "expression: "
3315 > "switch( " str " ) {" \n
3316 > "case " (read-string "pattern: ") \n
3317 > _ \n
3318 ( "other pattern, %s: "
3319 "case " str > \n
3320 > _ \n)
3321 "case *" > \n
3322 > _ \n
3323 resume:
3324 ?\} > \n)
3325 (sh "expression: "
3326 > "case " str " in" \n
3327 ( "pattern, %s: "
3328 > str sh-non-closing-paren \n
3329 > _ \n
3330 ";;" \n)
3331 > "*" sh-non-closing-paren \n
3332 > _ \n
3333 resume:
3334 "esac" > \n))
3336 (define-skeleton sh-for
3337 "Insert a for loop. See `sh-feature'."
3338 (csh sh-modify sh
3339 1 ""
3340 2 "foreach "
3341 4 " ( "
3342 6 " )"
3343 15 '<
3344 16 "end")
3345 (es sh-modify rc
3346 4 " = ")
3347 (rc sh-modify sh
3348 2 "for( "
3349 6 " ) {"
3350 15 ?\} )
3351 (sh "Index variable: "
3352 > "for " str " in " _ "; do" \n
3353 > _ | ?$ & (sh-remember-variable str) \n
3354 "done" > \n))
3358 (define-skeleton sh-indexed-loop
3359 "Insert an indexed loop from 1 to n. See `sh-feature'."
3360 (bash sh-modify posix)
3361 (csh "Index variable: "
3362 "@ " str " = 1" \n
3363 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3364 > _ ?$ str \n
3365 "@ " str "++" \n
3366 < "end" \n)
3367 (es sh-modify rc
3368 4 " =")
3369 (ksh88 "Index variable: "
3370 > "integer " str "=0" \n
3371 > "while (( ( " str " += 1 ) <= "
3372 (read-string "upper limit: ")
3373 " )); do" \n
3374 > _ ?$ (sh-remember-variable str) > \n
3375 "done" > \n)
3376 (posix "Index variable: "
3377 > str "=1" \n
3378 "while [ $" str " -le "
3379 (read-string "upper limit: ")
3380 " ]; do" \n
3381 > _ ?$ str \n
3382 str ?= (sh-add (sh-remember-variable str) 1) \n
3383 "done" > \n)
3384 (rc "Index variable: "
3385 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3386 (read-string "upper limit: ")
3387 "; i++ ) print i }'`}) {" \n
3388 > _ ?$ (sh-remember-variable str) \n
3389 ?\} > \n)
3390 (sh "Index variable: "
3391 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3392 (read-string "upper limit: ")
3393 "; i++ ) print i }'`; do" \n
3394 > _ ?$ (sh-remember-variable str) \n
3395 "done" > \n))
3398 (defun sh-shell-initialize-variables ()
3399 "Scan the buffer for variable assignments.
3400 Add these variables to `sh-shell-variables'."
3401 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3402 (save-excursion
3403 (goto-char (point-min))
3404 (setq sh-shell-variables-initialized t)
3405 (while (search-forward "=" nil t)
3406 (sh-assignment 0)))
3407 (message "Scanning buffer `%s' for variable assignments...done"
3408 (buffer-name)))
3410 (defvar sh-add-buffer)
3412 (defun sh-add-completer (string predicate code)
3413 "Do completion using `sh-shell-variables', but initialize it first.
3414 This function is designed for use as the \"completion table\",
3415 so it takes three arguments:
3416 STRING, the current buffer contents;
3417 PREDICATE, the predicate for filtering possible matches;
3418 CODE, which says what kind of things to do.
3419 CODE can be nil, t or `lambda'.
3420 nil means to return the best completion of STRING, or nil if there is none.
3421 t means to return a list of all possible completions of STRING.
3422 `lambda' means to return t if STRING is a valid completion as it stands."
3423 (let ((vars
3424 (with-current-buffer sh-add-buffer
3425 (or sh-shell-variables-initialized
3426 (sh-shell-initialize-variables))
3427 (nconc (mapcar (lambda (var)
3428 (substring var 0 (string-match "=" var)))
3429 process-environment)
3430 sh-shell-variables))))
3431 (complete-with-action code vars string predicate)))
3433 (defun sh-add (var delta)
3434 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3435 (interactive
3436 (let ((sh-add-buffer (current-buffer)))
3437 (list (completing-read "Variable: " 'sh-add-completer)
3438 (prefix-numeric-value current-prefix-arg))))
3439 (insert (sh-feature '((bash . "$(( ")
3440 (ksh88 . "$(( ")
3441 (posix . "$(( ")
3442 (rc . "`{expr $")
3443 (sh . "`expr $")
3444 (zsh . "$[ ")))
3445 (sh-remember-variable var)
3446 (if (< delta 0) " - " " + ")
3447 (number-to-string (abs delta))
3448 (sh-feature '((bash . " ))")
3449 (ksh88 . " ))")
3450 (posix . " ))")
3451 (rc . "}")
3452 (sh . "`")
3453 (zsh . " ]")))))
3457 (define-skeleton sh-function
3458 "Insert a function definition. See `sh-feature'."
3459 (bash sh-modify ksh88
3460 3 "() {")
3461 (ksh88 "name: "
3462 "function " str " {" \n
3463 > _ \n
3464 < "}" \n)
3465 (rc sh-modify ksh88
3466 1 "fn ")
3467 (sh ()
3468 "() {" \n
3469 > _ \n
3470 < "}" \n))
3474 (define-skeleton sh-if
3475 "Insert an if statement. See `sh-feature'."
3476 (csh "condition: "
3477 "if( " str " ) then" \n
3478 > _ \n
3479 ( "other condition, %s: "
3480 < "else if( " str " ) then" \n
3481 > _ \n)
3482 < "else" \n
3483 > _ \n
3484 resume:
3485 < "endif" \n)
3486 (es "condition: "
3487 > "if { " str " } {" \n
3488 > _ \n
3489 ( "other condition, %s: "
3490 "} { " str " } {" > \n
3491 > _ \n)
3492 "} {" > \n
3493 > _ \n
3494 resume:
3495 ?\} > \n)
3496 (rc "condition: "
3497 > "if( " str " ) {" \n
3498 > _ \n
3499 ( "other condition, %s: "
3500 "} else if( " str " ) {" > \n
3501 > _ \n)
3502 "} else {" > \n
3503 > _ \n
3504 resume:
3505 ?\} > \n)
3506 (sh "condition: "
3507 '(setq input (sh-feature sh-test))
3508 > "if " str "; then" \n
3509 > _ \n
3510 ( "other condition, %s: "
3511 > "elif " str "; then" > \n
3512 > \n)
3513 "else" > \n
3514 > \n
3515 resume:
3516 "fi" > \n))
3520 (define-skeleton sh-repeat
3521 "Insert a repeat loop definition. See `sh-feature'."
3522 (es nil
3523 > "forever {" \n
3524 > _ \n
3525 ?\} > \n)
3526 (zsh "factor: "
3527 > "repeat " str "; do" > \n
3528 > \n
3529 "done" > \n))
3531 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3535 (define-skeleton sh-select
3536 "Insert a select statement. See `sh-feature'."
3537 (ksh88 "Index variable: "
3538 > "select " str " in " _ "; do" \n
3539 > ?$ str \n
3540 "done" > \n)
3541 (bash sh-append ksh88))
3542 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3546 (define-skeleton sh-tmp-file
3547 "Insert code to setup temporary file handling. See `sh-feature'."
3548 (bash sh-append ksh88)
3549 (csh (file-name-nondirectory (buffer-file-name))
3550 "set tmp = `mktemp -t " str ".XXXXXX`" \n
3551 "onintr exit" \n _
3552 (and (goto-char (point-max))
3553 (not (bolp))
3554 ?\n)
3555 "exit:\n"
3556 "rm $tmp* >&/dev/null" > \n)
3557 (es (file-name-nondirectory (buffer-file-name))
3558 > "local( signals = $signals sighup sigint;" \n
3559 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
3560 > "catch @ e {" \n
3561 > "rm $tmp^* >[2]/dev/null" \n
3562 "throw $e" \n
3563 "} {" > \n
3564 _ \n
3565 ?\} > \n
3566 ?\} > \n)
3567 (ksh88 sh-modify sh
3568 7 "EXIT")
3569 (rc (file-name-nondirectory (buffer-file-name))
3570 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
3571 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3572 (sh (file-name-nondirectory (buffer-file-name))
3573 > "TMP=`mktemp -t " str ".XXXXXX`" \n
3574 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
3578 (define-skeleton sh-until
3579 "Insert an until loop. See `sh-feature'."
3580 (sh "condition: "
3581 '(setq input (sh-feature sh-test))
3582 > "until " str "; do" \n
3583 > _ \n
3584 "done" > \n))
3585 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3589 (define-skeleton sh-while
3590 "Insert a while loop. See `sh-feature'."
3591 (csh sh-modify sh
3592 2 ""
3593 3 "while( "
3594 5 " )"
3595 10 '<
3596 11 "end")
3597 (es sh-modify sh
3598 3 "while { "
3599 5 " } {"
3600 10 ?\} )
3601 (rc sh-modify sh
3602 3 "while( "
3603 5 " ) {"
3604 10 ?\} )
3605 (sh "condition: "
3606 '(setq input (sh-feature sh-test))
3607 > "while " str "; do" \n
3608 > _ \n
3609 "done" > \n))
3613 (define-skeleton sh-while-getopts
3614 "Insert a while getopts loop. See `sh-feature'.
3615 Prompts for an options string which consists of letters for each recognized
3616 option followed by a colon `:' if the option accepts an argument."
3617 (bash sh-modify sh
3618 18 "${0##*/}")
3619 (csh nil
3620 "while( 1 )" \n
3621 > "switch( \"$1\" )" \n
3622 '(setq input '("- x" . 2))
3624 ( "option, %s: "
3625 < "case " '(eval str)
3626 '(if (string-match " +" str)
3627 (setq v1 (substring str (match-end 0))
3628 str (substring str 0 (match-beginning 0)))
3629 (setq v1 nil))
3630 str ?: \n
3631 > "set " v1 & " = $2" | -4 & _ \n
3632 (if v1 "shift") & \n
3633 "breaksw" \n)
3634 < "case --:" \n
3635 > "shift" \n
3636 < "default:" \n
3637 > "break" \n
3638 resume:
3639 < < "endsw" \n
3640 "shift" \n
3641 < "end" \n)
3642 (ksh88 sh-modify sh
3643 16 "print"
3644 18 "${0##*/}"
3645 37 "OPTIND-1")
3646 (posix sh-modify sh
3647 18 "$(basename $0)")
3648 (sh "optstring: "
3649 > "while getopts :" str " OPT; do" \n
3650 > "case $OPT in" \n
3651 '(setq v1 (append (vconcat str) nil))
3652 ( (prog1 (if v1 (char-to-string (car v1)))
3653 (if (eq (nth 1 v1) ?:)
3654 (setq v1 (nthcdr 2 v1)
3655 v2 "\"$OPTARG\"")
3656 (setq v1 (cdr v1)
3657 v2 nil)))
3658 > str "|+" str sh-non-closing-paren \n
3659 > _ v2 \n
3660 > ";;" \n)
3661 > "*" sh-non-closing-paren \n
3662 > "echo" " \"usage: " "`basename $0`"
3663 " [+-" '(setq v1 (point)) str
3664 '(save-excursion
3665 (while (search-backward ":" v1 t)
3666 (replace-match " ARG] [+-" t t)))
3667 (if (eq (preceding-char) ?-) -5)
3668 (if (and (sequencep v1) (length v1)) "] " "} ")
3669 "[--] ARGS...\"" \n
3670 "exit 2" > \n
3671 "esac" >
3672 \n "done"
3673 > \n
3674 "shift " (sh-add "OPTIND" -1) \n
3675 "OPTIND=1" \n))
3679 (defun sh-assignment (arg)
3680 "Remember preceding identifier for future completion and do self-insert."
3681 (interactive "p")
3682 (self-insert-command arg)
3683 (if (<= arg 1)
3684 (sh-remember-variable
3685 (save-excursion
3686 (if (re-search-forward (sh-feature sh-assignment-regexp)
3687 (prog1 (point)
3688 (beginning-of-line 1))
3690 (match-string 1))))))
3693 (defun sh-maybe-here-document (arg)
3694 "Insert self. Without prefix, following unquoted `<' inserts here document.
3695 The document is bounded by `sh-here-document-word'."
3696 (interactive "*P")
3697 (self-insert-command (prefix-numeric-value arg))
3698 (or arg
3699 (not (looking-back "[^<]<<"))
3700 (save-excursion
3701 (backward-char 2)
3702 (sh-quoted-p))
3703 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
3704 (make-string (/ (current-indentation) tab-width) ?\t)
3705 ""))
3706 (delim (replace-regexp-in-string "['\"]" ""
3707 sh-here-document-word)))
3708 (insert sh-here-document-word)
3709 (or (eolp) (looking-at "[ \t]") (insert ?\s))
3710 (end-of-line 1)
3711 (while
3712 (sh-quoted-p)
3713 (end-of-line 2))
3714 (insert ?\n tabs)
3715 (save-excursion
3716 (insert ?\n tabs (replace-regexp-in-string
3717 "\\`-?[ \t]*" "" delim))))))
3720 ;; various other commands
3722 (autoload 'comint-dynamic-complete "comint"
3723 "Dynamically perform completion at point." t)
3725 (autoload 'shell-dynamic-complete-command "shell"
3726 "Dynamically complete the command at point." t)
3728 (autoload 'comint-dynamic-complete-filename "comint"
3729 "Dynamically complete the filename at point." t)
3731 (autoload 'shell-dynamic-complete-environment-variable "shell"
3732 "Dynamically complete the environment variable at point." t)
3736 (defun sh-beginning-of-command ()
3737 "Move point to successive beginnings of commands."
3738 (interactive)
3739 (if (re-search-backward sh-beginning-of-command nil t)
3740 (goto-char (match-beginning 2))))
3742 (defun sh-end-of-command ()
3743 "Move point to successive ends of commands."
3744 (interactive)
3745 (if (re-search-forward sh-end-of-command nil t)
3746 (goto-char (match-end 1))))
3748 ;; Backslashification. Stolen from make-mode.el.
3750 (defun sh-backslash-region (from to delete-flag)
3751 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3752 With no argument, inserts backslashes and aligns existing backslashes.
3753 With an argument, deletes the backslashes.
3755 This function does not modify the last line of the region if the region ends
3756 right at the start of the following line; it does not modify blank lines
3757 at the start of the region. So you can put the region around an entire
3758 shell command and conveniently use this command."
3759 (interactive "r\nP")
3760 (save-excursion
3761 (goto-char from)
3762 (let ((column sh-backslash-column)
3763 (endmark (make-marker)))
3764 (move-marker endmark to)
3765 ;; Compute the smallest column number past the ends of all the lines.
3766 (if sh-backslash-align
3767 (progn
3768 (if (not delete-flag)
3769 (while (< (point) to)
3770 (end-of-line)
3771 (if (= (preceding-char) ?\\)
3772 (progn (forward-char -1)
3773 (skip-chars-backward " \t")))
3774 (setq column (max column (1+ (current-column))))
3775 (forward-line 1)))
3776 ;; Adjust upward to a tab column, if that doesn't push
3777 ;; past the margin.
3778 (if (> (% column tab-width) 0)
3779 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
3780 tab-width)))
3781 (if (< adjusted (window-width))
3782 (setq column adjusted))))))
3783 ;; Don't modify blank lines at start of region.
3784 (goto-char from)
3785 (while (and (< (point) endmark) (eolp))
3786 (forward-line 1))
3787 ;; Add or remove backslashes on all the lines.
3788 (while (and (< (point) endmark)
3789 ;; Don't backslashify the last line
3790 ;; if the region ends right at the start of the next line.
3791 (save-excursion
3792 (forward-line 1)
3793 (< (point) endmark)))
3794 (if (not delete-flag)
3795 (sh-append-backslash column)
3796 (sh-delete-backslash))
3797 (forward-line 1))
3798 (move-marker endmark nil))))
3800 (defun sh-append-backslash (column)
3801 (end-of-line)
3802 ;; Note that "\\\\" is needed to get one backslash.
3803 (if (= (preceding-char) ?\\)
3804 (progn (forward-char -1)
3805 (delete-horizontal-space)
3806 (indent-to column (if sh-backslash-align nil 1)))
3807 (indent-to column (if sh-backslash-align nil 1))
3808 (insert "\\")))
3810 (defun sh-delete-backslash ()
3811 (end-of-line)
3812 (or (bolp)
3813 (progn
3814 (forward-char -1)
3815 (if (looking-at "\\\\")
3816 (delete-region (1+ (point))
3817 (progn (skip-chars-backward " \t") (point)))))))
3819 (provide 'sh-script)
3821 ;;; sh-script.el ends here