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