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