vi.c 129 KB

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