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