3
0

vi.c 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * tiny vi.c: A small 'vi' clone
  4. * Copyright (C) 2000, 2001 Sterling Huxley <sterling@europa.com>
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. /*
  9. * Things To Do:
  10. * EXINIT
  11. * $HOME/.exrc and ./.exrc
  12. * add magic to search /foo.*bar
  13. * add :help command
  14. * :map macros
  15. * if mark[] values were line numbers rather than pointers
  16. * it would be easier to change the mark when add/delete lines
  17. * More intelligence in refresh()
  18. * ":r !cmd" and "!cmd" to filter text through an external command
  19. * An "ex" line oriented mode- maybe using "cmdedit"
  20. */
  21. //config:config VI
  22. //config: bool "vi"
  23. //config: default y
  24. //config: help
  25. //config: 'vi' is a text editor. More specifically, it is the One True
  26. //config: text editor <grin>. It does, however, have a rather steep
  27. //config: learning curve. If you are not already comfortable with 'vi'
  28. //config: you may wish to use something else.
  29. //config:
  30. //config:config FEATURE_VI_MAX_LEN
  31. //config: int "Maximum screen width"
  32. //config: range 256 16384
  33. //config: default 4096
  34. //config: depends on VI
  35. //config: help
  36. //config: Contrary to what you may think, this is not eating much.
  37. //config: Make it smaller than 4k only if you are very limited on memory.
  38. //config:
  39. //config:config FEATURE_VI_8BIT
  40. //config: bool "Allow to display 8-bit chars (otherwise shows dots)"
  41. //config: default n
  42. //config: depends on VI
  43. //config: help
  44. //config: If your terminal can display characters with high bit set,
  45. //config: you may want to enable this. Note: vi is not Unicode-capable.
  46. //config: If your terminal combines several 8-bit bytes into one character
  47. //config: (as in Unicode mode), this will not work properly.
  48. //config:
  49. //config:config FEATURE_VI_COLON
  50. //config: bool "Enable \":\" colon commands (no \"ex\" mode)"
  51. //config: default y
  52. //config: depends on VI
  53. //config: help
  54. //config: Enable a limited set of colon commands. This does not
  55. //config: provide an "ex" mode.
  56. //config:
  57. //config:config FEATURE_VI_YANKMARK
  58. //config: bool "Enable yank/put commands and mark cmds"
  59. //config: default y
  60. //config: depends on VI
  61. //config: help
  62. //config: This will enable you to use yank and put, as well as mark.
  63. //config:
  64. //config:config FEATURE_VI_SEARCH
  65. //config: bool "Enable search and replace cmds"
  66. //config: default y
  67. //config: depends on VI
  68. //config: help
  69. //config: Select this if you wish to be able to do search and replace.
  70. //config:
  71. //config:config FEATURE_VI_REGEX_SEARCH
  72. //config: bool "Enable regex in search and replace"
  73. //config: default n # Uses GNU regex, which may be unavailable. FIXME
  74. //config: depends on FEATURE_VI_SEARCH
  75. //config: help
  76. //config: Use extended regex search.
  77. //config:
  78. //config:config FEATURE_VI_USE_SIGNALS
  79. //config: bool "Catch signals"
  80. //config: default y
  81. //config: depends on VI
  82. //config: help
  83. //config: Selecting this option will make vi signal aware. This will support
  84. //config: SIGWINCH to deal with Window Changes, catch ^Z and ^C and alarms.
  85. //config:
  86. //config:config FEATURE_VI_DOT_CMD
  87. //config: bool "Remember previous cmd and \".\" cmd"
  88. //config: default y
  89. //config: depends on VI
  90. //config: help
  91. //config: Make vi remember the last command and be able to repeat it.
  92. //config:
  93. //config:config FEATURE_VI_READONLY
  94. //config: bool "Enable -R option and \"view\" mode"
  95. //config: default y
  96. //config: depends on VI
  97. //config: help
  98. //config: Enable the read-only command line option, which allows the user to
  99. //config: open a file in read-only mode.
  100. //config:
  101. //config:config FEATURE_VI_SETOPTS
  102. //config: bool "Enable settable options, ai ic showmatch"
  103. //config: default y
  104. //config: depends on VI
  105. //config: help
  106. //config: Enable the editor to set some (ai, ic, showmatch) options.
  107. //config:
  108. //config:config FEATURE_VI_SET
  109. //config: bool "Support :set"
  110. //config: default y
  111. //config: depends on VI
  112. //config:
  113. //config:config FEATURE_VI_WIN_RESIZE
  114. //config: bool "Handle window resize"
  115. //config: default y
  116. //config: depends on VI
  117. //config: help
  118. //config: Behave nicely with terminals that get resized.
  119. //config:
  120. //config:config FEATURE_VI_ASK_TERMINAL
  121. //config: bool "Use 'tell me cursor position' ESC sequence to measure window"
  122. //config: default y
  123. //config: depends on VI
  124. //config: help
  125. //config: If terminal size can't be retrieved and $LINES/$COLUMNS are not set,
  126. //config: this option makes vi perform a last-ditch effort to find it:
  127. //config: position cursor to 999,999 and ask terminal to report real
  128. //config: cursor position using "ESC [ 6 n" escape sequence, then read stdin.
  129. //config: This is not clean but helps a lot on serial lines and such.
  130. //config:
  131. //config:config FEATURE_VI_UNDO
  132. //config: bool "Support undo command \"u\""
  133. //config: default y
  134. //config: depends on VI
  135. //config: help
  136. //config: Support the 'u' command to undo insertion, deletion, and replacement
  137. //config: of text.
  138. //config:
  139. //config:config FEATURE_VI_UNDO_QUEUE
  140. //config: bool "Enable undo operation queuing"
  141. //config: default y
  142. //config: depends on FEATURE_VI_UNDO
  143. //config: help
  144. //config: The vi undo functions can use an intermediate queue to greatly lower
  145. //config: malloc() calls and overhead. When the maximum size of this queue is
  146. //config: reached, the contents of the queue are committed to the undo stack.
  147. //config: This increases the size of the undo code and allows some undo
  148. //config: operations (especially un-typing/backspacing) to be far more useful.
  149. //config:
  150. //config:config FEATURE_VI_UNDO_QUEUE_MAX
  151. //config: int "Maximum undo character queue size"
  152. //config: default 256
  153. //config: range 32 65536
  154. //config: depends on FEATURE_VI_UNDO_QUEUE
  155. //config: help
  156. //config: This option sets the number of bytes used at runtime for the queue.
  157. //config: Smaller values will create more undo objects and reduce the amount
  158. //config: of typed or backspaced characters that are grouped into one undo
  159. //config: operation; larger values increase the potential size of each undo
  160. //config: and will generally malloc() larger objects and less frequently.
  161. //config: Unless you want more (or less) frequent "undo points" while typing,
  162. //config: you should probably leave this unchanged.
  163. //applet:IF_VI(APPLET(vi, BB_DIR_BIN, BB_SUID_DROP))
  164. //kbuild:lib-$(CONFIG_VI) += vi.o
  165. //usage:#define vi_trivial_usage
  166. //usage: "[OPTIONS] [FILE]..."
  167. //usage:#define vi_full_usage "\n\n"
  168. //usage: "Edit FILE\n"
  169. //usage: IF_FEATURE_VI_COLON(
  170. //usage: "\n -c CMD Initial command to run ($EXINIT also available)"
  171. //usage: )
  172. //usage: IF_FEATURE_VI_READONLY(
  173. //usage: "\n -R Read-only"
  174. //usage: )
  175. //usage: "\n -H List available features"
  176. #include "libbb.h"
  177. /* Should be after libbb.h: on some systems regex.h needs sys/types.h: */
  178. #if ENABLE_FEATURE_VI_REGEX_SEARCH
  179. # include <regex.h>
  180. #endif
  181. /* the CRASHME code is unmaintained, and doesn't currently build */
  182. #define ENABLE_FEATURE_VI_CRASHME 0
  183. #if ENABLE_LOCALE_SUPPORT
  184. #if ENABLE_FEATURE_VI_8BIT
  185. //FIXME: this does not work properly for Unicode anyway
  186. # define Isprint(c) (isprint)(c)
  187. #else
  188. # define Isprint(c) isprint_asciionly(c)
  189. #endif
  190. #else
  191. /* 0x9b is Meta-ESC */
  192. #if ENABLE_FEATURE_VI_8BIT
  193. # define Isprint(c) ((unsigned char)(c) >= ' ' && (c) != 0x7f && (unsigned char)(c) != 0x9b)
  194. #else
  195. # define Isprint(c) ((unsigned char)(c) >= ' ' && (unsigned char)(c) < 0x7f)
  196. #endif
  197. #endif
  198. enum {
  199. MAX_TABSTOP = 32, // sanity limit
  200. // User input len. Need not be extra big.
  201. // Lines in file being edited *can* be bigger than this.
  202. MAX_INPUT_LEN = 128,
  203. // Sanity limits. We have only one buffer of this size.
  204. MAX_SCR_COLS = CONFIG_FEATURE_VI_MAX_LEN,
  205. MAX_SCR_ROWS = CONFIG_FEATURE_VI_MAX_LEN,
  206. };
  207. /* VT102 ESC sequences.
  208. * See "Xterm Control Sequences"
  209. * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  210. */
  211. /* Inverse/Normal text */
  212. #define ESC_BOLD_TEXT "\033[7m"
  213. #define ESC_NORM_TEXT "\033[0m"
  214. /* Bell */
  215. #define ESC_BELL "\007"
  216. /* Clear-to-end-of-line */
  217. #define ESC_CLEAR2EOL "\033[K"
  218. /* Clear-to-end-of-screen.
  219. * (We use default param here.
  220. * Full sequence is "ESC [ <num> J",
  221. * <num> is 0/1/2 = "erase below/above/all".)
  222. */
  223. #define ESC_CLEAR2EOS "\033[J"
  224. /* Cursor to given coordinate (1,1: top left) */
  225. #define ESC_SET_CURSOR_POS "\033[%u;%uH"
  226. //UNUSED
  227. ///* Cursor up and down */
  228. //#define ESC_CURSOR_UP "\033[A"
  229. //#define ESC_CURSOR_DOWN "\n"
  230. #if ENABLE_FEATURE_VI_DOT_CMD || ENABLE_FEATURE_VI_YANKMARK
  231. // cmds modifying text[]
  232. // vda: removed "aAiIs" as they switch us into insert mode
  233. // and remembering input for replay after them makes no sense
  234. static const char modifying_cmds[] ALIGN1 = "cCdDJoOpPrRxX<>~";
  235. #endif
  236. enum {
  237. YANKONLY = FALSE,
  238. YANKDEL = TRUE,
  239. FORWARD = 1, // code depends on "1" for array index
  240. BACK = -1, // code depends on "-1" for array index
  241. LIMITED = 0, // how much of text[] in char_search
  242. FULL = 1, // how much of text[] in char_search
  243. S_BEFORE_WS = 1, // used in skip_thing() for moving "dot"
  244. S_TO_WS = 2, // used in skip_thing() for moving "dot"
  245. S_OVER_WS = 3, // used in skip_thing() for moving "dot"
  246. S_END_PUNCT = 4, // used in skip_thing() for moving "dot"
  247. S_END_ALNUM = 5, // used in skip_thing() for moving "dot"
  248. };
  249. /* vi.c expects chars to be unsigned. */
  250. /* busybox build system provides that, but it's better */
  251. /* to audit and fix the source */
  252. struct globals {
  253. /* many references - keep near the top of globals */
  254. char *text, *end; // pointers to the user data in memory
  255. char *dot; // where all the action takes place
  256. int text_size; // size of the allocated buffer
  257. /* the rest */
  258. smallint vi_setops;
  259. #define VI_AUTOINDENT 1
  260. #define VI_SHOWMATCH 2
  261. #define VI_IGNORECASE 4
  262. #define VI_ERR_METHOD 8
  263. #define autoindent (vi_setops & VI_AUTOINDENT)
  264. #define showmatch (vi_setops & VI_SHOWMATCH )
  265. #define ignorecase (vi_setops & VI_IGNORECASE)
  266. /* indicate error with beep or flash */
  267. #define err_method (vi_setops & VI_ERR_METHOD)
  268. #if ENABLE_FEATURE_VI_READONLY
  269. smallint readonly_mode;
  270. #define SET_READONLY_FILE(flags) ((flags) |= 0x01)
  271. #define SET_READONLY_MODE(flags) ((flags) |= 0x02)
  272. #define UNSET_READONLY_FILE(flags) ((flags) &= 0xfe)
  273. #else
  274. #define SET_READONLY_FILE(flags) ((void)0)
  275. #define SET_READONLY_MODE(flags) ((void)0)
  276. #define UNSET_READONLY_FILE(flags) ((void)0)
  277. #endif
  278. smallint editing; // >0 while we are editing a file
  279. // [code audit says "can be 0, 1 or 2 only"]
  280. smallint cmd_mode; // 0=command 1=insert 2=replace
  281. int modified_count; // buffer contents changed if !0
  282. int last_modified_count; // = -1;
  283. int save_argc; // how many file names on cmd line
  284. int cmdcnt; // repetition count
  285. unsigned rows, columns; // the terminal screen is this size
  286. #if ENABLE_FEATURE_VI_ASK_TERMINAL
  287. int get_rowcol_error;
  288. #endif
  289. int crow, ccol; // cursor is on Crow x Ccol
  290. int offset; // chars scrolled off the screen to the left
  291. int have_status_msg; // is default edit status needed?
  292. // [don't make smallint!]
  293. int last_status_cksum; // hash of current status line
  294. char *current_filename;
  295. char *screenbegin; // index into text[], of top line on the screen
  296. char *screen; // pointer to the virtual screen buffer
  297. int screensize; // and its size
  298. int tabstop;
  299. int last_forward_char; // last char searched for with 'f' (int because of Unicode)
  300. char erase_char; // the users erase character
  301. char last_input_char; // last char read from user
  302. #if ENABLE_FEATURE_VI_DOT_CMD
  303. smallint adding2q; // are we currently adding user input to q
  304. int lmc_len; // length of last_modifying_cmd
  305. char *ioq, *ioq_start; // pointer to string for get_one_char to "read"
  306. #endif
  307. #if ENABLE_FEATURE_VI_USE_SIGNALS || ENABLE_FEATURE_VI_CRASHME
  308. int my_pid;
  309. #endif
  310. #if ENABLE_FEATURE_VI_SEARCH
  311. char *last_search_pattern; // last pattern from a '/' or '?' search
  312. #endif
  313. /* former statics */
  314. #if ENABLE_FEATURE_VI_YANKMARK
  315. char *edit_file__cur_line;
  316. #endif
  317. int refresh__old_offset;
  318. int format_edit_status__tot;
  319. /* a few references only */
  320. #if ENABLE_FEATURE_VI_YANKMARK
  321. int YDreg, Ureg; // default delete register and orig line for "U"
  322. char *reg[28]; // named register a-z, "D", and "U" 0-25,26,27
  323. char *mark[28]; // user marks points somewhere in text[]- a-z and previous context ''
  324. char *context_start, *context_end;
  325. #endif
  326. #if ENABLE_FEATURE_VI_USE_SIGNALS
  327. sigjmp_buf restart; // catch_sig()
  328. #endif
  329. struct termios term_orig; // remember what the cooked mode was
  330. #if ENABLE_FEATURE_VI_COLON
  331. char *initial_cmds[3]; // currently 2 entries, NULL terminated
  332. #endif
  333. // Should be just enough to hold a key sequence,
  334. // but CRASHME mode uses it as generated command buffer too
  335. #if ENABLE_FEATURE_VI_CRASHME
  336. char readbuffer[128];
  337. #else
  338. char readbuffer[KEYCODE_BUFFER_SIZE];
  339. #endif
  340. #define STATUS_BUFFER_LEN 200
  341. char status_buffer[STATUS_BUFFER_LEN]; // messages to the user
  342. #if ENABLE_FEATURE_VI_DOT_CMD
  343. char last_modifying_cmd[MAX_INPUT_LEN]; // last modifying cmd for "."
  344. #endif
  345. char get_input_line__buf[MAX_INPUT_LEN]; /* former static */
  346. char scr_out_buf[MAX_SCR_COLS + MAX_TABSTOP * 2];
  347. #if ENABLE_FEATURE_VI_UNDO
  348. // undo_push() operations
  349. #define UNDO_INS 0
  350. #define UNDO_DEL 1
  351. #define UNDO_INS_CHAIN 2
  352. #define UNDO_DEL_CHAIN 3
  353. // UNDO_*_QUEUED must be equal to UNDO_xxx ORed with UNDO_QUEUED_FLAG
  354. #define UNDO_QUEUED_FLAG 4
  355. #define UNDO_INS_QUEUED 4
  356. #define UNDO_DEL_QUEUED 5
  357. #define UNDO_USE_SPOS 32
  358. #define UNDO_EMPTY 64
  359. // Pass-through flags for functions that can be undone
  360. #define NO_UNDO 0
  361. #define ALLOW_UNDO 1
  362. #define ALLOW_UNDO_CHAIN 2
  363. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  364. #define ALLOW_UNDO_QUEUED 3
  365. char undo_queue_state;
  366. int undo_q;
  367. char *undo_queue_spos; // Start position of queued operation
  368. char undo_queue[CONFIG_FEATURE_VI_UNDO_QUEUE_MAX];
  369. # else
  370. // If undo queuing disabled, don't invoke the missing queue logic
  371. #define ALLOW_UNDO_QUEUED 1
  372. # endif
  373. struct undo_object {
  374. struct undo_object *prev; // Linking back avoids list traversal (LIFO)
  375. int start; // Offset where the data should be restored/deleted
  376. int length; // total data size
  377. uint8_t u_type; // 0=deleted, 1=inserted, 2=swapped
  378. char undo_text[1]; // text that was deleted (if deletion)
  379. } *undo_stack_tail;
  380. #endif /* ENABLE_FEATURE_VI_UNDO */
  381. };
  382. #define G (*ptr_to_globals)
  383. #define text (G.text )
  384. #define text_size (G.text_size )
  385. #define end (G.end )
  386. #define dot (G.dot )
  387. #define reg (G.reg )
  388. #define vi_setops (G.vi_setops )
  389. #define editing (G.editing )
  390. #define cmd_mode (G.cmd_mode )
  391. #define modified_count (G.modified_count )
  392. #define last_modified_count (G.last_modified_count)
  393. #define save_argc (G.save_argc )
  394. #define cmdcnt (G.cmdcnt )
  395. #define rows (G.rows )
  396. #define columns (G.columns )
  397. #define crow (G.crow )
  398. #define ccol (G.ccol )
  399. #define offset (G.offset )
  400. #define status_buffer (G.status_buffer )
  401. #define have_status_msg (G.have_status_msg )
  402. #define last_status_cksum (G.last_status_cksum )
  403. #define current_filename (G.current_filename )
  404. #define screen (G.screen )
  405. #define screensize (G.screensize )
  406. #define screenbegin (G.screenbegin )
  407. #define tabstop (G.tabstop )
  408. #define last_forward_char (G.last_forward_char )
  409. #define erase_char (G.erase_char )
  410. #define last_input_char (G.last_input_char )
  411. #if ENABLE_FEATURE_VI_READONLY
  412. #define readonly_mode (G.readonly_mode )
  413. #else
  414. #define readonly_mode 0
  415. #endif
  416. #define adding2q (G.adding2q )
  417. #define lmc_len (G.lmc_len )
  418. #define ioq (G.ioq )
  419. #define ioq_start (G.ioq_start )
  420. #define my_pid (G.my_pid )
  421. #define last_search_pattern (G.last_search_pattern)
  422. #define edit_file__cur_line (G.edit_file__cur_line)
  423. #define refresh__old_offset (G.refresh__old_offset)
  424. #define format_edit_status__tot (G.format_edit_status__tot)
  425. #define YDreg (G.YDreg )
  426. #define Ureg (G.Ureg )
  427. #define mark (G.mark )
  428. #define context_start (G.context_start )
  429. #define context_end (G.context_end )
  430. #define restart (G.restart )
  431. #define term_orig (G.term_orig )
  432. #define initial_cmds (G.initial_cmds )
  433. #define readbuffer (G.readbuffer )
  434. #define scr_out_buf (G.scr_out_buf )
  435. #define last_modifying_cmd (G.last_modifying_cmd )
  436. #define get_input_line__buf (G.get_input_line__buf)
  437. #if ENABLE_FEATURE_VI_UNDO
  438. #define undo_stack_tail (G.undo_stack_tail )
  439. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  440. #define undo_queue_state (G.undo_queue_state)
  441. #define undo_q (G.undo_q )
  442. #define undo_queue (G.undo_queue )
  443. #define undo_queue_spos (G.undo_queue_spos )
  444. # endif
  445. #endif
  446. #define INIT_G() do { \
  447. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  448. last_modified_count = -1; \
  449. /* "" but has space for 2 chars: */ \
  450. IF_FEATURE_VI_SEARCH(last_search_pattern = xzalloc(2);) \
  451. } while (0)
  452. static void edit_file(char *); // edit one file
  453. static void do_cmd(int); // execute a command
  454. static int next_tabstop(int);
  455. static void sync_cursor(char *, int *, int *); // synchronize the screen cursor to dot
  456. static char *begin_line(char *); // return pointer to cur line B-o-l
  457. static char *end_line(char *); // return pointer to cur line E-o-l
  458. static char *prev_line(char *); // return pointer to prev line B-o-l
  459. static char *next_line(char *); // return pointer to next line B-o-l
  460. static char *end_screen(void); // get pointer to last char on screen
  461. static int count_lines(char *, char *); // count line from start to stop
  462. static char *find_line(int); // find beginning of line #li
  463. static char *move_to_col(char *, int); // move "p" to column l
  464. static void dot_left(void); // move dot left- dont leave line
  465. static void dot_right(void); // move dot right- dont leave line
  466. static void dot_begin(void); // move dot to B-o-l
  467. static void dot_end(void); // move dot to E-o-l
  468. static void dot_next(void); // move dot to next line B-o-l
  469. static void dot_prev(void); // move dot to prev line B-o-l
  470. static void dot_scroll(int, int); // move the screen up or down
  471. static void dot_skip_over_ws(void); // move dot pat WS
  472. static char *bound_dot(char *); // make sure text[0] <= P < "end"
  473. static char *new_screen(int, int); // malloc virtual screen memory
  474. #if !ENABLE_FEATURE_VI_UNDO
  475. #define char_insert(a,b,c) char_insert(a,b)
  476. #endif
  477. static char *char_insert(char *, char, int); // insert the char c at 'p'
  478. // might reallocate text[]! use p += stupid_insert(p, ...),
  479. // and be careful to not use pointers into potentially freed text[]!
  480. static uintptr_t stupid_insert(char *, char); // stupidly insert the char c at 'p'
  481. static int find_range(char **, char **, char); // return pointers for an object
  482. static int st_test(char *, int, int, char *); // helper for skip_thing()
  483. static char *skip_thing(char *, int, int, int); // skip some object
  484. static char *find_pair(char *, char); // find matching pair () [] {}
  485. #if !ENABLE_FEATURE_VI_UNDO
  486. #define text_hole_delete(a,b,c) text_hole_delete(a,b)
  487. #endif
  488. static char *text_hole_delete(char *, char *, int); // at "p", delete a 'size' byte hole
  489. // might reallocate text[]! use p += text_hole_make(p, ...),
  490. // and be careful to not use pointers into potentially freed text[]!
  491. static uintptr_t text_hole_make(char *, int); // at "p", make a 'size' byte hole
  492. #if !ENABLE_FEATURE_VI_UNDO
  493. #define yank_delete(a,b,c,d,e) yank_delete(a,b,c,d)
  494. #endif
  495. static char *yank_delete(char *, char *, int, int, int); // yank text[] into register then delete
  496. static void show_help(void); // display some help info
  497. static void rawmode(void); // set "raw" mode on tty
  498. static void cookmode(void); // return to "cooked" mode on tty
  499. // sleep for 'h' 1/100 seconds, return 1/0 if stdin is (ready for read)/(not ready)
  500. static int mysleep(int);
  501. static int readit(void); // read (maybe cursor) key from stdin
  502. static int get_one_char(void); // read 1 char from stdin
  503. // file_insert might reallocate text[]!
  504. static int file_insert(const char *, char *, int);
  505. static int file_write(char *, char *, char *);
  506. static void place_cursor(int, int);
  507. static void screen_erase(void);
  508. static void clear_to_eol(void);
  509. static void clear_to_eos(void);
  510. static void go_bottom_and_clear_to_eol(void);
  511. static void standout_start(void); // send "start reverse video" sequence
  512. static void standout_end(void); // send "end reverse video" sequence
  513. static void flash(int); // flash the terminal screen
  514. static void show_status_line(void); // put a message on the bottom line
  515. static void status_line(const char *, ...); // print to status buf
  516. static void status_line_bold(const char *, ...);
  517. static void status_line_bold_errno(const char *fn);
  518. static void not_implemented(const char *); // display "Not implemented" message
  519. static int format_edit_status(void); // format file status on status line
  520. static void redraw(int); // force a full screen refresh
  521. static char* format_line(char* /*, int*/);
  522. static void refresh(int); // update the terminal from screen[]
  523. static void indicate_error(void); // use flash or beep to indicate error
  524. static void Hit_Return(void);
  525. #if ENABLE_FEATURE_VI_SEARCH
  526. static char *char_search(char *, const char *, int, int); // search for pattern starting at p
  527. #endif
  528. #if ENABLE_FEATURE_VI_COLON
  529. static char *get_one_address(char *, int *); // get colon addr, if present
  530. static char *get_address(char *, int *, int *); // get two colon addrs, if present
  531. #endif
  532. static void colon(char *); // execute the "colon" mode cmds
  533. #if ENABLE_FEATURE_VI_USE_SIGNALS
  534. static void winch_sig(int); // catch window size changes
  535. static void suspend_sig(int); // catch ctrl-Z
  536. static void catch_sig(int); // catch ctrl-C and alarm time-outs
  537. #endif
  538. #if ENABLE_FEATURE_VI_DOT_CMD
  539. static void start_new_cmd_q(char); // new queue for command
  540. static void end_cmd_q(void); // stop saving input chars
  541. #else
  542. #define end_cmd_q() ((void)0)
  543. #endif
  544. #if ENABLE_FEATURE_VI_SETOPTS
  545. static void showmatching(char *); // show the matching pair () [] {}
  546. #endif
  547. #if ENABLE_FEATURE_VI_YANKMARK || (ENABLE_FEATURE_VI_COLON && ENABLE_FEATURE_VI_SEARCH) || ENABLE_FEATURE_VI_CRASHME
  548. // might reallocate text[]! use p += string_insert(p, ...),
  549. // and be careful to not use pointers into potentially freed text[]!
  550. # if !ENABLE_FEATURE_VI_UNDO
  551. #define string_insert(a,b,c) string_insert(a,b)
  552. # endif
  553. static uintptr_t string_insert(char *, const char *, int); // insert the string at 'p'
  554. #endif
  555. #if ENABLE_FEATURE_VI_YANKMARK
  556. static char *text_yank(char *, char *, int); // save copy of "p" into a register
  557. static char what_reg(void); // what is letter of current YDreg
  558. static void check_context(char); // remember context for '' command
  559. #endif
  560. #if ENABLE_FEATURE_VI_UNDO
  561. static void flush_undo_data(void);
  562. static void undo_push(char *, unsigned int, unsigned char); // Push an operation on the undo stack
  563. static void undo_pop(void); // Undo the last operation
  564. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  565. static void undo_queue_commit(void); // Flush any queued objects to the undo stack
  566. # else
  567. # define undo_queue_commit() ((void)0)
  568. # endif
  569. #else
  570. #define flush_undo_data() ((void)0)
  571. #define undo_queue_commit() ((void)0)
  572. #endif
  573. #if ENABLE_FEATURE_VI_CRASHME
  574. static void crash_dummy();
  575. static void crash_test();
  576. static int crashme = 0;
  577. #endif
  578. static void write1(const char *out)
  579. {
  580. fputs(out, stdout);
  581. }
  582. int vi_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  583. int vi_main(int argc, char **argv)
  584. {
  585. int c;
  586. INIT_G();
  587. #if ENABLE_FEATURE_VI_UNDO
  588. /* undo_stack_tail = NULL; - already is */
  589. #if ENABLE_FEATURE_VI_UNDO_QUEUE
  590. undo_queue_state = UNDO_EMPTY;
  591. /* undo_q = 0; - already is */
  592. #endif
  593. #endif
  594. #if ENABLE_FEATURE_VI_USE_SIGNALS || ENABLE_FEATURE_VI_CRASHME
  595. my_pid = getpid();
  596. #endif
  597. #if ENABLE_FEATURE_VI_CRASHME
  598. srand((long) my_pid);
  599. #endif
  600. #ifdef NO_SUCH_APPLET_YET
  601. /* If we aren't "vi", we are "view" */
  602. if (ENABLE_FEATURE_VI_READONLY && applet_name[2]) {
  603. SET_READONLY_MODE(readonly_mode);
  604. }
  605. #endif
  606. // autoindent is not default in vim 7.3
  607. vi_setops = /*VI_AUTOINDENT |*/ VI_SHOWMATCH | VI_IGNORECASE;
  608. // 1- process $HOME/.exrc file (not inplemented yet)
  609. // 2- process EXINIT variable from environment
  610. // 3- process command line args
  611. #if ENABLE_FEATURE_VI_COLON
  612. {
  613. char *p = getenv("EXINIT");
  614. if (p && *p)
  615. initial_cmds[0] = xstrndup(p, MAX_INPUT_LEN);
  616. }
  617. #endif
  618. while ((c = getopt(argc, argv, "hCRH" IF_FEATURE_VI_COLON("c:"))) != -1) {
  619. switch (c) {
  620. #if ENABLE_FEATURE_VI_CRASHME
  621. case 'C':
  622. crashme = 1;
  623. break;
  624. #endif
  625. #if ENABLE_FEATURE_VI_READONLY
  626. case 'R': // Read-only flag
  627. SET_READONLY_MODE(readonly_mode);
  628. break;
  629. #endif
  630. #if ENABLE_FEATURE_VI_COLON
  631. case 'c': // cmd line vi command
  632. if (*optarg)
  633. initial_cmds[initial_cmds[0] != NULL] = xstrndup(optarg, MAX_INPUT_LEN);
  634. break;
  635. #endif
  636. case 'H':
  637. show_help();
  638. /* fall through */
  639. default:
  640. bb_show_usage();
  641. return 1;
  642. }
  643. }
  644. // The argv array can be used by the ":next" and ":rewind" commands
  645. argv += optind;
  646. argc -= optind;
  647. //----- This is the main file handling loop --------------
  648. save_argc = argc;
  649. optind = 0;
  650. // "Save cursor, use alternate screen buffer, clear screen"
  651. write1("\033[?1049h");
  652. while (1) {
  653. edit_file(argv[optind]); /* param might be NULL */
  654. if (++optind >= argc)
  655. break;
  656. }
  657. // "Use normal screen buffer, restore cursor"
  658. write1("\033[?1049l");
  659. //-----------------------------------------------------------
  660. return 0;
  661. }
  662. /* read text from file or create an empty buf */
  663. /* will also update current_filename */
  664. static int init_text_buffer(char *fn)
  665. {
  666. int rc;
  667. /* allocate/reallocate text buffer */
  668. free(text);
  669. text_size = 10240;
  670. screenbegin = dot = end = text = xzalloc(text_size);
  671. if (fn != current_filename) {
  672. free(current_filename);
  673. current_filename = xstrdup(fn);
  674. }
  675. rc = file_insert(fn, text, 1);
  676. if (rc < 0) {
  677. // file doesnt exist. Start empty buf with dummy line
  678. char_insert(text, '\n', NO_UNDO);
  679. }
  680. flush_undo_data();
  681. modified_count = 0;
  682. last_modified_count = -1;
  683. #if ENABLE_FEATURE_VI_YANKMARK
  684. /* init the marks */
  685. memset(mark, 0, sizeof(mark));
  686. #endif
  687. return rc;
  688. }
  689. #if ENABLE_FEATURE_VI_WIN_RESIZE
  690. static int query_screen_dimensions(void)
  691. {
  692. int err = get_terminal_width_height(STDIN_FILENO, &columns, &rows);
  693. if (rows > MAX_SCR_ROWS)
  694. rows = MAX_SCR_ROWS;
  695. if (columns > MAX_SCR_COLS)
  696. columns = MAX_SCR_COLS;
  697. return err;
  698. }
  699. #else
  700. # define query_screen_dimensions() (0)
  701. #endif
  702. static void edit_file(char *fn)
  703. {
  704. #if ENABLE_FEATURE_VI_YANKMARK
  705. #define cur_line edit_file__cur_line
  706. #endif
  707. int c;
  708. #if ENABLE_FEATURE_VI_USE_SIGNALS
  709. int sig;
  710. #endif
  711. editing = 1; // 0 = exit, 1 = one file, 2 = multiple files
  712. rawmode();
  713. rows = 24;
  714. columns = 80;
  715. IF_FEATURE_VI_ASK_TERMINAL(G.get_rowcol_error =) query_screen_dimensions();
  716. #if ENABLE_FEATURE_VI_ASK_TERMINAL
  717. if (G.get_rowcol_error /* TODO? && no input on stdin */) {
  718. uint64_t k;
  719. write1("\033[999;999H" "\033[6n");
  720. fflush_all();
  721. k = read_key(STDIN_FILENO, readbuffer, /*timeout_ms:*/ 100);
  722. if ((int32_t)k == KEYCODE_CURSOR_POS) {
  723. uint32_t rc = (k >> 32);
  724. columns = (rc & 0x7fff);
  725. if (columns > MAX_SCR_COLS)
  726. columns = MAX_SCR_COLS;
  727. rows = ((rc >> 16) & 0x7fff);
  728. if (rows > MAX_SCR_ROWS)
  729. rows = MAX_SCR_ROWS;
  730. }
  731. }
  732. #endif
  733. new_screen(rows, columns); // get memory for virtual screen
  734. init_text_buffer(fn);
  735. #if ENABLE_FEATURE_VI_YANKMARK
  736. YDreg = 26; // default Yank/Delete reg
  737. Ureg = 27; // hold orig line for "U" cmd
  738. mark[26] = mark[27] = text; // init "previous context"
  739. #endif
  740. last_forward_char = last_input_char = '\0';
  741. crow = 0;
  742. ccol = 0;
  743. #if ENABLE_FEATURE_VI_USE_SIGNALS
  744. signal(SIGINT, catch_sig);
  745. signal(SIGWINCH, winch_sig);
  746. signal(SIGTSTP, suspend_sig);
  747. sig = sigsetjmp(restart, 1);
  748. if (sig != 0) {
  749. screenbegin = dot = text;
  750. }
  751. #endif
  752. cmd_mode = 0; // 0=command 1=insert 2='R'eplace
  753. cmdcnt = 0;
  754. tabstop = 8;
  755. offset = 0; // no horizontal offset
  756. c = '\0';
  757. #if ENABLE_FEATURE_VI_DOT_CMD
  758. free(ioq_start);
  759. ioq = ioq_start = NULL;
  760. lmc_len = 0;
  761. adding2q = 0;
  762. #endif
  763. #if ENABLE_FEATURE_VI_COLON
  764. {
  765. char *p, *q;
  766. int n = 0;
  767. while ((p = initial_cmds[n]) != NULL) {
  768. do {
  769. q = p;
  770. p = strchr(q, '\n');
  771. if (p)
  772. while (*p == '\n')
  773. *p++ = '\0';
  774. if (*q)
  775. colon(q);
  776. } while (p);
  777. free(initial_cmds[n]);
  778. initial_cmds[n] = NULL;
  779. n++;
  780. }
  781. }
  782. #endif
  783. redraw(FALSE); // dont force every col re-draw
  784. //------This is the main Vi cmd handling loop -----------------------
  785. while (editing > 0) {
  786. #if ENABLE_FEATURE_VI_CRASHME
  787. if (crashme > 0) {
  788. if ((end - text) > 1) {
  789. crash_dummy(); // generate a random command
  790. } else {
  791. crashme = 0;
  792. string_insert(text, "\n\n##### Ran out of text to work on. #####\n\n", NO_UNDO); // insert the string
  793. dot = text;
  794. refresh(FALSE);
  795. }
  796. }
  797. #endif
  798. last_input_char = c = get_one_char(); // get a cmd from user
  799. #if ENABLE_FEATURE_VI_YANKMARK
  800. // save a copy of the current line- for the 'U" command
  801. if (begin_line(dot) != cur_line) {
  802. cur_line = begin_line(dot);
  803. text_yank(begin_line(dot), end_line(dot), Ureg);
  804. }
  805. #endif
  806. #if ENABLE_FEATURE_VI_DOT_CMD
  807. // These are commands that change text[].
  808. // Remember the input for the "." command
  809. if (!adding2q && ioq_start == NULL
  810. && cmd_mode == 0 // command mode
  811. && c > '\0' // exclude NUL and non-ASCII chars
  812. && c < 0x7f // (Unicode and such)
  813. && strchr(modifying_cmds, c)
  814. ) {
  815. start_new_cmd_q(c);
  816. }
  817. #endif
  818. do_cmd(c); // execute the user command
  819. // poll to see if there is input already waiting. if we are
  820. // not able to display output fast enough to keep up, skip
  821. // the display update until we catch up with input.
  822. if (!readbuffer[0] && mysleep(0) == 0) {
  823. // no input pending - so update output
  824. refresh(FALSE);
  825. show_status_line();
  826. }
  827. #if ENABLE_FEATURE_VI_CRASHME
  828. if (crashme > 0)
  829. crash_test(); // test editor variables
  830. #endif
  831. }
  832. //-------------------------------------------------------------------
  833. go_bottom_and_clear_to_eol();
  834. cookmode();
  835. #undef cur_line
  836. }
  837. //----- The Colon commands -------------------------------------
  838. #if ENABLE_FEATURE_VI_COLON
  839. static char *get_one_address(char *p, int *addr) // get colon addr, if present
  840. {
  841. int st;
  842. char *q;
  843. IF_FEATURE_VI_YANKMARK(char c;)
  844. IF_FEATURE_VI_SEARCH(char *pat;)
  845. *addr = -1; // assume no addr
  846. if (*p == '.') { // the current line
  847. p++;
  848. q = begin_line(dot);
  849. *addr = count_lines(text, q);
  850. }
  851. #if ENABLE_FEATURE_VI_YANKMARK
  852. else if (*p == '\'') { // is this a mark addr
  853. p++;
  854. c = tolower(*p);
  855. p++;
  856. if (c >= 'a' && c <= 'z') {
  857. // we have a mark
  858. c = c - 'a';
  859. q = mark[(unsigned char) c];
  860. if (q != NULL) { // is mark valid
  861. *addr = count_lines(text, q);
  862. }
  863. }
  864. }
  865. #endif
  866. #if ENABLE_FEATURE_VI_SEARCH
  867. else if (*p == '/') { // a search pattern
  868. q = strchrnul(++p, '/');
  869. pat = xstrndup(p, q - p); // save copy of pattern
  870. p = q;
  871. if (*p == '/')
  872. p++;
  873. q = char_search(dot, pat, FORWARD, FULL);
  874. if (q != NULL) {
  875. *addr = count_lines(text, q);
  876. }
  877. free(pat);
  878. }
  879. #endif
  880. else if (*p == '$') { // the last line in file
  881. p++;
  882. q = begin_line(end - 1);
  883. *addr = count_lines(text, q);
  884. } else if (isdigit(*p)) { // specific line number
  885. sscanf(p, "%d%n", addr, &st);
  886. p += st;
  887. } else {
  888. // unrecognized address - assume -1
  889. *addr = -1;
  890. }
  891. return p;
  892. }
  893. static char *get_address(char *p, int *b, int *e) // get two colon addrs, if present
  894. {
  895. //----- get the address' i.e., 1,3 'a,'b -----
  896. // get FIRST addr, if present
  897. while (isblank(*p))
  898. p++; // skip over leading spaces
  899. if (*p == '%') { // alias for 1,$
  900. p++;
  901. *b = 1;
  902. *e = count_lines(text, end-1);
  903. goto ga0;
  904. }
  905. p = get_one_address(p, b);
  906. while (isblank(*p))
  907. p++;
  908. if (*p == ',') { // is there a address separator
  909. p++;
  910. while (isblank(*p))
  911. p++;
  912. // get SECOND addr, if present
  913. p = get_one_address(p, e);
  914. }
  915. ga0:
  916. while (isblank(*p))
  917. p++; // skip over trailing spaces
  918. return p;
  919. }
  920. #if ENABLE_FEATURE_VI_SET && ENABLE_FEATURE_VI_SETOPTS
  921. static void setops(const char *args, const char *opname, int flg_no,
  922. const char *short_opname, int opt)
  923. {
  924. const char *a = args + flg_no;
  925. int l = strlen(opname) - 1; /* opname have + ' ' */
  926. // maybe strncmp? we had tons of erroneous strncasecmp's...
  927. if (strncasecmp(a, opname, l) == 0
  928. || strncasecmp(a, short_opname, 2) == 0
  929. ) {
  930. if (flg_no)
  931. vi_setops &= ~opt;
  932. else
  933. vi_setops |= opt;
  934. }
  935. }
  936. #endif
  937. #endif /* FEATURE_VI_COLON */
  938. // buf must be no longer than MAX_INPUT_LEN!
  939. static void colon(char *buf)
  940. {
  941. #if !ENABLE_FEATURE_VI_COLON
  942. /* Simple ":cmd" handler with minimal set of commands */
  943. char *p = buf;
  944. int cnt;
  945. if (*p == ':')
  946. p++;
  947. cnt = strlen(p);
  948. if (cnt == 0)
  949. return;
  950. if (strncmp(p, "quit", cnt) == 0
  951. || strncmp(p, "q!", cnt) == 0
  952. ) {
  953. if (modified_count && p[1] != '!') {
  954. status_line_bold("No write since last change (:%s! overrides)", p);
  955. } else {
  956. editing = 0;
  957. }
  958. return;
  959. }
  960. if (strncmp(p, "write", cnt) == 0
  961. || strncmp(p, "wq", cnt) == 0
  962. || strncmp(p, "wn", cnt) == 0
  963. || (p[0] == 'x' && !p[1])
  964. ) {
  965. if (modified_count != 0 || p[0] != 'x') {
  966. cnt = file_write(current_filename, text, end - 1);
  967. }
  968. if (cnt < 0) {
  969. if (cnt == -1)
  970. status_line_bold("Write error: %s", strerror(errno));
  971. } else {
  972. modified_count = 0;
  973. last_modified_count = -1;
  974. status_line("'%s' %dL, %dC",
  975. current_filename,
  976. count_lines(text, end - 1), cnt
  977. );
  978. if (p[0] == 'x'
  979. || p[1] == 'q' || p[1] == 'n'
  980. || p[1] == 'Q' || p[1] == 'N'
  981. ) {
  982. editing = 0;
  983. }
  984. }
  985. return;
  986. }
  987. if (strncmp(p, "file", cnt) == 0) {
  988. last_status_cksum = 0; // force status update
  989. return;
  990. }
  991. if (sscanf(p, "%d", &cnt) > 0) {
  992. dot = find_line(cnt);
  993. dot_skip_over_ws();
  994. return;
  995. }
  996. not_implemented(p);
  997. #else
  998. char c, *orig_buf, *buf1, *q, *r;
  999. char *fn, cmd[MAX_INPUT_LEN], args[MAX_INPUT_LEN];
  1000. int i, l, li, b, e;
  1001. int useforce;
  1002. // :3154 // if (-e line 3154) goto it else stay put
  1003. // :4,33w! foo // write a portion of buffer to file "foo"
  1004. // :w // write all of buffer to current file
  1005. // :q // quit
  1006. // :q! // quit- dont care about modified file
  1007. // :'a,'z!sort -u // filter block through sort
  1008. // :'f // goto mark "f"
  1009. // :'fl // list literal the mark "f" line
  1010. // :.r bar // read file "bar" into buffer before dot
  1011. // :/123/,/abc/d // delete lines from "123" line to "abc" line
  1012. // :/xyz/ // goto the "xyz" line
  1013. // :s/find/replace/ // substitute pattern "find" with "replace"
  1014. // :!<cmd> // run <cmd> then return
  1015. //
  1016. if (!buf[0])
  1017. goto ret;
  1018. if (*buf == ':')
  1019. buf++; // move past the ':'
  1020. li = i = 0;
  1021. b = e = -1;
  1022. q = text; // assume 1,$ for the range
  1023. r = end - 1;
  1024. li = count_lines(text, end - 1);
  1025. fn = current_filename;
  1026. // look for optional address(es) :. :1 :1,9 :'q,'a :%
  1027. buf = get_address(buf, &b, &e);
  1028. // remember orig command line
  1029. orig_buf = buf;
  1030. // get the COMMAND into cmd[]
  1031. buf1 = cmd;
  1032. while (*buf != '\0') {
  1033. if (isspace(*buf))
  1034. break;
  1035. *buf1++ = *buf++;
  1036. }
  1037. *buf1 = '\0';
  1038. // get any ARGuments
  1039. while (isblank(*buf))
  1040. buf++;
  1041. strcpy(args, buf);
  1042. useforce = FALSE;
  1043. buf1 = last_char_is(cmd, '!');
  1044. if (buf1) {
  1045. useforce = TRUE;
  1046. *buf1 = '\0'; // get rid of !
  1047. }
  1048. if (b >= 0) {
  1049. // if there is only one addr, then the addr
  1050. // is the line number of the single line the
  1051. // user wants. So, reset the end
  1052. // pointer to point at end of the "b" line
  1053. q = find_line(b); // what line is #b
  1054. r = end_line(q);
  1055. li = 1;
  1056. }
  1057. if (e >= 0) {
  1058. // we were given two addrs. change the
  1059. // end pointer to the addr given by user.
  1060. r = find_line(e); // what line is #e
  1061. r = end_line(r);
  1062. li = e - b + 1;
  1063. }
  1064. // ------------ now look for the command ------------
  1065. i = strlen(cmd);
  1066. if (i == 0) { // :123CR goto line #123
  1067. if (b >= 0) {
  1068. dot = find_line(b); // what line is #b
  1069. dot_skip_over_ws();
  1070. }
  1071. }
  1072. #if ENABLE_FEATURE_ALLOW_EXEC
  1073. else if (cmd[0] == '!') { // run a cmd
  1074. int retcode;
  1075. // :!ls run the <cmd>
  1076. go_bottom_and_clear_to_eol();
  1077. cookmode();
  1078. retcode = system(orig_buf + 1); // run the cmd
  1079. if (retcode)
  1080. printf("\nshell returned %i\n\n", retcode);
  1081. rawmode();
  1082. Hit_Return(); // let user see results
  1083. }
  1084. #endif
  1085. else if (cmd[0] == '=' && !cmd[1]) { // where is the address
  1086. if (b < 0) { // no addr given- use defaults
  1087. b = e = count_lines(text, dot);
  1088. }
  1089. status_line("%d", b);
  1090. } else if (strncmp(cmd, "delete", i) == 0) { // delete lines
  1091. if (b < 0) { // no addr given- use defaults
  1092. q = begin_line(dot); // assume .,. for the range
  1093. r = end_line(dot);
  1094. }
  1095. dot = yank_delete(q, r, 1, YANKDEL, ALLOW_UNDO); // save, then delete lines
  1096. dot_skip_over_ws();
  1097. } else if (strncmp(cmd, "edit", i) == 0) { // Edit a file
  1098. int size;
  1099. // don't edit, if the current file has been modified
  1100. if (modified_count && !useforce) {
  1101. status_line_bold("No write since last change (:%s! overrides)", cmd);
  1102. goto ret;
  1103. }
  1104. if (args[0]) {
  1105. // the user supplied a file name
  1106. fn = args;
  1107. } else if (current_filename && current_filename[0]) {
  1108. // no user supplied name- use the current filename
  1109. // fn = current_filename; was set by default
  1110. } else {
  1111. // no user file name, no current name- punt
  1112. status_line_bold("No current filename");
  1113. goto ret;
  1114. }
  1115. size = init_text_buffer(fn);
  1116. #if ENABLE_FEATURE_VI_YANKMARK
  1117. if (Ureg >= 0 && Ureg < 28) {
  1118. free(reg[Ureg]); // free orig line reg- for 'U'
  1119. reg[Ureg] = NULL;
  1120. }
  1121. if (YDreg >= 0 && YDreg < 28) {
  1122. free(reg[YDreg]); // free default yank/delete register
  1123. reg[YDreg] = NULL;
  1124. }
  1125. #endif
  1126. // how many lines in text[]?
  1127. li = count_lines(text, end - 1);
  1128. status_line("'%s'%s"
  1129. IF_FEATURE_VI_READONLY("%s")
  1130. " %dL, %dC",
  1131. current_filename,
  1132. (size < 0 ? " [New file]" : ""),
  1133. IF_FEATURE_VI_READONLY(
  1134. ((readonly_mode) ? " [Readonly]" : ""),
  1135. )
  1136. li, (int)(end - text)
  1137. );
  1138. } else if (strncmp(cmd, "file", i) == 0) { // what File is this
  1139. if (b != -1 || e != -1) {
  1140. status_line_bold("No address allowed on this command");
  1141. goto ret;
  1142. }
  1143. if (args[0]) {
  1144. // user wants a new filename
  1145. free(current_filename);
  1146. current_filename = xstrdup(args);
  1147. } else {
  1148. // user wants file status info
  1149. last_status_cksum = 0; // force status update
  1150. }
  1151. } else if (strncmp(cmd, "features", i) == 0) { // what features are available
  1152. // print out values of all features
  1153. go_bottom_and_clear_to_eol();
  1154. cookmode();
  1155. show_help();
  1156. rawmode();
  1157. Hit_Return();
  1158. } else if (strncmp(cmd, "list", i) == 0) { // literal print line
  1159. if (b < 0) { // no addr given- use defaults
  1160. q = begin_line(dot); // assume .,. for the range
  1161. r = end_line(dot);
  1162. }
  1163. go_bottom_and_clear_to_eol();
  1164. puts("\r");
  1165. for (; q <= r; q++) {
  1166. int c_is_no_print;
  1167. c = *q;
  1168. c_is_no_print = (c & 0x80) && !Isprint(c);
  1169. if (c_is_no_print) {
  1170. c = '.';
  1171. standout_start();
  1172. }
  1173. if (c == '\n') {
  1174. write1("$\r");
  1175. } else if (c < ' ' || c == 127) {
  1176. bb_putchar('^');
  1177. if (c == 127)
  1178. c = '?';
  1179. else
  1180. c += '@';
  1181. }
  1182. bb_putchar(c);
  1183. if (c_is_no_print)
  1184. standout_end();
  1185. }
  1186. Hit_Return();
  1187. } else if (strncmp(cmd, "quit", i) == 0 // quit
  1188. || strncmp(cmd, "next", i) == 0 // edit next file
  1189. || strncmp(cmd, "prev", i) == 0 // edit previous file
  1190. ) {
  1191. int n;
  1192. if (useforce) {
  1193. if (*cmd == 'q') {
  1194. // force end of argv list
  1195. optind = save_argc;
  1196. }
  1197. editing = 0;
  1198. goto ret;
  1199. }
  1200. // don't exit if the file been modified
  1201. if (modified_count) {
  1202. status_line_bold("No write since last change (:%s! overrides)", cmd);
  1203. goto ret;
  1204. }
  1205. // are there other file to edit
  1206. n = save_argc - optind - 1;
  1207. if (*cmd == 'q' && n > 0) {
  1208. status_line_bold("%d more file(s) to edit", n);
  1209. goto ret;
  1210. }
  1211. if (*cmd == 'n' && n <= 0) {
  1212. status_line_bold("No more files to edit");
  1213. goto ret;
  1214. }
  1215. if (*cmd == 'p') {
  1216. // are there previous files to edit
  1217. if (optind < 1) {
  1218. status_line_bold("No previous files to edit");
  1219. goto ret;
  1220. }
  1221. optind -= 2;
  1222. }
  1223. editing = 0;
  1224. } else if (strncmp(cmd, "read", i) == 0) { // read file into text[]
  1225. int size;
  1226. fn = args;
  1227. if (!fn[0]) {
  1228. status_line_bold("No filename given");
  1229. goto ret;
  1230. }
  1231. if (b < 0) { // no addr given- use defaults
  1232. q = begin_line(dot); // assume "dot"
  1233. }
  1234. // read after current line- unless user said ":0r foo"
  1235. if (b != 0) {
  1236. q = next_line(q);
  1237. // read after last line
  1238. if (q == end-1)
  1239. ++q;
  1240. }
  1241. { // dance around potentially-reallocated text[]
  1242. uintptr_t ofs = q - text;
  1243. size = file_insert(fn, q, 0);
  1244. q = text + ofs;
  1245. }
  1246. if (size < 0)
  1247. goto ret; // nothing was inserted
  1248. // how many lines in text[]?
  1249. li = count_lines(q, q + size - 1);
  1250. status_line("'%s'"
  1251. IF_FEATURE_VI_READONLY("%s")
  1252. " %dL, %dC",
  1253. fn,
  1254. IF_FEATURE_VI_READONLY((readonly_mode ? " [Readonly]" : ""),)
  1255. li, size
  1256. );
  1257. if (size > 0) {
  1258. // if the insert is before "dot" then we need to update
  1259. if (q <= dot)
  1260. dot += size;
  1261. }
  1262. } else if (strncmp(cmd, "rewind", i) == 0) { // rewind cmd line args
  1263. if (modified_count && !useforce) {
  1264. status_line_bold("No write since last change (:%s! overrides)", cmd);
  1265. } else {
  1266. // reset the filenames to edit
  1267. optind = -1; /* start from 0th file */
  1268. editing = 0;
  1269. }
  1270. #if ENABLE_FEATURE_VI_SET
  1271. } else if (strncmp(cmd, "set", i) == 0) { // set or clear features
  1272. #if ENABLE_FEATURE_VI_SETOPTS
  1273. char *argp;
  1274. #endif
  1275. i = 0; // offset into args
  1276. // only blank is regarded as args delimiter. What about tab '\t'?
  1277. if (!args[0] || strcasecmp(args, "all") == 0) {
  1278. // print out values of all options
  1279. #if ENABLE_FEATURE_VI_SETOPTS
  1280. status_line_bold(
  1281. "%sautoindent "
  1282. "%sflash "
  1283. "%signorecase "
  1284. "%sshowmatch "
  1285. "tabstop=%u",
  1286. autoindent ? "" : "no",
  1287. err_method ? "" : "no",
  1288. ignorecase ? "" : "no",
  1289. showmatch ? "" : "no",
  1290. tabstop
  1291. );
  1292. #endif
  1293. goto ret;
  1294. }
  1295. #if ENABLE_FEATURE_VI_SETOPTS
  1296. argp = args;
  1297. while (*argp) {
  1298. if (strncmp(argp, "no", 2) == 0)
  1299. i = 2; // ":set noautoindent"
  1300. setops(argp, "autoindent ", i, "ai", VI_AUTOINDENT);
  1301. setops(argp, "flash " , i, "fl", VI_ERR_METHOD);
  1302. setops(argp, "ignorecase ", i, "ic", VI_IGNORECASE);
  1303. setops(argp, "showmatch " , i, "sm", VI_SHOWMATCH );
  1304. if (strncmp(argp + i, "tabstop=", 8) == 0) {
  1305. int t = 0;
  1306. sscanf(argp + i+8, "%u", &t);
  1307. if (t > 0 && t <= MAX_TABSTOP)
  1308. tabstop = t;
  1309. }
  1310. argp = skip_non_whitespace(argp);
  1311. argp = skip_whitespace(argp);
  1312. }
  1313. #endif /* FEATURE_VI_SETOPTS */
  1314. #endif /* FEATURE_VI_SET */
  1315. #if ENABLE_FEATURE_VI_SEARCH
  1316. } else if (cmd[0] == 's') { // substitute a pattern with a replacement pattern
  1317. char *F, *R, *flags;
  1318. size_t len_F, len_R;
  1319. int gflag; // global replace flag
  1320. #if ENABLE_FEATURE_VI_UNDO
  1321. int dont_chain_first_item = ALLOW_UNDO;
  1322. #endif
  1323. // F points to the "find" pattern
  1324. // R points to the "replace" pattern
  1325. // replace the cmd line delimiters "/" with NULs
  1326. c = orig_buf[1]; // what is the delimiter
  1327. F = orig_buf + 2; // start of "find"
  1328. R = strchr(F, c); // middle delimiter
  1329. if (!R)
  1330. goto colon_s_fail;
  1331. len_F = R - F;
  1332. *R++ = '\0'; // terminate "find"
  1333. flags = strchr(R, c);
  1334. if (!flags)
  1335. goto colon_s_fail;
  1336. len_R = flags - R;
  1337. *flags++ = '\0'; // terminate "replace"
  1338. gflag = *flags;
  1339. q = begin_line(q);
  1340. if (b < 0) { // maybe :s/foo/bar/
  1341. q = begin_line(dot); // start with cur line
  1342. b = count_lines(text, q); // cur line number
  1343. }
  1344. if (e < 0)
  1345. e = b; // maybe :.s/foo/bar/
  1346. for (i = b; i <= e; i++) { // so, :20,23 s \0 find \0 replace \0
  1347. char *ls = q; // orig line start
  1348. char *found;
  1349. vc4:
  1350. found = char_search(q, F, FORWARD, LIMITED); // search cur line only for "find"
  1351. if (found) {
  1352. uintptr_t bias;
  1353. // we found the "find" pattern - delete it
  1354. // For undo support, the first item should not be chained
  1355. text_hole_delete(found, found + len_F - 1, dont_chain_first_item);
  1356. #if ENABLE_FEATURE_VI_UNDO
  1357. dont_chain_first_item = ALLOW_UNDO_CHAIN;
  1358. #endif
  1359. // insert the "replace" patern
  1360. bias = string_insert(found, R, ALLOW_UNDO_CHAIN);
  1361. found += bias;
  1362. ls += bias;
  1363. /*q += bias; - recalculated anyway */
  1364. // check for "global" :s/foo/bar/g
  1365. if (gflag == 'g') {
  1366. if ((found + len_R) < end_line(ls)) {
  1367. q = found + len_R;
  1368. goto vc4; // don't let q move past cur line
  1369. }
  1370. }
  1371. }
  1372. q = next_line(ls);
  1373. }
  1374. #endif /* FEATURE_VI_SEARCH */
  1375. } else if (strncmp(cmd, "version", i) == 0) { // show software version
  1376. status_line(BB_VER);
  1377. } else if (strncmp(cmd, "write", i) == 0 // write text to file
  1378. || strncmp(cmd, "wq", i) == 0
  1379. || strncmp(cmd, "wn", i) == 0
  1380. || (cmd[0] == 'x' && !cmd[1])
  1381. ) {
  1382. int size;
  1383. //int forced = FALSE;
  1384. // is there a file name to write to?
  1385. if (args[0]) {
  1386. fn = args;
  1387. }
  1388. #if ENABLE_FEATURE_VI_READONLY
  1389. if (readonly_mode && !useforce) {
  1390. status_line_bold("'%s' is read only", fn);
  1391. goto ret;
  1392. }
  1393. #endif
  1394. //if (useforce) {
  1395. // if "fn" is not write-able, chmod u+w
  1396. // sprintf(syscmd, "chmod u+w %s", fn);
  1397. // system(syscmd);
  1398. // forced = TRUE;
  1399. //}
  1400. if (modified_count != 0 || cmd[0] != 'x') {
  1401. size = r - q + 1;
  1402. l = file_write(fn, q, r);
  1403. } else {
  1404. size = 0;
  1405. l = 0;
  1406. }
  1407. //if (useforce && forced) {
  1408. // chmod u-w
  1409. // sprintf(syscmd, "chmod u-w %s", fn);
  1410. // system(syscmd);
  1411. // forced = FALSE;
  1412. //}
  1413. if (l < 0) {
  1414. if (l == -1)
  1415. status_line_bold_errno(fn);
  1416. } else {
  1417. // how many lines written
  1418. li = count_lines(q, q + l - 1);
  1419. status_line("'%s' %dL, %dC", fn, li, l);
  1420. if (l == size) {
  1421. if (q == text && q + l == end) {
  1422. modified_count = 0;
  1423. last_modified_count = -1;
  1424. }
  1425. if (cmd[0] == 'x'
  1426. || cmd[1] == 'q' || cmd[1] == 'n'
  1427. || cmd[1] == 'Q' || cmd[1] == 'N'
  1428. ) {
  1429. editing = 0;
  1430. }
  1431. }
  1432. }
  1433. #if ENABLE_FEATURE_VI_YANKMARK
  1434. } else if (strncmp(cmd, "yank", i) == 0) { // yank lines
  1435. if (b < 0) { // no addr given- use defaults
  1436. q = begin_line(dot); // assume .,. for the range
  1437. r = end_line(dot);
  1438. }
  1439. text_yank(q, r, YDreg);
  1440. li = count_lines(q, r);
  1441. status_line("Yank %d lines (%d chars) into [%c]",
  1442. li, strlen(reg[YDreg]), what_reg());
  1443. #endif
  1444. } else {
  1445. // cmd unknown
  1446. not_implemented(cmd);
  1447. }
  1448. ret:
  1449. dot = bound_dot(dot); // make sure "dot" is valid
  1450. return;
  1451. #if ENABLE_FEATURE_VI_SEARCH
  1452. colon_s_fail:
  1453. status_line(":s expression missing delimiters");
  1454. #endif
  1455. #endif /* FEATURE_VI_COLON */
  1456. }
  1457. static void Hit_Return(void)
  1458. {
  1459. int c;
  1460. standout_start();
  1461. write1("[Hit return to continue]");
  1462. standout_end();
  1463. while ((c = get_one_char()) != '\n' && c != '\r')
  1464. continue;
  1465. redraw(TRUE); // force redraw all
  1466. }
  1467. static int next_tabstop(int col)
  1468. {
  1469. return col + ((tabstop - 1) - (col % tabstop));
  1470. }
  1471. //----- Synchronize the cursor to Dot --------------------------
  1472. static NOINLINE void sync_cursor(char *d, int *row, int *col)
  1473. {
  1474. char *beg_cur; // begin and end of "d" line
  1475. char *tp;
  1476. int cnt, ro, co;
  1477. beg_cur = begin_line(d); // first char of cur line
  1478. if (beg_cur < screenbegin) {
  1479. // "d" is before top line on screen
  1480. // how many lines do we have to move
  1481. cnt = count_lines(beg_cur, screenbegin);
  1482. sc1:
  1483. screenbegin = beg_cur;
  1484. if (cnt > (rows - 1) / 2) {
  1485. // we moved too many lines. put "dot" in middle of screen
  1486. for (cnt = 0; cnt < (rows - 1) / 2; cnt++) {
  1487. screenbegin = prev_line(screenbegin);
  1488. }
  1489. }
  1490. } else {
  1491. char *end_scr; // begin and end of screen
  1492. end_scr = end_screen(); // last char of screen
  1493. if (beg_cur > end_scr) {
  1494. // "d" is after bottom line on screen
  1495. // how many lines do we have to move
  1496. cnt = count_lines(end_scr, beg_cur);
  1497. if (cnt > (rows - 1) / 2)
  1498. goto sc1; // too many lines
  1499. for (ro = 0; ro < cnt - 1; ro++) {
  1500. // move screen begin the same amount
  1501. screenbegin = next_line(screenbegin);
  1502. // now, move the end of screen
  1503. end_scr = next_line(end_scr);
  1504. end_scr = end_line(end_scr);
  1505. }
  1506. }
  1507. }
  1508. // "d" is on screen- find out which row
  1509. tp = screenbegin;
  1510. for (ro = 0; ro < rows - 1; ro++) { // drive "ro" to correct row
  1511. if (tp == beg_cur)
  1512. break;
  1513. tp = next_line(tp);
  1514. }
  1515. // find out what col "d" is on
  1516. co = 0;
  1517. while (tp < d) { // drive "co" to correct column
  1518. if (*tp == '\n') //vda || *tp == '\0')
  1519. break;
  1520. if (*tp == '\t') {
  1521. // handle tabs like real vi
  1522. if (d == tp && cmd_mode) {
  1523. break;
  1524. }
  1525. co = next_tabstop(co);
  1526. } else if ((unsigned char)*tp < ' ' || *tp == 0x7f) {
  1527. co++; // display as ^X, use 2 columns
  1528. }
  1529. co++;
  1530. tp++;
  1531. }
  1532. // "co" is the column where "dot" is.
  1533. // The screen has "columns" columns.
  1534. // The currently displayed columns are 0+offset -- columns+ofset
  1535. // |-------------------------------------------------------------|
  1536. // ^ ^ ^
  1537. // offset | |------- columns ----------------|
  1538. //
  1539. // If "co" is already in this range then we do not have to adjust offset
  1540. // but, we do have to subtract the "offset" bias from "co".
  1541. // If "co" is outside this range then we have to change "offset".
  1542. // If the first char of a line is a tab the cursor will try to stay
  1543. // in column 7, but we have to set offset to 0.
  1544. if (co < 0 + offset) {
  1545. offset = co;
  1546. }
  1547. if (co >= columns + offset) {
  1548. offset = co - columns + 1;
  1549. }
  1550. // if the first char of the line is a tab, and "dot" is sitting on it
  1551. // force offset to 0.
  1552. if (d == beg_cur && *d == '\t') {
  1553. offset = 0;
  1554. }
  1555. co -= offset;
  1556. *row = ro;
  1557. *col = co;
  1558. }
  1559. //----- Text Movement Routines ---------------------------------
  1560. static char *begin_line(char *p) // return pointer to first char cur line
  1561. {
  1562. if (p > text) {
  1563. p = memrchr(text, '\n', p - text);
  1564. if (!p)
  1565. return text;
  1566. return p + 1;
  1567. }
  1568. return p;
  1569. }
  1570. static char *end_line(char *p) // return pointer to NL of cur line
  1571. {
  1572. if (p < end - 1) {
  1573. p = memchr(p, '\n', end - p - 1);
  1574. if (!p)
  1575. return end - 1;
  1576. }
  1577. return p;
  1578. }
  1579. static char *dollar_line(char *p) // return pointer to just before NL line
  1580. {
  1581. p = end_line(p);
  1582. // Try to stay off of the Newline
  1583. if (*p == '\n' && (p - begin_line(p)) > 0)
  1584. p--;
  1585. return p;
  1586. }
  1587. static char *prev_line(char *p) // return pointer first char prev line
  1588. {
  1589. p = begin_line(p); // goto beginning of cur line
  1590. if (p > text && p[-1] == '\n')
  1591. p--; // step to prev line
  1592. p = begin_line(p); // goto beginning of prev line
  1593. return p;
  1594. }
  1595. static char *next_line(char *p) // return pointer first char next line
  1596. {
  1597. p = end_line(p);
  1598. if (p < end - 1 && *p == '\n')
  1599. p++; // step to next line
  1600. return p;
  1601. }
  1602. //----- Text Information Routines ------------------------------
  1603. static char *end_screen(void)
  1604. {
  1605. char *q;
  1606. int cnt;
  1607. // find new bottom line
  1608. q = screenbegin;
  1609. for (cnt = 0; cnt < rows - 2; cnt++)
  1610. q = next_line(q);
  1611. q = end_line(q);
  1612. return q;
  1613. }
  1614. // count line from start to stop
  1615. static int count_lines(char *start, char *stop)
  1616. {
  1617. char *q;
  1618. int cnt;
  1619. if (stop < start) { // start and stop are backwards- reverse them
  1620. q = start;
  1621. start = stop;
  1622. stop = q;
  1623. }
  1624. cnt = 0;
  1625. stop = end_line(stop);
  1626. while (start <= stop && start <= end - 1) {
  1627. start = end_line(start);
  1628. if (*start == '\n')
  1629. cnt++;
  1630. start++;
  1631. }
  1632. return cnt;
  1633. }
  1634. static char *find_line(int li) // find beginning of line #li
  1635. {
  1636. char *q;
  1637. for (q = text; li > 1; li--) {
  1638. q = next_line(q);
  1639. }
  1640. return q;
  1641. }
  1642. //----- Dot Movement Routines ----------------------------------
  1643. static void dot_left(void)
  1644. {
  1645. undo_queue_commit();
  1646. if (dot > text && dot[-1] != '\n')
  1647. dot--;
  1648. }
  1649. static void dot_right(void)
  1650. {
  1651. undo_queue_commit();
  1652. if (dot < end - 1 && *dot != '\n')
  1653. dot++;
  1654. }
  1655. static void dot_begin(void)
  1656. {
  1657. undo_queue_commit();
  1658. dot = begin_line(dot); // return pointer to first char cur line
  1659. }
  1660. static void dot_end(void)
  1661. {
  1662. undo_queue_commit();
  1663. dot = end_line(dot); // return pointer to last char cur line
  1664. }
  1665. static char *move_to_col(char *p, int l)
  1666. {
  1667. int co;
  1668. p = begin_line(p);
  1669. co = 0;
  1670. while (co < l && p < end) {
  1671. if (*p == '\n') //vda || *p == '\0')
  1672. break;
  1673. if (*p == '\t') {
  1674. co = next_tabstop(co);
  1675. } else if (*p < ' ' || *p == 127) {
  1676. co++; // display as ^X, use 2 columns
  1677. }
  1678. co++;
  1679. p++;
  1680. }
  1681. return p;
  1682. }
  1683. static void dot_next(void)
  1684. {
  1685. undo_queue_commit();
  1686. dot = next_line(dot);
  1687. }
  1688. static void dot_prev(void)
  1689. {
  1690. undo_queue_commit();
  1691. dot = prev_line(dot);
  1692. }
  1693. static void dot_scroll(int cnt, int dir)
  1694. {
  1695. char *q;
  1696. undo_queue_commit();
  1697. for (; cnt > 0; cnt--) {
  1698. if (dir < 0) {
  1699. // scroll Backwards
  1700. // ctrl-Y scroll up one line
  1701. screenbegin = prev_line(screenbegin);
  1702. } else {
  1703. // scroll Forwards
  1704. // ctrl-E scroll down one line
  1705. screenbegin = next_line(screenbegin);
  1706. }
  1707. }
  1708. // make sure "dot" stays on the screen so we dont scroll off
  1709. if (dot < screenbegin)
  1710. dot = screenbegin;
  1711. q = end_screen(); // find new bottom line
  1712. if (dot > q)
  1713. dot = begin_line(q); // is dot is below bottom line?
  1714. dot_skip_over_ws();
  1715. }
  1716. static void dot_skip_over_ws(void)
  1717. {
  1718. // skip WS
  1719. while (isspace(*dot) && *dot != '\n' && dot < end - 1)
  1720. dot++;
  1721. }
  1722. static char *bound_dot(char *p) // make sure text[0] <= P < "end"
  1723. {
  1724. if (p >= end && end > text) {
  1725. p = end - 1;
  1726. indicate_error();
  1727. }
  1728. if (p < text) {
  1729. p = text;
  1730. indicate_error();
  1731. }
  1732. return p;
  1733. }
  1734. //----- Helper Utility Routines --------------------------------
  1735. //----------------------------------------------------------------
  1736. //----- Char Routines --------------------------------------------
  1737. /* Chars that are part of a word-
  1738. * 0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
  1739. * Chars that are Not part of a word (stoppers)
  1740. * !"#$%&'()*+,-./:;<=>?@[\]^`{|}~
  1741. * Chars that are WhiteSpace
  1742. * TAB NEWLINE VT FF RETURN SPACE
  1743. * DO NOT COUNT NEWLINE AS WHITESPACE
  1744. */
  1745. static char *new_screen(int ro, int co)
  1746. {
  1747. int li;
  1748. free(screen);
  1749. screensize = ro * co + 8;
  1750. screen = xmalloc(screensize);
  1751. // initialize the new screen. assume this will be a empty file.
  1752. screen_erase();
  1753. // non-existent text[] lines start with a tilde (~).
  1754. for (li = 1; li < ro - 1; li++) {
  1755. screen[(li * co) + 0] = '~';
  1756. }
  1757. return screen;
  1758. }
  1759. #if ENABLE_FEATURE_VI_SEARCH
  1760. # if ENABLE_FEATURE_VI_REGEX_SEARCH
  1761. // search for pattern starting at p
  1762. static char *char_search(char *p, const char *pat, int dir, int range)
  1763. {
  1764. struct re_pattern_buffer preg;
  1765. const char *err;
  1766. char *q;
  1767. int i;
  1768. int size;
  1769. re_syntax_options = RE_SYNTAX_POSIX_EXTENDED;
  1770. if (ignorecase)
  1771. re_syntax_options = RE_SYNTAX_POSIX_EXTENDED | RE_ICASE;
  1772. memset(&preg, 0, sizeof(preg));
  1773. err = re_compile_pattern(pat, strlen(pat), &preg);
  1774. if (err != NULL) {
  1775. status_line_bold("bad search pattern '%s': %s", pat, err);
  1776. return p;
  1777. }
  1778. // assume a LIMITED forward search
  1779. q = end - 1;
  1780. if (dir == BACK)
  1781. q = text;
  1782. // RANGE could be negative if we are searching backwards
  1783. range = q - p;
  1784. q = p;
  1785. size = range;
  1786. if (range < 0) {
  1787. size = -size;
  1788. q = p - size;
  1789. if (q < text)
  1790. q = text;
  1791. }
  1792. // search for the compiled pattern, preg, in p[]
  1793. // range < 0: search backward
  1794. // range > 0: search forward
  1795. // 0 < start < size
  1796. // re_search() < 0: not found or error
  1797. // re_search() >= 0: index of found pattern
  1798. // struct pattern char int int int struct reg
  1799. // re_search(*pattern_buffer, *string, size, start, range, *regs)
  1800. i = re_search(&preg, q, size, /*start:*/ 0, range, /*struct re_registers*:*/ NULL);
  1801. regfree(&preg);
  1802. if (i < 0)
  1803. return NULL;
  1804. if (dir == FORWARD)
  1805. p = p + i;
  1806. else
  1807. p = p - i;
  1808. return p;
  1809. }
  1810. # else
  1811. # if ENABLE_FEATURE_VI_SETOPTS
  1812. static int mycmp(const char *s1, const char *s2, int len)
  1813. {
  1814. if (ignorecase) {
  1815. return strncasecmp(s1, s2, len);
  1816. }
  1817. return strncmp(s1, s2, len);
  1818. }
  1819. # else
  1820. # define mycmp strncmp
  1821. # endif
  1822. static char *char_search(char *p, const char *pat, int dir, int range)
  1823. {
  1824. char *start, *stop;
  1825. int len;
  1826. len = strlen(pat);
  1827. if (dir == FORWARD) {
  1828. stop = end - 1; // assume range is p..end-1
  1829. if (range == LIMITED)
  1830. stop = next_line(p); // range is to next line
  1831. for (start = p; start < stop; start++) {
  1832. if (mycmp(start, pat, len) == 0) {
  1833. return start;
  1834. }
  1835. }
  1836. } else if (dir == BACK) {
  1837. stop = text; // assume range is text..p
  1838. if (range == LIMITED)
  1839. stop = prev_line(p); // range is to prev line
  1840. for (start = p - len; start >= stop; start--) {
  1841. if (mycmp(start, pat, len) == 0) {
  1842. return start;
  1843. }
  1844. }
  1845. }
  1846. // pattern not found
  1847. return NULL;
  1848. }
  1849. # endif
  1850. #endif /* FEATURE_VI_SEARCH */
  1851. static char *char_insert(char *p, char c, int undo) // insert the char c at 'p'
  1852. {
  1853. if (c == 22) { // Is this an ctrl-V?
  1854. p += stupid_insert(p, '^'); // use ^ to indicate literal next
  1855. refresh(FALSE); // show the ^
  1856. c = get_one_char();
  1857. *p = c;
  1858. #if ENABLE_FEATURE_VI_UNDO
  1859. switch (undo) {
  1860. case ALLOW_UNDO:
  1861. undo_push(p, 1, UNDO_INS);
  1862. break;
  1863. case ALLOW_UNDO_CHAIN:
  1864. undo_push(p, 1, UNDO_INS_CHAIN);
  1865. break;
  1866. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  1867. case ALLOW_UNDO_QUEUED:
  1868. undo_push(p, 1, UNDO_INS_QUEUED);
  1869. break;
  1870. # endif
  1871. }
  1872. #else
  1873. modified_count++;
  1874. #endif /* ENABLE_FEATURE_VI_UNDO */
  1875. p++;
  1876. } else if (c == 27) { // Is this an ESC?
  1877. cmd_mode = 0;
  1878. undo_queue_commit();
  1879. cmdcnt = 0;
  1880. end_cmd_q(); // stop adding to q
  1881. last_status_cksum = 0; // force status update
  1882. if ((p[-1] != '\n') && (dot > text)) {
  1883. p--;
  1884. }
  1885. } else if (c == erase_char || c == 8 || c == 127) { // Is this a BS
  1886. if (p > text) {
  1887. p--;
  1888. p = text_hole_delete(p, p, ALLOW_UNDO_QUEUED); // shrink buffer 1 char
  1889. }
  1890. } else {
  1891. // insert a char into text[]
  1892. if (c == 13)
  1893. c = '\n'; // translate \r to \n
  1894. #if ENABLE_FEATURE_VI_UNDO
  1895. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  1896. if (c == '\n')
  1897. undo_queue_commit();
  1898. # endif
  1899. switch (undo) {
  1900. case ALLOW_UNDO:
  1901. undo_push(p, 1, UNDO_INS);
  1902. break;
  1903. case ALLOW_UNDO_CHAIN:
  1904. undo_push(p, 1, UNDO_INS_CHAIN);
  1905. break;
  1906. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  1907. case ALLOW_UNDO_QUEUED:
  1908. undo_push(p, 1, UNDO_INS_QUEUED);
  1909. break;
  1910. # endif
  1911. }
  1912. #else
  1913. modified_count++;
  1914. #endif /* ENABLE_FEATURE_VI_UNDO */
  1915. p += 1 + stupid_insert(p, c); // insert the char
  1916. #if ENABLE_FEATURE_VI_SETOPTS
  1917. if (showmatch && strchr(")]}", c) != NULL) {
  1918. showmatching(p - 1);
  1919. }
  1920. if (autoindent && c == '\n') { // auto indent the new line
  1921. char *q;
  1922. size_t len;
  1923. q = prev_line(p); // use prev line as template
  1924. len = strspn(q, " \t"); // space or tab
  1925. if (len) {
  1926. uintptr_t bias;
  1927. bias = text_hole_make(p, len);
  1928. p += bias;
  1929. q += bias;
  1930. #if ENABLE_FEATURE_VI_UNDO
  1931. undo_push(p, len, UNDO_INS);
  1932. #endif
  1933. memcpy(p, q, len);
  1934. p += len;
  1935. }
  1936. }
  1937. #endif
  1938. }
  1939. return p;
  1940. }
  1941. // might reallocate text[]! use p += stupid_insert(p, ...),
  1942. // and be careful to not use pointers into potentially freed text[]!
  1943. static uintptr_t stupid_insert(char *p, char c) // stupidly insert the char c at 'p'
  1944. {
  1945. uintptr_t bias;
  1946. bias = text_hole_make(p, 1);
  1947. p += bias;
  1948. *p = c;
  1949. return bias;
  1950. }
  1951. static int find_range(char **start, char **stop, char c)
  1952. {
  1953. char *save_dot, *p, *q, *t;
  1954. int cnt, multiline = 0;
  1955. save_dot = dot;
  1956. p = q = dot;
  1957. if (strchr("cdy><", c)) {
  1958. // these cmds operate on whole lines
  1959. p = q = begin_line(p);
  1960. for (cnt = 1; cnt < cmdcnt; cnt++) {
  1961. q = next_line(q);
  1962. }
  1963. q = end_line(q);
  1964. } else if (strchr("^%$0bBeEfth\b\177", c)) {
  1965. // These cmds operate on char positions
  1966. do_cmd(c); // execute movement cmd
  1967. q = dot;
  1968. } else if (strchr("wW", c)) {
  1969. do_cmd(c); // execute movement cmd
  1970. // if we are at the next word's first char
  1971. // step back one char
  1972. // but check the possibilities when it is true
  1973. if (dot > text && ((isspace(dot[-1]) && !isspace(dot[0]))
  1974. || (ispunct(dot[-1]) && !ispunct(dot[0]))
  1975. || (isalnum(dot[-1]) && !isalnum(dot[0]))))
  1976. dot--; // move back off of next word
  1977. if (dot > text && *dot == '\n')
  1978. dot--; // stay off NL
  1979. q = dot;
  1980. } else if (strchr("H-k{", c)) {
  1981. // these operate on multi-lines backwards
  1982. q = end_line(dot); // find NL
  1983. do_cmd(c); // execute movement cmd
  1984. dot_begin();
  1985. p = dot;
  1986. } else if (strchr("L+j}\r\n", c)) {
  1987. // these operate on multi-lines forwards
  1988. p = begin_line(dot);
  1989. do_cmd(c); // execute movement cmd
  1990. dot_end(); // find NL
  1991. q = dot;
  1992. } else {
  1993. // nothing -- this causes any other values of c to
  1994. // represent the one-character range under the
  1995. // cursor. this is correct for ' ' and 'l', but
  1996. // perhaps no others.
  1997. //
  1998. }
  1999. if (q < p) {
  2000. t = q;
  2001. q = p;
  2002. p = t;
  2003. }
  2004. // backward char movements don't include start position
  2005. if (q > p && strchr("^0bBh\b\177", c)) q--;
  2006. multiline = 0;
  2007. for (t = p; t <= q; t++) {
  2008. if (*t == '\n') {
  2009. multiline = 1;
  2010. break;
  2011. }
  2012. }
  2013. *start = p;
  2014. *stop = q;
  2015. dot = save_dot;
  2016. return multiline;
  2017. }
  2018. static int st_test(char *p, int type, int dir, char *tested)
  2019. {
  2020. char c, c0, ci;
  2021. int test, inc;
  2022. inc = dir;
  2023. c = c0 = p[0];
  2024. ci = p[inc];
  2025. test = 0;
  2026. if (type == S_BEFORE_WS) {
  2027. c = ci;
  2028. test = (!isspace(c) || c == '\n');
  2029. }
  2030. if (type == S_TO_WS) {
  2031. c = c0;
  2032. test = (!isspace(c) || c == '\n');
  2033. }
  2034. if (type == S_OVER_WS) {
  2035. c = c0;
  2036. test = isspace(c);
  2037. }
  2038. if (type == S_END_PUNCT) {
  2039. c = ci;
  2040. test = ispunct(c);
  2041. }
  2042. if (type == S_END_ALNUM) {
  2043. c = ci;
  2044. test = (isalnum(c) || c == '_');
  2045. }
  2046. *tested = c;
  2047. return test;
  2048. }
  2049. static char *skip_thing(char *p, int linecnt, int dir, int type)
  2050. {
  2051. char c;
  2052. while (st_test(p, type, dir, &c)) {
  2053. // make sure we limit search to correct number of lines
  2054. if (c == '\n' && --linecnt < 1)
  2055. break;
  2056. if (dir >= 0 && p >= end - 1)
  2057. break;
  2058. if (dir < 0 && p <= text)
  2059. break;
  2060. p += dir; // move to next char
  2061. }
  2062. return p;
  2063. }
  2064. // find matching char of pair () [] {}
  2065. // will crash if c is not one of these
  2066. static char *find_pair(char *p, const char c)
  2067. {
  2068. const char *braces = "()[]{}";
  2069. char match;
  2070. int dir, level;
  2071. dir = strchr(braces, c) - braces;
  2072. dir ^= 1;
  2073. match = braces[dir];
  2074. dir = ((dir & 1) << 1) - 1; /* 1 for ([{, -1 for )\} */
  2075. // look for match, count levels of pairs (( ))
  2076. level = 1;
  2077. for (;;) {
  2078. p += dir;
  2079. if (p < text || p >= end)
  2080. return NULL;
  2081. if (*p == c)
  2082. level++; // increase pair levels
  2083. if (*p == match) {
  2084. level--; // reduce pair level
  2085. if (level == 0)
  2086. return p; // found matching pair
  2087. }
  2088. }
  2089. }
  2090. #if ENABLE_FEATURE_VI_SETOPTS
  2091. // show the matching char of a pair, () [] {}
  2092. static void showmatching(char *p)
  2093. {
  2094. char *q, *save_dot;
  2095. // we found half of a pair
  2096. q = find_pair(p, *p); // get loc of matching char
  2097. if (q == NULL) {
  2098. indicate_error(); // no matching char
  2099. } else {
  2100. // "q" now points to matching pair
  2101. save_dot = dot; // remember where we are
  2102. dot = q; // go to new loc
  2103. refresh(FALSE); // let the user see it
  2104. mysleep(40); // give user some time
  2105. dot = save_dot; // go back to old loc
  2106. refresh(FALSE);
  2107. }
  2108. }
  2109. #endif /* FEATURE_VI_SETOPTS */
  2110. #if ENABLE_FEATURE_VI_UNDO
  2111. static void flush_undo_data(void)
  2112. {
  2113. struct undo_object *undo_entry;
  2114. while (undo_stack_tail) {
  2115. undo_entry = undo_stack_tail;
  2116. undo_stack_tail = undo_entry->prev;
  2117. free(undo_entry);
  2118. }
  2119. }
  2120. // Undo functions and hooks added by Jody Bruchon (jody@jodybruchon.com)
  2121. static void undo_push(char *src, unsigned int length, uint8_t u_type) // Add to the undo stack
  2122. {
  2123. struct undo_object *undo_entry;
  2124. // "u_type" values
  2125. // UNDO_INS: insertion, undo will remove from buffer
  2126. // UNDO_DEL: deleted text, undo will restore to buffer
  2127. // UNDO_{INS,DEL}_CHAIN: Same as above but also calls undo_pop() when complete
  2128. // The CHAIN operations are for handling multiple operations that the user
  2129. // performs with a single action, i.e. REPLACE mode or find-and-replace commands
  2130. // UNDO_{INS,DEL}_QUEUED: If queuing feature is enabled, allow use of the queue
  2131. // for the INS/DEL operation. The raw values should be equal to the values of
  2132. // UNDO_{INS,DEL} ORed with UNDO_QUEUED_FLAG
  2133. #if ENABLE_FEATURE_VI_UNDO_QUEUE
  2134. // This undo queuing functionality groups multiple character typing or backspaces
  2135. // into a single large undo object. This greatly reduces calls to malloc() for
  2136. // single-character operations while typing and has the side benefit of letting
  2137. // an undo operation remove chunks of text rather than a single character.
  2138. switch (u_type) {
  2139. case UNDO_EMPTY: // Just in case this ever happens...
  2140. return;
  2141. case UNDO_DEL_QUEUED:
  2142. if (length != 1)
  2143. return; // Only queue single characters
  2144. switch (undo_queue_state) {
  2145. case UNDO_EMPTY:
  2146. undo_queue_state = UNDO_DEL;
  2147. case UNDO_DEL:
  2148. undo_queue_spos = src;
  2149. undo_q++;
  2150. undo_queue[CONFIG_FEATURE_VI_UNDO_QUEUE_MAX - undo_q] = *src;
  2151. // If queue is full, dump it into an object
  2152. if (undo_q == CONFIG_FEATURE_VI_UNDO_QUEUE_MAX)
  2153. undo_queue_commit();
  2154. return;
  2155. case UNDO_INS:
  2156. // Switch from storing inserted text to deleted text
  2157. undo_queue_commit();
  2158. undo_push(src, length, UNDO_DEL_QUEUED);
  2159. return;
  2160. }
  2161. break;
  2162. case UNDO_INS_QUEUED:
  2163. if (length != 1)
  2164. return;
  2165. switch (undo_queue_state) {
  2166. case UNDO_EMPTY:
  2167. undo_queue_state = UNDO_INS;
  2168. undo_queue_spos = src;
  2169. case UNDO_INS:
  2170. undo_q++; // Don't need to save any data for insertions
  2171. if (undo_q == CONFIG_FEATURE_VI_UNDO_QUEUE_MAX)
  2172. undo_queue_commit();
  2173. return;
  2174. case UNDO_DEL:
  2175. // Switch from storing deleted text to inserted text
  2176. undo_queue_commit();
  2177. undo_push(src, length, UNDO_INS_QUEUED);
  2178. return;
  2179. }
  2180. break;
  2181. }
  2182. #else
  2183. // If undo queuing is disabled, ignore the queuing flag entirely
  2184. u_type = u_type & ~UNDO_QUEUED_FLAG;
  2185. #endif
  2186. // Allocate a new undo object
  2187. if (u_type == UNDO_DEL || u_type == UNDO_DEL_CHAIN) {
  2188. // For UNDO_DEL objects, save deleted text
  2189. if ((src + length) == end)
  2190. length--;
  2191. // If this deletion empties text[], strip the newline. When the buffer becomes
  2192. // zero-length, a newline is added back, which requires this to compensate.
  2193. undo_entry = xzalloc(offsetof(struct undo_object, undo_text) + length);
  2194. memcpy(undo_entry->undo_text, src, length);
  2195. } else {
  2196. undo_entry = xzalloc(sizeof(*undo_entry));
  2197. }
  2198. undo_entry->length = length;
  2199. #if ENABLE_FEATURE_VI_UNDO_QUEUE
  2200. if ((u_type & UNDO_USE_SPOS) != 0) {
  2201. undo_entry->start = undo_queue_spos - text; // use start position from queue
  2202. } else {
  2203. undo_entry->start = src - text; // use offset from start of text buffer
  2204. }
  2205. u_type = (u_type & ~UNDO_USE_SPOS);
  2206. #else
  2207. undo_entry->start = src - text;
  2208. #endif
  2209. undo_entry->u_type = u_type;
  2210. // Push it on undo stack
  2211. undo_entry->prev = undo_stack_tail;
  2212. undo_stack_tail = undo_entry;
  2213. modified_count++;
  2214. }
  2215. static void undo_pop(void) // Undo the last operation
  2216. {
  2217. int repeat;
  2218. char *u_start, *u_end;
  2219. struct undo_object *undo_entry;
  2220. // Commit pending undo queue before popping (should be unnecessary)
  2221. undo_queue_commit();
  2222. undo_entry = undo_stack_tail;
  2223. // Check for an empty undo stack
  2224. if (!undo_entry) {
  2225. status_line("Already at oldest change");
  2226. return;
  2227. }
  2228. switch (undo_entry->u_type) {
  2229. case UNDO_DEL:
  2230. case UNDO_DEL_CHAIN:
  2231. // make hole and put in text that was deleted; deallocate text
  2232. u_start = text + undo_entry->start;
  2233. text_hole_make(u_start, undo_entry->length);
  2234. memcpy(u_start, undo_entry->undo_text, undo_entry->length);
  2235. status_line("Undo [%d] %s %d chars at position %d",
  2236. modified_count, "restored",
  2237. undo_entry->length, undo_entry->start
  2238. );
  2239. break;
  2240. case UNDO_INS:
  2241. case UNDO_INS_CHAIN:
  2242. // delete what was inserted
  2243. u_start = undo_entry->start + text;
  2244. u_end = u_start - 1 + undo_entry->length;
  2245. text_hole_delete(u_start, u_end, NO_UNDO);
  2246. status_line("Undo [%d] %s %d chars at position %d",
  2247. modified_count, "deleted",
  2248. undo_entry->length, undo_entry->start
  2249. );
  2250. break;
  2251. }
  2252. repeat = 0;
  2253. switch (undo_entry->u_type) {
  2254. // If this is the end of a chain, lower modification count and refresh display
  2255. case UNDO_DEL:
  2256. case UNDO_INS:
  2257. dot = (text + undo_entry->start);
  2258. refresh(FALSE);
  2259. break;
  2260. case UNDO_DEL_CHAIN:
  2261. case UNDO_INS_CHAIN:
  2262. repeat = 1;
  2263. break;
  2264. }
  2265. // Deallocate the undo object we just processed
  2266. undo_stack_tail = undo_entry->prev;
  2267. free(undo_entry);
  2268. modified_count--;
  2269. // For chained operations, continue popping all the way down the chain.
  2270. if (repeat) {
  2271. undo_pop(); // Follow the undo chain if one exists
  2272. }
  2273. }
  2274. #if ENABLE_FEATURE_VI_UNDO_QUEUE
  2275. static void undo_queue_commit(void) // Flush any queued objects to the undo stack
  2276. {
  2277. // Pushes the queue object onto the undo stack
  2278. if (undo_q > 0) {
  2279. // Deleted character undo events grow from the end
  2280. undo_push(undo_queue + CONFIG_FEATURE_VI_UNDO_QUEUE_MAX - undo_q,
  2281. undo_q,
  2282. (undo_queue_state | UNDO_USE_SPOS)
  2283. );
  2284. undo_queue_state = UNDO_EMPTY;
  2285. undo_q = 0;
  2286. }
  2287. }
  2288. #endif
  2289. #endif /* ENABLE_FEATURE_VI_UNDO */
  2290. // open a hole in text[]
  2291. // might reallocate text[]! use p += text_hole_make(p, ...),
  2292. // and be careful to not use pointers into potentially freed text[]!
  2293. static uintptr_t text_hole_make(char *p, int size) // at "p", make a 'size' byte hole
  2294. {
  2295. uintptr_t bias = 0;
  2296. if (size <= 0)
  2297. return bias;
  2298. end += size; // adjust the new END
  2299. if (end >= (text + text_size)) {
  2300. char *new_text;
  2301. text_size += end - (text + text_size) + 10240;
  2302. new_text = xrealloc(text, text_size);
  2303. bias = (new_text - text);
  2304. screenbegin += bias;
  2305. dot += bias;
  2306. end += bias;
  2307. p += bias;
  2308. #if ENABLE_FEATURE_VI_YANKMARK
  2309. {
  2310. int i;
  2311. for (i = 0; i < ARRAY_SIZE(mark); i++)
  2312. if (mark[i])
  2313. mark[i] += bias;
  2314. }
  2315. #endif
  2316. text = new_text;
  2317. }
  2318. memmove(p + size, p, end - size - p);
  2319. memset(p, ' ', size); // clear new hole
  2320. return bias;
  2321. }
  2322. // close a hole in text[]
  2323. // "undo" value indicates if this operation should be undo-able
  2324. static char *text_hole_delete(char *p, char *q, int undo) // delete "p" through "q", inclusive
  2325. {
  2326. char *src, *dest;
  2327. int cnt, hole_size;
  2328. // move forwards, from beginning
  2329. // assume p <= q
  2330. src = q + 1;
  2331. dest = p;
  2332. if (q < p) { // they are backward- swap them
  2333. src = p + 1;
  2334. dest = q;
  2335. }
  2336. hole_size = q - p + 1;
  2337. cnt = end - src;
  2338. #if ENABLE_FEATURE_VI_UNDO
  2339. switch (undo) {
  2340. case NO_UNDO:
  2341. break;
  2342. case ALLOW_UNDO:
  2343. undo_push(p, hole_size, UNDO_DEL);
  2344. break;
  2345. case ALLOW_UNDO_CHAIN:
  2346. undo_push(p, hole_size, UNDO_DEL_CHAIN);
  2347. break;
  2348. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  2349. case ALLOW_UNDO_QUEUED:
  2350. undo_push(p, hole_size, UNDO_DEL_QUEUED);
  2351. break;
  2352. # endif
  2353. }
  2354. modified_count--;
  2355. #endif
  2356. if (src < text || src > end)
  2357. goto thd0;
  2358. if (dest < text || dest >= end)
  2359. goto thd0;
  2360. modified_count++;
  2361. if (src >= end)
  2362. goto thd_atend; // just delete the end of the buffer
  2363. memmove(dest, src, cnt);
  2364. thd_atend:
  2365. end = end - hole_size; // adjust the new END
  2366. if (dest >= end)
  2367. dest = end - 1; // make sure dest in below end-1
  2368. if (end <= text)
  2369. dest = end = text; // keep pointers valid
  2370. thd0:
  2371. return dest;
  2372. }
  2373. // copy text into register, then delete text.
  2374. // if dist <= 0, do not include, or go past, a NewLine
  2375. //
  2376. static char *yank_delete(char *start, char *stop, int dist, int yf, int undo)
  2377. {
  2378. char *p;
  2379. // make sure start <= stop
  2380. if (start > stop) {
  2381. // they are backwards, reverse them
  2382. p = start;
  2383. start = stop;
  2384. stop = p;
  2385. }
  2386. if (dist <= 0) {
  2387. // we cannot cross NL boundaries
  2388. p = start;
  2389. if (*p == '\n')
  2390. return p;
  2391. // dont go past a NewLine
  2392. for (; p + 1 <= stop; p++) {
  2393. if (p[1] == '\n') {
  2394. stop = p; // "stop" just before NewLine
  2395. break;
  2396. }
  2397. }
  2398. }
  2399. p = start;
  2400. #if ENABLE_FEATURE_VI_YANKMARK
  2401. text_yank(start, stop, YDreg);
  2402. #endif
  2403. if (yf == YANKDEL) {
  2404. p = text_hole_delete(start, stop, undo);
  2405. } // delete lines
  2406. return p;
  2407. }
  2408. static void show_help(void)
  2409. {
  2410. puts("These features are available:"
  2411. #if ENABLE_FEATURE_VI_SEARCH
  2412. "\n\tPattern searches with / and ?"
  2413. #endif
  2414. #if ENABLE_FEATURE_VI_DOT_CMD
  2415. "\n\tLast command repeat with ."
  2416. #endif
  2417. #if ENABLE_FEATURE_VI_YANKMARK
  2418. "\n\tLine marking with 'x"
  2419. "\n\tNamed buffers with \"x"
  2420. #endif
  2421. #if ENABLE_FEATURE_VI_READONLY
  2422. //not implemented: "\n\tReadonly if vi is called as \"view\""
  2423. //redundant: usage text says this too: "\n\tReadonly with -R command line arg"
  2424. #endif
  2425. #if ENABLE_FEATURE_VI_SET
  2426. "\n\tSome colon mode commands with :"
  2427. #endif
  2428. #if ENABLE_FEATURE_VI_SETOPTS
  2429. "\n\tSettable options with \":set\""
  2430. #endif
  2431. #if ENABLE_FEATURE_VI_USE_SIGNALS
  2432. "\n\tSignal catching- ^C"
  2433. "\n\tJob suspend and resume with ^Z"
  2434. #endif
  2435. #if ENABLE_FEATURE_VI_WIN_RESIZE
  2436. "\n\tAdapt to window re-sizes"
  2437. #endif
  2438. );
  2439. }
  2440. #if ENABLE_FEATURE_VI_DOT_CMD
  2441. static void start_new_cmd_q(char c)
  2442. {
  2443. // get buffer for new cmd
  2444. // if there is a current cmd count put it in the buffer first
  2445. if (cmdcnt > 0) {
  2446. lmc_len = sprintf(last_modifying_cmd, "%d%c", cmdcnt, c);
  2447. } else { // just save char c onto queue
  2448. last_modifying_cmd[0] = c;
  2449. lmc_len = 1;
  2450. }
  2451. adding2q = 1;
  2452. }
  2453. static void end_cmd_q(void)
  2454. {
  2455. #if ENABLE_FEATURE_VI_YANKMARK
  2456. YDreg = 26; // go back to default Yank/Delete reg
  2457. #endif
  2458. adding2q = 0;
  2459. }
  2460. #endif /* FEATURE_VI_DOT_CMD */
  2461. #if ENABLE_FEATURE_VI_YANKMARK \
  2462. || (ENABLE_FEATURE_VI_COLON && ENABLE_FEATURE_VI_SEARCH) \
  2463. || ENABLE_FEATURE_VI_CRASHME
  2464. // might reallocate text[]! use p += string_insert(p, ...),
  2465. // and be careful to not use pointers into potentially freed text[]!
  2466. static uintptr_t string_insert(char *p, const char *s, int undo) // insert the string at 'p'
  2467. {
  2468. uintptr_t bias;
  2469. int i;
  2470. i = strlen(s);
  2471. #if ENABLE_FEATURE_VI_UNDO
  2472. switch (undo) {
  2473. case ALLOW_UNDO:
  2474. undo_push(p, i, UNDO_INS);
  2475. break;
  2476. case ALLOW_UNDO_CHAIN:
  2477. undo_push(p, i, UNDO_INS_CHAIN);
  2478. break;
  2479. }
  2480. #endif
  2481. bias = text_hole_make(p, i);
  2482. p += bias;
  2483. memcpy(p, s, i);
  2484. #if ENABLE_FEATURE_VI_YANKMARK
  2485. {
  2486. int cnt;
  2487. for (cnt = 0; *s != '\0'; s++) {
  2488. if (*s == '\n')
  2489. cnt++;
  2490. }
  2491. status_line("Put %d lines (%d chars) from [%c]", cnt, i, what_reg());
  2492. }
  2493. #endif
  2494. return bias;
  2495. }
  2496. #endif
  2497. #if ENABLE_FEATURE_VI_YANKMARK
  2498. static char *text_yank(char *p, char *q, int dest) // copy text into a register
  2499. {
  2500. int cnt = q - p;
  2501. if (cnt < 0) { // they are backwards- reverse them
  2502. p = q;
  2503. cnt = -cnt;
  2504. }
  2505. free(reg[dest]); // if already a yank register, free it
  2506. reg[dest] = xstrndup(p, cnt + 1);
  2507. return p;
  2508. }
  2509. static char what_reg(void)
  2510. {
  2511. char c;
  2512. c = 'D'; // default to D-reg
  2513. if (0 <= YDreg && YDreg <= 25)
  2514. c = 'a' + (char) YDreg;
  2515. if (YDreg == 26)
  2516. c = 'D';
  2517. if (YDreg == 27)
  2518. c = 'U';
  2519. return c;
  2520. }
  2521. static void check_context(char cmd)
  2522. {
  2523. // A context is defined to be "modifying text"
  2524. // Any modifying command establishes a new context.
  2525. if (dot < context_start || dot > context_end) {
  2526. if (strchr(modifying_cmds, cmd) != NULL) {
  2527. // we are trying to modify text[]- make this the current context
  2528. mark[27] = mark[26]; // move cur to prev
  2529. mark[26] = dot; // move local to cur
  2530. context_start = prev_line(prev_line(dot));
  2531. context_end = next_line(next_line(dot));
  2532. //loiter= start_loiter= now;
  2533. }
  2534. }
  2535. }
  2536. static char *swap_context(char *p) // goto new context for '' command make this the current context
  2537. {
  2538. char *tmp;
  2539. // the current context is in mark[26]
  2540. // the previous context is in mark[27]
  2541. // only swap context if other context is valid
  2542. if (text <= mark[27] && mark[27] <= end - 1) {
  2543. tmp = mark[27];
  2544. mark[27] = p;
  2545. mark[26] = p = tmp;
  2546. context_start = prev_line(prev_line(prev_line(p)));
  2547. context_end = next_line(next_line(next_line(p)));
  2548. }
  2549. return p;
  2550. }
  2551. #endif /* FEATURE_VI_YANKMARK */
  2552. //----- Set terminal attributes --------------------------------
  2553. static void rawmode(void)
  2554. {
  2555. // no TERMIOS_CLEAR_ISIG: leave ISIG on - allow signals
  2556. set_termios_to_raw(STDIN_FILENO, &term_orig, TERMIOS_RAW_CRNL);
  2557. erase_char = term_orig.c_cc[VERASE];
  2558. }
  2559. static void cookmode(void)
  2560. {
  2561. fflush_all();
  2562. tcsetattr_stdin_TCSANOW(&term_orig);
  2563. }
  2564. #if ENABLE_FEATURE_VI_USE_SIGNALS
  2565. //----- Come here when we get a window resize signal ---------
  2566. static void winch_sig(int sig UNUSED_PARAM)
  2567. {
  2568. int save_errno = errno;
  2569. // FIXME: do it in main loop!!!
  2570. signal(SIGWINCH, winch_sig);
  2571. query_screen_dimensions();
  2572. new_screen(rows, columns); // get memory for virtual screen
  2573. redraw(TRUE); // re-draw the screen
  2574. errno = save_errno;
  2575. }
  2576. //----- Come here when we get a continue signal -------------------
  2577. static void cont_sig(int sig UNUSED_PARAM)
  2578. {
  2579. int save_errno = errno;
  2580. rawmode(); // terminal to "raw"
  2581. last_status_cksum = 0; // force status update
  2582. redraw(TRUE); // re-draw the screen
  2583. signal(SIGTSTP, suspend_sig);
  2584. signal(SIGCONT, SIG_DFL);
  2585. //kill(my_pid, SIGCONT); // huh? why? we are already "continued"...
  2586. errno = save_errno;
  2587. }
  2588. //----- Come here when we get a Suspend signal -------------------
  2589. static void suspend_sig(int sig UNUSED_PARAM)
  2590. {
  2591. int save_errno = errno;
  2592. go_bottom_and_clear_to_eol();
  2593. cookmode(); // terminal to "cooked"
  2594. signal(SIGCONT, cont_sig);
  2595. signal(SIGTSTP, SIG_DFL);
  2596. kill(my_pid, SIGTSTP);
  2597. errno = save_errno;
  2598. }
  2599. //----- Come here when we get a signal ---------------------------
  2600. static void catch_sig(int sig)
  2601. {
  2602. signal(SIGINT, catch_sig);
  2603. siglongjmp(restart, sig);
  2604. }
  2605. #endif /* FEATURE_VI_USE_SIGNALS */
  2606. static int mysleep(int hund) // sleep for 'hund' 1/100 seconds or stdin ready
  2607. {
  2608. struct pollfd pfd[1];
  2609. if (hund != 0)
  2610. fflush_all();
  2611. pfd[0].fd = STDIN_FILENO;
  2612. pfd[0].events = POLLIN;
  2613. return safe_poll(pfd, 1, hund*10) > 0;
  2614. }
  2615. //----- IO Routines --------------------------------------------
  2616. static int readit(void) // read (maybe cursor) key from stdin
  2617. {
  2618. int c;
  2619. fflush_all();
  2620. // Wait for input. TIMEOUT = -1 makes read_key wait even
  2621. // on nonblocking stdin.
  2622. // Note: read_key sets errno to 0 on success.
  2623. again:
  2624. c = read_key(STDIN_FILENO, readbuffer, /*timeout:*/ -1);
  2625. if (c == -1) { // EOF/error
  2626. if (errno == EAGAIN) // paranoia
  2627. goto again;
  2628. go_bottom_and_clear_to_eol();
  2629. cookmode(); // terminal to "cooked"
  2630. bb_error_msg_and_die("can't read user input");
  2631. }
  2632. return c;
  2633. }
  2634. //----- IO Routines --------------------------------------------
  2635. static int get_one_char(void)
  2636. {
  2637. int c;
  2638. #if ENABLE_FEATURE_VI_DOT_CMD
  2639. if (!adding2q) {
  2640. // we are not adding to the q.
  2641. // but, we may be reading from a q
  2642. if (ioq == 0) {
  2643. // there is no current q, read from STDIN
  2644. c = readit(); // get the users input
  2645. } else {
  2646. // there is a queue to get chars from first
  2647. // careful with correct sign expansion!
  2648. c = (unsigned char)*ioq++;
  2649. if (c == '\0') {
  2650. // the end of the q, read from STDIN
  2651. free(ioq_start);
  2652. ioq_start = ioq = 0;
  2653. c = readit(); // get the users input
  2654. }
  2655. }
  2656. } else {
  2657. // adding STDIN chars to q
  2658. c = readit(); // get the users input
  2659. if (lmc_len >= MAX_INPUT_LEN - 1) {
  2660. status_line_bold("last_modifying_cmd overrun");
  2661. } else {
  2662. // add new char to q
  2663. last_modifying_cmd[lmc_len++] = c;
  2664. }
  2665. }
  2666. #else
  2667. c = readit(); // get the users input
  2668. #endif /* FEATURE_VI_DOT_CMD */
  2669. return c;
  2670. }
  2671. // Get input line (uses "status line" area)
  2672. static char *get_input_line(const char *prompt)
  2673. {
  2674. // char [MAX_INPUT_LEN]
  2675. #define buf get_input_line__buf
  2676. int c;
  2677. int i;
  2678. strcpy(buf, prompt);
  2679. last_status_cksum = 0; // force status update
  2680. go_bottom_and_clear_to_eol();
  2681. write1(prompt); // write out the :, /, or ? prompt
  2682. i = strlen(buf);
  2683. while (i < MAX_INPUT_LEN) {
  2684. c = get_one_char();
  2685. if (c == '\n' || c == '\r' || c == 27)
  2686. break; // this is end of input
  2687. if (c == erase_char || c == 8 || c == 127) {
  2688. // user wants to erase prev char
  2689. buf[--i] = '\0';
  2690. write1("\b \b"); // erase char on screen
  2691. if (i <= 0) // user backs up before b-o-l, exit
  2692. break;
  2693. } else if (c > 0 && c < 256) { // exclude Unicode
  2694. // (TODO: need to handle Unicode)
  2695. buf[i] = c;
  2696. buf[++i] = '\0';
  2697. bb_putchar(c);
  2698. }
  2699. }
  2700. refresh(FALSE);
  2701. return buf;
  2702. #undef buf
  2703. }
  2704. // might reallocate text[]!
  2705. static int file_insert(const char *fn, char *p, int initial)
  2706. {
  2707. int cnt = -1;
  2708. int fd, size;
  2709. struct stat statbuf;
  2710. if (p < text)
  2711. p = text;
  2712. if (p > end)
  2713. p = end;
  2714. fd = open(fn, O_RDONLY);
  2715. if (fd < 0) {
  2716. if (!initial)
  2717. status_line_bold_errno(fn);
  2718. return cnt;
  2719. }
  2720. /* Validate file */
  2721. if (fstat(fd, &statbuf) < 0) {
  2722. status_line_bold_errno(fn);
  2723. goto fi;
  2724. }
  2725. if (!S_ISREG(statbuf.st_mode)) {
  2726. status_line_bold("'%s' is not a regular file", fn);
  2727. goto fi;
  2728. }
  2729. size = (statbuf.st_size < INT_MAX ? (int)statbuf.st_size : INT_MAX);
  2730. p += text_hole_make(p, size);
  2731. cnt = full_read(fd, p, size);
  2732. if (cnt < 0) {
  2733. status_line_bold_errno(fn);
  2734. p = text_hole_delete(p, p + size - 1, NO_UNDO); // un-do buffer insert
  2735. } else if (cnt < size) {
  2736. // There was a partial read, shrink unused space
  2737. p = text_hole_delete(p + cnt, p + size - 1, NO_UNDO);
  2738. status_line_bold("can't read '%s'", fn);
  2739. }
  2740. fi:
  2741. close(fd);
  2742. #if ENABLE_FEATURE_VI_READONLY
  2743. if (initial
  2744. && ((access(fn, W_OK) < 0) ||
  2745. /* root will always have access()
  2746. * so we check fileperms too */
  2747. !(statbuf.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH))
  2748. )
  2749. ) {
  2750. SET_READONLY_FILE(readonly_mode);
  2751. }
  2752. #endif
  2753. return cnt;
  2754. }
  2755. static int file_write(char *fn, char *first, char *last)
  2756. {
  2757. int fd, cnt, charcnt;
  2758. if (fn == 0) {
  2759. status_line_bold("No current filename");
  2760. return -2;
  2761. }
  2762. /* By popular request we do not open file with O_TRUNC,
  2763. * but instead ftruncate() it _after_ successful write.
  2764. * Might reduce amount of data lost on power fail etc.
  2765. */
  2766. fd = open(fn, (O_WRONLY | O_CREAT), 0666);
  2767. if (fd < 0)
  2768. return -1;
  2769. cnt = last - first + 1;
  2770. charcnt = full_write(fd, first, cnt);
  2771. ftruncate(fd, charcnt);
  2772. if (charcnt == cnt) {
  2773. // good write
  2774. //modified_count = FALSE;
  2775. } else {
  2776. charcnt = 0;
  2777. }
  2778. close(fd);
  2779. return charcnt;
  2780. }
  2781. //----- Terminal Drawing ---------------------------------------
  2782. // The terminal is made up of 'rows' line of 'columns' columns.
  2783. // classically this would be 24 x 80.
  2784. // screen coordinates
  2785. // 0,0 ... 0,79
  2786. // 1,0 ... 1,79
  2787. // . ... .
  2788. // . ... .
  2789. // 22,0 ... 22,79
  2790. // 23,0 ... 23,79 <- status line
  2791. //----- Move the cursor to row x col (count from 0, not 1) -------
  2792. static void place_cursor(int row, int col)
  2793. {
  2794. char cm1[sizeof(ESC_SET_CURSOR_POS) + sizeof(int)*3 * 2];
  2795. if (row < 0) row = 0;
  2796. if (row >= rows) row = rows - 1;
  2797. if (col < 0) col = 0;
  2798. if (col >= columns) col = columns - 1;
  2799. sprintf(cm1, ESC_SET_CURSOR_POS, row + 1, col + 1);
  2800. write1(cm1);
  2801. }
  2802. //----- Erase from cursor to end of line -----------------------
  2803. static void clear_to_eol(void)
  2804. {
  2805. write1(ESC_CLEAR2EOL);
  2806. }
  2807. static void go_bottom_and_clear_to_eol(void)
  2808. {
  2809. place_cursor(rows - 1, 0);
  2810. clear_to_eol();
  2811. }
  2812. //----- Erase from cursor to end of screen -----------------------
  2813. static void clear_to_eos(void)
  2814. {
  2815. write1(ESC_CLEAR2EOS);
  2816. }
  2817. //----- Start standout mode ------------------------------------
  2818. static void standout_start(void)
  2819. {
  2820. write1(ESC_BOLD_TEXT);
  2821. }
  2822. //----- End standout mode --------------------------------------
  2823. static void standout_end(void)
  2824. {
  2825. write1(ESC_NORM_TEXT);
  2826. }
  2827. //----- Flash the screen --------------------------------------
  2828. static void flash(int h)
  2829. {
  2830. standout_start();
  2831. redraw(TRUE);
  2832. mysleep(h);
  2833. standout_end();
  2834. redraw(TRUE);
  2835. }
  2836. static void indicate_error(void)
  2837. {
  2838. #if ENABLE_FEATURE_VI_CRASHME
  2839. if (crashme > 0)
  2840. return; // generate a random command
  2841. #endif
  2842. if (!err_method) {
  2843. write1(ESC_BELL);
  2844. } else {
  2845. flash(10);
  2846. }
  2847. }
  2848. //----- Screen[] Routines --------------------------------------
  2849. //----- Erase the Screen[] memory ------------------------------
  2850. static void screen_erase(void)
  2851. {
  2852. memset(screen, ' ', screensize); // clear new screen
  2853. }
  2854. static int bufsum(char *buf, int count)
  2855. {
  2856. int sum = 0;
  2857. char *e = buf + count;
  2858. while (buf < e)
  2859. sum += (unsigned char) *buf++;
  2860. return sum;
  2861. }
  2862. //----- Draw the status line at bottom of the screen -------------
  2863. static void show_status_line(void)
  2864. {
  2865. int cnt = 0, cksum = 0;
  2866. // either we already have an error or status message, or we
  2867. // create one.
  2868. if (!have_status_msg) {
  2869. cnt = format_edit_status();
  2870. cksum = bufsum(status_buffer, cnt);
  2871. }
  2872. if (have_status_msg || ((cnt > 0 && last_status_cksum != cksum))) {
  2873. last_status_cksum = cksum; // remember if we have seen this line
  2874. go_bottom_and_clear_to_eol();
  2875. write1(status_buffer);
  2876. if (have_status_msg) {
  2877. if (((int)strlen(status_buffer) - (have_status_msg - 1)) >
  2878. (columns - 1) ) {
  2879. have_status_msg = 0;
  2880. Hit_Return();
  2881. }
  2882. have_status_msg = 0;
  2883. }
  2884. place_cursor(crow, ccol); // put cursor back in correct place
  2885. }
  2886. fflush_all();
  2887. }
  2888. //----- format the status buffer, the bottom line of screen ------
  2889. // format status buffer, with STANDOUT mode
  2890. static void status_line_bold(const char *format, ...)
  2891. {
  2892. va_list args;
  2893. va_start(args, format);
  2894. strcpy(status_buffer, ESC_BOLD_TEXT);
  2895. vsprintf(status_buffer + sizeof(ESC_BOLD_TEXT)-1, format, args);
  2896. strcat(status_buffer, ESC_NORM_TEXT);
  2897. va_end(args);
  2898. have_status_msg = 1 + sizeof(ESC_BOLD_TEXT) + sizeof(ESC_NORM_TEXT) - 2;
  2899. }
  2900. static void status_line_bold_errno(const char *fn)
  2901. {
  2902. status_line_bold("'%s' %s", fn, strerror(errno));
  2903. }
  2904. // format status buffer
  2905. static void status_line(const char *format, ...)
  2906. {
  2907. va_list args;
  2908. va_start(args, format);
  2909. vsprintf(status_buffer, format, args);
  2910. va_end(args);
  2911. have_status_msg = 1;
  2912. }
  2913. // copy s to buf, convert unprintable
  2914. static void print_literal(char *buf, const char *s)
  2915. {
  2916. char *d;
  2917. unsigned char c;
  2918. buf[0] = '\0';
  2919. if (!s[0])
  2920. s = "(NULL)";
  2921. d = buf;
  2922. for (; *s; s++) {
  2923. int c_is_no_print;
  2924. c = *s;
  2925. c_is_no_print = (c & 0x80) && !Isprint(c);
  2926. if (c_is_no_print) {
  2927. strcpy(d, ESC_NORM_TEXT);
  2928. d += sizeof(ESC_NORM_TEXT)-1;
  2929. c = '.';
  2930. }
  2931. if (c < ' ' || c == 0x7f) {
  2932. *d++ = '^';
  2933. c |= '@'; /* 0x40 */
  2934. if (c == 0x7f)
  2935. c = '?';
  2936. }
  2937. *d++ = c;
  2938. *d = '\0';
  2939. if (c_is_no_print) {
  2940. strcpy(d, ESC_BOLD_TEXT);
  2941. d += sizeof(ESC_BOLD_TEXT)-1;
  2942. }
  2943. if (*s == '\n') {
  2944. *d++ = '$';
  2945. *d = '\0';
  2946. }
  2947. if (d - buf > MAX_INPUT_LEN - 10) // paranoia
  2948. break;
  2949. }
  2950. }
  2951. static void not_implemented(const char *s)
  2952. {
  2953. char buf[MAX_INPUT_LEN];
  2954. print_literal(buf, s);
  2955. status_line_bold("\'%s\' is not implemented", buf);
  2956. }
  2957. // show file status on status line
  2958. static int format_edit_status(void)
  2959. {
  2960. static const char cmd_mode_indicator[] ALIGN1 = "-IR-";
  2961. #define tot format_edit_status__tot
  2962. int cur, percent, ret, trunc_at;
  2963. // modified_count is now a counter rather than a flag. this
  2964. // helps reduce the amount of line counting we need to do.
  2965. // (this will cause a mis-reporting of modified status
  2966. // once every MAXINT editing operations.)
  2967. // it would be nice to do a similar optimization here -- if
  2968. // we haven't done a motion that could have changed which line
  2969. // we're on, then we shouldn't have to do this count_lines()
  2970. cur = count_lines(text, dot);
  2971. // count_lines() is expensive.
  2972. // Call it only if something was changed since last time
  2973. // we were here:
  2974. if (modified_count != last_modified_count) {
  2975. tot = cur + count_lines(dot, end - 1) - 1;
  2976. last_modified_count = modified_count;
  2977. }
  2978. // current line percent
  2979. // ------------- ~~ ----------
  2980. // total lines 100
  2981. if (tot > 0) {
  2982. percent = (100 * cur) / tot;
  2983. } else {
  2984. cur = tot = 0;
  2985. percent = 100;
  2986. }
  2987. trunc_at = columns < STATUS_BUFFER_LEN-1 ?
  2988. columns : STATUS_BUFFER_LEN-1;
  2989. ret = snprintf(status_buffer, trunc_at+1,
  2990. #if ENABLE_FEATURE_VI_READONLY
  2991. "%c %s%s%s %d/%d %d%%",
  2992. #else
  2993. "%c %s%s %d/%d %d%%",
  2994. #endif
  2995. cmd_mode_indicator[cmd_mode & 3],
  2996. (current_filename != NULL ? current_filename : "No file"),
  2997. #if ENABLE_FEATURE_VI_READONLY
  2998. (readonly_mode ? " [Readonly]" : ""),
  2999. #endif
  3000. (modified_count ? " [Modified]" : ""),
  3001. cur, tot, percent);
  3002. if (ret >= 0 && ret < trunc_at)
  3003. return ret; /* it all fit */
  3004. return trunc_at; /* had to truncate */
  3005. #undef tot
  3006. }
  3007. //----- Force refresh of all Lines -----------------------------
  3008. static void redraw(int full_screen)
  3009. {
  3010. place_cursor(0, 0);
  3011. clear_to_eos();
  3012. screen_erase(); // erase the internal screen buffer
  3013. last_status_cksum = 0; // force status update
  3014. refresh(full_screen); // this will redraw the entire display
  3015. show_status_line();
  3016. }
  3017. //----- Format a text[] line into a buffer ---------------------
  3018. static char* format_line(char *src /*, int li*/)
  3019. {
  3020. unsigned char c;
  3021. int co;
  3022. int ofs = offset;
  3023. char *dest = scr_out_buf; // [MAX_SCR_COLS + MAX_TABSTOP * 2]
  3024. c = '~'; // char in col 0 in non-existent lines is '~'
  3025. co = 0;
  3026. while (co < columns + tabstop) {
  3027. // have we gone past the end?
  3028. if (src < end) {
  3029. c = *src++;
  3030. if (c == '\n')
  3031. break;
  3032. if ((c & 0x80) && !Isprint(c)) {
  3033. c = '.';
  3034. }
  3035. if (c < ' ' || c == 0x7f) {
  3036. if (c == '\t') {
  3037. c = ' ';
  3038. // co % 8 != 7
  3039. while ((co % tabstop) != (tabstop - 1)) {
  3040. dest[co++] = c;
  3041. }
  3042. } else {
  3043. dest[co++] = '^';
  3044. if (c == 0x7f)
  3045. c = '?';
  3046. else
  3047. c += '@'; // Ctrl-X -> 'X'
  3048. }
  3049. }
  3050. }
  3051. dest[co++] = c;
  3052. // discard scrolled-off-to-the-left portion,
  3053. // in tabstop-sized pieces
  3054. if (ofs >= tabstop && co >= tabstop) {
  3055. memmove(dest, dest + tabstop, co);
  3056. co -= tabstop;
  3057. ofs -= tabstop;
  3058. }
  3059. if (src >= end)
  3060. break;
  3061. }
  3062. // check "short line, gigantic offset" case
  3063. if (co < ofs)
  3064. ofs = co;
  3065. // discard last scrolled off part
  3066. co -= ofs;
  3067. dest += ofs;
  3068. // fill the rest with spaces
  3069. if (co < columns)
  3070. memset(&dest[co], ' ', columns - co);
  3071. return dest;
  3072. }
  3073. //----- Refresh the changed screen lines -----------------------
  3074. // Copy the source line from text[] into the buffer and note
  3075. // if the current screenline is different from the new buffer.
  3076. // If they differ then that line needs redrawing on the terminal.
  3077. //
  3078. static void refresh(int full_screen)
  3079. {
  3080. #define old_offset refresh__old_offset
  3081. int li, changed;
  3082. char *tp, *sp; // pointer into text[] and screen[]
  3083. if (ENABLE_FEATURE_VI_WIN_RESIZE IF_FEATURE_VI_ASK_TERMINAL(&& !G.get_rowcol_error) ) {
  3084. unsigned c = columns, r = rows;
  3085. query_screen_dimensions();
  3086. full_screen |= (c - columns) | (r - rows);
  3087. }
  3088. sync_cursor(dot, &crow, &ccol); // where cursor will be (on "dot")
  3089. tp = screenbegin; // index into text[] of top line
  3090. // compare text[] to screen[] and mark screen[] lines that need updating
  3091. for (li = 0; li < rows - 1; li++) {
  3092. int cs, ce; // column start & end
  3093. char *out_buf;
  3094. // format current text line
  3095. out_buf = format_line(tp /*, li*/);
  3096. // skip to the end of the current text[] line
  3097. if (tp < end) {
  3098. char *t = memchr(tp, '\n', end - tp);
  3099. if (!t) t = end - 1;
  3100. tp = t + 1;
  3101. }
  3102. // see if there are any changes between virtual screen and out_buf
  3103. changed = FALSE; // assume no change
  3104. cs = 0;
  3105. ce = columns - 1;
  3106. sp = &screen[li * columns]; // start of screen line
  3107. if (full_screen) {
  3108. // force re-draw of every single column from 0 - columns-1
  3109. goto re0;
  3110. }
  3111. // compare newly formatted buffer with virtual screen
  3112. // look forward for first difference between buf and screen
  3113. for (; cs <= ce; cs++) {
  3114. if (out_buf[cs] != sp[cs]) {
  3115. changed = TRUE; // mark for redraw
  3116. break;
  3117. }
  3118. }
  3119. // look backward for last difference between out_buf and screen
  3120. for (; ce >= cs; ce--) {
  3121. if (out_buf[ce] != sp[ce]) {
  3122. changed = TRUE; // mark for redraw
  3123. break;
  3124. }
  3125. }
  3126. // now, cs is index of first diff, and ce is index of last diff
  3127. // if horz offset has changed, force a redraw
  3128. if (offset != old_offset) {
  3129. re0:
  3130. changed = TRUE;
  3131. }
  3132. // make a sanity check of columns indexes
  3133. if (cs < 0) cs = 0;
  3134. if (ce > columns - 1) ce = columns - 1;
  3135. if (cs > ce) { cs = 0; ce = columns - 1; }
  3136. // is there a change between virtual screen and out_buf
  3137. if (changed) {
  3138. // copy changed part of buffer to virtual screen
  3139. memcpy(sp+cs, out_buf+cs, ce-cs+1);
  3140. place_cursor(li, cs);
  3141. // write line out to terminal
  3142. fwrite(&sp[cs], ce - cs + 1, 1, stdout);
  3143. }
  3144. }
  3145. place_cursor(crow, ccol);
  3146. old_offset = offset;
  3147. #undef old_offset
  3148. }
  3149. //---------------------------------------------------------------------
  3150. //----- the Ascii Chart -----------------------------------------------
  3151. //
  3152. // 00 nul 01 soh 02 stx 03 etx 04 eot 05 enq 06 ack 07 bel
  3153. // 08 bs 09 ht 0a nl 0b vt 0c np 0d cr 0e so 0f si
  3154. // 10 dle 11 dc1 12 dc2 13 dc3 14 dc4 15 nak 16 syn 17 etb
  3155. // 18 can 19 em 1a sub 1b esc 1c fs 1d gs 1e rs 1f us
  3156. // 20 sp 21 ! 22 " 23 # 24 $ 25 % 26 & 27 '
  3157. // 28 ( 29 ) 2a * 2b + 2c , 2d - 2e . 2f /
  3158. // 30 0 31 1 32 2 33 3 34 4 35 5 36 6 37 7
  3159. // 38 8 39 9 3a : 3b ; 3c < 3d = 3e > 3f ?
  3160. // 40 @ 41 A 42 B 43 C 44 D 45 E 46 F 47 G
  3161. // 48 H 49 I 4a J 4b K 4c L 4d M 4e N 4f O
  3162. // 50 P 51 Q 52 R 53 S 54 T 55 U 56 V 57 W
  3163. // 58 X 59 Y 5a Z 5b [ 5c \ 5d ] 5e ^ 5f _
  3164. // 60 ` 61 a 62 b 63 c 64 d 65 e 66 f 67 g
  3165. // 68 h 69 i 6a j 6b k 6c l 6d m 6e n 6f o
  3166. // 70 p 71 q 72 r 73 s 74 t 75 u 76 v 77 w
  3167. // 78 x 79 y 7a z 7b { 7c | 7d } 7e ~ 7f del
  3168. //---------------------------------------------------------------------
  3169. //----- Execute a Vi Command -----------------------------------
  3170. static void do_cmd(int c)
  3171. {
  3172. char *p, *q, *save_dot;
  3173. char buf[12];
  3174. int dir;
  3175. int cnt, i, j;
  3176. int c1;
  3177. // c1 = c; // quiet the compiler
  3178. // cnt = yf = 0; // quiet the compiler
  3179. // p = q = save_dot = buf; // quiet the compiler
  3180. memset(buf, '\0', sizeof(buf));
  3181. show_status_line();
  3182. /* if this is a cursor key, skip these checks */
  3183. switch (c) {
  3184. case KEYCODE_UP:
  3185. case KEYCODE_DOWN:
  3186. case KEYCODE_LEFT:
  3187. case KEYCODE_RIGHT:
  3188. case KEYCODE_HOME:
  3189. case KEYCODE_END:
  3190. case KEYCODE_PAGEUP:
  3191. case KEYCODE_PAGEDOWN:
  3192. case KEYCODE_DELETE:
  3193. goto key_cmd_mode;
  3194. }
  3195. if (cmd_mode == 2) {
  3196. // flip-flop Insert/Replace mode
  3197. if (c == KEYCODE_INSERT)
  3198. goto dc_i;
  3199. // we are 'R'eplacing the current *dot with new char
  3200. if (*dot == '\n') {
  3201. // don't Replace past E-o-l
  3202. cmd_mode = 1; // convert to insert
  3203. undo_queue_commit();
  3204. } else {
  3205. if (1 <= c || Isprint(c)) {
  3206. if (c != 27)
  3207. dot = yank_delete(dot, dot, 0, YANKDEL, ALLOW_UNDO); // delete char
  3208. dot = char_insert(dot, c, ALLOW_UNDO_CHAIN); // insert new char
  3209. }
  3210. goto dc1;
  3211. }
  3212. }
  3213. if (cmd_mode == 1) {
  3214. // hitting "Insert" twice means "R" replace mode
  3215. if (c == KEYCODE_INSERT) goto dc5;
  3216. // insert the char c at "dot"
  3217. if (1 <= c || Isprint(c)) {
  3218. dot = char_insert(dot, c, ALLOW_UNDO_QUEUED);
  3219. }
  3220. goto dc1;
  3221. }
  3222. key_cmd_mode:
  3223. switch (c) {
  3224. //case 0x01: // soh
  3225. //case 0x09: // ht
  3226. //case 0x0b: // vt
  3227. //case 0x0e: // so
  3228. //case 0x0f: // si
  3229. //case 0x10: // dle
  3230. //case 0x11: // dc1
  3231. //case 0x13: // dc3
  3232. #if ENABLE_FEATURE_VI_CRASHME
  3233. case 0x14: // dc4 ctrl-T
  3234. crashme = (crashme == 0) ? 1 : 0;
  3235. break;
  3236. #endif
  3237. //case 0x16: // syn
  3238. //case 0x17: // etb
  3239. //case 0x18: // can
  3240. //case 0x1c: // fs
  3241. //case 0x1d: // gs
  3242. //case 0x1e: // rs
  3243. //case 0x1f: // us
  3244. //case '!': // !-
  3245. //case '#': // #-
  3246. //case '&': // &-
  3247. //case '(': // (-
  3248. //case ')': // )-
  3249. //case '*': // *-
  3250. //case '=': // =-
  3251. //case '@': // @-
  3252. //case 'F': // F-
  3253. //case 'K': // K-
  3254. //case 'Q': // Q-
  3255. //case 'S': // S-
  3256. //case 'T': // T-
  3257. //case 'V': // V-
  3258. //case '[': // [-
  3259. //case '\\': // \-
  3260. //case ']': // ]-
  3261. //case '_': // _-
  3262. //case '`': // `-
  3263. //case 'v': // v-
  3264. default: // unrecognized command
  3265. buf[0] = c;
  3266. buf[1] = '\0';
  3267. not_implemented(buf);
  3268. end_cmd_q(); // stop adding to q
  3269. case 0x00: // nul- ignore
  3270. break;
  3271. case 2: // ctrl-B scroll up full screen
  3272. case KEYCODE_PAGEUP: // Cursor Key Page Up
  3273. dot_scroll(rows - 2, -1);
  3274. break;
  3275. case 4: // ctrl-D scroll down half screen
  3276. dot_scroll((rows - 2) / 2, 1);
  3277. break;
  3278. case 5: // ctrl-E scroll down one line
  3279. dot_scroll(1, 1);
  3280. break;
  3281. case 6: // ctrl-F scroll down full screen
  3282. case KEYCODE_PAGEDOWN: // Cursor Key Page Down
  3283. dot_scroll(rows - 2, 1);
  3284. break;
  3285. case 7: // ctrl-G show current status
  3286. last_status_cksum = 0; // force status update
  3287. break;
  3288. case 'h': // h- move left
  3289. case KEYCODE_LEFT: // cursor key Left
  3290. case 8: // ctrl-H- move left (This may be ERASE char)
  3291. case 0x7f: // DEL- move left (This may be ERASE char)
  3292. do {
  3293. dot_left();
  3294. } while (--cmdcnt > 0);
  3295. break;
  3296. case 10: // Newline ^J
  3297. case 'j': // j- goto next line, same col
  3298. case KEYCODE_DOWN: // cursor key Down
  3299. do {
  3300. dot_next(); // go to next B-o-l
  3301. // try stay in same col
  3302. dot = move_to_col(dot, ccol + offset);
  3303. } while (--cmdcnt > 0);
  3304. break;
  3305. case 12: // ctrl-L force redraw whole screen
  3306. case 18: // ctrl-R force redraw
  3307. place_cursor(0, 0);
  3308. clear_to_eos();
  3309. //mysleep(10); // why???
  3310. screen_erase(); // erase the internal screen buffer
  3311. last_status_cksum = 0; // force status update
  3312. refresh(TRUE); // this will redraw the entire display
  3313. break;
  3314. case 13: // Carriage Return ^M
  3315. case '+': // +- goto next line
  3316. do {
  3317. dot_next();
  3318. dot_skip_over_ws();
  3319. } while (--cmdcnt > 0);
  3320. break;
  3321. case 21: // ctrl-U scroll up half screen
  3322. dot_scroll((rows - 2) / 2, -1);
  3323. break;
  3324. case 25: // ctrl-Y scroll up one line
  3325. dot_scroll(1, -1);
  3326. break;
  3327. case 27: // esc
  3328. if (cmd_mode == 0)
  3329. indicate_error();
  3330. cmd_mode = 0; // stop insrting
  3331. undo_queue_commit();
  3332. end_cmd_q();
  3333. last_status_cksum = 0; // force status update
  3334. break;
  3335. case ' ': // move right
  3336. case 'l': // move right
  3337. case KEYCODE_RIGHT: // Cursor Key Right
  3338. do {
  3339. dot_right();
  3340. } while (--cmdcnt > 0);
  3341. break;
  3342. #if ENABLE_FEATURE_VI_YANKMARK
  3343. case '"': // "- name a register to use for Delete/Yank
  3344. c1 = (get_one_char() | 0x20) - 'a'; // | 0x20 is tolower()
  3345. if ((unsigned)c1 <= 25) { // a-z?
  3346. YDreg = c1;
  3347. } else {
  3348. indicate_error();
  3349. }
  3350. break;
  3351. case '\'': // '- goto a specific mark
  3352. c1 = (get_one_char() | 0x20);
  3353. if ((unsigned)(c1 - 'a') <= 25) { // a-z?
  3354. c1 = (c1 - 'a');
  3355. // get the b-o-l
  3356. q = mark[c1];
  3357. if (text <= q && q < end) {
  3358. dot = q;
  3359. dot_begin(); // go to B-o-l
  3360. dot_skip_over_ws();
  3361. }
  3362. } else if (c1 == '\'') { // goto previous context
  3363. dot = swap_context(dot); // swap current and previous context
  3364. dot_begin(); // go to B-o-l
  3365. dot_skip_over_ws();
  3366. } else {
  3367. indicate_error();
  3368. }
  3369. break;
  3370. case 'm': // m- Mark a line
  3371. // this is really stupid. If there are any inserts or deletes
  3372. // between text[0] and dot then this mark will not point to the
  3373. // correct location! It could be off by many lines!
  3374. // Well..., at least its quick and dirty.
  3375. c1 = (get_one_char() | 0x20) - 'a';
  3376. if ((unsigned)c1 <= 25) { // a-z?
  3377. // remember the line
  3378. mark[c1] = dot;
  3379. } else {
  3380. indicate_error();
  3381. }
  3382. break;
  3383. case 'P': // P- Put register before
  3384. case 'p': // p- put register after
  3385. p = reg[YDreg];
  3386. if (p == NULL) {
  3387. status_line_bold("Nothing in register %c", what_reg());
  3388. break;
  3389. }
  3390. // are we putting whole lines or strings
  3391. if (strchr(p, '\n') != NULL) {
  3392. if (c == 'P') {
  3393. dot_begin(); // putting lines- Put above
  3394. }
  3395. if (c == 'p') {
  3396. // are we putting after very last line?
  3397. if (end_line(dot) == (end - 1)) {
  3398. dot = end; // force dot to end of text[]
  3399. } else {
  3400. dot_next(); // next line, then put before
  3401. }
  3402. }
  3403. } else {
  3404. if (c == 'p')
  3405. dot_right(); // move to right, can move to NL
  3406. }
  3407. string_insert(dot, p, ALLOW_UNDO); // insert the string
  3408. end_cmd_q(); // stop adding to q
  3409. break;
  3410. case 'U': // U- Undo; replace current line with original version
  3411. if (reg[Ureg] != NULL) {
  3412. p = begin_line(dot);
  3413. q = end_line(dot);
  3414. p = text_hole_delete(p, q, ALLOW_UNDO); // delete cur line
  3415. p += string_insert(p, reg[Ureg], ALLOW_UNDO_CHAIN); // insert orig line
  3416. dot = p;
  3417. dot_skip_over_ws();
  3418. }
  3419. break;
  3420. #endif /* FEATURE_VI_YANKMARK */
  3421. #if ENABLE_FEATURE_VI_UNDO
  3422. case 'u': // u- undo last operation
  3423. undo_pop();
  3424. break;
  3425. #endif
  3426. case '$': // $- goto end of line
  3427. case KEYCODE_END: // Cursor Key End
  3428. for (;;) {
  3429. dot = end_line(dot);
  3430. if (--cmdcnt <= 0)
  3431. break;
  3432. dot_next();
  3433. }
  3434. break;
  3435. case '%': // %- find matching char of pair () [] {}
  3436. for (q = dot; q < end && *q != '\n'; q++) {
  3437. if (strchr("()[]{}", *q) != NULL) {
  3438. // we found half of a pair
  3439. p = find_pair(q, *q);
  3440. if (p == NULL) {
  3441. indicate_error();
  3442. } else {
  3443. dot = p;
  3444. }
  3445. break;
  3446. }
  3447. }
  3448. if (*q == '\n')
  3449. indicate_error();
  3450. break;
  3451. case 'f': // f- forward to a user specified char
  3452. last_forward_char = get_one_char(); // get the search char
  3453. //
  3454. // dont separate these two commands. 'f' depends on ';'
  3455. //
  3456. //**** fall through to ... ';'
  3457. case ';': // ;- look at rest of line for last forward char
  3458. do {
  3459. if (last_forward_char == 0)
  3460. break;
  3461. q = dot + 1;
  3462. while (q < end - 1 && *q != '\n' && *q != last_forward_char) {
  3463. q++;
  3464. }
  3465. if (*q == last_forward_char)
  3466. dot = q;
  3467. } while (--cmdcnt > 0);
  3468. break;
  3469. case ',': // repeat latest 'f' in opposite direction
  3470. if (last_forward_char == 0)
  3471. break;
  3472. do {
  3473. q = dot - 1;
  3474. while (q >= text && *q != '\n' && *q != last_forward_char) {
  3475. q--;
  3476. }
  3477. if (q >= text && *q == last_forward_char)
  3478. dot = q;
  3479. } while (--cmdcnt > 0);
  3480. break;
  3481. case '-': // -- goto prev line
  3482. do {
  3483. dot_prev();
  3484. dot_skip_over_ws();
  3485. } while (--cmdcnt > 0);
  3486. break;
  3487. #if ENABLE_FEATURE_VI_DOT_CMD
  3488. case '.': // .- repeat the last modifying command
  3489. // Stuff the last_modifying_cmd back into stdin
  3490. // and let it be re-executed.
  3491. if (lmc_len > 0) {
  3492. last_modifying_cmd[lmc_len] = 0;
  3493. ioq = ioq_start = xstrdup(last_modifying_cmd);
  3494. }
  3495. break;
  3496. #endif
  3497. #if ENABLE_FEATURE_VI_SEARCH
  3498. case '?': // /- search for a pattern
  3499. case '/': // /- search for a pattern
  3500. buf[0] = c;
  3501. buf[1] = '\0';
  3502. q = get_input_line(buf); // get input line- use "status line"
  3503. if (q[0] && !q[1]) {
  3504. if (last_search_pattern[0])
  3505. last_search_pattern[0] = c;
  3506. goto dc3; // if no pat re-use old pat
  3507. }
  3508. if (q[0]) { // strlen(q) > 1: new pat- save it and find
  3509. // there is a new pat
  3510. free(last_search_pattern);
  3511. last_search_pattern = xstrdup(q);
  3512. goto dc3; // now find the pattern
  3513. }
  3514. // user changed mind and erased the "/"- do nothing
  3515. break;
  3516. case 'N': // N- backward search for last pattern
  3517. dir = BACK; // assume BACKWARD search
  3518. p = dot - 1;
  3519. if (last_search_pattern[0] == '?') {
  3520. dir = FORWARD;
  3521. p = dot + 1;
  3522. }
  3523. goto dc4; // now search for pattern
  3524. break;
  3525. case 'n': // n- repeat search for last pattern
  3526. // search rest of text[] starting at next char
  3527. // if search fails return orignal "p" not the "p+1" address
  3528. do {
  3529. const char *msg;
  3530. dc3:
  3531. dir = FORWARD; // assume FORWARD search
  3532. p = dot + 1;
  3533. if (last_search_pattern[0] == '?') {
  3534. dir = BACK;
  3535. p = dot - 1;
  3536. }
  3537. dc4:
  3538. q = char_search(p, last_search_pattern + 1, dir, FULL);
  3539. if (q != NULL) {
  3540. dot = q; // good search, update "dot"
  3541. msg = NULL;
  3542. goto dc2;
  3543. }
  3544. // no pattern found between "dot" and "end"- continue at top
  3545. p = text;
  3546. if (dir == BACK) {
  3547. p = end - 1;
  3548. }
  3549. q = char_search(p, last_search_pattern + 1, dir, FULL);
  3550. if (q != NULL) { // found something
  3551. dot = q; // found new pattern- goto it
  3552. msg = "search hit BOTTOM, continuing at TOP";
  3553. if (dir == BACK) {
  3554. msg = "search hit TOP, continuing at BOTTOM";
  3555. }
  3556. } else {
  3557. msg = "Pattern not found";
  3558. }
  3559. dc2:
  3560. if (msg)
  3561. status_line_bold("%s", msg);
  3562. } while (--cmdcnt > 0);
  3563. break;
  3564. case '{': // {- move backward paragraph
  3565. q = char_search(dot, "\n\n", BACK, FULL);
  3566. if (q != NULL) { // found blank line
  3567. dot = next_line(q); // move to next blank line
  3568. }
  3569. break;
  3570. case '}': // }- move forward paragraph
  3571. q = char_search(dot, "\n\n", FORWARD, FULL);
  3572. if (q != NULL) { // found blank line
  3573. dot = next_line(q); // move to next blank line
  3574. }
  3575. break;
  3576. #endif /* FEATURE_VI_SEARCH */
  3577. case '0': // 0- goto beginning of line
  3578. case '1': // 1-
  3579. case '2': // 2-
  3580. case '3': // 3-
  3581. case '4': // 4-
  3582. case '5': // 5-
  3583. case '6': // 6-
  3584. case '7': // 7-
  3585. case '8': // 8-
  3586. case '9': // 9-
  3587. if (c == '0' && cmdcnt < 1) {
  3588. dot_begin(); // this was a standalone zero
  3589. } else {
  3590. cmdcnt = cmdcnt * 10 + (c - '0'); // this 0 is part of a number
  3591. }
  3592. break;
  3593. case ':': // :- the colon mode commands
  3594. p = get_input_line(":"); // get input line- use "status line"
  3595. colon(p); // execute the command
  3596. break;
  3597. case '<': // <- Left shift something
  3598. case '>': // >- Right shift something
  3599. cnt = count_lines(text, dot); // remember what line we are on
  3600. c1 = get_one_char(); // get the type of thing to delete
  3601. find_range(&p, &q, c1);
  3602. yank_delete(p, q, 1, YANKONLY, NO_UNDO); // save copy before change
  3603. p = begin_line(p);
  3604. q = end_line(q);
  3605. i = count_lines(p, q); // # of lines we are shifting
  3606. for ( ; i > 0; i--, p = next_line(p)) {
  3607. if (c == '<') {
  3608. // shift left- remove tab or 8 spaces
  3609. if (*p == '\t') {
  3610. // shrink buffer 1 char
  3611. text_hole_delete(p, p, NO_UNDO);
  3612. } else if (*p == ' ') {
  3613. // we should be calculating columns, not just SPACE
  3614. for (j = 0; *p == ' ' && j < tabstop; j++) {
  3615. text_hole_delete(p, p, NO_UNDO);
  3616. }
  3617. }
  3618. } else if (c == '>') {
  3619. // shift right -- add tab or 8 spaces
  3620. char_insert(p, '\t', ALLOW_UNDO);
  3621. }
  3622. }
  3623. dot = find_line(cnt); // what line were we on
  3624. dot_skip_over_ws();
  3625. end_cmd_q(); // stop adding to q
  3626. break;
  3627. case 'A': // A- append at e-o-l
  3628. dot_end(); // go to e-o-l
  3629. //**** fall through to ... 'a'
  3630. case 'a': // a- append after current char
  3631. if (*dot != '\n')
  3632. dot++;
  3633. goto dc_i;
  3634. break;
  3635. case 'B': // B- back a blank-delimited Word
  3636. case 'E': // E- end of a blank-delimited word
  3637. case 'W': // W- forward a blank-delimited word
  3638. dir = FORWARD;
  3639. if (c == 'B')
  3640. dir = BACK;
  3641. do {
  3642. if (c == 'W' || isspace(dot[dir])) {
  3643. dot = skip_thing(dot, 1, dir, S_TO_WS);
  3644. dot = skip_thing(dot, 2, dir, S_OVER_WS);
  3645. }
  3646. if (c != 'W')
  3647. dot = skip_thing(dot, 1, dir, S_BEFORE_WS);
  3648. } while (--cmdcnt > 0);
  3649. break;
  3650. case 'C': // C- Change to e-o-l
  3651. case 'D': // D- delete to e-o-l
  3652. save_dot = dot;
  3653. dot = dollar_line(dot); // move to before NL
  3654. // copy text into a register and delete
  3655. dot = yank_delete(save_dot, dot, 0, YANKDEL, ALLOW_UNDO); // delete to e-o-l
  3656. if (c == 'C')
  3657. goto dc_i; // start inserting
  3658. #if ENABLE_FEATURE_VI_DOT_CMD
  3659. if (c == 'D')
  3660. end_cmd_q(); // stop adding to q
  3661. #endif
  3662. break;
  3663. case 'g': // 'gg' goto a line number (vim) (default: very first line)
  3664. c1 = get_one_char();
  3665. if (c1 != 'g') {
  3666. buf[0] = 'g';
  3667. // c1 < 0 if the key was special. Try "g<up-arrow>"
  3668. // TODO: if Unicode?
  3669. buf[1] = (c1 >= 0 ? c1 : '*');
  3670. buf[2] = '\0';
  3671. not_implemented(buf);
  3672. break;
  3673. }
  3674. if (cmdcnt == 0)
  3675. cmdcnt = 1;
  3676. /* fall through */
  3677. case 'G': // G- goto to a line number (default= E-O-F)
  3678. dot = end - 1; // assume E-O-F
  3679. if (cmdcnt > 0) {
  3680. dot = find_line(cmdcnt); // what line is #cmdcnt
  3681. }
  3682. dot_skip_over_ws();
  3683. break;
  3684. case 'H': // H- goto top line on screen
  3685. dot = screenbegin;
  3686. if (cmdcnt > (rows - 1)) {
  3687. cmdcnt = (rows - 1);
  3688. }
  3689. if (--cmdcnt > 0) {
  3690. do_cmd('+');
  3691. }
  3692. dot_skip_over_ws();
  3693. break;
  3694. case 'I': // I- insert before first non-blank
  3695. dot_begin(); // 0
  3696. dot_skip_over_ws();
  3697. //**** fall through to ... 'i'
  3698. case 'i': // i- insert before current char
  3699. case KEYCODE_INSERT: // Cursor Key Insert
  3700. dc_i:
  3701. cmd_mode = 1; // start inserting
  3702. undo_queue_commit(); // commit queue when cmd_mode changes
  3703. break;
  3704. case 'J': // J- join current and next lines together
  3705. do {
  3706. dot_end(); // move to NL
  3707. if (dot < end - 1) { // make sure not last char in text[]
  3708. #if ENABLE_FEATURE_VI_UNDO
  3709. undo_push(dot, 1, UNDO_DEL);
  3710. *dot++ = ' '; // replace NL with space
  3711. undo_push((dot - 1), 1, UNDO_INS_CHAIN);
  3712. #else
  3713. *dot++ = ' ';
  3714. modified_count++;
  3715. #endif
  3716. while (isblank(*dot)) { // delete leading WS
  3717. text_hole_delete(dot, dot, ALLOW_UNDO_CHAIN);
  3718. }
  3719. }
  3720. } while (--cmdcnt > 0);
  3721. end_cmd_q(); // stop adding to q
  3722. break;
  3723. case 'L': // L- goto bottom line on screen
  3724. dot = end_screen();
  3725. if (cmdcnt > (rows - 1)) {
  3726. cmdcnt = (rows - 1);
  3727. }
  3728. if (--cmdcnt > 0) {
  3729. do_cmd('-');
  3730. }
  3731. dot_begin();
  3732. dot_skip_over_ws();
  3733. break;
  3734. case 'M': // M- goto middle line on screen
  3735. dot = screenbegin;
  3736. for (cnt = 0; cnt < (rows-1) / 2; cnt++)
  3737. dot = next_line(dot);
  3738. break;
  3739. case 'O': // O- open a empty line above
  3740. // 0i\n ESC -i
  3741. p = begin_line(dot);
  3742. if (p[-1] == '\n') {
  3743. dot_prev();
  3744. case 'o': // o- open a empty line below; Yes, I know it is in the middle of the "if (..."
  3745. dot_end();
  3746. dot = char_insert(dot, '\n', ALLOW_UNDO);
  3747. } else {
  3748. dot_begin(); // 0
  3749. dot = char_insert(dot, '\n', ALLOW_UNDO); // i\n ESC
  3750. dot_prev(); // -
  3751. }
  3752. goto dc_i;
  3753. break;
  3754. case 'R': // R- continuous Replace char
  3755. dc5:
  3756. cmd_mode = 2;
  3757. undo_queue_commit();
  3758. break;
  3759. case KEYCODE_DELETE:
  3760. if (dot < end - 1)
  3761. dot = yank_delete(dot, dot, 1, YANKDEL, ALLOW_UNDO);
  3762. break;
  3763. case 'X': // X- delete char before dot
  3764. case 'x': // x- delete the current char
  3765. case 's': // s- substitute the current char
  3766. dir = 0;
  3767. if (c == 'X')
  3768. dir = -1;
  3769. do {
  3770. if (dot[dir] != '\n') {
  3771. if (c == 'X')
  3772. dot--; // delete prev char
  3773. dot = yank_delete(dot, dot, 0, YANKDEL, ALLOW_UNDO); // delete char
  3774. }
  3775. } while (--cmdcnt > 0);
  3776. end_cmd_q(); // stop adding to q
  3777. if (c == 's')
  3778. goto dc_i; // start inserting
  3779. break;
  3780. case 'Z': // Z- if modified, {write}; exit
  3781. // ZZ means to save file (if necessary), then exit
  3782. c1 = get_one_char();
  3783. if (c1 != 'Z') {
  3784. indicate_error();
  3785. break;
  3786. }
  3787. if (modified_count) {
  3788. if (ENABLE_FEATURE_VI_READONLY && readonly_mode) {
  3789. status_line_bold("'%s' is read only", current_filename);
  3790. break;
  3791. }
  3792. cnt = file_write(current_filename, text, end - 1);
  3793. if (cnt < 0) {
  3794. if (cnt == -1)
  3795. status_line_bold("Write error: %s", strerror(errno));
  3796. } else if (cnt == (end - 1 - text + 1)) {
  3797. editing = 0;
  3798. }
  3799. } else {
  3800. editing = 0;
  3801. }
  3802. break;
  3803. case '^': // ^- move to first non-blank on line
  3804. dot_begin();
  3805. dot_skip_over_ws();
  3806. break;
  3807. case 'b': // b- back a word
  3808. case 'e': // e- end of word
  3809. dir = FORWARD;
  3810. if (c == 'b')
  3811. dir = BACK;
  3812. do {
  3813. if ((dot + dir) < text || (dot + dir) > end - 1)
  3814. break;
  3815. dot += dir;
  3816. if (isspace(*dot)) {
  3817. dot = skip_thing(dot, (c == 'e') ? 2 : 1, dir, S_OVER_WS);
  3818. }
  3819. if (isalnum(*dot) || *dot == '_') {
  3820. dot = skip_thing(dot, 1, dir, S_END_ALNUM);
  3821. } else if (ispunct(*dot)) {
  3822. dot = skip_thing(dot, 1, dir, S_END_PUNCT);
  3823. }
  3824. } while (--cmdcnt > 0);
  3825. break;
  3826. case 'c': // c- change something
  3827. case 'd': // d- delete something
  3828. #if ENABLE_FEATURE_VI_YANKMARK
  3829. case 'y': // y- yank something
  3830. case 'Y': // Y- Yank a line
  3831. #endif
  3832. {
  3833. int yf, ml, whole = 0;
  3834. yf = YANKDEL; // assume either "c" or "d"
  3835. #if ENABLE_FEATURE_VI_YANKMARK
  3836. if (c == 'y' || c == 'Y')
  3837. yf = YANKONLY;
  3838. #endif
  3839. c1 = 'y';
  3840. if (c != 'Y')
  3841. c1 = get_one_char(); // get the type of thing to delete
  3842. // determine range, and whether it spans lines
  3843. ml = find_range(&p, &q, c1);
  3844. place_cursor(0, 0);
  3845. if (c1 == 27) { // ESC- user changed mind and wants out
  3846. c = c1 = 27; // Escape- do nothing
  3847. } else if (strchr("wW", c1)) {
  3848. if (c == 'c') {
  3849. // don't include trailing WS as part of word
  3850. while (isblank(*q)) {
  3851. if (q <= text || q[-1] == '\n')
  3852. break;
  3853. q--;
  3854. }
  3855. }
  3856. dot = yank_delete(p, q, ml, yf, ALLOW_UNDO); // delete word
  3857. } else if (strchr("^0bBeEft%$ lh\b\177", c1)) {
  3858. // partial line copy text into a register and delete
  3859. dot = yank_delete(p, q, ml, yf, ALLOW_UNDO); // delete word
  3860. } else if (strchr("cdykjHL+-{}\r\n", c1)) {
  3861. // whole line copy text into a register and delete
  3862. dot = yank_delete(p, q, ml, yf, ALLOW_UNDO); // delete lines
  3863. whole = 1;
  3864. } else {
  3865. // could not recognize object
  3866. c = c1 = 27; // error-
  3867. ml = 0;
  3868. indicate_error();
  3869. }
  3870. if (ml && whole) {
  3871. if (c == 'c') {
  3872. dot = char_insert(dot, '\n', ALLOW_UNDO_CHAIN);
  3873. // on the last line of file don't move to prev line
  3874. if (whole && dot != (end-1)) {
  3875. dot_prev();
  3876. }
  3877. } else if (c == 'd') {
  3878. dot_begin();
  3879. dot_skip_over_ws();
  3880. }
  3881. }
  3882. if (c1 != 27) {
  3883. // if CHANGING, not deleting, start inserting after the delete
  3884. if (c == 'c') {
  3885. strcpy(buf, "Change");
  3886. goto dc_i; // start inserting
  3887. }
  3888. if (c == 'd') {
  3889. strcpy(buf, "Delete");
  3890. }
  3891. #if ENABLE_FEATURE_VI_YANKMARK
  3892. if (c == 'y' || c == 'Y') {
  3893. strcpy(buf, "Yank");
  3894. }
  3895. p = reg[YDreg];
  3896. q = p + strlen(p);
  3897. for (cnt = 0; p <= q; p++) {
  3898. if (*p == '\n')
  3899. cnt++;
  3900. }
  3901. status_line("%s %d lines (%d chars) using [%c]",
  3902. buf, cnt, strlen(reg[YDreg]), what_reg());
  3903. #endif
  3904. end_cmd_q(); // stop adding to q
  3905. }
  3906. break;
  3907. }
  3908. case 'k': // k- goto prev line, same col
  3909. case KEYCODE_UP: // cursor key Up
  3910. do {
  3911. dot_prev();
  3912. dot = move_to_col(dot, ccol + offset); // try stay in same col
  3913. } while (--cmdcnt > 0);
  3914. break;
  3915. case 'r': // r- replace the current char with user input
  3916. c1 = get_one_char(); // get the replacement char
  3917. if (*dot != '\n') {
  3918. #if ENABLE_FEATURE_VI_UNDO
  3919. undo_push(dot, 1, UNDO_DEL);
  3920. *dot = c1;
  3921. undo_push(dot, 1, UNDO_INS_CHAIN);
  3922. #else
  3923. *dot = c1;
  3924. modified_count++;
  3925. #endif
  3926. }
  3927. end_cmd_q(); // stop adding to q
  3928. break;
  3929. case 't': // t- move to char prior to next x
  3930. last_forward_char = get_one_char();
  3931. do_cmd(';');
  3932. if (*dot == last_forward_char)
  3933. dot_left();
  3934. last_forward_char = 0;
  3935. break;
  3936. case 'w': // w- forward a word
  3937. do {
  3938. if (isalnum(*dot) || *dot == '_') { // we are on ALNUM
  3939. dot = skip_thing(dot, 1, FORWARD, S_END_ALNUM);
  3940. } else if (ispunct(*dot)) { // we are on PUNCT
  3941. dot = skip_thing(dot, 1, FORWARD, S_END_PUNCT);
  3942. }
  3943. if (dot < end - 1)
  3944. dot++; // move over word
  3945. if (isspace(*dot)) {
  3946. dot = skip_thing(dot, 2, FORWARD, S_OVER_WS);
  3947. }
  3948. } while (--cmdcnt > 0);
  3949. break;
  3950. case 'z': // z-
  3951. c1 = get_one_char(); // get the replacement char
  3952. cnt = 0;
  3953. if (c1 == '.')
  3954. cnt = (rows - 2) / 2; // put dot at center
  3955. if (c1 == '-')
  3956. cnt = rows - 2; // put dot at bottom
  3957. screenbegin = begin_line(dot); // start dot at top
  3958. dot_scroll(cnt, -1);
  3959. break;
  3960. case '|': // |- move to column "cmdcnt"
  3961. dot = move_to_col(dot, cmdcnt - 1); // try to move to column
  3962. break;
  3963. case '~': // ~- flip the case of letters a-z -> A-Z
  3964. do {
  3965. #if ENABLE_FEATURE_VI_UNDO
  3966. if (islower(*dot)) {
  3967. undo_push(dot, 1, UNDO_DEL);
  3968. *dot = toupper(*dot);
  3969. undo_push(dot, 1, UNDO_INS_CHAIN);
  3970. } else if (isupper(*dot)) {
  3971. undo_push(dot, 1, UNDO_DEL);
  3972. *dot = tolower(*dot);
  3973. undo_push(dot, 1, UNDO_INS_CHAIN);
  3974. }
  3975. #else
  3976. if (islower(*dot)) {
  3977. *dot = toupper(*dot);
  3978. modified_count++;
  3979. } else if (isupper(*dot)) {
  3980. *dot = tolower(*dot);
  3981. modified_count++;
  3982. }
  3983. #endif
  3984. dot_right();
  3985. } while (--cmdcnt > 0);
  3986. end_cmd_q(); // stop adding to q
  3987. break;
  3988. //----- The Cursor and Function Keys -----------------------------
  3989. case KEYCODE_HOME: // Cursor Key Home
  3990. dot_begin();
  3991. break;
  3992. // The Fn keys could point to do_macro which could translate them
  3993. #if 0
  3994. case KEYCODE_FUN1: // Function Key F1
  3995. case KEYCODE_FUN2: // Function Key F2
  3996. case KEYCODE_FUN3: // Function Key F3
  3997. case KEYCODE_FUN4: // Function Key F4
  3998. case KEYCODE_FUN5: // Function Key F5
  3999. case KEYCODE_FUN6: // Function Key F6
  4000. case KEYCODE_FUN7: // Function Key F7
  4001. case KEYCODE_FUN8: // Function Key F8
  4002. case KEYCODE_FUN9: // Function Key F9
  4003. case KEYCODE_FUN10: // Function Key F10
  4004. case KEYCODE_FUN11: // Function Key F11
  4005. case KEYCODE_FUN12: // Function Key F12
  4006. break;
  4007. #endif
  4008. }
  4009. dc1:
  4010. // if text[] just became empty, add back an empty line
  4011. if (end == text) {
  4012. char_insert(text, '\n', NO_UNDO); // start empty buf with dummy line
  4013. dot = text;
  4014. }
  4015. // it is OK for dot to exactly equal to end, otherwise check dot validity
  4016. if (dot != end) {
  4017. dot = bound_dot(dot); // make sure "dot" is valid
  4018. }
  4019. #if ENABLE_FEATURE_VI_YANKMARK
  4020. check_context(c); // update the current context
  4021. #endif
  4022. if (!isdigit(c))
  4023. cmdcnt = 0; // cmd was not a number, reset cmdcnt
  4024. cnt = dot - begin_line(dot);
  4025. // Try to stay off of the Newline
  4026. if (*dot == '\n' && cnt > 0 && cmd_mode == 0)
  4027. dot--;
  4028. }
  4029. /* NB! the CRASHME code is unmaintained, and doesn't currently build */
  4030. #if ENABLE_FEATURE_VI_CRASHME
  4031. static int totalcmds = 0;
  4032. static int Mp = 85; // Movement command Probability
  4033. static int Np = 90; // Non-movement command Probability
  4034. static int Dp = 96; // Delete command Probability
  4035. static int Ip = 97; // Insert command Probability
  4036. static int Yp = 98; // Yank command Probability
  4037. static int Pp = 99; // Put command Probability
  4038. static int M = 0, N = 0, I = 0, D = 0, Y = 0, P = 0, U = 0;
  4039. static const char chars[20] = "\t012345 abcdABCD-=.$";
  4040. static const char *const words[20] = {
  4041. "this", "is", "a", "test",
  4042. "broadcast", "the", "emergency", "of",
  4043. "system", "quick", "brown", "fox",
  4044. "jumped", "over", "lazy", "dogs",
  4045. "back", "January", "Febuary", "March"
  4046. };
  4047. static const char *const lines[20] = {
  4048. "You should have received a copy of the GNU General Public License\n",
  4049. "char c, cm, *cmd, *cmd1;\n",
  4050. "generate a command by percentages\n",
  4051. "Numbers may be typed as a prefix to some commands.\n",
  4052. "Quit, discarding changes!\n",
  4053. "Forced write, if permission originally not valid.\n",
  4054. "In general, any ex or ed command (such as substitute or delete).\n",
  4055. "I have tickets available for the Blazers vs LA Clippers for Monday, Janurary 1 at 1:00pm.\n",
  4056. "Please get w/ me and I will go over it with you.\n",
  4057. "The following is a list of scheduled, committed changes.\n",
  4058. "1. Launch Norton Antivirus (Start, Programs, Norton Antivirus)\n",
  4059. "Reminder....Town Meeting in Central Perk cafe today at 3:00pm.\n",
  4060. "Any question about transactions please contact Sterling Huxley.\n",
  4061. "I will try to get back to you by Friday, December 31.\n",
  4062. "This Change will be implemented on Friday.\n",
  4063. "Let me know if you have problems accessing this;\n",
  4064. "Sterling Huxley recently added you to the access list.\n",
  4065. "Would you like to go to lunch?\n",
  4066. "The last command will be automatically run.\n",
  4067. "This is too much english for a computer geek.\n",
  4068. };
  4069. static char *multilines[20] = {
  4070. "You should have received a copy of the GNU General Public License\n",
  4071. "char c, cm, *cmd, *cmd1;\n",
  4072. "generate a command by percentages\n",
  4073. "Numbers may be typed as a prefix to some commands.\n",
  4074. "Quit, discarding changes!\n",
  4075. "Forced write, if permission originally not valid.\n",
  4076. "In general, any ex or ed command (such as substitute or delete).\n",
  4077. "I have tickets available for the Blazers vs LA Clippers for Monday, Janurary 1 at 1:00pm.\n",
  4078. "Please get w/ me and I will go over it with you.\n",
  4079. "The following is a list of scheduled, committed changes.\n",
  4080. "1. Launch Norton Antivirus (Start, Programs, Norton Antivirus)\n",
  4081. "Reminder....Town Meeting in Central Perk cafe today at 3:00pm.\n",
  4082. "Any question about transactions please contact Sterling Huxley.\n",
  4083. "I will try to get back to you by Friday, December 31.\n",
  4084. "This Change will be implemented on Friday.\n",
  4085. "Let me know if you have problems accessing this;\n",
  4086. "Sterling Huxley recently added you to the access list.\n",
  4087. "Would you like to go to lunch?\n",
  4088. "The last command will be automatically run.\n",
  4089. "This is too much english for a computer geek.\n",
  4090. };
  4091. // create a random command to execute
  4092. static void crash_dummy()
  4093. {
  4094. static int sleeptime; // how long to pause between commands
  4095. char c, cm, *cmd, *cmd1;
  4096. int i, cnt, thing, rbi, startrbi, percent;
  4097. // "dot" movement commands
  4098. cmd1 = " \n\r\002\004\005\006\025\0310^$-+wWeEbBhjklHL";
  4099. // is there already a command running?
  4100. if (readbuffer[0] > 0)
  4101. goto cd1;
  4102. cd0:
  4103. readbuffer[0] = 'X';
  4104. startrbi = rbi = 1;
  4105. sleeptime = 0; // how long to pause between commands
  4106. memset(readbuffer, '\0', sizeof(readbuffer));
  4107. // generate a command by percentages
  4108. percent = (int) lrand48() % 100; // get a number from 0-99
  4109. if (percent < Mp) { // Movement commands
  4110. // available commands
  4111. cmd = cmd1;
  4112. M++;
  4113. } else if (percent < Np) { // non-movement commands
  4114. cmd = "mz<>\'\""; // available commands
  4115. N++;
  4116. } else if (percent < Dp) { // Delete commands
  4117. cmd = "dx"; // available commands
  4118. D++;
  4119. } else if (percent < Ip) { // Inset commands
  4120. cmd = "iIaAsrJ"; // available commands
  4121. I++;
  4122. } else if (percent < Yp) { // Yank commands
  4123. cmd = "yY"; // available commands
  4124. Y++;
  4125. } else if (percent < Pp) { // Put commands
  4126. cmd = "pP"; // available commands
  4127. P++;
  4128. } else {
  4129. // We do not know how to handle this command, try again
  4130. U++;
  4131. goto cd0;
  4132. }
  4133. // randomly pick one of the available cmds from "cmd[]"
  4134. i = (int) lrand48() % strlen(cmd);
  4135. cm = cmd[i];
  4136. if (strchr(":\024", cm))
  4137. goto cd0; // dont allow colon or ctrl-T commands
  4138. readbuffer[rbi++] = cm; // put cmd into input buffer
  4139. // now we have the command-
  4140. // there are 1, 2, and multi char commands
  4141. // find out which and generate the rest of command as necessary
  4142. if (strchr("dmryz<>\'\"", cm)) { // 2-char commands
  4143. cmd1 = " \n\r0$^-+wWeEbBhjklHL";
  4144. if (cm == 'm' || cm == '\'' || cm == '\"') { // pick a reg[]
  4145. cmd1 = "abcdefghijklmnopqrstuvwxyz";
  4146. }
  4147. thing = (int) lrand48() % strlen(cmd1); // pick a movement command
  4148. c = cmd1[thing];
  4149. readbuffer[rbi++] = c; // add movement to input buffer
  4150. }
  4151. if (strchr("iIaAsc", cm)) { // multi-char commands
  4152. if (cm == 'c') {
  4153. // change some thing
  4154. thing = (int) lrand48() % strlen(cmd1); // pick a movement command
  4155. c = cmd1[thing];
  4156. readbuffer[rbi++] = c; // add movement to input buffer
  4157. }
  4158. thing = (int) lrand48() % 4; // what thing to insert
  4159. cnt = (int) lrand48() % 10; // how many to insert
  4160. for (i = 0; i < cnt; i++) {
  4161. if (thing == 0) { // insert chars
  4162. readbuffer[rbi++] = chars[((int) lrand48() % strlen(chars))];
  4163. } else if (thing == 1) { // insert words
  4164. strcat(readbuffer, words[(int) lrand48() % 20]);
  4165. strcat(readbuffer, " ");
  4166. sleeptime = 0; // how fast to type
  4167. } else if (thing == 2) { // insert lines
  4168. strcat(readbuffer, lines[(int) lrand48() % 20]);
  4169. sleeptime = 0; // how fast to type
  4170. } else { // insert multi-lines
  4171. strcat(readbuffer, multilines[(int) lrand48() % 20]);
  4172. sleeptime = 0; // how fast to type
  4173. }
  4174. }
  4175. strcat(readbuffer, "\033");
  4176. }
  4177. readbuffer[0] = strlen(readbuffer + 1);
  4178. cd1:
  4179. totalcmds++;
  4180. if (sleeptime > 0)
  4181. mysleep(sleeptime); // sleep 1/100 sec
  4182. }
  4183. // test to see if there are any errors
  4184. static void crash_test()
  4185. {
  4186. static time_t oldtim;
  4187. time_t tim;
  4188. char d[2], msg[80];
  4189. msg[0] = '\0';
  4190. if (end < text) {
  4191. strcat(msg, "end<text ");
  4192. }
  4193. if (end > textend) {
  4194. strcat(msg, "end>textend ");
  4195. }
  4196. if (dot < text) {
  4197. strcat(msg, "dot<text ");
  4198. }
  4199. if (dot > end) {
  4200. strcat(msg, "dot>end ");
  4201. }
  4202. if (screenbegin < text) {
  4203. strcat(msg, "screenbegin<text ");
  4204. }
  4205. if (screenbegin > end - 1) {
  4206. strcat(msg, "screenbegin>end-1 ");
  4207. }
  4208. if (msg[0]) {
  4209. printf("\n\n%d: \'%c\' %s\n\n\n%s[Hit return to continue]%s",
  4210. totalcmds, last_input_char, msg, ESC_BOLD_TEXT, ESC_NORM_TEXT);
  4211. fflush_all();
  4212. while (safe_read(STDIN_FILENO, d, 1) > 0) {
  4213. if (d[0] == '\n' || d[0] == '\r')
  4214. break;
  4215. }
  4216. }
  4217. tim = time(NULL);
  4218. if (tim >= (oldtim + 3)) {
  4219. sprintf(status_buffer,
  4220. "Tot=%d: M=%d N=%d I=%d D=%d Y=%d P=%d U=%d size=%d",
  4221. totalcmds, M, N, I, D, Y, P, U, end - text + 1);
  4222. oldtim = tim;
  4223. }
  4224. }
  4225. #endif