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