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