sh-script.el 126 KB

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