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