vi.c 121 KB

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