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