Merged from miles@gnu.org--gnu-2005 (patch 655)
[bpt/emacs.git] / 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 (forward-comment (- (point-max)))
990 (when (eq (char-before) ?|)
991 (backward-char 1) t)))
992 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
993 sh-st-punc)))
994
995 (defconst sh-font-lock-syntactic-keywords
996 ;; A `#' begins a comment when it is unquoted and at the beginning of a
997 ;; word. In the shell, words are separated by metacharacters.
998 ;; The list of special chars is taken from the single-unix spec
999 ;; of the shell command language (under `quoting') but with `$' removed.
1000 `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol)
1001 ;; Make sure $@ and @? are correctly recognized as sexps.
1002 ("\\$\\([?@]\\)" 1 ,sh-st-symbol)
1003 ;; Find HEREDOC starters and add a corresponding rule for the ender.
1004 (sh-font-lock-here-doc
1005 (2 (sh-font-lock-open-heredoc
1006 (match-beginning 0) (match-string 1)) nil t)
1007 (5 (sh-font-lock-close-heredoc
1008 (match-beginning 0) (match-string 4)
1009 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3))))
1010 nil t))
1011 ;; Distinguish the special close-paren in `case'.
1012 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
1013
1014 (defun sh-font-lock-syntactic-face-function (state)
1015 (if (nth 3 state)
1016 (if (char-valid-p (nth 3 state))
1017 font-lock-string-face
1018 sh-heredoc-face)
1019 font-lock-comment-face))
1020
1021 (defgroup sh-indentation nil
1022 "Variables controlling indentation in shell scripts.
1023
1024 Note: customizing these variables will not affect existing buffers if
1025 `sh-make-vars-local' is no-nil. See the documentation for
1026 variable `sh-make-vars-local', command `sh-make-vars-local'
1027 and command `sh-reset-indent-vars-to-global-values'."
1028 :group 'sh-script)
1029
1030
1031 (defcustom sh-set-shell-hook nil
1032 "*Hook run by `sh-set-shell'."
1033 :type 'hook
1034 :group 'sh-script)
1035
1036 (defcustom sh-mode-hook nil
1037 "*Hook run by `sh-mode'."
1038 :type 'hook
1039 :group 'sh-script)
1040
1041 (defcustom sh-learn-basic-offset nil
1042 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1043
1044 nil mean: never.
1045 t means: only if there seems to be an obvious value.
1046 Anything else means: whenever we have a \"good guess\" as to the value."
1047 :type '(choice
1048 (const :tag "Never" nil)
1049 (const :tag "Only if sure" t)
1050 (const :tag "If have a good guess" usually))
1051 :group 'sh-indentation)
1052
1053 (defcustom sh-popup-occur-buffer nil
1054 "*Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1055 If t it is always shown. If nil, it is shown only when there
1056 are conflicts."
1057 :type '(choice
1058 (const :tag "Only when there are conflicts." nil)
1059 (const :tag "Always" t))
1060 :group 'sh-indentation)
1061
1062 (defcustom sh-blink t
1063 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
1064 The position on the line is not necessarily meaningful.
1065 In some cases the line will be the matching keyword, but this is not
1066 always the case."
1067 :type 'boolean
1068 :group 'sh-indentation)
1069
1070 (defcustom sh-first-lines-indent 0
1071 "*The indentation of the first non-blank non-comment line.
1072 Usually 0 meaning first column.
1073 Can be set to a number, or to nil which means leave it as is."
1074 :type '(choice
1075 (const :tag "Leave as is" nil)
1076 (integer :tag "Column number"
1077 :menu-tag "Indent to this col (0 means first col)" ))
1078 :group 'sh-indentation)
1079
1080
1081 (defcustom sh-basic-offset 4
1082 "*The default indentation increment.
1083 This value is used for the `+' and `-' symbols in an indentation variable."
1084 :type 'integer
1085 :group 'sh-indentation)
1086
1087 (defcustom sh-indent-comment nil
1088 "*How a comment line is to be indented.
1089 nil means leave it as it is;
1090 t means indent it as a normal line, aligning it to previous non-blank
1091 non-comment line;
1092 a number means align to that column, e.g. 0 means fist column."
1093 :type '(choice
1094 (const :tag "Leave as is." nil)
1095 (const :tag "Indent as a normal line." t)
1096 (integer :menu-tag "Indent to this col (0 means first col)."
1097 :tag "Indent to column number.") )
1098 :group 'sh-indentation)
1099
1100
1101 (defvar sh-debug nil
1102 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1103
1104
1105 ;; Uncomment this defun and comment the defmacro for debugging.
1106 ;; (defun sh-debug (&rest args)
1107 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1108 ;; (if sh-debug
1109 ;; (apply 'message args)))
1110 (defmacro sh-debug (&rest args))
1111
1112 (defconst sh-symbol-list
1113 '((const :tag "+ " :value +
1114 :menu-tag "+ Indent right by sh-basic-offset")
1115 (const :tag "- " :value -
1116 :menu-tag "- Indent left by sh-basic-offset")
1117 (const :tag "++" :value ++
1118 :menu-tag "++ Indent right twice sh-basic-offset")
1119 (const :tag "--" :value --
1120 :menu-tag "-- Indent left twice sh-basic-offset")
1121 (const :tag "* " :value *
1122 :menu-tag "* Indent right half sh-basic-offset")
1123 (const :tag "/ " :value /
1124 :menu-tag "/ Indent left half sh-basic-offset")))
1125
1126 (defcustom sh-indent-for-else 0
1127 "*How much to indent an `else' relative to its `if'. Usually 0."
1128 :type `(choice
1129 (integer :menu-tag "A number (positive=>indent right)"
1130 :tag "A number")
1131 (const :tag "--") ;; separator!
1132 ,@ sh-symbol-list
1133 )
1134 :group 'sh-indentation)
1135
1136 (defconst sh-number-or-symbol-list
1137 (append '((integer :menu-tag "A number (positive=>indent right)"
1138 :tag "A number")
1139 (const :tag "--")) ; separator
1140 sh-symbol-list))
1141
1142 (defcustom sh-indent-for-fi 0
1143 "*How much to indent a `fi' relative to its `if'. Usually 0."
1144 :type `(choice ,@ sh-number-or-symbol-list )
1145 :group 'sh-indentation)
1146
1147 (defcustom sh-indent-for-done 0
1148 "*How much to indent a `done' relative to its matching stmt. Usually 0."
1149 :type `(choice ,@ sh-number-or-symbol-list )
1150 :group 'sh-indentation)
1151
1152 (defcustom sh-indent-after-else '+
1153 "*How much to indent a statement after an `else' statement."
1154 :type `(choice ,@ sh-number-or-symbol-list )
1155 :group 'sh-indentation)
1156
1157 (defcustom sh-indent-after-if '+
1158 "*How much to indent a statement after an `if' statement.
1159 This includes lines after `else' and `elif' statements, too, but
1160 does not affect the `else', `elif' or `fi' statements themselves."
1161 :type `(choice ,@ sh-number-or-symbol-list )
1162 :group 'sh-indentation)
1163
1164 (defcustom sh-indent-for-then 0
1165 "*How much to indent a `then' relative to its `if'."
1166 :type `(choice ,@ sh-number-or-symbol-list )
1167 :group 'sh-indentation)
1168
1169 (defcustom sh-indent-for-do 0
1170 "*How much to indent a `do' statement.
1171 This is relative to the statement before the `do', typically a
1172 `while', `until', `for', `repeat' or `select' statement."
1173 :type `(choice ,@ sh-number-or-symbol-list)
1174 :group 'sh-indentation)
1175
1176 (defcustom sh-indent-after-do '+
1177 "*How much to indent a line after a `do' statement.
1178 This is used when the `do' is the first word of the line.
1179 This is relative to the statement before the `do', typically a
1180 `while', `until', `for', `repeat' or `select' statement."
1181 :type `(choice ,@ sh-number-or-symbol-list)
1182 :group 'sh-indentation)
1183
1184 (defcustom sh-indent-after-loop-construct '+
1185 "*How much to indent a statement after a loop construct.
1186
1187 This variable is used when the keyword `do' is on the same line as the
1188 loop statement (e.g., `until', `while' or `for').
1189 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1190 :type `(choice ,@ sh-number-or-symbol-list)
1191 :group 'sh-indentation)
1192
1193
1194 (defcustom sh-indent-after-done 0
1195 "*How much to indent a statement after a `done' keyword.
1196 Normally this is 0, which aligns the `done' to the matching
1197 looping construct line.
1198 Setting it non-zero allows you to have the `do' statement on a line
1199 by itself and align the done under to do."
1200 :type `(choice ,@ sh-number-or-symbol-list)
1201 :group 'sh-indentation)
1202
1203 (defcustom sh-indent-for-case-label '+
1204 "*How much to indent a case label statement.
1205 This is relative to the line containing the `case' statement."
1206 :type `(choice ,@ sh-number-or-symbol-list)
1207 :group 'sh-indentation)
1208
1209 (defcustom sh-indent-for-case-alt '++
1210 "*How much to indent statements after the case label.
1211 This is relative to the line containing the `case' statement."
1212 :type `(choice ,@ sh-number-or-symbol-list)
1213 :group 'sh-indentation)
1214
1215
1216 (defcustom sh-indent-for-continuation '+
1217 "*How much to indent for a continuation statement."
1218 :type `(choice ,@ sh-number-or-symbol-list)
1219 :group 'sh-indentation)
1220
1221 (defcustom sh-indent-after-open '+
1222 "*How much to indent after a line with an opening parenthesis or brace.
1223 For an open paren after a function, `sh-indent-after-function' is used."
1224 :type `(choice ,@ sh-number-or-symbol-list)
1225 :group 'sh-indentation)
1226
1227 (defcustom sh-indent-after-function '+
1228 "*How much to indent after a function line."
1229 :type `(choice ,@ sh-number-or-symbol-list)
1230 :group 'sh-indentation)
1231
1232 ;; These 2 are for the rc shell:
1233
1234 (defcustom sh-indent-after-switch '+
1235 "*How much to indent a `case' statement relative to the `switch' statement.
1236 This is for the rc shell."
1237 :type `(choice ,@ sh-number-or-symbol-list)
1238 :group 'sh-indentation)
1239
1240 (defcustom sh-indent-after-case '+
1241 "*How much to indent a statement relative to the `case' statement.
1242 This is for the rc shell."
1243 :type `(choice ,@ sh-number-or-symbol-list)
1244 :group 'sh-indentation)
1245
1246 (defcustom sh-backslash-column 48
1247 "*Column in which `sh-backslash-region' inserts backslashes."
1248 :type 'integer
1249 :group 'sh)
1250
1251 (defcustom sh-backslash-align t
1252 "*If non-nil, `sh-backslash-region' will align backslashes."
1253 :type 'boolean
1254 :group 'sh)
1255
1256 ;; Internal use - not designed to be changed by the user:
1257
1258 (defun sh-mkword-regexpr (word)
1259 "Make a regexp which matches WORD as a word.
1260 This specifically excludes an occurrence of WORD followed by
1261 punctuation characters like '-'."
1262 (concat word "\\([^-a-z0-9_]\\|$\\)"))
1263
1264 (defconst sh-re-done (sh-mkword-regexpr "done"))
1265
1266
1267 (defconst sh-kws-for-done
1268 '((sh . ( "while" "until" "for" ) )
1269 (bash . ( "while" "until" "for" "select" ) )
1270 (ksh88 . ( "while" "until" "for" "select" ) )
1271 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1272 "Which keywords can match the word `done' in this shell.")
1273
1274
1275 (defconst sh-indent-supported
1276 '((sh . t)
1277 (csh . nil)
1278 (rc . t))
1279 "Shell types that shell indenting can do something with.")
1280
1281 (defvar sh-indent-supported-here nil
1282 "Non-nil if we support indentation for the current buffer's shell type.")
1283
1284 (defconst sh-var-list
1285 '(
1286 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1287 sh-indent-after-do sh-indent-after-done
1288 sh-indent-after-else
1289 sh-indent-after-if
1290 sh-indent-after-loop-construct
1291 sh-indent-after-open
1292 sh-indent-comment
1293 sh-indent-for-case-alt
1294 sh-indent-for-case-label
1295 sh-indent-for-continuation
1296 sh-indent-for-do
1297 sh-indent-for-done
1298 sh-indent-for-else
1299 sh-indent-for-fi
1300 sh-indent-for-then
1301 )
1302 "A list of variables used by script mode to control indentation.
1303 This list is used when switching between buffer-local and global
1304 values of variables, and for the commands using indentation styles.")
1305
1306 (defvar sh-make-vars-local t
1307 "*Controls whether indentation variables are local to the buffer.
1308 If non-nil, indentation variables are made local initially.
1309 If nil, you can later make the variables local by invoking
1310 command `sh-make-vars-local'.
1311 The default is t because I assume that in one Emacs session one is
1312 frequently editing existing scripts with different styles.")
1313
1314 \f
1315 ;; mode-command and utility functions
1316
1317 ;;;###autoload
1318 (defun sh-mode ()
1319 "Major mode for editing shell scripts.
1320 This mode works for many shells, since they all have roughly the same syntax,
1321 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1322 Unless the file's magic number indicates the shell, your usual shell is
1323 assumed. Since filenames rarely give a clue, they are not further analyzed.
1324
1325 This mode adapts to the variations between shells (see `sh-set-shell') by
1326 means of an inheritance based feature lookup (see `sh-feature'). This
1327 mechanism applies to all variables (including skeletons) that pertain to
1328 shell-specific features.
1329
1330 The default style of this mode is that of Rosenblatt's Korn shell book.
1331 The syntax of the statements varies with the shell being used. The
1332 following commands are available, based on the current shell's syntax:
1333
1334 \\[sh-case] case statement
1335 \\[sh-for] for loop
1336 \\[sh-function] function definition
1337 \\[sh-if] if statement
1338 \\[sh-indexed-loop] indexed loop from 1 to n
1339 \\[sh-while-getopts] while getopts loop
1340 \\[sh-repeat] repeat loop
1341 \\[sh-select] select loop
1342 \\[sh-until] until loop
1343 \\[sh-while] while loop
1344
1345 For sh and rc shells indentation commands are:
1346 \\[sh-show-indent] Show the variable controlling this line's indentation.
1347 \\[sh-set-indent] Set then variable controlling this line's indentation.
1348 \\[sh-learn-line-indent] Change the indentation variable so this line
1349 would indent to the way it currently is.
1350 \\[sh-learn-buffer-indent] Set the indentation variables so the
1351 buffer indents as it currently is indented.
1352
1353
1354 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1355 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1356 \\[sh-end-of-command] Go to end of successive commands.
1357 \\[sh-beginning-of-command] Go to beginning of successive commands.
1358 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1359 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1360
1361 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1362 \{, (, [, ', \", `
1363 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1364
1365 If you generally program a shell different from your login shell you can
1366 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1367 indicate what shell it is use `sh-alias-alist' to translate.
1368
1369 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1370 with your script for an edit-interpret-debug cycle."
1371 (interactive)
1372 (kill-all-local-variables)
1373 (setq major-mode 'sh-mode
1374 mode-name "Shell-script")
1375 (use-local-map sh-mode-map)
1376 (make-local-variable 'skeleton-end-hook)
1377 (make-local-variable 'paragraph-start)
1378 (make-local-variable 'paragraph-separate)
1379 (make-local-variable 'comment-start)
1380 (make-local-variable 'comment-start-skip)
1381 (make-local-variable 'require-final-newline)
1382 (make-local-variable 'sh-header-marker)
1383 (make-local-variable 'sh-shell-file)
1384 (make-local-variable 'sh-shell)
1385 (make-local-variable 'skeleton-pair-alist)
1386 (make-local-variable 'skeleton-pair-filter)
1387 (make-local-variable 'comint-dynamic-complete-functions)
1388 (make-local-variable 'comint-prompt-regexp)
1389 (make-local-variable 'font-lock-defaults)
1390 (make-local-variable 'skeleton-filter)
1391 (make-local-variable 'skeleton-newline-indent-rigidly)
1392 (make-local-variable 'sh-shell-variables)
1393 (make-local-variable 'sh-shell-variables-initialized)
1394 (make-local-variable 'imenu-generic-expression)
1395 (make-local-variable 'sh-indent-supported-here)
1396 (make-local-variable 'skeleton-pair-default-alist)
1397 (setq skeleton-pair-default-alist sh-skeleton-pair-default-alist)
1398 (setq skeleton-end-hook (lambda ()
1399 (or (eolp) (newline) (indent-relative)))
1400 paragraph-start (concat page-delimiter "\\|$")
1401 paragraph-separate paragraph-start
1402 comment-start "# "
1403 comment-start-skip "#+[\t ]*"
1404 local-abbrev-table sh-mode-abbrev-table
1405 comint-dynamic-complete-functions sh-dynamic-complete-functions
1406 ;; we can't look if previous line ended with `\'
1407 comint-prompt-regexp "^[ \t]*"
1408 imenu-case-fold-search nil
1409 font-lock-defaults
1410 `((sh-font-lock-keywords
1411 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1412 nil nil
1413 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1414 (font-lock-syntactic-keywords . sh-font-lock-syntactic-keywords)
1415 (font-lock-syntactic-face-function
1416 . sh-font-lock-syntactic-face-function))
1417 skeleton-pair-alist '((?` _ ?`))
1418 skeleton-pair-filter 'sh-quoted-p
1419 skeleton-further-elements '((< '(- (min sh-indentation
1420 (current-column)))))
1421 skeleton-filter 'sh-feature
1422 skeleton-newline-indent-rigidly t
1423 sh-indent-supported-here nil)
1424 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1425 ;; Parse or insert magic number for exec, and set all variables depending
1426 ;; on the shell thus determined.
1427 (let ((interpreter
1428 (save-excursion
1429 (goto-char (point-min))
1430 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1431 (match-string 2))
1432 ((and buffer-file-name
1433 (string-match "\\.m?spec\\'" buffer-file-name))
1434 "rpm")))))
1435 (sh-set-shell (or interpreter sh-shell-file) nil nil))
1436 (run-mode-hooks 'sh-mode-hook))
1437
1438 ;;;###autoload
1439 (defalias 'shell-script-mode 'sh-mode)
1440
1441
1442 (defun sh-font-lock-keywords (&optional keywords)
1443 "Function to get simple fontification based on `sh-font-lock-keywords'.
1444 This adds rules for comments and assignments."
1445 (sh-feature sh-font-lock-keywords-var
1446 (when (stringp (sh-feature sh-assignment-regexp))
1447 (lambda (list)
1448 `((,(sh-feature sh-assignment-regexp)
1449 1 font-lock-variable-name-face)
1450 ,@keywords
1451 ,@list
1452 ,@executable-font-lock-keywords)))))
1453
1454 (defun sh-font-lock-keywords-1 (&optional builtins)
1455 "Function to get better fontification including keywords."
1456 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1457 (regexp-opt (sh-feature sh-leading-keywords) t)
1458 "[ \t]+\\)?"
1459 (regexp-opt (append (sh-feature sh-leading-keywords)
1460 (sh-feature sh-other-keywords))
1461 t))))
1462 (sh-font-lock-keywords
1463 `(,@(if builtins
1464 `((,(concat keywords "[ \t]+\\)?"
1465 (regexp-opt (sh-feature sh-builtins) t)
1466 "\\>")
1467 (2 font-lock-keyword-face nil t)
1468 (6 font-lock-builtin-face))
1469 ,@(sh-feature sh-font-lock-keywords-var-2)))
1470 (,(concat keywords "\\)\\>")
1471 2 font-lock-keyword-face)
1472 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1473
1474 (defun sh-font-lock-keywords-2 ()
1475 "Function to get better fontification including keywords and builtins."
1476 (sh-font-lock-keywords-1 t))
1477
1478
1479 (defvar sh-regexp-for-done nil
1480 "A buffer-local regexp to match opening keyword for done.")
1481
1482 (defvar sh-kw-alist nil
1483 "A buffer-local, since it is shell-type dependent, list of keywords.")
1484
1485 ;; ( key-word first-on-this on-prev-line )
1486 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1487 ;; having 3 elements:
1488 ;; a keyword
1489 ;; a rule to check when the keyword appears on "this" line
1490 ;; a rule to check when the keyword appears on "the previous" line
1491 ;; The keyword is usually a string and is the first word on a line.
1492 ;; If this keyword appears on the line whose indentation is to be
1493 ;; calculated, the rule in element 2 is called. If this returns
1494 ;; non-zero, the resulting point (which may be changed by the rule)
1495 ;; is used as the default indentation.
1496 ;; If it returned false or the keyword was not found in the table,
1497 ;; then the keyword from the previous line is looked up and the rule
1498 ;; in element 3 is called. In this case, however,
1499 ;; `sh-get-indent-info' does not stop but may keep going and test
1500 ;; other keywords against rules in element 3. This is because the
1501 ;; preceding line could have, for example, an opening "if" and an
1502 ;; opening "while" keyword and we need to add the indentation offsets
1503 ;; for both.
1504 ;;
1505 (defconst sh-kw
1506 '((sh
1507 ("if" nil sh-handle-prev-if)
1508 ("elif" sh-handle-this-else sh-handle-prev-else)
1509 ("else" sh-handle-this-else sh-handle-prev-else)
1510 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1511 ("then" sh-handle-this-then sh-handle-prev-then)
1512 ("(" nil sh-handle-prev-open)
1513 ("{" nil sh-handle-prev-open)
1514 ("[" nil sh-handle-prev-open)
1515 ("}" sh-handle-this-close nil)
1516 (")" sh-handle-this-close nil)
1517 ("]" sh-handle-this-close nil)
1518 ("case" nil sh-handle-prev-case)
1519 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1520 (case-label nil sh-handle-after-case-label) ;; ???
1521 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1522 ("done" sh-handle-this-done sh-handle-prev-done)
1523 ("do" sh-handle-this-do sh-handle-prev-do))
1524
1525 ;; Note: we don't need specific stuff for bash and zsh shells;
1526 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1527 ;; these shells use.
1528 (rc
1529 ("{" nil sh-handle-prev-open)
1530 ("}" sh-handle-this-close nil)
1531 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1532
1533
1534
1535 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1536 "Set this buffer's shell to SHELL (a string).
1537 When used interactively, insert the proper starting #!-line,
1538 and make the visited file executable via `executable-set-magic',
1539 perhaps querying depending on the value of `executable-query'.
1540
1541 When this function is called noninteractively, INSERT-FLAG (the third
1542 argument) controls whether to insert a #!-line and think about making
1543 the visited file executable, and NO-QUERY-FLAG (the second argument)
1544 controls whether to query about making the visited file executable.
1545
1546 Calls the value of `sh-set-shell-hook' if set."
1547 (interactive (list (completing-read (format "Shell \(default %s\): "
1548 sh-shell-file)
1549 interpreter-mode-alist
1550 (lambda (x) (eq (cdr x) 'sh-mode))
1551 nil nil nil sh-shell-file)
1552 (eq executable-query 'function)
1553 t))
1554 (if (string-match "\\.exe\\'" shell)
1555 (setq shell (substring shell 0 (match-beginning 0))))
1556 (setq sh-shell (intern (file-name-nondirectory shell))
1557 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1558 sh-shell))
1559 (if insert-flag
1560 (setq sh-shell-file
1561 (executable-set-magic shell (sh-feature sh-shell-arg)
1562 no-query-flag insert-flag)))
1563 (let ((tem (sh-feature sh-require-final-newline)))
1564 (if (eq tem t)
1565 (setq require-final-newline mode-require-final-newline)))
1566 (setq
1567 mode-line-process (format "[%s]" sh-shell)
1568 sh-shell-variables nil
1569 sh-shell-variables-initialized nil
1570 imenu-generic-expression (sh-feature sh-imenu-generic-expression))
1571 (make-local-variable 'sh-mode-syntax-table)
1572 (let ((tem (sh-feature sh-mode-syntax-table-input)))
1573 (setq sh-mode-syntax-table
1574 (if tem (apply 'sh-mode-syntax-table tem)
1575 sh-mode-default-syntax-table)))
1576 (set-syntax-table sh-mode-syntax-table)
1577 (dolist (var (sh-feature sh-variables))
1578 (sh-remember-variable var))
1579 (make-local-variable 'indent-line-function)
1580 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1581 (progn
1582 (message "Setting up indent for shell type %s" sh-shell)
1583 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1584 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1585 (let ((regexp (sh-feature sh-kws-for-done)))
1586 (if regexp
1587 (set (make-local-variable 'sh-regexp-for-done)
1588 (sh-mkword-regexpr (regexp-opt regexp t)))))
1589 (message "setting up indent stuff")
1590 ;; sh-mode has already made indent-line-function local
1591 ;; but do it in case this is called before that.
1592 (setq indent-line-function 'sh-indent-line)
1593 (if sh-make-vars-local
1594 (sh-make-vars-local))
1595 (message "Indentation setup for shell type %s" sh-shell))
1596 (message "No indentation for this shell type.")
1597 (setq indent-line-function 'sh-basic-indent-line))
1598 (when font-lock-mode
1599 (setq font-lock-set-defaults nil)
1600 (font-lock-set-defaults)
1601 (font-lock-fontify-buffer))
1602 (run-hooks 'sh-set-shell-hook))
1603
1604
1605 (defun sh-feature (alist &optional function)
1606 "Index ALIST by the current shell.
1607 If ALIST isn't a list where every element is a cons, it is returned as is.
1608 Else indexing follows an inheritance logic which works in two ways:
1609
1610 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1611 the alist contains no value for the current shell.
1612 The ultimate default is always `sh'.
1613
1614 - If the value thus looked up is a list starting with `sh-append',
1615 we call the function `sh-append' with the rest of the list as
1616 arguments, and use the value. However, the next element of the
1617 list is not used as-is; instead, we look it up recursively
1618 in ALIST to allow the function called to define the value for
1619 one shell to be derived from another shell.
1620 The value thus determined is physically replaced into the alist.
1621
1622 If FUNCTION is non-nil, it is called with one argument,
1623 the value thus obtained, and the result is used instead."
1624 (or (if (consp alist)
1625 ;; Check for something that isn't a valid alist.
1626 (let ((l alist))
1627 (while (and l (consp (car l)))
1628 (setq l (cdr l)))
1629 (if l alist)))
1630
1631 (let ((orig-sh-shell sh-shell))
1632 (let ((sh-shell sh-shell)
1633 elt val)
1634 (while (and sh-shell
1635 (not (setq elt (assq sh-shell alist))))
1636 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1637 ;; If the shell is not known, treat it as sh.
1638 (unless elt
1639 (setq elt (assq 'sh alist)))
1640 (setq val (cdr elt))
1641 (if (and (consp val)
1642 (memq (car val) '(sh-append sh-modify)))
1643 (setq val
1644 (apply (car val)
1645 ;; Refer to the value for a different shell,
1646 ;; as a kind of inheritance.
1647 (let ((sh-shell (car (cdr val))))
1648 (sh-feature alist))
1649 (cddr val))))
1650 (if function
1651 (setq sh-shell orig-sh-shell
1652 val (funcall function val)))
1653 val))))
1654
1655
1656
1657 ;; I commented this out because nobody calls it -- rms.
1658 ;;(defun sh-abbrevs (ancestor &rest list)
1659 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1660 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1661 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1662 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1663 ;;EXPANSION may be either a string or a skeleton command."
1664 ;; (or (if (boundp sh-shell)
1665 ;; (symbol-value sh-shell))
1666 ;; (progn
1667 ;; (if (listp ancestor)
1668 ;; (nconc list ancestor))
1669 ;; (define-abbrev-table sh-shell ())
1670 ;; (if (vectorp ancestor)
1671 ;; (mapatoms (lambda (atom)
1672 ;; (or (eq atom 0)
1673 ;; (define-abbrev (symbol-value sh-shell)
1674 ;; (symbol-name atom)
1675 ;; (symbol-value atom)
1676 ;; (symbol-function atom))))
1677 ;; ancestor))
1678 ;; (while list
1679 ;; (define-abbrev (symbol-value sh-shell)
1680 ;; (car list)
1681 ;; (if (stringp (car (cdr list)))
1682 ;; (car (cdr list))
1683 ;; "")
1684 ;; (if (symbolp (car (cdr list)))
1685 ;; (car (cdr list))))
1686 ;; (setq list (cdr (cdr list)))))
1687 ;; (symbol-value sh-shell)))
1688
1689
1690 (defun sh-append (ancestor &rest list)
1691 "Return list composed of first argument (a list) physically appended to rest."
1692 (nconc list ancestor))
1693
1694
1695 (defun sh-modify (skeleton &rest list)
1696 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1697 (setq skeleton (copy-sequence skeleton))
1698 (while list
1699 (setcar (or (nthcdr (car list) skeleton)
1700 (error "Index %d out of bounds" (car list)))
1701 (car (cdr list)))
1702 (setq list (nthcdr 2 list)))
1703 skeleton)
1704
1705
1706 (defun sh-basic-indent-line ()
1707 "Indent a line for Sh mode (shell script mode).
1708 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1709 Lines containing only comments are considered empty."
1710 (interactive)
1711 (let ((previous (save-excursion
1712 (while (and (progn (beginning-of-line)
1713 (not (bobp)))
1714 (progn
1715 (forward-line -1)
1716 (back-to-indentation)
1717 (or (eolp)
1718 (eq (following-char) ?#)))))
1719 (current-column)))
1720 current)
1721 (save-excursion
1722 (indent-to (if (eq this-command 'newline-and-indent)
1723 previous
1724 (if (< (current-column)
1725 (setq current (progn (back-to-indentation)
1726 (current-column))))
1727 (if (eolp) previous 0)
1728 (delete-region (point)
1729 (progn (beginning-of-line) (point)))
1730 (if (eolp)
1731 (max previous (* (1+ (/ current sh-indentation))
1732 sh-indentation))
1733 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1734 (if (< (current-column) (current-indentation))
1735 (skip-chars-forward " \t"))))
1736
1737
1738 (defun sh-execute-region (start end &optional flag)
1739 "Pass optional header and region to a subshell for noninteractive execution.
1740 The working directory is that of the buffer, and only environment variables
1741 are already set which is why you can mark a header within the script.
1742
1743 With a positive prefix ARG, instead of sending region, define header from
1744 beginning of buffer to point. With a negative prefix ARG, instead of sending
1745 region, clear header."
1746 (interactive "r\nP")
1747 (if flag
1748 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1749 (point-marker)))
1750 (if sh-header-marker
1751 (save-excursion
1752 (let (buffer-undo-list)
1753 (goto-char sh-header-marker)
1754 (append-to-buffer (current-buffer) start end)
1755 (shell-command-on-region (point-min)
1756 (setq end (+ sh-header-marker
1757 (- end start)))
1758 sh-shell-file)
1759 (delete-region sh-header-marker end)))
1760 (shell-command-on-region start end (concat sh-shell-file " -")))))
1761
1762
1763 (defun sh-remember-variable (var)
1764 "Make VARIABLE available for future completing reads in this buffer."
1765 (or (< (length var) sh-remember-variable-min)
1766 (getenv var)
1767 (assoc var sh-shell-variables)
1768 (push (cons var var) sh-shell-variables))
1769 var)
1770
1771
1772
1773 (defun sh-quoted-p ()
1774 "Is point preceded by an odd number of backslashes?"
1775 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1776 \f
1777 ;; Indentation stuff.
1778 (defun sh-must-support-indent ()
1779 "*Signal an error if the shell type for this buffer is not supported.
1780 Also, the buffer must be in Shell-script mode."
1781 (unless sh-indent-supported-here
1782 (error "This buffer's shell does not support indentation through Emacs")))
1783
1784 (defun sh-make-vars-local ()
1785 "Make the indentation variables local to this buffer.
1786 Normally they already are local. This command is provided in case
1787 variable `sh-make-vars-local' has been set to nil.
1788
1789 To revert all these variables to the global values, use
1790 command `sh-reset-indent-vars-to-global-values'."
1791 (interactive)
1792 (mapcar 'make-local-variable sh-var-list)
1793 (message "Indentation variable are now local."))
1794
1795 (defun sh-reset-indent-vars-to-global-values ()
1796 "Reset local indentation variables to the global values.
1797 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1798 (interactive)
1799 (mapcar 'kill-local-variable sh-var-list)
1800 (if sh-make-vars-local
1801 (mapcar 'make-local-variable sh-var-list)))
1802
1803
1804 ;; Theoretically these are only needed in shell and derived modes.
1805 ;; However, the routines which use them are only called in those modes.
1806 (defconst sh-special-keywords "then\\|do")
1807
1808 (defun sh-help-string-for-variable (var)
1809 "Construct a string for `sh-read-variable' when changing variable VAR ."
1810 (let ((msg (documentation-property var 'variable-documentation))
1811 (msg2 ""))
1812 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
1813 (setq msg2
1814 (format "\n
1815 You can enter a number (positive to increase indentation,
1816 negative to decrease indentation, zero for no change to indentation).
1817
1818 Or, you can enter one of the following symbols which are relative to
1819 the value of variable `sh-basic-offset'
1820 which in this buffer is currently %s.
1821
1822 \t%s."
1823 sh-basic-offset
1824 (mapconcat (lambda (x)
1825 (nth (1- (length x)) x))
1826 sh-symbol-list "\n\t"))))
1827 (concat
1828 ;; The following shows the global not the local value!
1829 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1830 msg msg2)))
1831
1832 (defun sh-read-variable (var)
1833 "Read a new value for indentation variable VAR."
1834 (interactive "*variable? ") ;; to test
1835 (let ((minibuffer-help-form `(sh-help-string-for-variable
1836 (quote ,var)))
1837 val)
1838 (setq val (read-from-minibuffer
1839 (format "New value for %s (press %s for help): "
1840 var (single-key-description help-char))
1841 (format "%s" (symbol-value var))
1842 nil t))
1843 val))
1844
1845
1846
1847 (defun sh-in-comment-or-string (start)
1848 "Return non-nil if START is in a comment or string."
1849 (save-excursion
1850 (let ((state (syntax-ppss start)))
1851 (or (nth 3 state) (nth 4 state)))))
1852
1853 (defun sh-goto-matching-if ()
1854 "Go to the matching if for a fi.
1855 This handles nested if..fi pairs."
1856 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1857 (if found
1858 (goto-char found))))
1859
1860
1861 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1862 ;; line whose indentation is being handled contain XXX;
1863 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1864
1865 (defun sh-handle-prev-if ()
1866 (list '(+ sh-indent-after-if)))
1867
1868 (defun sh-handle-this-else ()
1869 (if (sh-goto-matching-if)
1870 ;; (list "aligned to if")
1871 (list "aligned to if" '(+ sh-indent-for-else))
1872 nil
1873 ))
1874
1875 (defun sh-handle-prev-else ()
1876 (if (sh-goto-matching-if)
1877 (list '(+ sh-indent-after-if))
1878 ))
1879
1880 (defun sh-handle-this-fi ()
1881 (if (sh-goto-matching-if)
1882 (list "aligned to if" '(+ sh-indent-for-fi))
1883 nil
1884 ))
1885
1886 (defun sh-handle-prev-fi ()
1887 ;; Why do we have this rule? Because we must go back to the if
1888 ;; to get its indent. We may continue back from there.
1889 ;; We return nil because we don't have anything to add to result,
1890 ;; the side affect of setting align-point is all that matters.
1891 ;; we could return a comment (a string) but I can't think of a good one...
1892 (sh-goto-matching-if)
1893 nil)
1894
1895 (defun sh-handle-this-then ()
1896 (let ((p (sh-goto-matching-if)))
1897 (if p
1898 (list '(+ sh-indent-for-then))
1899 )))
1900
1901 (defun sh-handle-prev-then ()
1902 (let ((p (sh-goto-matching-if)))
1903 (if p
1904 (list '(+ sh-indent-after-if))
1905 )))
1906
1907 (defun sh-handle-prev-open ()
1908 (save-excursion
1909 (let ((x (sh-prev-stmt)))
1910 (if (and x
1911 (progn
1912 (goto-char x)
1913 (or
1914 (looking-at "function\\b")
1915 (looking-at "\\s-*\\S-+\\s-*()")
1916 )))
1917 (list '(+ sh-indent-after-function))
1918 (list '(+ sh-indent-after-open)))
1919 )))
1920
1921 (defun sh-handle-this-close ()
1922 (forward-char 1) ;; move over ")"
1923 (if (sh-safe-forward-sexp -1)
1924 (list "aligned to opening paren")))
1925
1926 (defun sh-goto-matching-case ()
1927 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1928 (if found (goto-char found))))
1929
1930 (defun sh-handle-prev-case ()
1931 ;; This is typically called when point is on same line as a case
1932 ;; we shouldn't -- and can't find prev-case
1933 (if (looking-at ".*\\<case\\>")
1934 (list '(+ sh-indent-for-case-label))
1935 (error "We don't seem to be on a line with a case"))) ;; debug
1936
1937 (defun sh-handle-this-esac ()
1938 (if (sh-goto-matching-case)
1939 (list "aligned to matching case")))
1940
1941 (defun sh-handle-prev-esac ()
1942 (if (sh-goto-matching-case)
1943 (list "matching case")))
1944
1945 (defun sh-handle-after-case-label ()
1946 (if (sh-goto-matching-case)
1947 (list '(+ sh-indent-for-case-alt))))
1948
1949 (defun sh-handle-prev-case-alt-end ()
1950 (if (sh-goto-matching-case)
1951 (list '(+ sh-indent-for-case-label))))
1952
1953 (defun sh-safe-forward-sexp (&optional arg)
1954 "Try and do a `forward-sexp', but do not error.
1955 Return new point if successful, nil if an error occurred."
1956 (condition-case nil
1957 (progn
1958 (forward-sexp (or arg 1))
1959 (point)) ;; return point if successful
1960 (error
1961 (sh-debug "oops!(1) %d" (point))
1962 nil))) ;; return nil if fail
1963
1964 (defun sh-goto-match-for-done ()
1965 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
1966 (if found
1967 (goto-char found))))
1968
1969 (defun sh-handle-this-done ()
1970 (if (sh-goto-match-for-done)
1971 (list "aligned to do stmt" '(+ sh-indent-for-done))))
1972
1973 (defun sh-handle-prev-done ()
1974 (if (sh-goto-match-for-done)
1975 (list "previous done")))
1976
1977 (defun sh-handle-this-do ()
1978 (if (sh-goto-match-for-done)
1979 (list '(+ sh-indent-for-do))))
1980
1981 (defun sh-handle-prev-do ()
1982 (cond
1983 ((save-restriction
1984 (narrow-to-region
1985 (point)
1986 (save-excursion
1987 (beginning-of-line)
1988 (point)))
1989 (sh-goto-match-for-done))
1990 (sh-debug "match for done found on THIS line")
1991 (list '(+ sh-indent-after-loop-construct)))
1992 ((sh-goto-match-for-done)
1993 (sh-debug "match for done found on PREV line")
1994 (list '(+ sh-indent-after-do)))
1995 (t
1996 (message "match for done NOT found")
1997 nil)))
1998
1999 ;; for rc:
2000 (defun sh-find-prev-switch ()
2001 "Find the line for the switch keyword matching this line's case keyword."
2002 (re-search-backward "\\<switch\\>" nil t))
2003
2004 (defun sh-handle-this-rc-case ()
2005 (if (sh-find-prev-switch)
2006 (list '(+ sh-indent-after-switch))
2007 ;; (list '(+ sh-indent-for-case-label))
2008 nil))
2009
2010 (defun sh-handle-prev-rc-case ()
2011 (list '(+ sh-indent-after-case)))
2012
2013 (defun sh-check-rule (n thing)
2014 (let ((rule (nth n (assoc thing sh-kw-alist)))
2015 (val nil))
2016 (if rule
2017 (progn
2018 (setq val (funcall rule))
2019 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2020 n thing (point) rule val)))
2021 val))
2022
2023
2024 (defun sh-get-indent-info ()
2025 "Return indent-info for this line.
2026 This is a list. nil means the line is to be left as is.
2027 Otherwise it contains one or more of the following sublists:
2028 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2029 relative to. If present, this is always the first of the
2030 sublists. The indentation of the line in question is
2031 derived from the indentation of this point, possibly
2032 modified by subsequent sublists.
2033 \(+ VAR\)
2034 \(- VAR\) Get the value of variable VAR and add to or subtract from
2035 the indentation calculated so far.
2036 \(= VAR\) Get the value of variable VAR and *replace* the
2037 indentation with its value. This only occurs for
2038 special variables such as `sh-indent-comment'.
2039 STRING This is ignored for the purposes of calculating
2040 indentation, it is printed in certain cases to help show
2041 what the indentation is based on."
2042 ;; See comments before `sh-kw'.
2043 (save-excursion
2044 (let ((have-result nil)
2045 this-kw
2046 start
2047 val
2048 (result nil)
2049 (align-point nil)
2050 prev-line-end x)
2051 (beginning-of-line)
2052 ;; Note: setting result to t means we are done and will return nil.
2053 ;;(This function never returns just t.)
2054 (cond
2055 ((or (and (boundp 'font-lock-string-face) (not (bobp))
2056 (eq (get-text-property (1- (point)) 'face)
2057 font-lock-string-face))
2058 (eq (get-text-property (point) 'face) sh-heredoc-face))
2059 (setq result t)
2060 (setq have-result t))
2061 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2062 (if (bobp)
2063 (setq result t) ;; return nil if 1st line!
2064 (setq result (list '(= sh-indent-comment)))
2065 ;; we still need to get previous line in case
2066 ;; sh-indent-comment is t (indent as normal)
2067 (setq align-point (sh-prev-line nil))
2068 (setq have-result nil)
2069 ))
2070 ) ;; cond
2071
2072 (unless have-result
2073 ;; Continuation lines are handled specially
2074 (if (sh-this-is-a-continuation)
2075 (progn
2076 (setq result
2077 (if (save-excursion
2078 (beginning-of-line)
2079 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2080 ;; By convention, if the continuation \ is not
2081 ;; preceded by a SPC or a TAB it means that the line
2082 ;; is cut at a place where spaces cannot be freely
2083 ;; added/removed. I.e. do not indent the line.
2084 (list '(= nil))
2085 ;; We assume the line being continued is already
2086 ;; properly indented...
2087 ;; (setq prev-line-end (sh-prev-line))
2088 (setq align-point (sh-prev-line nil))
2089 (list '(+ sh-indent-for-continuation))))
2090 (setq have-result t))
2091 (beginning-of-line)
2092 (skip-chars-forward " \t")
2093 (setq this-kw (sh-get-kw)))
2094
2095 ;; Handle "this" keyword: first word on the line we're
2096 ;; calculating indentation info for.
2097 (if this-kw
2098 (if (setq val (sh-check-rule 1 this-kw))
2099 (progn
2100 (setq align-point (point))
2101 (sh-debug
2102 "this - setting align-point to %d" align-point)
2103 (setq result (append result val))
2104 (setq have-result t)
2105 ;; set prev-line to continue processing remainder
2106 ;; of this line as a previous line
2107 (setq prev-line-end (point))
2108 ))))
2109
2110 (unless have-result
2111 (setq prev-line-end (sh-prev-line 'end)))
2112
2113 (if prev-line-end
2114 (save-excursion
2115 ;; We start off at beginning of this line.
2116 ;; Scan previous statements while this is <=
2117 ;; start of previous line.
2118 (setq start (point)) ;; for debug only
2119 (goto-char prev-line-end)
2120 (setq x t)
2121 (while (and x (setq x (sh-prev-thing)))
2122 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2123 (cond
2124 ((and (equal x ")")
2125 (equal (get-text-property (1- (point)) 'syntax-table)
2126 sh-st-punc))
2127 (sh-debug "Case label) here")
2128 (setq x 'case-label)
2129 (if (setq val (sh-check-rule 2 x))
2130 (progn
2131 (setq result (append result val))
2132 (setq align-point (point))))
2133 (or (bobp)
2134 (forward-char -1))
2135 (skip-chars-forward "[a-z0-9]*?")
2136 )
2137 ((string-match "[])}]" x)
2138 (setq x (sh-safe-forward-sexp -1))
2139 (if x
2140 (progn
2141 (setq align-point (point))
2142 (setq result (append result
2143 (list "aligned to opening paren")))
2144 )))
2145 ((string-match "[[({]" x)
2146 (sh-debug "Checking special thing: %s" x)
2147 (if (setq val (sh-check-rule 2 x))
2148 (setq result (append result val)))
2149 (forward-char -1)
2150 (setq align-point (point)))
2151 ((string-match "[\"'`]" x)
2152 (sh-debug "Skipping back for %s" x)
2153 ;; this was oops-2
2154 (setq x (sh-safe-forward-sexp -1)))
2155 ((stringp x)
2156 (sh-debug "Checking string %s at %s" x (point))
2157 (if (setq val (sh-check-rule 2 x))
2158 ;; (or (eq t (car val))
2159 ;; (eq t (car (car val))))
2160 (setq result (append result val)))
2161 ;; not sure about this test Wed Jan 27 23:48:35 1999
2162 (setq align-point (point))
2163 (unless (bolp)
2164 (forward-char -1)))
2165 (t
2166 (error "Don't know what to do with %s" x))
2167 )
2168 ) ;; while
2169 (sh-debug "result is %s" result)
2170 )
2171 (sh-debug "No prev line!")
2172 (sh-debug "result: %s align-point: %s" result align-point)
2173 )
2174
2175 (if align-point
2176 ;; was: (setq result (append result (list (list t align-point))))
2177 (setq result (append (list (list t align-point)) result))
2178 )
2179 (sh-debug "result is now: %s" result)
2180
2181 (or result
2182 (setq result (list (if prev-line-end
2183 (list t prev-line-end)
2184 (list '= 'sh-first-lines-indent)))))
2185
2186 (if (eq result t)
2187 (setq result nil))
2188 (sh-debug "result is: %s" result)
2189 result
2190 ) ;; let
2191 ))
2192
2193
2194 (defun sh-get-indent-var-for-line (&optional info)
2195 "Return the variable controlling indentation for this line.
2196 If there is not [just] one such variable, return a string
2197 indicating the problem.
2198 If INFO is supplied it is used, else it is calculated."
2199 (let ((var nil)
2200 (result nil)
2201 (reason nil)
2202 sym elt)
2203 (or info
2204 (setq info (sh-get-indent-info)))
2205 (if (null info)
2206 (setq result "this line to be left as is")
2207 (while (and info (null result))
2208 (setq elt (car info))
2209 (cond
2210 ((stringp elt)
2211 (setq reason elt)
2212 )
2213 ((not (listp elt))
2214 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2215 ;; so it is a list
2216 ((eq t (car elt))
2217 ) ;; nothing
2218 ((symbolp (setq sym (nth 1 elt)))
2219 ;; A bit of a kludge - when we see the sh-indent-comment
2220 ;; ignore other variables. Otherwise it is tricky to
2221 ;; "learn" the comment indentation.
2222 (if (eq var 'sh-indent-comment)
2223 (setq result var)
2224 (if var
2225 (setq result
2226 "this line is controlled by more than 1 variable.")
2227 (setq var sym))))
2228 (t
2229 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2230 (setq info (cdr info))
2231 ))
2232 (or result
2233 (setq result var))
2234 (or result
2235 (setq result reason))
2236 (if (null result)
2237 ;; e.g. just had (t POS)
2238 (setq result "line has default indentation"))
2239 result))
2240
2241
2242
2243 ;; Finding the previous line isn't trivial.
2244 ;; We must *always* go back one more and see if that is a continuation
2245 ;; line -- it is the PREVIOUS line which is continued, not the one
2246 ;; we are going to!
2247 ;; Also, we want to treat a whole "here document" as one big line,
2248 ;; because we may want to a align to the beginning of it.
2249 ;;
2250 ;; What we do:
2251 ;; - go back to previous non-empty line
2252 ;; - if this is in a here-document, go to the beginning of it
2253 ;; - while previous line is continued, go back one line
2254 (defun sh-prev-line (&optional end)
2255 "Back to end of previous non-comment non-empty line.
2256 Go to beginning of logical line unless END is non-nil, in which case
2257 we go to the end of the previous line and do not check for continuations."
2258 (save-excursion
2259 (beginning-of-line)
2260 (forward-comment (- (point-max)))
2261 (unless end (beginning-of-line))
2262 (when (and (not (bobp))
2263 (equal (get-text-property (1- (point)) 'face)
2264 sh-heredoc-face))
2265 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2266 (when p1
2267 (goto-char p1)
2268 (if end
2269 (end-of-line)
2270 (beginning-of-line)))))
2271 (unless end
2272 ;; we must check previous lines to see if they are continuation lines
2273 ;; if so, we must return position of first of them
2274 (while (and (sh-this-is-a-continuation)
2275 (>= 0 (forward-line -1))))
2276 (beginning-of-line)
2277 (skip-chars-forward " \t"))
2278 (point)))
2279
2280
2281 (defun sh-prev-stmt ()
2282 "Return the address of the previous stmt or nil."
2283 ;; This is used when we are trying to find a matching keyword.
2284 ;; Searching backward for the keyword would certainly be quicker, but
2285 ;; it is hard to remove "false matches" -- such as if the keyword
2286 ;; appears in a string or quote. This way is slower, but (I think) safer.
2287 (interactive)
2288 (save-excursion
2289 (let ((going t)
2290 (start (point))
2291 (found nil)
2292 (prev nil))
2293 (skip-chars-backward " \t;|&({[")
2294 (while (and (not found)
2295 (not (bobp))
2296 going)
2297 ;; Do a backward-sexp if possible, else backup bit by bit...
2298 (if (sh-safe-forward-sexp -1)
2299 (progn
2300 (if (looking-at sh-special-keywords)
2301 (progn
2302 (setq found prev))
2303 (setq prev (point))
2304 ))
2305 ;; backward-sexp failed
2306 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2307 (forward-char -1))
2308 (if (bolp)
2309 (let ((back (sh-prev-line nil)))
2310 (if back
2311 (goto-char back)
2312 (setq going nil)))))
2313 (unless found
2314 (skip-chars-backward " \t")
2315 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2316 (eq (char-before) ?\;)
2317 (looking-at "\\s-*[|&]"))
2318 (setq found (point)))))
2319 (if found
2320 (goto-char found))
2321 (if found
2322 (progn
2323 (skip-chars-forward " \t|&({[")
2324 (setq found (point))))
2325 (if (>= (point) start)
2326 (progn
2327 (debug "We didn't move!")
2328 (setq found nil))
2329 (or found
2330 (sh-debug "Did not find prev stmt.")))
2331 found)))
2332
2333
2334 (defun sh-get-word ()
2335 "Get a shell word skipping whitespace from point."
2336 (interactive)
2337 (skip-chars-forward "\t ")
2338 (let ((start (point)))
2339 (while
2340 (if (looking-at "[\"'`]")
2341 (sh-safe-forward-sexp)
2342 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2343 (> (skip-chars-forward "-_a-zA-Z$0-9") 0)
2344 ))
2345 (buffer-substring start (point))
2346 ))
2347
2348 (defun sh-prev-thing ()
2349 "Return the previous thing this logical line."
2350 ;; This is called when `sh-get-indent-info' is working backwards on
2351 ;; the previous line(s) finding what keywords may be relevant for
2352 ;; indenting. It moves over sexps if possible, and will stop
2353 ;; on a ; and at the beginning of a line if it is not a continuation
2354 ;; line.
2355 ;;
2356 ;; Added a kludge for ";;"
2357 ;; Possible return values:
2358 ;; nil - nothing
2359 ;; a string - possibly a keyword
2360 ;;
2361 (if (bolp)
2362 nil
2363 (let (c min-point
2364 (start (point)))
2365 (save-restriction
2366 (narrow-to-region
2367 (if (sh-this-is-a-continuation)
2368 (setq min-point (sh-prev-line nil))
2369 (save-excursion
2370 (beginning-of-line)
2371 (setq min-point (point))))
2372 (point))
2373 (skip-chars-backward " \t;")
2374 (unless (looking-at "\\s-*;;")
2375 (skip-chars-backward "^)}];\"'`({[")
2376 (setq c (char-before))))
2377 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2378 (point) c start min-point)
2379 (if (< (point) min-point)
2380 (error "point %d < min-point %d" (point) min-point))
2381 (cond
2382 ((looking-at "\\s-*;;")
2383 ;; (message "Found ;; !")
2384 ";;")
2385 ((or (eq c ?\n)
2386 (eq c nil)
2387 (eq c ?\;))
2388 (save-excursion
2389 ;; skip forward over white space newline and \ at eol
2390 (skip-chars-forward " \t\n\\\\")
2391 (sh-debug "Now at %d start=%d" (point) start)
2392 (if (>= (point) start)
2393 (progn
2394 (sh-debug "point: %d >= start: %d" (point) start)
2395 nil)
2396 (sh-get-word))
2397 ))
2398 (t
2399 ;; c -- return a string
2400 (char-to-string c)
2401 ))
2402 )))
2403
2404
2405 (defun sh-this-is-a-continuation ()
2406 "Return non-nil if current line is a continuation of previous line."
2407 (save-excursion
2408 (and (zerop (forward-line -1))
2409 (looking-at ".*\\\\$")
2410 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2411 nil nil nil t))))))
2412
2413 (defun sh-get-kw (&optional where and-move)
2414 "Return first word of line from WHERE.
2415 If AND-MOVE is non-nil then move to end of word."
2416 (let ((start (point)))
2417 (if where
2418 (goto-char where))
2419 (prog1
2420 (buffer-substring (point)
2421 (progn (skip-chars-forward "^ \t\n;&")(point)))
2422 (unless and-move
2423 (goto-char start)))))
2424
2425 (defun sh-find-prev-matching (open close &optional depth)
2426 "Find a matching token for a set of opening and closing keywords.
2427 This takes into account that there may be nested open..close pairings.
2428 OPEN and CLOSE are regexps denoting the tokens to be matched.
2429 Optional parameter DEPTH (usually 1) says how many to look for."
2430 (let ((parse-sexp-ignore-comments t)
2431 prev)
2432 (setq depth (or depth 1))
2433 (save-excursion
2434 (condition-case nil
2435 (while (and
2436 (/= 0 depth)
2437 (not (bobp))
2438 (setq prev (sh-prev-stmt)))
2439 (goto-char prev)
2440 (save-excursion
2441 (if (looking-at "\\\\\n")
2442 (progn
2443 (forward-char 2)
2444 (skip-chars-forward " \t")))
2445 (cond
2446 ((looking-at open)
2447 (setq depth (1- depth))
2448 (sh-debug "found open at %d - depth = %d" (point) depth))
2449 ((looking-at close)
2450 (setq depth (1+ depth))
2451 (sh-debug "found close - depth = %d" depth))
2452 (t
2453 ))))
2454 (error nil))
2455 (if (eq depth 0)
2456 prev ;; (point)
2457 nil)
2458 )))
2459
2460
2461 (defun sh-var-value (var &optional ignore-error)
2462 "Return the value of variable VAR, interpreting symbols.
2463 It can also return t or nil.
2464 If an invalid value is found, throw an error unless Optional argument
2465 IGNORE-ERROR is non-nil."
2466 (let ((val (symbol-value var)))
2467 (cond
2468 ((numberp val)
2469 val)
2470 ((eq val t)
2471 val)
2472 ((null val)
2473 val)
2474 ((eq val '+)
2475 sh-basic-offset)
2476 ((eq val '-)
2477 (- sh-basic-offset))
2478 ((eq val '++)
2479 (* 2 sh-basic-offset))
2480 ((eq val '--)
2481 (* 2 (- sh-basic-offset)))
2482 ((eq val '*)
2483 (/ sh-basic-offset 2))
2484 ((eq val '/)
2485 (/ (- sh-basic-offset) 2))
2486 (t
2487 (if ignore-error
2488 (progn
2489 (message "Don't know how to handle %s's value of %s" var val)
2490 0)
2491 (error "Don't know how to handle %s's value of %s" var val))
2492 ))))
2493
2494 (defun sh-set-var-value (var value &optional no-symbol)
2495 "Set variable VAR to VALUE.
2496 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2497 can be represented by a symbol then do so."
2498 (cond
2499 (no-symbol
2500 (set var value))
2501 ((= value sh-basic-offset)
2502 (set var '+))
2503 ((= value (- sh-basic-offset))
2504 (set var '-))
2505 ((eq value (* 2 sh-basic-offset))
2506 (set var '++))
2507 ((eq value (* 2 (- sh-basic-offset)))
2508 (set var '--))
2509 ((eq value (/ sh-basic-offset 2))
2510 (set var '*))
2511 ((eq value (/ (- sh-basic-offset) 2))
2512 (set var '/))
2513 (t
2514 (set var value)))
2515 )
2516
2517
2518 (defun sh-calculate-indent (&optional info)
2519 "Return the indentation for the current line.
2520 If INFO is supplied it is used, else it is calculated from current line."
2521 (let ((ofs 0)
2522 (base-value 0)
2523 elt a b var val)
2524 (or info
2525 (setq info (sh-get-indent-info)))
2526 (when info
2527 (while info
2528 (sh-debug "info: %s ofs=%s" info ofs)
2529 (setq elt (car info))
2530 (cond
2531 ((stringp elt)) ;; do nothing?
2532 ((listp elt)
2533 (setq a (car (car info)))
2534 (setq b (nth 1 (car info)))
2535 (cond
2536 ((eq a t)
2537 (save-excursion
2538 (goto-char b)
2539 (setq val (current-indentation)))
2540 (setq base-value val))
2541 ((symbolp b)
2542 (setq val (sh-var-value b))
2543 (cond
2544 ((eq a '=)
2545 (cond
2546 ((null val)
2547 ;; no indentation
2548 ;; set info to nil so we stop immediately
2549 (setq base-value nil ofs nil info nil))
2550 ((eq val t) (setq ofs 0)) ;; indent as normal line
2551 (t
2552 ;; The following assume the (t POS) come first!
2553 (setq ofs val base-value 0)
2554 (setq info nil)))) ;; ? stop now
2555 ((eq a '+) (setq ofs (+ ofs val)))
2556 ((eq a '-) (setq ofs (- ofs val)))
2557 (t
2558 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2559 (t
2560 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2561 (t
2562 (error "sh-calculate-indent invalid elt %s" elt)))
2563 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2564 a b val base-value ofs)
2565 (setq info (cdr info)))
2566 ;; return value:
2567 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2568
2569 (cond
2570 ((or (null base-value)(null ofs))
2571 nil)
2572 ((and (numberp base-value)(numberp ofs))
2573 (sh-debug "base (%d) + ofs (%d) = %d"
2574 base-value ofs (+ base-value ofs))
2575 (+ base-value ofs)) ;; return value
2576 (t
2577 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2578 base-value ofs)
2579 nil)))))
2580
2581
2582 (defun sh-indent-line ()
2583 "Indent the current line."
2584 (interactive)
2585 (let ((indent (sh-calculate-indent))
2586 (pos (- (point-max) (point))))
2587 (when indent
2588 (beginning-of-line)
2589 (skip-chars-forward " \t")
2590 (indent-line-to indent)
2591 ;; If initial point was within line's indentation,
2592 ;; position after the indentation. Else stay at same point in text.
2593 (if (> (- (point-max) pos) (point))
2594 (goto-char (- (point-max) pos))))))
2595
2596
2597 (defun sh-blink (blinkpos &optional msg)
2598 "Move cursor momentarily to BLINKPOS and display MSG."
2599 ;; We can get here without it being a number on first line
2600 (if (numberp blinkpos)
2601 (save-excursion
2602 (goto-char blinkpos)
2603 (if msg (message "%s" msg) (message nil))
2604 (sit-for blink-matching-delay))
2605 (if msg (message "%s" msg) (message nil))))
2606
2607 (defun sh-show-indent (arg)
2608 "Show the how the currently line would be indented.
2609 This tells you which variable, if any, controls the indentation of
2610 this line.
2611 If optional arg ARG is non-null (called interactively with a prefix),
2612 a pop up window describes this variable.
2613 If variable `sh-blink' is non-nil then momentarily go to the line
2614 we are indenting relative to, if applicable."
2615 (interactive "P")
2616 (sh-must-support-indent)
2617 (let* ((info (sh-get-indent-info))
2618 (var (sh-get-indent-var-for-line info))
2619 (curr-indent (current-indentation))
2620 val msg)
2621 (if (stringp var)
2622 (message "%s" (setq msg var))
2623 (setq val (sh-calculate-indent info))
2624
2625 (if (eq curr-indent val)
2626 (setq msg (format "%s is %s" var (symbol-value var)))
2627 (setq msg
2628 (if val
2629 (format "%s (%s) would change indent from %d to: %d"
2630 var (symbol-value var) curr-indent val)
2631 (format "%s (%s) would leave line as is"
2632 var (symbol-value var)))
2633 ))
2634 (if (and arg var)
2635 (describe-variable var)))
2636 (if sh-blink
2637 (let ((info (sh-get-indent-info)))
2638 (if (and info (listp (car info))
2639 (eq (car (car info)) t))
2640 (sh-blink (nth 1 (car info)) msg)
2641 (message "%s" msg)))
2642 (message "%s" msg))
2643 ))
2644
2645 (defun sh-set-indent ()
2646 "Set the indentation for the current line.
2647 If the current line is controlled by an indentation variable, prompt
2648 for a new value for it."
2649 (interactive)
2650 (sh-must-support-indent)
2651 (let* ((info (sh-get-indent-info))
2652 (var (sh-get-indent-var-for-line info))
2653 val old-val indent-val)
2654 (if (stringp var)
2655 (message "Cannot set indent - %s" var)
2656 (setq old-val (symbol-value var))
2657 (setq val (sh-read-variable var))
2658 (condition-case nil
2659 (progn
2660 (set var val)
2661 (setq indent-val (sh-calculate-indent info))
2662 (if indent-val
2663 (message "Variable: %s Value: %s would indent to: %d"
2664 var (symbol-value var) indent-val)
2665 (message "Variable: %s Value: %s would leave line as is."
2666 var (symbol-value var)))
2667 ;; I'm not sure about this, indenting it now?
2668 ;; No. Because it would give the impression that an undo would
2669 ;; restore thing, but the value has been altered.
2670 ;; (sh-indent-line)
2671 )
2672 (error
2673 (set var old-val)
2674 (message "Bad value for %s, restoring to previous value %s"
2675 var old-val)
2676 (sit-for 1)
2677 nil))
2678 )))
2679
2680
2681 (defun sh-learn-line-indent (arg)
2682 "Learn how to indent a line as it currently is indented.
2683
2684 If there is an indentation variable which controls this line's indentation,
2685 then set it to a value which would indent the line the way it
2686 presently is.
2687
2688 If the value can be represented by one of the symbols then do so
2689 unless optional argument ARG (the prefix when interactive) is non-nil."
2690 (interactive "*P")
2691 (sh-must-support-indent)
2692 ;; I'm not sure if we show allow learning on an empty line.
2693 ;; Though it might occasionally be useful I think it usually
2694 ;; would just be confusing.
2695 (if (save-excursion
2696 (beginning-of-line)
2697 (looking-at "\\s-*$"))
2698 (message "sh-learn-line-indent ignores empty lines.")
2699 (let* ((info (sh-get-indent-info))
2700 (var (sh-get-indent-var-for-line info))
2701 ival sval diff new-val
2702 (no-symbol arg)
2703 (curr-indent (current-indentation)))
2704 (cond
2705 ((stringp var)
2706 (message "Cannot learn line - %s" var))
2707 ((eq var 'sh-indent-comment)
2708 ;; This is arbitrary...
2709 ;; - if curr-indent is 0, set to curr-indent
2710 ;; - else if it has the indentation of a "normal" line,
2711 ;; then set to t
2712 ;; - else set to curr-indent.
2713 (setq sh-indent-comment
2714 (if (= curr-indent 0)
2715 0
2716 (let* ((sh-indent-comment t)
2717 (val2 (sh-calculate-indent info)))
2718 (if (= val2 curr-indent)
2719 t
2720 curr-indent))))
2721 (message "%s set to %s" var (symbol-value var))
2722 )
2723 ((numberp (setq sval (sh-var-value var)))
2724 (setq ival (sh-calculate-indent info))
2725 (setq diff (- curr-indent ival))
2726
2727 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2728 curr-indent ival diff var sval)
2729 (setq new-val (+ sval diff))
2730 ;;; I commented out this because someone might want to replace
2731 ;;; a value of `+' with the current value of sh-basic-offset
2732 ;;; or vice-versa.
2733 ;;; (if (= 0 diff)
2734 ;;; (message "No change needed!")
2735 (sh-set-var-value var new-val no-symbol)
2736 (message "%s set to %s" var (symbol-value var))
2737 )
2738 (t
2739 (debug)
2740 (message "Cannot change %s" var))))))
2741
2742
2743
2744 (defun sh-mark-init (buffer)
2745 "Initialize a BUFFER to be used by `sh-mark-line'."
2746 (with-current-buffer (get-buffer-create buffer)
2747 (erase-buffer)
2748 (occur-mode)))
2749
2750
2751 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2752 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2753 Buffer BUFFER is in `occur-mode'.
2754 If ADD-LINENUM is non-nil the message is preceded by the line number.
2755 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2756 so that `occur-next' and `occur-prev' will work."
2757 (let ((m1 (make-marker))
2758 start
2759 (line ""))
2760 (when point
2761 (set-marker m1 point (current-buffer))
2762 (if add-linenum
2763 (setq line (format "%d: " (1+ (count-lines 1 point))))))
2764 (save-excursion
2765 (if (get-buffer buffer)
2766 (set-buffer (get-buffer buffer))
2767 (set-buffer (get-buffer-create buffer))
2768 (occur-mode)
2769 )
2770 (goto-char (point-max))
2771 (setq start (point))
2772 (insert line)
2773 (if occur-point
2774 (setq occur-point (point)))
2775 (insert message)
2776 (if point
2777 (add-text-properties
2778 start (point)
2779 '(mouse-face highlight
2780 help-echo "mouse-2: go to the line where I learned this")))
2781 (insert "\n")
2782 (if point
2783 (progn
2784 (put-text-property start (point) 'occur-target m1)
2785 (if occur-point
2786 (put-text-property start occur-point
2787 'occur-match t))
2788 ))
2789 )))
2790
2791
2792
2793 ;; Is this really worth having?
2794 (defvar sh-learned-buffer-hook nil
2795 "*An abnormal hook, called with an alist of learned variables.")
2796 ;; Example of how to use sh-learned-buffer-hook
2797 ;;
2798 ;; (defun what-i-learned (list)
2799 ;; (let ((p list))
2800 ;; (save-excursion
2801 ;; (set-buffer "*scratch*")
2802 ;; (goto-char (point-max))
2803 ;; (insert "(setq\n")
2804 ;; (while p
2805 ;; (insert (format " %s %s \n"
2806 ;; (nth 0 (car p)) (nth 1 (car p))))
2807 ;; (setq p (cdr p)))
2808 ;; (insert ")\n")
2809 ;; )))
2810 ;;
2811 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2812
2813
2814 ;; Originally this was sh-learn-region-indent (beg end)
2815 ;; However, in practice this was awkward so I changed it to
2816 ;; use the whole buffer. Use narrowing if needbe.
2817 (defun sh-learn-buffer-indent (&optional arg)
2818 "Learn how to indent the buffer the way it currently is.
2819
2820 Output in buffer \"*indent*\" shows any lines which have conflicting
2821 values of a variable, and the final value of all variables learned.
2822 This buffer is popped to automatically if there are any discrepancies.
2823
2824 If no prefix ARG is given, then variables are set to numbers.
2825 If a prefix arg is given, then variables are set to symbols when
2826 applicable -- e.g. to symbol `+' if the value is that of the
2827 basic indent.
2828 If a positive numerical prefix is given, then `sh-basic-offset'
2829 is set to the prefix's numerical value.
2830 Otherwise, sh-basic-offset may or may not be changed, according
2831 to the value of variable `sh-learn-basic-offset'.
2832
2833 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2834 function completes. The function is abnormal because it is called
2835 with an alist of variables learned. This feature may be changed or
2836 removed in the future.
2837
2838 This command can often take a long time to run."
2839 (interactive "P")
2840 (sh-must-support-indent)
2841 (save-excursion
2842 (goto-char (point-min))
2843 (let ((learned-var-list nil)
2844 (out-buffer "*indent*")
2845 (num-diffs 0)
2846 previous-set-info
2847 (max 17)
2848 vec
2849 msg
2850 (comment-col nil) ;; number if all same, t if seen diff values
2851 (comments-always-default t) ;; nil if we see one not default
2852 initial-msg
2853 (specified-basic-offset (and arg (numberp arg)
2854 (> arg 0)))
2855 (linenum 0)
2856 suggested)
2857 (setq vec (make-vector max 0))
2858 (sh-mark-init out-buffer)
2859
2860 (if specified-basic-offset
2861 (progn
2862 (setq sh-basic-offset arg)
2863 (setq initial-msg
2864 (format "Using specified sh-basic-offset of %d"
2865 sh-basic-offset)))
2866 (setq initial-msg
2867 (format "Initial value of sh-basic-offset: %s"
2868 sh-basic-offset)))
2869
2870 (while (< (point) (point-max))
2871 (setq linenum (1+ linenum))
2872 ;; (if (zerop (% linenum 10))
2873 (message "line %d" linenum)
2874 ;; )
2875 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2876 (let* ((sh-indent-comment t) ;; info must return default indent
2877 (info (sh-get-indent-info))
2878 (var (sh-get-indent-var-for-line info))
2879 sval ival diff new-val
2880 (curr-indent (current-indentation)))
2881 (cond
2882 ((null var)
2883 nil)
2884 ((stringp var)
2885 nil)
2886 ((numberp (setq sval (sh-var-value var 'no-error)))
2887 ;; the numberp excludes comments since sval will be t.
2888 (setq ival (sh-calculate-indent))
2889 (setq diff (- curr-indent ival))
2890 (setq new-val (+ sval diff))
2891 (sh-set-var-value var new-val 'no-symbol)
2892 (unless (looking-at "\\s-*#") ;; don't learn from comments
2893 (if (setq previous-set-info (assoc var learned-var-list))
2894 (progn
2895 ;; it was already there, is it same value ?
2896 (unless (eq (symbol-value var)
2897 (nth 1 previous-set-info))
2898 (sh-mark-line
2899 (format "Variable %s was set to %s"
2900 var (symbol-value var))
2901 (point) out-buffer t t)
2902 (sh-mark-line
2903 (format " but was previously set to %s"
2904 (nth 1 previous-set-info))
2905 (nth 2 previous-set-info) out-buffer t)
2906 (setq num-diffs (1+ num-diffs))
2907 ;; (delete previous-set-info learned-var-list)
2908 (setcdr previous-set-info
2909 (list (symbol-value var) (point)))
2910 )
2911 )
2912 (setq learned-var-list
2913 (append (list (list var (symbol-value var)
2914 (point)))
2915 learned-var-list)))
2916 (if (numberp new-val)
2917 (progn
2918 (sh-debug
2919 "This line's indent value: %d" new-val)
2920 (if (< new-val 0)
2921 (setq new-val (- new-val)))
2922 (if (< new-val max)
2923 (aset vec new-val (1+ (aref vec new-val))))))
2924 ))
2925 ((eq var 'sh-indent-comment)
2926 (unless (= curr-indent (sh-calculate-indent info))
2927 ;; this is not the default indentation
2928 (setq comments-always-default nil)
2929 (if comment-col ;; then we have see one before
2930 (or (eq comment-col curr-indent)
2931 (setq comment-col t)) ;; seen a different one
2932 (setq comment-col curr-indent))
2933 ))
2934 (t
2935 (sh-debug "Cannot learn this line!!!")
2936 ))
2937 (sh-debug
2938 "at %s learned-var-list is %s" (point) learned-var-list)
2939 ))
2940 (forward-line 1)
2941 ) ;; while
2942 (if sh-debug
2943 (progn
2944 (setq msg (format
2945 "comment-col = %s comments-always-default = %s"
2946 comment-col comments-always-default))
2947 ;; (message msg)
2948 (sh-mark-line msg nil out-buffer)))
2949 (cond
2950 ((eq comment-col 0)
2951 (setq msg "\nComments are all in 1st column.\n"))
2952 (comments-always-default
2953 (setq msg "\nComments follow default indentation.\n")
2954 (setq comment-col t))
2955 ((numberp comment-col)
2956 (setq msg (format "\nComments are in col %d." comment-col)))
2957 (t
2958 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
2959 (setq comment-col nil)
2960 ))
2961 (sh-debug msg)
2962 (sh-mark-line msg nil out-buffer)
2963
2964 (sh-mark-line initial-msg nil out-buffer t t)
2965
2966 (setq suggested (sh-guess-basic-offset vec))
2967
2968 (if (and suggested (not specified-basic-offset))
2969 (let ((new-value
2970 (cond
2971 ;; t => set it if we have a single value as a number
2972 ((and (eq sh-learn-basic-offset t) (numberp suggested))
2973 suggested)
2974 ;; other non-nil => set it if only one value was found
2975 (sh-learn-basic-offset
2976 (if (numberp suggested)
2977 suggested
2978 (if (= (length suggested) 1)
2979 (car suggested))))
2980 (t
2981 nil))))
2982 (if new-value
2983 (progn
2984 (setq learned-var-list
2985 (append (list (list 'sh-basic-offset
2986 (setq sh-basic-offset new-value)
2987 (point-max)))
2988 learned-var-list))
2989 ;; Not sure if we need to put this line in, since
2990 ;; it will appear in the "Learned variable settings".
2991 (sh-mark-line
2992 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
2993 nil out-buffer))
2994 (sh-mark-line
2995 (if (listp suggested)
2996 (format "Possible value(s) for sh-basic-offset: %s"
2997 (mapconcat 'int-to-string suggested " "))
2998 (format "Suggested sh-basic-offset: %d" suggested))
2999 nil out-buffer))))
3000
3001
3002 (setq learned-var-list
3003 (append (list (list 'sh-indent-comment comment-col (point-max)))
3004 learned-var-list))
3005 (setq sh-indent-comment comment-col)
3006 (let ((name (buffer-name)))
3007 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3008 (if arg
3009 ;; Set learned variables to symbolic rather than numeric
3010 ;; values where possible.
3011 (dolist (learned-var (reverse learned-var-list))
3012 (let ((var (car learned-var))
3013 (val (nth 1 learned-var)))
3014 (when (and (not (eq var 'sh-basic-offset))
3015 (numberp val))
3016 (sh-set-var-value var val)))))
3017 (dolist (learned-var (reverse learned-var-list))
3018 (let ((var (car learned-var)))
3019 (sh-mark-line (format " %s %s" var (symbol-value var))
3020 (nth 2 learned-var) out-buffer)))
3021 (with-current-buffer out-buffer
3022 (goto-char (point-min))
3023 (insert
3024 (format "Indentation values for buffer %s.\n" name)
3025 (format "%d indentation variable%s different values%s\n\n"
3026 num-diffs
3027 (if (= num-diffs 1)
3028 " has" "s have")
3029 (if (zerop num-diffs)
3030 "." ":"))
3031 )))
3032 ;; Are abnormal hooks considered bad form?
3033 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3034 (if (or sh-popup-occur-buffer (> num-diffs 0))
3035 (pop-to-buffer out-buffer))
3036 )))
3037
3038 (defun sh-guess-basic-offset (vec)
3039 "See if we can determine a reasonable value for `sh-basic-offset'.
3040 This is experimental, heuristic and arbitrary!
3041 Argument VEC is a vector of information collected by
3042 `sh-learn-buffer-indent'.
3043 Return values:
3044 number - there appears to be a good single value
3045 list of numbers - no obvious one, here is a list of one or more
3046 reasonable choices
3047 nil - we couldn't find a reasonable one."
3048 (let* ((max (1- (length vec)))
3049 (i 1)
3050 (totals (make-vector max 0)))
3051 (while (< i max)
3052 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
3053 (if (zerop (% i 2))
3054 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3055 (if (< (* i 2) max)
3056 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3057 (setq i (1+ i)))
3058
3059 (let ((x nil)
3060 (result nil)
3061 tot sum p)
3062 (setq i 1)
3063 (while (< i max)
3064 (if (/= (aref totals i) 0)
3065 (setq x (append x (list (cons i (aref totals i))))))
3066 (setq i (1+ i)))
3067
3068 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3069 (setq tot (apply '+ (append totals nil)))
3070 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3071 vec totals tot))
3072 (cond
3073 ((zerop (length x))
3074 (message "no values!")) ;; we return nil
3075 ((= (length x) 1)
3076 (message "only value is %d" (car (car x)))
3077 (setq result (car (car x)))) ;; return single value
3078 ((> (cdr (car x)) (/ tot 2))
3079 ;; 1st is > 50%
3080 (message "basic-offset is probably %d" (car (car x)))
3081 (setq result (car (car x)))) ;; again, return a single value
3082 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3083 ;; 1st is >= 2 * 2nd
3084 (message "basic-offset could be %d" (car (car x)))
3085 (setq result (car (car x))))
3086 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3087 ;; 1st & 2nd together >= 50% - return a list
3088 (setq p x sum 0 result nil)
3089 (while (and p
3090 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3091 (setq result (append result (list (car (car p)))))
3092 (setq p (cdr p)))
3093 (message "Possible choices for sh-basic-offset: %s"
3094 (mapconcat 'int-to-string result " ")))
3095 (t
3096 (message "No obvious value for sh-basic-offset. Perhaps %d"
3097 (car (car x)))
3098 ;; result is nil here
3099 ))
3100 result)))
3101
3102 ;; ========================================================================
3103
3104 ;; Styles -- a quick and dirty way of saving the indentation settings.
3105
3106 (defvar sh-styles-alist nil
3107 "A list of all known shell indentation styles.")
3108
3109 (defun sh-name-style (name &optional confirm-overwrite)
3110 "Name the current indentation settings as a style called NAME.
3111 If this name exists, the command will prompt whether it should be
3112 overwritten if
3113 - - it was called interactively with a prefix argument, or
3114 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3115 ;; (interactive "sName for this style: ")
3116 (interactive
3117 (list
3118 (read-from-minibuffer "Name for this style? " )
3119 (not current-prefix-arg)))
3120 (let ((slist (cons name
3121 (mapcar (lambda (var) (cons var (symbol-value var)))
3122 sh-var-list)))
3123 (style (assoc name sh-styles-alist)))
3124 (if style
3125 (if (and confirm-overwrite
3126 (not (y-or-n-p "This style exists. Overwrite it? ")))
3127 (message "Not changing style %s" name)
3128 (message "Updating style %s" name)
3129 (setcdr style (cdr slist)))
3130 (message "Creating new style %s" name)
3131 (push slist sh-styles-alist))))
3132
3133 (defun sh-load-style (name)
3134 "Set shell indentation values for this buffer from those in style NAME."
3135 (interactive (list (completing-read
3136 "Which style to use for this buffer? "
3137 sh-styles-alist nil t)))
3138 (let ((sl (assoc name sh-styles-alist)))
3139 (if (null sl)
3140 (error "sh-load-style - style %s not known" name)
3141 (dolist (var (cdr sl))
3142 (set (car var) (cdr var))))))
3143
3144 (defun sh-save-styles-to-buffer (buff)
3145 "Save all current styles in elisp to buffer BUFF.
3146 This is always added to the end of the buffer."
3147 (interactive (list
3148 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3149 (with-current-buffer (get-buffer-create buff)
3150 (goto-char (point-max))
3151 (insert "\n")
3152 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3153
3154
3155 \f
3156 ;; statement syntax-commands for various shells
3157
3158 ;; You are welcome to add the syntax or even completely new statements as
3159 ;; appropriate for your favorite shell.
3160
3161 (defconst sh-non-closing-paren
3162 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3163 ;; that inherits this property, which then confuses the indentation.
3164 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3165
3166 (define-skeleton sh-case
3167 "Insert a case/switch statement. See `sh-feature'."
3168 (csh "expression: "
3169 "switch( " str " )" \n
3170 > "case " (read-string "pattern: ") ?: \n
3171 > _ \n
3172 "breaksw" \n
3173 ( "other pattern, %s: "
3174 < "case " str ?: \n
3175 > _ \n
3176 "breaksw" \n)
3177 < "default:" \n
3178 > _ \n
3179 resume:
3180 < < "endsw" \n)
3181 (es)
3182 (rc "expression: "
3183 > "switch( " str " ) {" \n
3184 > "case " (read-string "pattern: ") \n
3185 > _ \n
3186 ( "other pattern, %s: "
3187 "case " str > \n
3188 > _ \n)
3189 "case *" > \n
3190 > _ \n
3191 resume:
3192 ?\} > \n)
3193 (sh "expression: "
3194 > "case " str " in" \n
3195 ( "pattern, %s: "
3196 > str sh-non-closing-paren \n
3197 > _ \n
3198 ";;" \n)
3199 > "*" sh-non-closing-paren \n
3200 > _ \n
3201 resume:
3202 "esac" > \n))
3203
3204 (define-skeleton sh-for
3205 "Insert a for loop. See `sh-feature'."
3206 (csh sh-modify sh
3207 1 ""
3208 2 "foreach "
3209 4 " ( "
3210 6 " )"
3211 15 '<
3212 16 "end")
3213 (es sh-modify rc
3214 4 " = ")
3215 (rc sh-modify sh
3216 2 "for( "
3217 6 " ) {"
3218 15 ?\} )
3219 (sh "Index variable: "
3220 > "for " str " in " _ "; do" \n
3221 > _ | ?$ & (sh-remember-variable str) \n
3222 "done" > \n))
3223
3224
3225
3226 (define-skeleton sh-indexed-loop
3227 "Insert an indexed loop from 1 to n. See `sh-feature'."
3228 (bash sh-modify posix)
3229 (csh "Index variable: "
3230 "@ " str " = 1" \n
3231 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3232 > _ ?$ str \n
3233 "@ " str "++" \n
3234 < "end" \n)
3235 (es sh-modify rc
3236 4 " =")
3237 (ksh88 "Index variable: "
3238 > "integer " str "=0" \n
3239 > "while (( ( " str " += 1 ) <= "
3240 (read-string "upper limit: ")
3241 " )); do" \n
3242 > _ ?$ (sh-remember-variable str) > \n
3243 "done" > \n)
3244 (posix "Index variable: "
3245 > str "=1" \n
3246 "while [ $" str " -le "
3247 (read-string "upper limit: ")
3248 " ]; do" \n
3249 > _ ?$ str \n
3250 str ?= (sh-add (sh-remember-variable str) 1) \n
3251 "done" > \n)
3252 (rc "Index variable: "
3253 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3254 (read-string "upper limit: ")
3255 "; i++ ) print i }'`}) {" \n
3256 > _ ?$ (sh-remember-variable str) \n
3257 ?\} > \n)
3258 (sh "Index variable: "
3259 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3260 (read-string "upper limit: ")
3261 "; i++ ) print i }'`; do" \n
3262 > _ ?$ (sh-remember-variable str) \n
3263 "done" > \n))
3264
3265
3266 (defun sh-shell-initialize-variables ()
3267 "Scan the buffer for variable assignments.
3268 Add these variables to `sh-shell-variables'."
3269 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3270 (save-excursion
3271 (goto-char (point-min))
3272 (setq sh-shell-variables-initialized t)
3273 (while (search-forward "=" nil t)
3274 (sh-assignment 0)))
3275 (message "Scanning buffer `%s' for variable assignments...done"
3276 (buffer-name)))
3277
3278 (defvar sh-add-buffer)
3279
3280 (defun sh-add-completer (string predicate code)
3281 "Do completion using `sh-shell-variables', but initialize it first.
3282 This function is designed for use as the \"completion table\",
3283 so it takes three arguments:
3284 STRING, the current buffer contents;
3285 PREDICATE, the predicate for filtering possible matches;
3286 CODE, which says what kind of things to do.
3287 CODE can be nil, t or `lambda'.
3288 nil means to return the best completion of STRING, or nil if there is none.
3289 t means to return a list of all possible completions of STRING.
3290 `lambda' means to return t if STRING is a valid completion as it stands."
3291 (let ((sh-shell-variables
3292 (with-current-buffer sh-add-buffer
3293 (or sh-shell-variables-initialized
3294 (sh-shell-initialize-variables))
3295 (nconc (mapcar (lambda (var)
3296 (let ((name
3297 (substring var 0 (string-match "=" var))))
3298 (cons name name)))
3299 process-environment)
3300 sh-shell-variables))))
3301 (case code
3302 ((nil) (try-completion string sh-shell-variables predicate))
3303 (lambda (test-completion string sh-shell-variables predicate))
3304 (t (all-completions string sh-shell-variables predicate)))))
3305
3306 (defun sh-add (var delta)
3307 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3308 (interactive
3309 (let ((sh-add-buffer (current-buffer)))
3310 (list (completing-read "Variable: " 'sh-add-completer)
3311 (prefix-numeric-value current-prefix-arg))))
3312 (insert (sh-feature '((bash . "$(( ")
3313 (ksh88 . "$(( ")
3314 (posix . "$(( ")
3315 (rc . "`{expr $")
3316 (sh . "`expr $")
3317 (zsh . "$[ ")))
3318 (sh-remember-variable var)
3319 (if (< delta 0) " - " " + ")
3320 (number-to-string (abs delta))
3321 (sh-feature '((bash . " ))")
3322 (ksh88 . " ))")
3323 (posix . " ))")
3324 (rc . "}")
3325 (sh . "`")
3326 (zsh . " ]")))))
3327
3328
3329
3330 (define-skeleton sh-function
3331 "Insert a function definition. See `sh-feature'."
3332 (bash sh-modify ksh88
3333 3 "() {")
3334 (ksh88 "name: "
3335 "function " str " {" \n
3336 > _ \n
3337 < "}" \n)
3338 (rc sh-modify ksh88
3339 1 "fn ")
3340 (sh ()
3341 "() {" \n
3342 > _ \n
3343 < "}" \n))
3344
3345
3346
3347 (define-skeleton sh-if
3348 "Insert an if statement. See `sh-feature'."
3349 (csh "condition: "
3350 "if( " str " ) then" \n
3351 > _ \n
3352 ( "other condition, %s: "
3353 < "else if( " str " ) then" \n
3354 > _ \n)
3355 < "else" \n
3356 > _ \n
3357 resume:
3358 < "endif" \n)
3359 (es "condition: "
3360 > "if { " str " } {" \n
3361 > _ \n
3362 ( "other condition, %s: "
3363 "} { " str " } {" > \n
3364 > _ \n)
3365 "} {" > \n
3366 > _ \n
3367 resume:
3368 ?\} > \n)
3369 (rc "condition: "
3370 > "if( " str " ) {" \n
3371 > _ \n
3372 ( "other condition, %s: "
3373 "} else if( " str " ) {" > \n
3374 > _ \n)
3375 "} else {" > \n
3376 > _ \n
3377 resume:
3378 ?\} > \n)
3379 (sh "condition: "
3380 '(setq input (sh-feature sh-test))
3381 > "if " str "; then" \n
3382 > _ \n
3383 ( "other condition, %s: "
3384 > "elif " str "; then" > \n
3385 > \n)
3386 "else" > \n
3387 > \n
3388 resume:
3389 "fi" > \n))
3390
3391
3392
3393 (define-skeleton sh-repeat
3394 "Insert a repeat loop definition. See `sh-feature'."
3395 (es nil
3396 > "forever {" \n
3397 > _ \n
3398 ?\} > \n)
3399 (zsh "factor: "
3400 > "repeat " str "; do" > \n
3401 > \n
3402 "done" > \n))
3403
3404 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3405
3406
3407
3408 (define-skeleton sh-select
3409 "Insert a select statement. See `sh-feature'."
3410 (ksh88 "Index variable: "
3411 > "select " str " in " _ "; do" \n
3412 > ?$ str \n
3413 "done" > \n)
3414 (bash sh-append ksh88))
3415 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3416
3417
3418
3419 (define-skeleton sh-tmp-file
3420 "Insert code to setup temporary file handling. See `sh-feature'."
3421 (bash sh-append ksh88)
3422 (csh (file-name-nondirectory (buffer-file-name))
3423 "set tmp = `mktemp -t " str ".XXXXXX`" \n
3424 "onintr exit" \n _
3425 (and (goto-char (point-max))
3426 (not (bolp))
3427 ?\n)
3428 "exit:\n"
3429 "rm $tmp* >&/dev/null" > \n)
3430 (es (file-name-nondirectory (buffer-file-name))
3431 > "local( signals = $signals sighup sigint;" \n
3432 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
3433 > "catch @ e {" \n
3434 > "rm $tmp^* >[2]/dev/null" \n
3435 "throw $e" \n
3436 "} {" > \n
3437 _ \n
3438 ?\} > \n
3439 ?\} > \n)
3440 (ksh88 sh-modify sh
3441 7 "EXIT")
3442 (rc (file-name-nondirectory (buffer-file-name))
3443 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
3444 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3445 (sh (file-name-nondirectory (buffer-file-name))
3446 > "TMP=`mktemp -t " str ".XXXXXX`" \n
3447 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
3448
3449
3450
3451 (define-skeleton sh-until
3452 "Insert an until loop. See `sh-feature'."
3453 (sh "condition: "
3454 '(setq input (sh-feature sh-test))
3455 > "until " str "; do" \n
3456 > _ \n
3457 "done" > \n))
3458 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3459
3460
3461
3462 (define-skeleton sh-while
3463 "Insert a while loop. See `sh-feature'."
3464 (csh sh-modify sh
3465 2 ""
3466 3 "while( "
3467 5 " )"
3468 10 '<
3469 11 "end")
3470 (es sh-modify sh
3471 3 "while { "
3472 5 " } {"
3473 10 ?\} )
3474 (rc sh-modify sh
3475 3 "while( "
3476 5 " ) {"
3477 10 ?\} )
3478 (sh "condition: "
3479 '(setq input (sh-feature sh-test))
3480 > "while " str "; do" \n
3481 > _ \n
3482 "done" > \n))
3483
3484
3485
3486 (define-skeleton sh-while-getopts
3487 "Insert a while getopts loop. See `sh-feature'.
3488 Prompts for an options string which consists of letters for each recognized
3489 option followed by a colon `:' if the option accepts an argument."
3490 (bash sh-modify sh
3491 18 "${0##*/}")
3492 (csh nil
3493 "while( 1 )" \n
3494 > "switch( \"$1\" )" \n
3495 '(setq input '("- x" . 2))
3496 > >
3497 ( "option, %s: "
3498 < "case " '(eval str)
3499 '(if (string-match " +" str)
3500 (setq v1 (substring str (match-end 0))
3501 str (substring str 0 (match-beginning 0)))
3502 (setq v1 nil))
3503 str ?: \n
3504 > "set " v1 & " = $2" | -4 & _ \n
3505 (if v1 "shift") & \n
3506 "breaksw" \n)
3507 < "case --:" \n
3508 > "shift" \n
3509 < "default:" \n
3510 > "break" \n
3511 resume:
3512 < < "endsw" \n
3513 "shift" \n
3514 < "end" \n)
3515 (ksh88 sh-modify sh
3516 16 "print"
3517 18 "${0##*/}"
3518 37 "OPTIND-1")
3519 (posix sh-modify sh
3520 18 "$(basename $0)")
3521 (sh "optstring: "
3522 > "while getopts :" str " OPT; do" \n
3523 > "case $OPT in" \n
3524 '(setq v1 (append (vconcat str) nil))
3525 ( (prog1 (if v1 (char-to-string (car v1)))
3526 (if (eq (nth 1 v1) ?:)
3527 (setq v1 (nthcdr 2 v1)
3528 v2 "\"$OPTARG\"")
3529 (setq v1 (cdr v1)
3530 v2 nil)))
3531 > str "|+" str sh-non-closing-paren \n
3532 > _ v2 \n
3533 > ";;" \n)
3534 > "*" sh-non-closing-paren \n
3535 > "echo" " \"usage: " "`basename $0`"
3536 " [+-" '(setq v1 (point)) str
3537 '(save-excursion
3538 (while (search-backward ":" v1 t)
3539 (replace-match " ARG] [+-" t t)))
3540 (if (eq (preceding-char) ?-) -5)
3541 (if (and (sequencep v1) (length v1)) "] " "} ")
3542 "[--] ARGS...\"" \n
3543 "exit 2" > \n
3544 "esac" >
3545 \n "done"
3546 > \n
3547 "shift " (sh-add "OPTIND" -1) \n
3548 "OPTIND=1" \n))
3549
3550
3551
3552 (defun sh-assignment (arg)
3553 "Remember preceding identifier for future completion and do self-insert."
3554 (interactive "p")
3555 (self-insert-command arg)
3556 (if (<= arg 1)
3557 (sh-remember-variable
3558 (save-excursion
3559 (if (re-search-forward (sh-feature sh-assignment-regexp)
3560 (prog1 (point)
3561 (beginning-of-line 1))
3562 t)
3563 (match-string 1))))))
3564
3565
3566 (defun sh-maybe-here-document (arg)
3567 "Insert self. Without prefix, following unquoted `<' inserts here document.
3568 The document is bounded by `sh-here-document-word'."
3569 (interactive "*P")
3570 (self-insert-command (prefix-numeric-value arg))
3571 (or arg
3572 (not (eq (char-after (- (point) 2)) last-command-char))
3573 (save-excursion
3574 (backward-char 2)
3575 (sh-quoted-p))
3576 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
3577 (make-string (/ (current-indentation) tab-width) ?\t)
3578 ""))
3579 (delim (replace-regexp-in-string "['\"]" ""
3580 sh-here-document-word)))
3581 (insert sh-here-document-word)
3582 (or (eolp) (looking-at "[ \t]") (insert ?\s))
3583 (end-of-line 1)
3584 (while
3585 (sh-quoted-p)
3586 (end-of-line 2))
3587 (insert ?\n tabs)
3588 (save-excursion
3589 (insert ?\n tabs (replace-regexp-in-string
3590 "\\`-?[ \t]*" "" delim))))))
3591
3592 \f
3593 ;; various other commands
3594
3595 (autoload 'comint-dynamic-complete "comint"
3596 "Dynamically perform completion at point." t)
3597
3598 (autoload 'shell-dynamic-complete-command "shell"
3599 "Dynamically complete the command at point." t)
3600
3601 (autoload 'comint-dynamic-complete-filename "comint"
3602 "Dynamically complete the filename at point." t)
3603
3604 (autoload 'shell-dynamic-complete-environment-variable "shell"
3605 "Dynamically complete the environment variable at point." t)
3606
3607
3608
3609 (defun sh-newline-and-indent ()
3610 "Strip unquoted whitespace, insert newline, and indent like current line."
3611 (interactive "*")
3612 (indent-to (prog1 (current-indentation)
3613 (delete-region (point)
3614 (progn
3615 (or (zerop (skip-chars-backward " \t"))
3616 (if (sh-quoted-p)
3617 (forward-char)))
3618 (point)))
3619 (newline))))
3620
3621 (defun sh-beginning-of-command ()
3622 "Move point to successive beginnings of commands."
3623 (interactive)
3624 (if (re-search-backward sh-beginning-of-command nil t)
3625 (goto-char (match-beginning 2))))
3626
3627 (defun sh-end-of-command ()
3628 "Move point to successive ends of commands."
3629 (interactive)
3630 (if (re-search-forward sh-end-of-command nil t)
3631 (goto-char (match-end 1))))
3632
3633 ;; Backslashification. Stolen from make-mode.el.
3634
3635 (defun sh-backslash-region (from to delete-flag)
3636 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3637 With no argument, inserts backslashes and aligns existing backslashes.
3638 With an argument, deletes the backslashes.
3639
3640 This function does not modify the last line of the region if the region ends
3641 right at the start of the following line; it does not modify blank lines
3642 at the start of the region. So you can put the region around an entire
3643 shell command and conveniently use this command."
3644 (interactive "r\nP")
3645 (save-excursion
3646 (goto-char from)
3647 (let ((column sh-backslash-column)
3648 (endmark (make-marker)))
3649 (move-marker endmark to)
3650 ;; Compute the smallest column number past the ends of all the lines.
3651 (if sh-backslash-align
3652 (progn
3653 (if (not delete-flag)
3654 (while (< (point) to)
3655 (end-of-line)
3656 (if (= (preceding-char) ?\\)
3657 (progn (forward-char -1)
3658 (skip-chars-backward " \t")))
3659 (setq column (max column (1+ (current-column))))
3660 (forward-line 1)))
3661 ;; Adjust upward to a tab column, if that doesn't push
3662 ;; past the margin.
3663 (if (> (% column tab-width) 0)
3664 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
3665 tab-width)))
3666 (if (< adjusted (window-width))
3667 (setq column adjusted))))))
3668 ;; Don't modify blank lines at start of region.
3669 (goto-char from)
3670 (while (and (< (point) endmark) (eolp))
3671 (forward-line 1))
3672 ;; Add or remove backslashes on all the lines.
3673 (while (and (< (point) endmark)
3674 ;; Don't backslashify the last line
3675 ;; if the region ends right at the start of the next line.
3676 (save-excursion
3677 (forward-line 1)
3678 (< (point) endmark)))
3679 (if (not delete-flag)
3680 (sh-append-backslash column)
3681 (sh-delete-backslash))
3682 (forward-line 1))
3683 (move-marker endmark nil))))
3684
3685 (defun sh-append-backslash (column)
3686 (end-of-line)
3687 ;; Note that "\\\\" is needed to get one backslash.
3688 (if (= (preceding-char) ?\\)
3689 (progn (forward-char -1)
3690 (delete-horizontal-space)
3691 (indent-to column (if sh-backslash-align nil 1)))
3692 (indent-to column (if sh-backslash-align nil 1))
3693 (insert "\\")))
3694
3695 (defun sh-delete-backslash ()
3696 (end-of-line)
3697 (or (bolp)
3698 (progn
3699 (forward-char -1)
3700 (if (looking-at "\\\\")
3701 (delete-region (1+ (point))
3702 (progn (skip-chars-backward " \t") (point)))))))
3703
3704 (provide 'sh-script)
3705
3706 ;; arch-tag: eccd8b72-f337-4fc2-ae86-18155a69d937
3707 ;;; sh-script.el ends here