3
0

vi.c 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503
  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 beginning 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. // read after last line
  1239. if (q == end-1)
  1240. ++q;
  1241. }
  1242. { // dance around potentially-reallocated text[]
  1243. uintptr_t ofs = q - text;
  1244. size = file_insert(fn, q, 0);
  1245. q = text + ofs;
  1246. }
  1247. if (size < 0)
  1248. goto ret; // nothing was inserted
  1249. // how many lines in text[]?
  1250. li = count_lines(q, q + size - 1);
  1251. status_line("'%s'"
  1252. IF_FEATURE_VI_READONLY("%s")
  1253. " %dL, %dC",
  1254. fn,
  1255. IF_FEATURE_VI_READONLY((readonly_mode ? " [Readonly]" : ""),)
  1256. li, size
  1257. );
  1258. if (size > 0) {
  1259. // if the insert is before "dot" then we need to update
  1260. if (q <= dot)
  1261. dot += size;
  1262. }
  1263. } else if (strncmp(cmd, "rewind", i) == 0) { // rewind cmd line args
  1264. if (modified_count && !useforce) {
  1265. status_line_bold("No write since last change (:%s! overrides)", cmd);
  1266. } else {
  1267. // reset the filenames to edit
  1268. optind = -1; /* start from 0th file */
  1269. editing = 0;
  1270. }
  1271. #if ENABLE_FEATURE_VI_SET
  1272. } else if (strncmp(cmd, "set", i) == 0) { // set or clear features
  1273. #if ENABLE_FEATURE_VI_SETOPTS
  1274. char *argp;
  1275. #endif
  1276. i = 0; // offset into args
  1277. // only blank is regarded as args delimiter. What about tab '\t'?
  1278. if (!args[0] || strcasecmp(args, "all") == 0) {
  1279. // print out values of all options
  1280. #if ENABLE_FEATURE_VI_SETOPTS
  1281. status_line_bold(
  1282. "%sautoindent "
  1283. "%sflash "
  1284. "%signorecase "
  1285. "%sshowmatch "
  1286. "tabstop=%u",
  1287. autoindent ? "" : "no",
  1288. err_method ? "" : "no",
  1289. ignorecase ? "" : "no",
  1290. showmatch ? "" : "no",
  1291. tabstop
  1292. );
  1293. #endif
  1294. goto ret;
  1295. }
  1296. #if ENABLE_FEATURE_VI_SETOPTS
  1297. argp = args;
  1298. while (*argp) {
  1299. if (strncmp(argp, "no", 2) == 0)
  1300. i = 2; // ":set noautoindent"
  1301. setops(argp, "autoindent ", i, "ai", VI_AUTOINDENT);
  1302. setops(argp, "flash " , i, "fl", VI_ERR_METHOD);
  1303. setops(argp, "ignorecase ", i, "ic", VI_IGNORECASE);
  1304. setops(argp, "showmatch " , i, "sm", VI_SHOWMATCH );
  1305. if (strncmp(argp + i, "tabstop=", 8) == 0) {
  1306. int t = 0;
  1307. sscanf(argp + i+8, "%u", &t);
  1308. if (t > 0 && t <= MAX_TABSTOP)
  1309. tabstop = t;
  1310. }
  1311. argp = skip_non_whitespace(argp);
  1312. argp = skip_whitespace(argp);
  1313. }
  1314. #endif /* FEATURE_VI_SETOPTS */
  1315. #endif /* FEATURE_VI_SET */
  1316. #if ENABLE_FEATURE_VI_SEARCH
  1317. } else if (cmd[0] == 's') { // substitute a pattern with a replacement pattern
  1318. char *F, *R, *flags;
  1319. size_t len_F, len_R;
  1320. int gflag; // global replace flag
  1321. #if ENABLE_FEATURE_VI_UNDO
  1322. int dont_chain_first_item = ALLOW_UNDO;
  1323. #endif
  1324. // F points to the "find" pattern
  1325. // R points to the "replace" pattern
  1326. // replace the cmd line delimiters "/" with NULs
  1327. c = orig_buf[1]; // what is the delimiter
  1328. F = orig_buf + 2; // start of "find"
  1329. R = strchr(F, c); // middle delimiter
  1330. if (!R)
  1331. goto colon_s_fail;
  1332. len_F = R - F;
  1333. *R++ = '\0'; // terminate "find"
  1334. flags = strchr(R, c);
  1335. if (!flags)
  1336. goto colon_s_fail;
  1337. len_R = flags - R;
  1338. *flags++ = '\0'; // terminate "replace"
  1339. gflag = *flags;
  1340. q = begin_line(q);
  1341. if (b < 0) { // maybe :s/foo/bar/
  1342. q = begin_line(dot); // start with cur line
  1343. b = count_lines(text, q); // cur line number
  1344. }
  1345. if (e < 0)
  1346. e = b; // maybe :.s/foo/bar/
  1347. for (i = b; i <= e; i++) { // so, :20,23 s \0 find \0 replace \0
  1348. char *ls = q; // orig line start
  1349. char *found;
  1350. vc4:
  1351. found = char_search(q, F, FORWARD, LIMITED); // search cur line only for "find"
  1352. if (found) {
  1353. uintptr_t bias;
  1354. // we found the "find" pattern - delete it
  1355. // For undo support, the first item should not be chained
  1356. text_hole_delete(found, found + len_F - 1, dont_chain_first_item);
  1357. #if ENABLE_FEATURE_VI_UNDO
  1358. dont_chain_first_item = ALLOW_UNDO_CHAIN;
  1359. #endif
  1360. // insert the "replace" patern
  1361. bias = string_insert(found, R, ALLOW_UNDO_CHAIN);
  1362. found += bias;
  1363. ls += bias;
  1364. /*q += bias; - recalculated anyway */
  1365. // check for "global" :s/foo/bar/g
  1366. if (gflag == 'g') {
  1367. if ((found + len_R) < end_line(ls)) {
  1368. q = found + len_R;
  1369. goto vc4; // don't let q move past cur line
  1370. }
  1371. }
  1372. }
  1373. q = next_line(ls);
  1374. }
  1375. #endif /* FEATURE_VI_SEARCH */
  1376. } else if (strncmp(cmd, "version", i) == 0) { // show software version
  1377. status_line(BB_VER " " BB_BT);
  1378. } else if (strncmp(cmd, "write", i) == 0 // write text to file
  1379. || strncmp(cmd, "wq", i) == 0
  1380. || strncmp(cmd, "wn", i) == 0
  1381. || (cmd[0] == 'x' && !cmd[1])
  1382. ) {
  1383. int size;
  1384. //int forced = FALSE;
  1385. // is there a file name to write to?
  1386. if (args[0]) {
  1387. fn = args;
  1388. }
  1389. #if ENABLE_FEATURE_VI_READONLY
  1390. if (readonly_mode && !useforce) {
  1391. status_line_bold("'%s' is read only", fn);
  1392. goto ret;
  1393. }
  1394. #endif
  1395. // how many lines in text[]?
  1396. li = count_lines(q, r);
  1397. size = r - q + 1;
  1398. //if (useforce) {
  1399. // if "fn" is not write-able, chmod u+w
  1400. // sprintf(syscmd, "chmod u+w %s", fn);
  1401. // system(syscmd);
  1402. // forced = TRUE;
  1403. //}
  1404. l = file_write(fn, q, r);
  1405. //if (useforce && forced) {
  1406. // chmod u-w
  1407. // sprintf(syscmd, "chmod u-w %s", fn);
  1408. // system(syscmd);
  1409. // forced = FALSE;
  1410. //}
  1411. if (l < 0) {
  1412. if (l == -1)
  1413. status_line_bold_errno(fn);
  1414. } else {
  1415. status_line("'%s' %dL, %dC", fn, li, l);
  1416. if (q == text && r == end - 1 && l == size) {
  1417. modified_count = 0;
  1418. last_modified_count = -1;
  1419. }
  1420. if ((cmd[0] == 'x' || cmd[1] == 'q' || cmd[1] == 'n'
  1421. || cmd[0] == 'X' || cmd[1] == 'Q' || cmd[1] == 'N'
  1422. )
  1423. && l == size
  1424. ) {
  1425. editing = 0;
  1426. }
  1427. }
  1428. #if ENABLE_FEATURE_VI_YANKMARK
  1429. } else if (strncmp(cmd, "yank", i) == 0) { // yank lines
  1430. if (b < 0) { // no addr given- use defaults
  1431. q = begin_line(dot); // assume .,. for the range
  1432. r = end_line(dot);
  1433. }
  1434. text_yank(q, r, YDreg);
  1435. li = count_lines(q, r);
  1436. status_line("Yank %d lines (%d chars) into [%c]",
  1437. li, strlen(reg[YDreg]), what_reg());
  1438. #endif
  1439. } else {
  1440. // cmd unknown
  1441. not_implemented(cmd);
  1442. }
  1443. ret:
  1444. dot = bound_dot(dot); // make sure "dot" is valid
  1445. return;
  1446. #if ENABLE_FEATURE_VI_SEARCH
  1447. colon_s_fail:
  1448. status_line(":s expression missing delimiters");
  1449. #endif
  1450. #endif /* FEATURE_VI_COLON */
  1451. }
  1452. static void Hit_Return(void)
  1453. {
  1454. int c;
  1455. standout_start();
  1456. write1("[Hit return to continue]");
  1457. standout_end();
  1458. while ((c = get_one_char()) != '\n' && c != '\r')
  1459. continue;
  1460. redraw(TRUE); // force redraw all
  1461. }
  1462. static int next_tabstop(int col)
  1463. {
  1464. return col + ((tabstop - 1) - (col % tabstop));
  1465. }
  1466. //----- Synchronize the cursor to Dot --------------------------
  1467. static NOINLINE void sync_cursor(char *d, int *row, int *col)
  1468. {
  1469. char *beg_cur; // begin and end of "d" line
  1470. char *tp;
  1471. int cnt, ro, co;
  1472. beg_cur = begin_line(d); // first char of cur line
  1473. if (beg_cur < screenbegin) {
  1474. // "d" is before top line on screen
  1475. // how many lines do we have to move
  1476. cnt = count_lines(beg_cur, screenbegin);
  1477. sc1:
  1478. screenbegin = beg_cur;
  1479. if (cnt > (rows - 1) / 2) {
  1480. // we moved too many lines. put "dot" in middle of screen
  1481. for (cnt = 0; cnt < (rows - 1) / 2; cnt++) {
  1482. screenbegin = prev_line(screenbegin);
  1483. }
  1484. }
  1485. } else {
  1486. char *end_scr; // begin and end of screen
  1487. end_scr = end_screen(); // last char of screen
  1488. if (beg_cur > end_scr) {
  1489. // "d" is after bottom line on screen
  1490. // how many lines do we have to move
  1491. cnt = count_lines(end_scr, beg_cur);
  1492. if (cnt > (rows - 1) / 2)
  1493. goto sc1; // too many lines
  1494. for (ro = 0; ro < cnt - 1; ro++) {
  1495. // move screen begin the same amount
  1496. screenbegin = next_line(screenbegin);
  1497. // now, move the end of screen
  1498. end_scr = next_line(end_scr);
  1499. end_scr = end_line(end_scr);
  1500. }
  1501. }
  1502. }
  1503. // "d" is on screen- find out which row
  1504. tp = screenbegin;
  1505. for (ro = 0; ro < rows - 1; ro++) { // drive "ro" to correct row
  1506. if (tp == beg_cur)
  1507. break;
  1508. tp = next_line(tp);
  1509. }
  1510. // find out what col "d" is on
  1511. co = 0;
  1512. while (tp < d) { // drive "co" to correct column
  1513. if (*tp == '\n') //vda || *tp == '\0')
  1514. break;
  1515. if (*tp == '\t') {
  1516. // handle tabs like real vi
  1517. if (d == tp && cmd_mode) {
  1518. break;
  1519. }
  1520. co = next_tabstop(co);
  1521. } else if ((unsigned char)*tp < ' ' || *tp == 0x7f) {
  1522. co++; // display as ^X, use 2 columns
  1523. }
  1524. co++;
  1525. tp++;
  1526. }
  1527. // "co" is the column where "dot" is.
  1528. // The screen has "columns" columns.
  1529. // The currently displayed columns are 0+offset -- columns+ofset
  1530. // |-------------------------------------------------------------|
  1531. // ^ ^ ^
  1532. // offset | |------- columns ----------------|
  1533. //
  1534. // If "co" is already in this range then we do not have to adjust offset
  1535. // but, we do have to subtract the "offset" bias from "co".
  1536. // If "co" is outside this range then we have to change "offset".
  1537. // If the first char of a line is a tab the cursor will try to stay
  1538. // in column 7, but we have to set offset to 0.
  1539. if (co < 0 + offset) {
  1540. offset = co;
  1541. }
  1542. if (co >= columns + offset) {
  1543. offset = co - columns + 1;
  1544. }
  1545. // if the first char of the line is a tab, and "dot" is sitting on it
  1546. // force offset to 0.
  1547. if (d == beg_cur && *d == '\t') {
  1548. offset = 0;
  1549. }
  1550. co -= offset;
  1551. *row = ro;
  1552. *col = co;
  1553. }
  1554. //----- Text Movement Routines ---------------------------------
  1555. static char *begin_line(char *p) // return pointer to first char cur line
  1556. {
  1557. if (p > text) {
  1558. p = memrchr(text, '\n', p - text);
  1559. if (!p)
  1560. return text;
  1561. return p + 1;
  1562. }
  1563. return p;
  1564. }
  1565. static char *end_line(char *p) // return pointer to NL of cur line
  1566. {
  1567. if (p < end - 1) {
  1568. p = memchr(p, '\n', end - p - 1);
  1569. if (!p)
  1570. return end - 1;
  1571. }
  1572. return p;
  1573. }
  1574. static char *dollar_line(char *p) // return pointer to just before NL line
  1575. {
  1576. p = end_line(p);
  1577. // Try to stay off of the Newline
  1578. if (*p == '\n' && (p - begin_line(p)) > 0)
  1579. p--;
  1580. return p;
  1581. }
  1582. static char *prev_line(char *p) // return pointer first char prev line
  1583. {
  1584. p = begin_line(p); // goto beginning of cur line
  1585. if (p > text && p[-1] == '\n')
  1586. p--; // step to prev line
  1587. p = begin_line(p); // goto beginning of prev line
  1588. return p;
  1589. }
  1590. static char *next_line(char *p) // return pointer first char next line
  1591. {
  1592. p = end_line(p);
  1593. if (p < end - 1 && *p == '\n')
  1594. p++; // step to next line
  1595. return p;
  1596. }
  1597. //----- Text Information Routines ------------------------------
  1598. static char *end_screen(void)
  1599. {
  1600. char *q;
  1601. int cnt;
  1602. // find new bottom line
  1603. q = screenbegin;
  1604. for (cnt = 0; cnt < rows - 2; cnt++)
  1605. q = next_line(q);
  1606. q = end_line(q);
  1607. return q;
  1608. }
  1609. // count line from start to stop
  1610. static int count_lines(char *start, char *stop)
  1611. {
  1612. char *q;
  1613. int cnt;
  1614. if (stop < start) { // start and stop are backwards- reverse them
  1615. q = start;
  1616. start = stop;
  1617. stop = q;
  1618. }
  1619. cnt = 0;
  1620. stop = end_line(stop);
  1621. while (start <= stop && start <= end - 1) {
  1622. start = end_line(start);
  1623. if (*start == '\n')
  1624. cnt++;
  1625. start++;
  1626. }
  1627. return cnt;
  1628. }
  1629. static char *find_line(int li) // find beginning of line #li
  1630. {
  1631. char *q;
  1632. for (q = text; li > 1; li--) {
  1633. q = next_line(q);
  1634. }
  1635. return q;
  1636. }
  1637. //----- Dot Movement Routines ----------------------------------
  1638. static void dot_left(void)
  1639. {
  1640. undo_queue_commit();
  1641. if (dot > text && dot[-1] != '\n')
  1642. dot--;
  1643. }
  1644. static void dot_right(void)
  1645. {
  1646. undo_queue_commit();
  1647. if (dot < end - 1 && *dot != '\n')
  1648. dot++;
  1649. }
  1650. static void dot_begin(void)
  1651. {
  1652. undo_queue_commit();
  1653. dot = begin_line(dot); // return pointer to first char cur line
  1654. }
  1655. static void dot_end(void)
  1656. {
  1657. undo_queue_commit();
  1658. dot = end_line(dot); // return pointer to last char cur line
  1659. }
  1660. static char *move_to_col(char *p, int l)
  1661. {
  1662. int co;
  1663. p = begin_line(p);
  1664. co = 0;
  1665. while (co < l && p < end) {
  1666. if (*p == '\n') //vda || *p == '\0')
  1667. break;
  1668. if (*p == '\t') {
  1669. co = next_tabstop(co);
  1670. } else if (*p < ' ' || *p == 127) {
  1671. co++; // display as ^X, use 2 columns
  1672. }
  1673. co++;
  1674. p++;
  1675. }
  1676. return p;
  1677. }
  1678. static void dot_next(void)
  1679. {
  1680. undo_queue_commit();
  1681. dot = next_line(dot);
  1682. }
  1683. static void dot_prev(void)
  1684. {
  1685. undo_queue_commit();
  1686. dot = prev_line(dot);
  1687. }
  1688. static void dot_scroll(int cnt, int dir)
  1689. {
  1690. char *q;
  1691. undo_queue_commit();
  1692. for (; cnt > 0; cnt--) {
  1693. if (dir < 0) {
  1694. // scroll Backwards
  1695. // ctrl-Y scroll up one line
  1696. screenbegin = prev_line(screenbegin);
  1697. } else {
  1698. // scroll Forwards
  1699. // ctrl-E scroll down one line
  1700. screenbegin = next_line(screenbegin);
  1701. }
  1702. }
  1703. // make sure "dot" stays on the screen so we dont scroll off
  1704. if (dot < screenbegin)
  1705. dot = screenbegin;
  1706. q = end_screen(); // find new bottom line
  1707. if (dot > q)
  1708. dot = begin_line(q); // is dot is below bottom line?
  1709. dot_skip_over_ws();
  1710. }
  1711. static void dot_skip_over_ws(void)
  1712. {
  1713. // skip WS
  1714. while (isspace(*dot) && *dot != '\n' && dot < end - 1)
  1715. dot++;
  1716. }
  1717. static char *bound_dot(char *p) // make sure text[0] <= P < "end"
  1718. {
  1719. if (p >= end && end > text) {
  1720. p = end - 1;
  1721. indicate_error();
  1722. }
  1723. if (p < text) {
  1724. p = text;
  1725. indicate_error();
  1726. }
  1727. return p;
  1728. }
  1729. //----- Helper Utility Routines --------------------------------
  1730. //----------------------------------------------------------------
  1731. //----- Char Routines --------------------------------------------
  1732. /* Chars that are part of a word-
  1733. * 0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
  1734. * Chars that are Not part of a word (stoppers)
  1735. * !"#$%&'()*+,-./:;<=>?@[\]^`{|}~
  1736. * Chars that are WhiteSpace
  1737. * TAB NEWLINE VT FF RETURN SPACE
  1738. * DO NOT COUNT NEWLINE AS WHITESPACE
  1739. */
  1740. static char *new_screen(int ro, int co)
  1741. {
  1742. int li;
  1743. free(screen);
  1744. screensize = ro * co + 8;
  1745. screen = xmalloc(screensize);
  1746. // initialize the new screen. assume this will be a empty file.
  1747. screen_erase();
  1748. // non-existent text[] lines start with a tilde (~).
  1749. for (li = 1; li < ro - 1; li++) {
  1750. screen[(li * co) + 0] = '~';
  1751. }
  1752. return screen;
  1753. }
  1754. #if ENABLE_FEATURE_VI_SEARCH
  1755. # if ENABLE_FEATURE_VI_REGEX_SEARCH
  1756. // search for pattern starting at p
  1757. static char *char_search(char *p, const char *pat, int dir, int range)
  1758. {
  1759. struct re_pattern_buffer preg;
  1760. const char *err;
  1761. char *q;
  1762. int i;
  1763. int size;
  1764. re_syntax_options = RE_SYNTAX_POSIX_EXTENDED;
  1765. if (ignorecase)
  1766. re_syntax_options = RE_SYNTAX_POSIX_EXTENDED | RE_ICASE;
  1767. memset(&preg, 0, sizeof(preg));
  1768. err = re_compile_pattern(pat, strlen(pat), &preg);
  1769. if (err != NULL) {
  1770. status_line_bold("bad search pattern '%s': %s", pat, err);
  1771. return p;
  1772. }
  1773. // assume a LIMITED forward search
  1774. q = end - 1;
  1775. if (dir == BACK)
  1776. q = text;
  1777. // RANGE could be negative if we are searching backwards
  1778. range = q - p;
  1779. q = p;
  1780. size = range;
  1781. if (range < 0) {
  1782. size = -size;
  1783. q = p - size;
  1784. if (q < text)
  1785. q = text;
  1786. }
  1787. // search for the compiled pattern, preg, in p[]
  1788. // range < 0: search backward
  1789. // range > 0: search forward
  1790. // 0 < start < size
  1791. // re_search() < 0: not found or error
  1792. // re_search() >= 0: index of found pattern
  1793. // struct pattern char int int int struct reg
  1794. // re_search(*pattern_buffer, *string, size, start, range, *regs)
  1795. i = re_search(&preg, q, size, /*start:*/ 0, range, /*struct re_registers*:*/ NULL);
  1796. regfree(&preg);
  1797. if (i < 0)
  1798. return NULL;
  1799. if (dir == FORWARD)
  1800. p = p + i;
  1801. else
  1802. p = p - i;
  1803. return p;
  1804. }
  1805. # else
  1806. # if ENABLE_FEATURE_VI_SETOPTS
  1807. static int mycmp(const char *s1, const char *s2, int len)
  1808. {
  1809. if (ignorecase) {
  1810. return strncasecmp(s1, s2, len);
  1811. }
  1812. return strncmp(s1, s2, len);
  1813. }
  1814. # else
  1815. # define mycmp strncmp
  1816. # endif
  1817. static char *char_search(char *p, const char *pat, int dir, int range)
  1818. {
  1819. char *start, *stop;
  1820. int len;
  1821. len = strlen(pat);
  1822. if (dir == FORWARD) {
  1823. stop = end - 1; // assume range is p..end-1
  1824. if (range == LIMITED)
  1825. stop = next_line(p); // range is to next line
  1826. for (start = p; start < stop; start++) {
  1827. if (mycmp(start, pat, len) == 0) {
  1828. return start;
  1829. }
  1830. }
  1831. } else if (dir == BACK) {
  1832. stop = text; // assume range is text..p
  1833. if (range == LIMITED)
  1834. stop = prev_line(p); // range is to prev line
  1835. for (start = p - len; start >= stop; start--) {
  1836. if (mycmp(start, pat, len) == 0) {
  1837. return start;
  1838. }
  1839. }
  1840. }
  1841. // pattern not found
  1842. return NULL;
  1843. }
  1844. # endif
  1845. #endif /* FEATURE_VI_SEARCH */
  1846. static char *char_insert(char *p, char c, int undo) // insert the char c at 'p'
  1847. {
  1848. if (c == 22) { // Is this an ctrl-V?
  1849. p += stupid_insert(p, '^'); // use ^ to indicate literal next
  1850. refresh(FALSE); // show the ^
  1851. c = get_one_char();
  1852. *p = c;
  1853. #if ENABLE_FEATURE_VI_UNDO
  1854. switch (undo) {
  1855. case ALLOW_UNDO:
  1856. undo_push(p, 1, UNDO_INS);
  1857. break;
  1858. case ALLOW_UNDO_CHAIN:
  1859. undo_push(p, 1, UNDO_INS_CHAIN);
  1860. break;
  1861. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  1862. case ALLOW_UNDO_QUEUED:
  1863. undo_push(p, 1, UNDO_INS_QUEUED);
  1864. break;
  1865. # endif
  1866. }
  1867. #else
  1868. modified_count++;
  1869. #endif /* ENABLE_FEATURE_VI_UNDO */
  1870. p++;
  1871. } else if (c == 27) { // Is this an ESC?
  1872. cmd_mode = 0;
  1873. undo_queue_commit();
  1874. cmdcnt = 0;
  1875. end_cmd_q(); // stop adding to q
  1876. last_status_cksum = 0; // force status update
  1877. if ((p[-1] != '\n') && (dot > text)) {
  1878. p--;
  1879. }
  1880. } else if (c == erase_char || c == 8 || c == 127) { // Is this a BS
  1881. if (p > text) {
  1882. p--;
  1883. p = text_hole_delete(p, p, ALLOW_UNDO_QUEUED); // shrink buffer 1 char
  1884. }
  1885. } else {
  1886. // insert a char into text[]
  1887. if (c == 13)
  1888. c = '\n'; // translate \r to \n
  1889. #if ENABLE_FEATURE_VI_UNDO
  1890. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  1891. if (c == '\n')
  1892. undo_queue_commit();
  1893. # endif
  1894. switch (undo) {
  1895. case ALLOW_UNDO:
  1896. undo_push(p, 1, UNDO_INS);
  1897. break;
  1898. case ALLOW_UNDO_CHAIN:
  1899. undo_push(p, 1, UNDO_INS_CHAIN);
  1900. break;
  1901. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  1902. case ALLOW_UNDO_QUEUED:
  1903. undo_push(p, 1, UNDO_INS_QUEUED);
  1904. break;
  1905. # endif
  1906. }
  1907. #else
  1908. modified_count++;
  1909. #endif /* ENABLE_FEATURE_VI_UNDO */
  1910. p += 1 + stupid_insert(p, c); // insert the char
  1911. #if ENABLE_FEATURE_VI_SETOPTS
  1912. if (showmatch && strchr(")]}", c) != NULL) {
  1913. showmatching(p - 1);
  1914. }
  1915. if (autoindent && c == '\n') { // auto indent the new line
  1916. char *q;
  1917. size_t len;
  1918. q = prev_line(p); // use prev line as template
  1919. len = strspn(q, " \t"); // space or tab
  1920. if (len) {
  1921. uintptr_t bias;
  1922. bias = text_hole_make(p, len);
  1923. p += bias;
  1924. q += bias;
  1925. #if ENABLE_FEATURE_VI_UNDO
  1926. undo_push(p, len, UNDO_INS);
  1927. #endif
  1928. memcpy(p, q, len);
  1929. p += len;
  1930. }
  1931. }
  1932. #endif
  1933. }
  1934. return p;
  1935. }
  1936. // might reallocate text[]! use p += stupid_insert(p, ...),
  1937. // and be careful to not use pointers into potentially freed text[]!
  1938. static uintptr_t stupid_insert(char *p, char c) // stupidly insert the char c at 'p'
  1939. {
  1940. uintptr_t bias;
  1941. bias = text_hole_make(p, 1);
  1942. p += bias;
  1943. *p = c;
  1944. return bias;
  1945. }
  1946. static int find_range(char **start, char **stop, char c)
  1947. {
  1948. char *save_dot, *p, *q, *t;
  1949. int cnt, multiline = 0;
  1950. save_dot = dot;
  1951. p = q = dot;
  1952. if (strchr("cdy><", c)) {
  1953. // these cmds operate on whole lines
  1954. p = q = begin_line(p);
  1955. for (cnt = 1; cnt < cmdcnt; cnt++) {
  1956. q = next_line(q);
  1957. }
  1958. q = end_line(q);
  1959. } else if (strchr("^%$0bBeEfth\b\177", c)) {
  1960. // These cmds operate on char positions
  1961. do_cmd(c); // execute movement cmd
  1962. q = dot;
  1963. } else if (strchr("wW", c)) {
  1964. do_cmd(c); // execute movement cmd
  1965. // if we are at the next word's first char
  1966. // step back one char
  1967. // but check the possibilities when it is true
  1968. if (dot > text && ((isspace(dot[-1]) && !isspace(dot[0]))
  1969. || (ispunct(dot[-1]) && !ispunct(dot[0]))
  1970. || (isalnum(dot[-1]) && !isalnum(dot[0]))))
  1971. dot--; // move back off of next word
  1972. if (dot > text && *dot == '\n')
  1973. dot--; // stay off NL
  1974. q = dot;
  1975. } else if (strchr("H-k{", c)) {
  1976. // these operate on multi-lines backwards
  1977. q = end_line(dot); // find NL
  1978. do_cmd(c); // execute movement cmd
  1979. dot_begin();
  1980. p = dot;
  1981. } else if (strchr("L+j}\r\n", c)) {
  1982. // these operate on multi-lines forwards
  1983. p = begin_line(dot);
  1984. do_cmd(c); // execute movement cmd
  1985. dot_end(); // find NL
  1986. q = dot;
  1987. } else {
  1988. // nothing -- this causes any other values of c to
  1989. // represent the one-character range under the
  1990. // cursor. this is correct for ' ' and 'l', but
  1991. // perhaps no others.
  1992. //
  1993. }
  1994. if (q < p) {
  1995. t = q;
  1996. q = p;
  1997. p = t;
  1998. }
  1999. // backward char movements don't include start position
  2000. if (q > p && strchr("^0bBh\b\177", c)) q--;
  2001. multiline = 0;
  2002. for (t = p; t <= q; t++) {
  2003. if (*t == '\n') {
  2004. multiline = 1;
  2005. break;
  2006. }
  2007. }
  2008. *start = p;
  2009. *stop = q;
  2010. dot = save_dot;
  2011. return multiline;
  2012. }
  2013. static int st_test(char *p, int type, int dir, char *tested)
  2014. {
  2015. char c, c0, ci;
  2016. int test, inc;
  2017. inc = dir;
  2018. c = c0 = p[0];
  2019. ci = p[inc];
  2020. test = 0;
  2021. if (type == S_BEFORE_WS) {
  2022. c = ci;
  2023. test = (!isspace(c) || c == '\n');
  2024. }
  2025. if (type == S_TO_WS) {
  2026. c = c0;
  2027. test = (!isspace(c) || c == '\n');
  2028. }
  2029. if (type == S_OVER_WS) {
  2030. c = c0;
  2031. test = isspace(c);
  2032. }
  2033. if (type == S_END_PUNCT) {
  2034. c = ci;
  2035. test = ispunct(c);
  2036. }
  2037. if (type == S_END_ALNUM) {
  2038. c = ci;
  2039. test = (isalnum(c) || c == '_');
  2040. }
  2041. *tested = c;
  2042. return test;
  2043. }
  2044. static char *skip_thing(char *p, int linecnt, int dir, int type)
  2045. {
  2046. char c;
  2047. while (st_test(p, type, dir, &c)) {
  2048. // make sure we limit search to correct number of lines
  2049. if (c == '\n' && --linecnt < 1)
  2050. break;
  2051. if (dir >= 0 && p >= end - 1)
  2052. break;
  2053. if (dir < 0 && p <= text)
  2054. break;
  2055. p += dir; // move to next char
  2056. }
  2057. return p;
  2058. }
  2059. // find matching char of pair () [] {}
  2060. // will crash if c is not one of these
  2061. static char *find_pair(char *p, const char c)
  2062. {
  2063. const char *braces = "()[]{}";
  2064. char match;
  2065. int dir, level;
  2066. dir = strchr(braces, c) - braces;
  2067. dir ^= 1;
  2068. match = braces[dir];
  2069. dir = ((dir & 1) << 1) - 1; /* 1 for ([{, -1 for )\} */
  2070. // look for match, count levels of pairs (( ))
  2071. level = 1;
  2072. for (;;) {
  2073. p += dir;
  2074. if (p < text || p >= end)
  2075. return NULL;
  2076. if (*p == c)
  2077. level++; // increase pair levels
  2078. if (*p == match) {
  2079. level--; // reduce pair level
  2080. if (level == 0)
  2081. return p; // found matching pair
  2082. }
  2083. }
  2084. }
  2085. #if ENABLE_FEATURE_VI_SETOPTS
  2086. // show the matching char of a pair, () [] {}
  2087. static void showmatching(char *p)
  2088. {
  2089. char *q, *save_dot;
  2090. // we found half of a pair
  2091. q = find_pair(p, *p); // get loc of matching char
  2092. if (q == NULL) {
  2093. indicate_error(); // no matching char
  2094. } else {
  2095. // "q" now points to matching pair
  2096. save_dot = dot; // remember where we are
  2097. dot = q; // go to new loc
  2098. refresh(FALSE); // let the user see it
  2099. mysleep(40); // give user some time
  2100. dot = save_dot; // go back to old loc
  2101. refresh(FALSE);
  2102. }
  2103. }
  2104. #endif /* FEATURE_VI_SETOPTS */
  2105. #if ENABLE_FEATURE_VI_UNDO
  2106. static void flush_undo_data(void)
  2107. {
  2108. struct undo_object *undo_entry;
  2109. while (undo_stack_tail) {
  2110. undo_entry = undo_stack_tail;
  2111. undo_stack_tail = undo_entry->prev;
  2112. free(undo_entry);
  2113. }
  2114. }
  2115. // Undo functions and hooks added by Jody Bruchon (jody@jodybruchon.com)
  2116. static void undo_push(char *src, unsigned int length, uint8_t u_type) // Add to the undo stack
  2117. {
  2118. struct undo_object *undo_entry;
  2119. // "u_type" values
  2120. // UNDO_INS: insertion, undo will remove from buffer
  2121. // UNDO_DEL: deleted text, undo will restore to buffer
  2122. // UNDO_{INS,DEL}_CHAIN: Same as above but also calls undo_pop() when complete
  2123. // The CHAIN operations are for handling multiple operations that the user
  2124. // performs with a single action, i.e. REPLACE mode or find-and-replace commands
  2125. // UNDO_{INS,DEL}_QUEUED: If queuing feature is enabled, allow use of the queue
  2126. // for the INS/DEL operation. The raw values should be equal to the values of
  2127. // UNDO_{INS,DEL} ORed with UNDO_QUEUED_FLAG
  2128. #if ENABLE_FEATURE_VI_UNDO_QUEUE
  2129. // This undo queuing functionality groups multiple character typing or backspaces
  2130. // into a single large undo object. This greatly reduces calls to malloc() for
  2131. // single-character operations while typing and has the side benefit of letting
  2132. // an undo operation remove chunks of text rather than a single character.
  2133. switch (u_type) {
  2134. case UNDO_EMPTY: // Just in case this ever happens...
  2135. return;
  2136. case UNDO_DEL_QUEUED:
  2137. if (length != 1)
  2138. return; // Only queue single characters
  2139. switch (undo_queue_state) {
  2140. case UNDO_EMPTY:
  2141. undo_queue_state = UNDO_DEL;
  2142. case UNDO_DEL:
  2143. undo_queue_spos = src;
  2144. undo_q++;
  2145. undo_queue[CONFIG_FEATURE_VI_UNDO_QUEUE_MAX - undo_q] = *src;
  2146. // If queue is full, dump it into an object
  2147. if (undo_q == CONFIG_FEATURE_VI_UNDO_QUEUE_MAX)
  2148. undo_queue_commit();
  2149. return;
  2150. case UNDO_INS:
  2151. // Switch from storing inserted text to deleted text
  2152. undo_queue_commit();
  2153. undo_push(src, length, UNDO_DEL_QUEUED);
  2154. return;
  2155. }
  2156. break;
  2157. case UNDO_INS_QUEUED:
  2158. if (length != 1)
  2159. return;
  2160. switch (undo_queue_state) {
  2161. case UNDO_EMPTY:
  2162. undo_queue_state = UNDO_INS;
  2163. undo_queue_spos = src;
  2164. case UNDO_INS:
  2165. undo_q++; // Don't need to save any data for insertions
  2166. if (undo_q == CONFIG_FEATURE_VI_UNDO_QUEUE_MAX)
  2167. undo_queue_commit();
  2168. return;
  2169. case UNDO_DEL:
  2170. // Switch from storing deleted text to inserted text
  2171. undo_queue_commit();
  2172. undo_push(src, length, UNDO_INS_QUEUED);
  2173. return;
  2174. }
  2175. break;
  2176. }
  2177. #else
  2178. // If undo queuing is disabled, ignore the queuing flag entirely
  2179. u_type = u_type & ~UNDO_QUEUED_FLAG;
  2180. #endif
  2181. // Allocate a new undo object
  2182. if (u_type == UNDO_DEL || u_type == UNDO_DEL_CHAIN) {
  2183. // For UNDO_DEL objects, save deleted text
  2184. if ((src + length) == end)
  2185. length--;
  2186. // If this deletion empties text[], strip the newline. When the buffer becomes
  2187. // zero-length, a newline is added back, which requires this to compensate.
  2188. undo_entry = xzalloc(offsetof(struct undo_object, undo_text) + length);
  2189. memcpy(undo_entry->undo_text, src, length);
  2190. } else {
  2191. undo_entry = xzalloc(sizeof(*undo_entry));
  2192. }
  2193. undo_entry->length = length;
  2194. #if ENABLE_FEATURE_VI_UNDO_QUEUE
  2195. if ((u_type & UNDO_USE_SPOS) != 0) {
  2196. undo_entry->start = undo_queue_spos - text; // use start position from queue
  2197. } else {
  2198. undo_entry->start = src - text; // use offset from start of text buffer
  2199. }
  2200. u_type = (u_type & ~UNDO_USE_SPOS);
  2201. #else
  2202. undo_entry->start = src - text;
  2203. #endif
  2204. undo_entry->u_type = u_type;
  2205. // Push it on undo stack
  2206. undo_entry->prev = undo_stack_tail;
  2207. undo_stack_tail = undo_entry;
  2208. modified_count++;
  2209. }
  2210. static void undo_pop(void) // Undo the last operation
  2211. {
  2212. int repeat;
  2213. char *u_start, *u_end;
  2214. struct undo_object *undo_entry;
  2215. // Commit pending undo queue before popping (should be unnecessary)
  2216. undo_queue_commit();
  2217. undo_entry = undo_stack_tail;
  2218. // Check for an empty undo stack
  2219. if (!undo_entry) {
  2220. status_line("Already at oldest change");
  2221. return;
  2222. }
  2223. switch (undo_entry->u_type) {
  2224. case UNDO_DEL:
  2225. case UNDO_DEL_CHAIN:
  2226. // make hole and put in text that was deleted; deallocate text
  2227. u_start = text + undo_entry->start;
  2228. text_hole_make(u_start, undo_entry->length);
  2229. memcpy(u_start, undo_entry->undo_text, undo_entry->length);
  2230. status_line("Undo [%d] %s %d chars at position %d",
  2231. modified_count, "restored",
  2232. undo_entry->length, undo_entry->start
  2233. );
  2234. break;
  2235. case UNDO_INS:
  2236. case UNDO_INS_CHAIN:
  2237. // delete what was inserted
  2238. u_start = undo_entry->start + text;
  2239. u_end = u_start - 1 + undo_entry->length;
  2240. text_hole_delete(u_start, u_end, NO_UNDO);
  2241. status_line("Undo [%d] %s %d chars at position %d",
  2242. modified_count, "deleted",
  2243. undo_entry->length, undo_entry->start
  2244. );
  2245. break;
  2246. }
  2247. repeat = 0;
  2248. switch (undo_entry->u_type) {
  2249. // If this is the end of a chain, lower modification count and refresh display
  2250. case UNDO_DEL:
  2251. case UNDO_INS:
  2252. dot = (text + undo_entry->start);
  2253. refresh(FALSE);
  2254. break;
  2255. case UNDO_DEL_CHAIN:
  2256. case UNDO_INS_CHAIN:
  2257. repeat = 1;
  2258. break;
  2259. }
  2260. // Deallocate the undo object we just processed
  2261. undo_stack_tail = undo_entry->prev;
  2262. free(undo_entry);
  2263. modified_count--;
  2264. // For chained operations, continue popping all the way down the chain.
  2265. if (repeat) {
  2266. undo_pop(); // Follow the undo chain if one exists
  2267. }
  2268. }
  2269. #if ENABLE_FEATURE_VI_UNDO_QUEUE
  2270. static void undo_queue_commit(void) // Flush any queued objects to the undo stack
  2271. {
  2272. // Pushes the queue object onto the undo stack
  2273. if (undo_q > 0) {
  2274. // Deleted character undo events grow from the end
  2275. undo_push(undo_queue + CONFIG_FEATURE_VI_UNDO_QUEUE_MAX - undo_q,
  2276. undo_q,
  2277. (undo_queue_state | UNDO_USE_SPOS)
  2278. );
  2279. undo_queue_state = UNDO_EMPTY;
  2280. undo_q = 0;
  2281. }
  2282. }
  2283. #endif
  2284. #endif /* ENABLE_FEATURE_VI_UNDO */
  2285. // open a hole in text[]
  2286. // might reallocate text[]! use p += text_hole_make(p, ...),
  2287. // and be careful to not use pointers into potentially freed text[]!
  2288. static uintptr_t text_hole_make(char *p, int size) // at "p", make a 'size' byte hole
  2289. {
  2290. uintptr_t bias = 0;
  2291. if (size <= 0)
  2292. return bias;
  2293. end += size; // adjust the new END
  2294. if (end >= (text + text_size)) {
  2295. char *new_text;
  2296. text_size += end - (text + text_size) + 10240;
  2297. new_text = xrealloc(text, text_size);
  2298. bias = (new_text - text);
  2299. screenbegin += bias;
  2300. dot += bias;
  2301. end += bias;
  2302. p += bias;
  2303. #if ENABLE_FEATURE_VI_YANKMARK
  2304. {
  2305. int i;
  2306. for (i = 0; i < ARRAY_SIZE(mark); i++)
  2307. if (mark[i])
  2308. mark[i] += bias;
  2309. }
  2310. #endif
  2311. text = new_text;
  2312. }
  2313. memmove(p + size, p, end - size - p);
  2314. memset(p, ' ', size); // clear new hole
  2315. return bias;
  2316. }
  2317. // close a hole in text[]
  2318. // "undo" value indicates if this operation should be undo-able
  2319. static char *text_hole_delete(char *p, char *q, int undo) // delete "p" through "q", inclusive
  2320. {
  2321. char *src, *dest;
  2322. int cnt, hole_size;
  2323. // move forwards, from beginning
  2324. // assume p <= q
  2325. src = q + 1;
  2326. dest = p;
  2327. if (q < p) { // they are backward- swap them
  2328. src = p + 1;
  2329. dest = q;
  2330. }
  2331. hole_size = q - p + 1;
  2332. cnt = end - src;
  2333. #if ENABLE_FEATURE_VI_UNDO
  2334. switch (undo) {
  2335. case NO_UNDO:
  2336. break;
  2337. case ALLOW_UNDO:
  2338. undo_push(p, hole_size, UNDO_DEL);
  2339. break;
  2340. case ALLOW_UNDO_CHAIN:
  2341. undo_push(p, hole_size, UNDO_DEL_CHAIN);
  2342. break;
  2343. # if ENABLE_FEATURE_VI_UNDO_QUEUE
  2344. case ALLOW_UNDO_QUEUED:
  2345. undo_push(p, hole_size, UNDO_DEL_QUEUED);
  2346. break;
  2347. # endif
  2348. }
  2349. modified_count--;
  2350. #endif
  2351. if (src < text || src > end)
  2352. goto thd0;
  2353. if (dest < text || dest >= end)
  2354. goto thd0;
  2355. modified_count++;
  2356. if (src >= end)
  2357. goto thd_atend; // just delete the end of the buffer
  2358. memmove(dest, src, cnt);
  2359. thd_atend:
  2360. end = end - hole_size; // adjust the new END
  2361. if (dest >= end)
  2362. dest = end - 1; // make sure dest in below end-1
  2363. if (end <= text)
  2364. dest = end = text; // keep pointers valid
  2365. thd0:
  2366. return dest;
  2367. }
  2368. // copy text into register, then delete text.
  2369. // if dist <= 0, do not include, or go past, a NewLine
  2370. //
  2371. static char *yank_delete(char *start, char *stop, int dist, int yf, int undo)
  2372. {
  2373. char *p;
  2374. // make sure start <= stop
  2375. if (start > stop) {
  2376. // they are backwards, reverse them
  2377. p = start;
  2378. start = stop;
  2379. stop = p;
  2380. }
  2381. if (dist <= 0) {
  2382. // we cannot cross NL boundaries
  2383. p = start;
  2384. if (*p == '\n')
  2385. return p;
  2386. // dont go past a NewLine
  2387. for (; p + 1 <= stop; p++) {
  2388. if (p[1] == '\n') {
  2389. stop = p; // "stop" just before NewLine
  2390. break;
  2391. }
  2392. }
  2393. }
  2394. p = start;
  2395. #if ENABLE_FEATURE_VI_YANKMARK
  2396. text_yank(start, stop, YDreg);
  2397. #endif
  2398. if (yf == YANKDEL) {
  2399. p = text_hole_delete(start, stop, undo);
  2400. } // delete lines
  2401. return p;
  2402. }
  2403. static void show_help(void)
  2404. {
  2405. puts("These features are available:"
  2406. #if ENABLE_FEATURE_VI_SEARCH
  2407. "\n\tPattern searches with / and ?"
  2408. #endif
  2409. #if ENABLE_FEATURE_VI_DOT_CMD
  2410. "\n\tLast command repeat with ."
  2411. #endif
  2412. #if ENABLE_FEATURE_VI_YANKMARK
  2413. "\n\tLine marking with 'x"
  2414. "\n\tNamed buffers with \"x"
  2415. #endif
  2416. #if ENABLE_FEATURE_VI_READONLY
  2417. //not implemented: "\n\tReadonly if vi is called as \"view\""
  2418. //redundant: usage text says this too: "\n\tReadonly with -R command line arg"
  2419. #endif
  2420. #if ENABLE_FEATURE_VI_SET
  2421. "\n\tSome colon mode commands with :"
  2422. #endif
  2423. #if ENABLE_FEATURE_VI_SETOPTS
  2424. "\n\tSettable options with \":set\""
  2425. #endif
  2426. #if ENABLE_FEATURE_VI_USE_SIGNALS
  2427. "\n\tSignal catching- ^C"
  2428. "\n\tJob suspend and resume with ^Z"
  2429. #endif
  2430. #if ENABLE_FEATURE_VI_WIN_RESIZE
  2431. "\n\tAdapt to window re-sizes"
  2432. #endif
  2433. );
  2434. }
  2435. #if ENABLE_FEATURE_VI_DOT_CMD
  2436. static void start_new_cmd_q(char c)
  2437. {
  2438. // get buffer for new cmd
  2439. // if there is a current cmd count put it in the buffer first
  2440. if (cmdcnt > 0) {
  2441. lmc_len = sprintf(last_modifying_cmd, "%d%c", cmdcnt, c);
  2442. } else { // just save char c onto queue
  2443. last_modifying_cmd[0] = c;
  2444. lmc_len = 1;
  2445. }
  2446. adding2q = 1;
  2447. }
  2448. static void end_cmd_q(void)
  2449. {
  2450. #if ENABLE_FEATURE_VI_YANKMARK
  2451. YDreg = 26; // go back to default Yank/Delete reg
  2452. #endif
  2453. adding2q = 0;
  2454. }
  2455. #endif /* FEATURE_VI_DOT_CMD */
  2456. #if ENABLE_FEATURE_VI_YANKMARK \
  2457. || (ENABLE_FEATURE_VI_COLON && ENABLE_FEATURE_VI_SEARCH) \
  2458. || ENABLE_FEATURE_VI_CRASHME
  2459. // might reallocate text[]! use p += string_insert(p, ...),
  2460. // and be careful to not use pointers into potentially freed text[]!
  2461. static uintptr_t string_insert(char *p, const char *s, int undo) // insert the string at 'p'
  2462. {
  2463. uintptr_t bias;
  2464. int i;
  2465. i = strlen(s);
  2466. #if ENABLE_FEATURE_VI_UNDO
  2467. switch (undo) {
  2468. case ALLOW_UNDO:
  2469. undo_push(p, i, UNDO_INS);
  2470. break;
  2471. case ALLOW_UNDO_CHAIN:
  2472. undo_push(p, i, UNDO_INS_CHAIN);
  2473. break;
  2474. }
  2475. #endif
  2476. bias = text_hole_make(p, i);
  2477. p += bias;
  2478. memcpy(p, s, i);
  2479. #if ENABLE_FEATURE_VI_YANKMARK
  2480. {
  2481. int cnt;
  2482. for (cnt = 0; *s != '\0'; s++) {
  2483. if (*s == '\n')
  2484. cnt++;
  2485. }
  2486. status_line("Put %d lines (%d chars) from [%c]", cnt, i, what_reg());
  2487. }
  2488. #endif
  2489. return bias;
  2490. }
  2491. #endif
  2492. #if ENABLE_FEATURE_VI_YANKMARK
  2493. static char *text_yank(char *p, char *q, int dest) // copy text into a register
  2494. {
  2495. int cnt = q - p;
  2496. if (cnt < 0) { // they are backwards- reverse them
  2497. p = q;
  2498. cnt = -cnt;
  2499. }
  2500. free(reg[dest]); // if already a yank register, free it
  2501. reg[dest] = xstrndup(p, cnt + 1);
  2502. return p;
  2503. }
  2504. static char what_reg(void)
  2505. {
  2506. char c;
  2507. c = 'D'; // default to D-reg
  2508. if (0 <= YDreg && YDreg <= 25)
  2509. c = 'a' + (char) YDreg;
  2510. if (YDreg == 26)
  2511. c = 'D';
  2512. if (YDreg == 27)
  2513. c = 'U';
  2514. return c;
  2515. }
  2516. static void check_context(char cmd)
  2517. {
  2518. // A context is defined to be "modifying text"
  2519. // Any modifying command establishes a new context.
  2520. if (dot < context_start || dot > context_end) {
  2521. if (strchr(modifying_cmds, cmd) != NULL) {
  2522. // we are trying to modify text[]- make this the current context
  2523. mark[27] = mark[26]; // move cur to prev
  2524. mark[26] = dot; // move local to cur
  2525. context_start = prev_line(prev_line(dot));
  2526. context_end = next_line(next_line(dot));
  2527. //loiter= start_loiter= now;
  2528. }
  2529. }
  2530. }
  2531. static char *swap_context(char *p) // goto new context for '' command make this the current context
  2532. {
  2533. char *tmp;
  2534. // the current context is in mark[26]
  2535. // the previous context is in mark[27]
  2536. // only swap context if other context is valid
  2537. if (text <= mark[27] && mark[27] <= end - 1) {
  2538. tmp = mark[27];
  2539. mark[27] = mark[26];
  2540. mark[26] = tmp;
  2541. p = mark[26]; // where we are going- previous context
  2542. context_start = prev_line(prev_line(prev_line(p)));
  2543. context_end = next_line(next_line(next_line(p)));
  2544. }
  2545. return p;
  2546. }
  2547. #endif /* FEATURE_VI_YANKMARK */
  2548. //----- Set terminal attributes --------------------------------
  2549. static void rawmode(void)
  2550. {
  2551. tcgetattr(0, &term_orig);
  2552. term_vi = term_orig;
  2553. term_vi.c_lflag &= (~ICANON & ~ECHO); // leave ISIG on - allow intr's
  2554. term_vi.c_iflag &= (~IXON & ~ICRNL);
  2555. term_vi.c_oflag &= (~ONLCR);
  2556. term_vi.c_cc[VMIN] = 1;
  2557. term_vi.c_cc[VTIME] = 0;
  2558. erase_char = term_vi.c_cc[VERASE];
  2559. tcsetattr_stdin_TCSANOW(&term_vi);
  2560. }
  2561. static void cookmode(void)
  2562. {
  2563. fflush_all();
  2564. tcsetattr_stdin_TCSANOW(&term_orig);
  2565. }
  2566. #if ENABLE_FEATURE_VI_USE_SIGNALS
  2567. //----- Come here when we get a window resize signal ---------
  2568. static void winch_sig(int sig UNUSED_PARAM)
  2569. {
  2570. int save_errno = errno;
  2571. // FIXME: do it in main loop!!!
  2572. signal(SIGWINCH, winch_sig);
  2573. query_screen_dimensions();
  2574. new_screen(rows, columns); // get memory for virtual screen
  2575. redraw(TRUE); // re-draw the screen
  2576. errno = save_errno;
  2577. }
  2578. //----- Come here when we get a continue signal -------------------
  2579. static void cont_sig(int sig UNUSED_PARAM)
  2580. {
  2581. int save_errno = errno;
  2582. rawmode(); // terminal to "raw"
  2583. last_status_cksum = 0; // force status update
  2584. redraw(TRUE); // re-draw the screen
  2585. signal(SIGTSTP, suspend_sig);
  2586. signal(SIGCONT, SIG_DFL);
  2587. //kill(my_pid, SIGCONT); // huh? why? we are already "continued"...
  2588. errno = save_errno;
  2589. }
  2590. //----- Come here when we get a Suspend signal -------------------
  2591. static void suspend_sig(int sig UNUSED_PARAM)
  2592. {
  2593. int save_errno = errno;
  2594. go_bottom_and_clear_to_eol();
  2595. cookmode(); // terminal to "cooked"
  2596. signal(SIGCONT, cont_sig);
  2597. signal(SIGTSTP, SIG_DFL);
  2598. kill(my_pid, SIGTSTP);
  2599. errno = save_errno;
  2600. }
  2601. //----- Come here when we get a signal ---------------------------
  2602. static void catch_sig(int sig)
  2603. {
  2604. signal(SIGINT, catch_sig);
  2605. siglongjmp(restart, sig);
  2606. }
  2607. #endif /* FEATURE_VI_USE_SIGNALS */
  2608. static int mysleep(int hund) // sleep for 'hund' 1/100 seconds or stdin ready
  2609. {
  2610. struct pollfd pfd[1];
  2611. if (hund != 0)
  2612. fflush_all();
  2613. pfd[0].fd = STDIN_FILENO;
  2614. pfd[0].events = POLLIN;
  2615. return safe_poll(pfd, 1, hund*10) > 0;
  2616. }
  2617. //----- IO Routines --------------------------------------------
  2618. static int readit(void) // read (maybe cursor) key from stdin
  2619. {
  2620. int c;
  2621. fflush_all();
  2622. c = read_key(STDIN_FILENO, readbuffer, /*timeout off:*/ -2);
  2623. if (c == -1) { // EOF/error
  2624. go_bottom_and_clear_to_eol();
  2625. cookmode(); // terminal to "cooked"
  2626. bb_error_msg_and_die("can't read user input");
  2627. }
  2628. return c;
  2629. }
  2630. //----- IO Routines --------------------------------------------
  2631. static int get_one_char(void)
  2632. {
  2633. int c;
  2634. #if ENABLE_FEATURE_VI_DOT_CMD
  2635. if (!adding2q) {
  2636. // we are not adding to the q.
  2637. // but, we may be reading from a q
  2638. if (ioq == 0) {
  2639. // there is no current q, read from STDIN
  2640. c = readit(); // get the users input
  2641. } else {
  2642. // there is a queue to get chars from first
  2643. // careful with correct sign expansion!
  2644. c = (unsigned char)*ioq++;
  2645. if (c == '\0') {
  2646. // the end of the q, read from STDIN
  2647. free(ioq_start);
  2648. ioq_start = ioq = 0;
  2649. c = readit(); // get the users input
  2650. }
  2651. }
  2652. } else {
  2653. // adding STDIN chars to q
  2654. c = readit(); // get the users input
  2655. if (lmc_len >= MAX_INPUT_LEN - 1) {
  2656. status_line_bold("last_modifying_cmd overrun");
  2657. } else {
  2658. // add new char to q
  2659. last_modifying_cmd[lmc_len++] = c;
  2660. }
  2661. }
  2662. #else
  2663. c = readit(); // get the users input
  2664. #endif /* FEATURE_VI_DOT_CMD */
  2665. return c;
  2666. }
  2667. // Get input line (uses "status line" area)
  2668. static char *get_input_line(const char *prompt)
  2669. {
  2670. // char [MAX_INPUT_LEN]
  2671. #define buf get_input_line__buf
  2672. int c;
  2673. int i;
  2674. strcpy(buf, prompt);
  2675. last_status_cksum = 0; // force status update
  2676. go_bottom_and_clear_to_eol();
  2677. write1(prompt); // write out the :, /, or ? prompt
  2678. i = strlen(buf);
  2679. while (i < MAX_INPUT_LEN) {
  2680. c = get_one_char();
  2681. if (c == '\n' || c == '\r' || c == 27)
  2682. break; // this is end of input
  2683. if (c == erase_char || c == 8 || c == 127) {
  2684. // user wants to erase prev char
  2685. buf[--i] = '\0';
  2686. write1("\b \b"); // erase char on screen
  2687. if (i <= 0) // user backs up before b-o-l, exit
  2688. break;
  2689. } else if (c > 0 && c < 256) { // exclude Unicode
  2690. // (TODO: need to handle Unicode)
  2691. buf[i] = c;
  2692. buf[++i] = '\0';
  2693. bb_putchar(c);
  2694. }
  2695. }
  2696. refresh(FALSE);
  2697. return buf;
  2698. #undef buf
  2699. }
  2700. // might reallocate text[]!
  2701. static int file_insert(const char *fn, char *p, int initial)
  2702. {
  2703. int cnt = -1;
  2704. int fd, size;
  2705. struct stat statbuf;
  2706. if (p < text)
  2707. p = text;
  2708. if (p > end)
  2709. p = end;
  2710. fd = open(fn, O_RDONLY);
  2711. if (fd < 0) {
  2712. if (!initial)
  2713. status_line_bold_errno(fn);
  2714. return cnt;
  2715. }
  2716. /* Validate file */
  2717. if (fstat(fd, &statbuf) < 0) {
  2718. status_line_bold_errno(fn);
  2719. goto fi;
  2720. }
  2721. if (!S_ISREG(statbuf.st_mode)) {
  2722. status_line_bold("'%s' is not a regular file", fn);
  2723. goto fi;
  2724. }
  2725. size = (statbuf.st_size < INT_MAX ? (int)statbuf.st_size : INT_MAX);
  2726. p += text_hole_make(p, size);
  2727. cnt = full_read(fd, p, size);
  2728. if (cnt < 0) {
  2729. status_line_bold_errno(fn);
  2730. p = text_hole_delete(p, p + size - 1, NO_UNDO); // un-do buffer insert
  2731. } else if (cnt < size) {
  2732. // There was a partial read, shrink unused space
  2733. p = text_hole_delete(p + cnt, p + size - 1, NO_UNDO);
  2734. status_line_bold("can't read '%s'", fn);
  2735. }
  2736. fi:
  2737. close(fd);
  2738. #if ENABLE_FEATURE_VI_READONLY
  2739. if (initial
  2740. && ((access(fn, W_OK) < 0) ||
  2741. /* root will always have access()
  2742. * so we check fileperms too */
  2743. !(statbuf.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH))
  2744. )
  2745. ) {
  2746. SET_READONLY_FILE(readonly_mode);
  2747. }
  2748. #endif
  2749. return cnt;
  2750. }
  2751. static int file_write(char *fn, char *first, char *last)
  2752. {
  2753. int fd, cnt, charcnt;
  2754. if (fn == 0) {
  2755. status_line_bold("No current filename");
  2756. return -2;
  2757. }
  2758. /* By popular request we do not open file with O_TRUNC,
  2759. * but instead ftruncate() it _after_ successful write.
  2760. * Might reduce amount of data lost on power fail etc.
  2761. */
  2762. fd = open(fn, (O_WRONLY | O_CREAT), 0666);
  2763. if (fd < 0)
  2764. return -1;
  2765. cnt = last - first + 1;
  2766. charcnt = full_write(fd, first, cnt);
  2767. ftruncate(fd, charcnt);
  2768. if (charcnt == cnt) {
  2769. // good write
  2770. //modified_count = FALSE;
  2771. } else {
  2772. charcnt = 0;
  2773. }
  2774. close(fd);
  2775. return charcnt;
  2776. }
  2777. //----- Terminal Drawing ---------------------------------------
  2778. // The terminal is made up of 'rows' line of 'columns' columns.
  2779. // classically this would be 24 x 80.
  2780. // screen coordinates
  2781. // 0,0 ... 0,79
  2782. // 1,0 ... 1,79
  2783. // . ... .
  2784. // . ... .
  2785. // 22,0 ... 22,79
  2786. // 23,0 ... 23,79 <- status line
  2787. //----- Move the cursor to row x col (count from 0, not 1) -------
  2788. static void place_cursor(int row, int col)
  2789. {
  2790. char cm1[sizeof(ESC_SET_CURSOR_POS) + sizeof(int)*3 * 2];
  2791. if (row < 0) row = 0;
  2792. if (row >= rows) row = rows - 1;
  2793. if (col < 0) col = 0;
  2794. if (col >= columns) col = columns - 1;
  2795. sprintf(cm1, ESC_SET_CURSOR_POS, row + 1, col + 1);
  2796. write1(cm1);
  2797. }
  2798. //----- Erase from cursor to end of line -----------------------
  2799. static void clear_to_eol(void)
  2800. {
  2801. write1(ESC_CLEAR2EOL);
  2802. }
  2803. static void go_bottom_and_clear_to_eol(void)
  2804. {
  2805. place_cursor(rows - 1, 0);
  2806. clear_to_eol();
  2807. }
  2808. //----- Erase from cursor to end of screen -----------------------
  2809. static void clear_to_eos(void)
  2810. {
  2811. write1(ESC_CLEAR2EOS);
  2812. }
  2813. //----- Start standout mode ------------------------------------
  2814. static void standout_start(void)
  2815. {
  2816. write1(ESC_BOLD_TEXT);
  2817. }
  2818. //----- End standout mode --------------------------------------
  2819. static void standout_end(void)
  2820. {
  2821. write1(ESC_NORM_TEXT);
  2822. }
  2823. //----- Flash the screen --------------------------------------
  2824. static void flash(int h)
  2825. {
  2826. standout_start();
  2827. redraw(TRUE);
  2828. mysleep(h);
  2829. standout_end();
  2830. redraw(TRUE);
  2831. }
  2832. static void indicate_error(void)
  2833. {
  2834. #if ENABLE_FEATURE_VI_CRASHME
  2835. if (crashme > 0)
  2836. return; // generate a random command
  2837. #endif
  2838. if (!err_method) {
  2839. write1(ESC_BELL);
  2840. } else {
  2841. flash(10);
  2842. }
  2843. }
  2844. //----- Screen[] Routines --------------------------------------
  2845. //----- Erase the Screen[] memory ------------------------------
  2846. static void screen_erase(void)
  2847. {
  2848. memset(screen, ' ', screensize); // clear new screen
  2849. }
  2850. static int bufsum(char *buf, int count)
  2851. {
  2852. int sum = 0;
  2853. char *e = buf + count;
  2854. while (buf < e)
  2855. sum += (unsigned char) *buf++;
  2856. return sum;
  2857. }
  2858. //----- Draw the status line at bottom of the screen -------------
  2859. static void show_status_line(void)
  2860. {
  2861. int cnt = 0, cksum = 0;
  2862. // either we already have an error or status message, or we
  2863. // create one.
  2864. if (!have_status_msg) {
  2865. cnt = format_edit_status();
  2866. cksum = bufsum(status_buffer, cnt);
  2867. }
  2868. if (have_status_msg || ((cnt > 0 && last_status_cksum != cksum))) {
  2869. last_status_cksum = cksum; // remember if we have seen this line
  2870. go_bottom_and_clear_to_eol();
  2871. write1(status_buffer);
  2872. if (have_status_msg) {
  2873. if (((int)strlen(status_buffer) - (have_status_msg - 1)) >
  2874. (columns - 1) ) {
  2875. have_status_msg = 0;
  2876. Hit_Return();
  2877. }
  2878. have_status_msg = 0;
  2879. }
  2880. place_cursor(crow, ccol); // put cursor back in correct place
  2881. }
  2882. fflush_all();
  2883. }
  2884. //----- format the status buffer, the bottom line of screen ------
  2885. // format status buffer, with STANDOUT mode
  2886. static void status_line_bold(const char *format, ...)
  2887. {
  2888. va_list args;
  2889. va_start(args, format);
  2890. strcpy(status_buffer, ESC_BOLD_TEXT);
  2891. vsprintf(status_buffer + sizeof(ESC_BOLD_TEXT)-1, format, args);
  2892. strcat(status_buffer, ESC_NORM_TEXT);
  2893. va_end(args);
  2894. have_status_msg = 1 + sizeof(ESC_BOLD_TEXT) + sizeof(ESC_NORM_TEXT) - 2;
  2895. }
  2896. static void status_line_bold_errno(const char *fn)
  2897. {
  2898. status_line_bold("'%s' %s", fn, strerror(errno));
  2899. }
  2900. // format status buffer
  2901. static void status_line(const char *format, ...)
  2902. {
  2903. va_list args;
  2904. va_start(args, format);
  2905. vsprintf(status_buffer, format, args);
  2906. va_end(args);
  2907. have_status_msg = 1;
  2908. }
  2909. // copy s to buf, convert unprintable
  2910. static void print_literal(char *buf, const char *s)
  2911. {
  2912. char *d;
  2913. unsigned char c;
  2914. buf[0] = '\0';
  2915. if (!s[0])
  2916. s = "(NULL)";
  2917. d = buf;
  2918. for (; *s; s++) {
  2919. int c_is_no_print;
  2920. c = *s;
  2921. c_is_no_print = (c & 0x80) && !Isprint(c);
  2922. if (c_is_no_print) {
  2923. strcpy(d, ESC_NORM_TEXT);
  2924. d += sizeof(ESC_NORM_TEXT)-1;
  2925. c = '.';
  2926. }
  2927. if (c < ' ' || c == 0x7f) {
  2928. *d++ = '^';
  2929. c |= '@'; /* 0x40 */
  2930. if (c == 0x7f)
  2931. c = '?';
  2932. }
  2933. *d++ = c;
  2934. *d = '\0';
  2935. if (c_is_no_print) {
  2936. strcpy(d, ESC_BOLD_TEXT);
  2937. d += sizeof(ESC_BOLD_TEXT)-1;
  2938. }
  2939. if (*s == '\n') {
  2940. *d++ = '$';
  2941. *d = '\0';
  2942. }
  2943. if (d - buf > MAX_INPUT_LEN - 10) // paranoia
  2944. break;
  2945. }
  2946. }
  2947. static void not_implemented(const char *s)
  2948. {
  2949. char buf[MAX_INPUT_LEN];
  2950. print_literal(buf, s);
  2951. status_line_bold("\'%s\' is not implemented", buf);
  2952. }
  2953. // show file status on status line
  2954. static int format_edit_status(void)
  2955. {
  2956. static const char cmd_mode_indicator[] ALIGN1 = "-IR-";
  2957. #define tot format_edit_status__tot
  2958. int cur, percent, ret, trunc_at;
  2959. // modified_count is now a counter rather than a flag. this
  2960. // helps reduce the amount of line counting we need to do.
  2961. // (this will cause a mis-reporting of modified status
  2962. // once every MAXINT editing operations.)
  2963. // it would be nice to do a similar optimization here -- if
  2964. // we haven't done a motion that could have changed which line
  2965. // we're on, then we shouldn't have to do this count_lines()
  2966. cur = count_lines(text, dot);
  2967. // count_lines() is expensive.
  2968. // Call it only if something was changed since last time
  2969. // we were here:
  2970. if (modified_count != last_modified_count) {
  2971. tot = cur + count_lines(dot, end - 1) - 1;
  2972. last_modified_count = modified_count;
  2973. }
  2974. // current line percent
  2975. // ------------- ~~ ----------
  2976. // total lines 100
  2977. if (tot > 0) {
  2978. percent = (100 * cur) / tot;
  2979. } else {
  2980. cur = tot = 0;
  2981. percent = 100;
  2982. }
  2983. trunc_at = columns < STATUS_BUFFER_LEN-1 ?
  2984. columns : STATUS_BUFFER_LEN-1;
  2985. ret = snprintf(status_buffer, trunc_at+1,
  2986. #if ENABLE_FEATURE_VI_READONLY
  2987. "%c %s%s%s %d/%d %d%%",
  2988. #else
  2989. "%c %s%s %d/%d %d%%",
  2990. #endif
  2991. cmd_mode_indicator[cmd_mode & 3],
  2992. (current_filename != NULL ? current_filename : "No file"),
  2993. #if ENABLE_FEATURE_VI_READONLY
  2994. (readonly_mode ? " [Readonly]" : ""),
  2995. #endif
  2996. (modified_count ? " [Modified]" : ""),
  2997. cur, tot, percent);
  2998. if (ret >= 0 && ret < trunc_at)
  2999. return ret; /* it all fit */
  3000. return trunc_at; /* had to truncate */
  3001. #undef tot
  3002. }
  3003. //----- Force refresh of all Lines -----------------------------
  3004. static void redraw(int full_screen)
  3005. {
  3006. place_cursor(0, 0);
  3007. clear_to_eos();
  3008. screen_erase(); // erase the internal screen buffer
  3009. last_status_cksum = 0; // force status update
  3010. refresh(full_screen); // this will redraw the entire display
  3011. show_status_line();
  3012. }
  3013. //----- Format a text[] line into a buffer ---------------------
  3014. static char* format_line(char *src /*, int li*/)
  3015. {
  3016. unsigned char c;
  3017. int co;
  3018. int ofs = offset;
  3019. char *dest = scr_out_buf; // [MAX_SCR_COLS + MAX_TABSTOP * 2]
  3020. c = '~'; // char in col 0 in non-existent lines is '~'
  3021. co = 0;
  3022. while (co < columns + tabstop) {
  3023. // have we gone past the end?
  3024. if (src < end) {
  3025. c = *src++;
  3026. if (c == '\n')
  3027. break;
  3028. if ((c & 0x80) && !Isprint(c)) {
  3029. c = '.';
  3030. }
  3031. if (c < ' ' || c == 0x7f) {
  3032. if (c == '\t') {
  3033. c = ' ';
  3034. // co % 8 != 7
  3035. while ((co % tabstop) != (tabstop - 1)) {
  3036. dest[co++] = c;
  3037. }
  3038. } else {
  3039. dest[co++] = '^';
  3040. if (c == 0x7f)
  3041. c = '?';
  3042. else
  3043. c += '@'; // Ctrl-X -> 'X'
  3044. }
  3045. }
  3046. }
  3047. dest[co++] = c;
  3048. // discard scrolled-off-to-the-left portion,
  3049. // in tabstop-sized pieces
  3050. if (ofs >= tabstop && co >= tabstop) {
  3051. memmove(dest, dest + tabstop, co);
  3052. co -= tabstop;
  3053. ofs -= tabstop;
  3054. }
  3055. if (src >= end)
  3056. break;
  3057. }
  3058. // check "short line, gigantic offset" case
  3059. if (co < ofs)
  3060. ofs = co;
  3061. // discard last scrolled off part
  3062. co -= ofs;
  3063. dest += ofs;
  3064. // fill the rest with spaces
  3065. if (co < columns)
  3066. memset(&dest[co], ' ', columns - co);
  3067. return dest;
  3068. }
  3069. //----- Refresh the changed screen lines -----------------------
  3070. // Copy the source line from text[] into the buffer and note
  3071. // if the current screenline is different from the new buffer.
  3072. // If they differ then that line needs redrawing on the terminal.
  3073. //
  3074. static void refresh(int full_screen)
  3075. {
  3076. #define old_offset refresh__old_offset
  3077. int li, changed;
  3078. char *tp, *sp; // pointer into text[] and screen[]
  3079. if (ENABLE_FEATURE_VI_WIN_RESIZE IF_FEATURE_VI_ASK_TERMINAL(&& !G.get_rowcol_error) ) {
  3080. unsigned c = columns, r = rows;
  3081. query_screen_dimensions();
  3082. full_screen |= (c - columns) | (r - rows);
  3083. }
  3084. sync_cursor(dot, &crow, &ccol); // where cursor will be (on "dot")
  3085. tp = screenbegin; // index into text[] of top line
  3086. // compare text[] to screen[] and mark screen[] lines that need updating
  3087. for (li = 0; li < rows - 1; li++) {
  3088. int cs, ce; // column start & end
  3089. char *out_buf;
  3090. // format current text line
  3091. out_buf = format_line(tp /*, li*/);
  3092. // skip to the end of the current text[] line
  3093. if (tp < end) {
  3094. char *t = memchr(tp, '\n', end - tp);
  3095. if (!t) t = end - 1;
  3096. tp = t + 1;
  3097. }
  3098. // see if there are any changes between virtual screen and out_buf
  3099. changed = FALSE; // assume no change
  3100. cs = 0;
  3101. ce = columns - 1;
  3102. sp = &screen[li * columns]; // start of screen line
  3103. if (full_screen) {
  3104. // force re-draw of every single column from 0 - columns-1
  3105. goto re0;
  3106. }
  3107. // compare newly formatted buffer with virtual screen
  3108. // look forward for first difference between buf and screen
  3109. for (; cs <= ce; cs++) {
  3110. if (out_buf[cs] != sp[cs]) {
  3111. changed = TRUE; // mark for redraw
  3112. break;
  3113. }
  3114. }
  3115. // look backward for last difference between out_buf and screen
  3116. for (; ce >= cs; ce--) {
  3117. if (out_buf[ce] != sp[ce]) {
  3118. changed = TRUE; // mark for redraw
  3119. break;
  3120. }
  3121. }
  3122. // now, cs is index of first diff, and ce is index of last diff
  3123. // if horz offset has changed, force a redraw
  3124. if (offset != old_offset) {
  3125. re0:
  3126. changed = TRUE;
  3127. }
  3128. // make a sanity check of columns indexes
  3129. if (cs < 0) cs = 0;
  3130. if (ce > columns - 1) ce = columns - 1;
  3131. if (cs > ce) { cs = 0; ce = columns - 1; }
  3132. // is there a change between virtual screen and out_buf
  3133. if (changed) {
  3134. // copy changed part of buffer to virtual screen
  3135. memcpy(sp+cs, out_buf+cs, ce-cs+1);
  3136. place_cursor(li, cs);
  3137. // write line out to terminal
  3138. fwrite(&sp[cs], ce - cs + 1, 1, stdout);
  3139. }
  3140. }
  3141. place_cursor(crow, ccol);
  3142. old_offset = offset;
  3143. #undef old_offset
  3144. }
  3145. //---------------------------------------------------------------------
  3146. //----- the Ascii Chart -----------------------------------------------
  3147. //
  3148. // 00 nul 01 soh 02 stx 03 etx 04 eot 05 enq 06 ack 07 bel
  3149. // 08 bs 09 ht 0a nl 0b vt 0c np 0d cr 0e so 0f si
  3150. // 10 dle 11 dc1 12 dc2 13 dc3 14 dc4 15 nak 16 syn 17 etb
  3151. // 18 can 19 em 1a sub 1b esc 1c fs 1d gs 1e rs 1f us
  3152. // 20 sp 21 ! 22 " 23 # 24 $ 25 % 26 & 27 '
  3153. // 28 ( 29 ) 2a * 2b + 2c , 2d - 2e . 2f /
  3154. // 30 0 31 1 32 2 33 3 34 4 35 5 36 6 37 7
  3155. // 38 8 39 9 3a : 3b ; 3c < 3d = 3e > 3f ?
  3156. // 40 @ 41 A 42 B 43 C 44 D 45 E 46 F 47 G
  3157. // 48 H 49 I 4a J 4b K 4c L 4d M 4e N 4f O
  3158. // 50 P 51 Q 52 R 53 S 54 T 55 U 56 V 57 W
  3159. // 58 X 59 Y 5a Z 5b [ 5c \ 5d ] 5e ^ 5f _
  3160. // 60 ` 61 a 62 b 63 c 64 d 65 e 66 f 67 g
  3161. // 68 h 69 i 6a j 6b k 6c l 6d m 6e n 6f o
  3162. // 70 p 71 q 72 r 73 s 74 t 75 u 76 v 77 w
  3163. // 78 x 79 y 7a z 7b { 7c | 7d } 7e ~ 7f del
  3164. //---------------------------------------------------------------------
  3165. //----- Execute a Vi Command -----------------------------------
  3166. static void do_cmd(int c)
  3167. {
  3168. char *p, *q, *save_dot;
  3169. char buf[12];
  3170. int dir;
  3171. int cnt, i, j;
  3172. int c1;
  3173. // c1 = c; // quiet the compiler
  3174. // cnt = yf = 0; // quiet the compiler
  3175. // p = q = save_dot = buf; // quiet the compiler
  3176. memset(buf, '\0', sizeof(buf));
  3177. show_status_line();
  3178. /* if this is a cursor key, skip these checks */
  3179. switch (c) {
  3180. case KEYCODE_UP:
  3181. case KEYCODE_DOWN:
  3182. case KEYCODE_LEFT:
  3183. case KEYCODE_RIGHT:
  3184. case KEYCODE_HOME:
  3185. case KEYCODE_END:
  3186. case KEYCODE_PAGEUP:
  3187. case KEYCODE_PAGEDOWN:
  3188. case KEYCODE_DELETE:
  3189. goto key_cmd_mode;
  3190. }
  3191. if (cmd_mode == 2) {
  3192. // flip-flop Insert/Replace mode
  3193. if (c == KEYCODE_INSERT)
  3194. goto dc_i;
  3195. // we are 'R'eplacing the current *dot with new char
  3196. if (*dot == '\n') {
  3197. // don't Replace past E-o-l
  3198. cmd_mode = 1; // convert to insert
  3199. undo_queue_commit();
  3200. } else {
  3201. if (1 <= c || Isprint(c)) {
  3202. if (c != 27)
  3203. dot = yank_delete(dot, dot, 0, YANKDEL, ALLOW_UNDO); // delete char
  3204. dot = char_insert(dot, c, ALLOW_UNDO_CHAIN); // insert new char
  3205. }
  3206. goto dc1;
  3207. }
  3208. }
  3209. if (cmd_mode == 1) {
  3210. // hitting "Insert" twice means "R" replace mode
  3211. if (c == KEYCODE_INSERT) goto dc5;
  3212. // insert the char c at "dot"
  3213. if (1 <= c || Isprint(c)) {
  3214. dot = char_insert(dot, c, ALLOW_UNDO_QUEUED);
  3215. }
  3216. goto dc1;
  3217. }
  3218. key_cmd_mode:
  3219. switch (c) {
  3220. //case 0x01: // soh
  3221. //case 0x09: // ht
  3222. //case 0x0b: // vt
  3223. //case 0x0e: // so
  3224. //case 0x0f: // si
  3225. //case 0x10: // dle
  3226. //case 0x11: // dc1
  3227. //case 0x13: // dc3
  3228. #if ENABLE_FEATURE_VI_CRASHME
  3229. case 0x14: // dc4 ctrl-T
  3230. crashme = (crashme == 0) ? 1 : 0;
  3231. break;
  3232. #endif
  3233. //case 0x16: // syn
  3234. //case 0x17: // etb
  3235. //case 0x18: // can
  3236. //case 0x1c: // fs
  3237. //case 0x1d: // gs
  3238. //case 0x1e: // rs
  3239. //case 0x1f: // us
  3240. //case '!': // !-
  3241. //case '#': // #-
  3242. //case '&': // &-
  3243. //case '(': // (-
  3244. //case ')': // )-
  3245. //case '*': // *-
  3246. //case '=': // =-
  3247. //case '@': // @-
  3248. //case 'F': // F-
  3249. //case 'K': // K-
  3250. //case 'Q': // Q-
  3251. //case 'S': // S-
  3252. //case 'T': // T-
  3253. //case 'V': // V-
  3254. //case '[': // [-
  3255. //case '\\': // \-
  3256. //case ']': // ]-
  3257. //case '_': // _-
  3258. //case '`': // `-
  3259. //case 'v': // v-
  3260. default: // unrecognized command
  3261. buf[0] = c;
  3262. buf[1] = '\0';
  3263. not_implemented(buf);
  3264. end_cmd_q(); // stop adding to q
  3265. case 0x00: // nul- ignore
  3266. break;
  3267. case 2: // ctrl-B scroll up full screen
  3268. case KEYCODE_PAGEUP: // Cursor Key Page Up
  3269. dot_scroll(rows - 2, -1);
  3270. break;
  3271. case 4: // ctrl-D scroll down half screen
  3272. dot_scroll((rows - 2) / 2, 1);
  3273. break;
  3274. case 5: // ctrl-E scroll down one line
  3275. dot_scroll(1, 1);
  3276. break;
  3277. case 6: // ctrl-F scroll down full screen
  3278. case KEYCODE_PAGEDOWN: // Cursor Key Page Down
  3279. dot_scroll(rows - 2, 1);
  3280. break;
  3281. case 7: // ctrl-G show current status
  3282. last_status_cksum = 0; // force status update
  3283. break;
  3284. case 'h': // h- move left
  3285. case KEYCODE_LEFT: // cursor key Left
  3286. case 8: // ctrl-H- move left (This may be ERASE char)
  3287. case 0x7f: // DEL- move left (This may be ERASE char)
  3288. do {
  3289. dot_left();
  3290. } while (--cmdcnt > 0);
  3291. break;
  3292. case 10: // Newline ^J
  3293. case 'j': // j- goto next line, same col
  3294. case KEYCODE_DOWN: // cursor key Down
  3295. do {
  3296. dot_next(); // go to next B-o-l
  3297. // try stay in same col
  3298. dot = move_to_col(dot, ccol + offset);
  3299. } while (--cmdcnt > 0);
  3300. break;
  3301. case 12: // ctrl-L force redraw whole screen
  3302. case 18: // ctrl-R force redraw
  3303. place_cursor(0, 0);
  3304. clear_to_eos();
  3305. //mysleep(10); // why???
  3306. screen_erase(); // erase the internal screen buffer
  3307. last_status_cksum = 0; // force status update
  3308. refresh(TRUE); // this will redraw the entire display
  3309. break;
  3310. case 13: // Carriage Return ^M
  3311. case '+': // +- goto next line
  3312. do {
  3313. dot_next();
  3314. dot_skip_over_ws();
  3315. } while (--cmdcnt > 0);
  3316. break;
  3317. case 21: // ctrl-U scroll up half screen
  3318. dot_scroll((rows - 2) / 2, -1);
  3319. break;
  3320. case 25: // ctrl-Y scroll up one line
  3321. dot_scroll(1, -1);
  3322. break;
  3323. case 27: // esc
  3324. if (cmd_mode == 0)
  3325. indicate_error();
  3326. cmd_mode = 0; // stop insrting
  3327. undo_queue_commit();
  3328. end_cmd_q();
  3329. last_status_cksum = 0; // force status update
  3330. break;
  3331. case ' ': // move right
  3332. case 'l': // move right
  3333. case KEYCODE_RIGHT: // Cursor Key Right
  3334. do {
  3335. dot_right();
  3336. } while (--cmdcnt > 0);
  3337. break;
  3338. #if ENABLE_FEATURE_VI_YANKMARK
  3339. case '"': // "- name a register to use for Delete/Yank
  3340. c1 = (get_one_char() | 0x20) - 'a'; // | 0x20 is tolower()
  3341. if ((unsigned)c1 <= 25) { // a-z?
  3342. YDreg = c1;
  3343. } else {
  3344. indicate_error();
  3345. }
  3346. break;
  3347. case '\'': // '- goto a specific mark
  3348. c1 = (get_one_char() | 0x20) - 'a';
  3349. if ((unsigned)c1 <= 25) { // a-z?
  3350. // get the b-o-l
  3351. q = mark[c1];
  3352. if (text <= q && q < end) {
  3353. dot = q;
  3354. dot_begin(); // go to B-o-l
  3355. dot_skip_over_ws();
  3356. }
  3357. } else if (c1 == '\'') { // goto previous context
  3358. dot = swap_context(dot); // swap current and previous context
  3359. dot_begin(); // go to B-o-l
  3360. dot_skip_over_ws();
  3361. } else {
  3362. indicate_error();
  3363. }
  3364. break;
  3365. case 'm': // m- Mark a line
  3366. // this is really stupid. If there are any inserts or deletes
  3367. // between text[0] and dot then this mark will not point to the
  3368. // correct location! It could be off by many lines!
  3369. // Well..., at least its quick and dirty.
  3370. c1 = (get_one_char() | 0x20) - 'a';
  3371. if ((unsigned)c1 <= 25) { // a-z?
  3372. // remember the line
  3373. mark[c1] = dot;
  3374. } else {
  3375. indicate_error();
  3376. }
  3377. break;
  3378. case 'P': // P- Put register before
  3379. case 'p': // p- put register after
  3380. p = reg[YDreg];
  3381. if (p == NULL) {
  3382. status_line_bold("Nothing in register %c", what_reg());
  3383. break;
  3384. }
  3385. // are we putting whole lines or strings
  3386. if (strchr(p, '\n') != NULL) {
  3387. if (c == 'P') {
  3388. dot_begin(); // putting lines- Put above
  3389. }
  3390. if (c == 'p') {
  3391. // are we putting after very last line?
  3392. if (end_line(dot) == (end - 1)) {
  3393. dot = end; // force dot to end of text[]
  3394. } else {
  3395. dot_next(); // next line, then put before
  3396. }
  3397. }
  3398. } else {
  3399. if (c == 'p')
  3400. dot_right(); // move to right, can move to NL
  3401. }
  3402. string_insert(dot, p, ALLOW_UNDO); // insert the string
  3403. end_cmd_q(); // stop adding to q
  3404. break;
  3405. case 'U': // U- Undo; replace current line with original version
  3406. if (reg[Ureg] != NULL) {
  3407. p = begin_line(dot);
  3408. q = end_line(dot);
  3409. p = text_hole_delete(p, q, ALLOW_UNDO); // delete cur line
  3410. p += string_insert(p, reg[Ureg], ALLOW_UNDO_CHAIN); // insert orig line
  3411. dot = p;
  3412. dot_skip_over_ws();
  3413. }
  3414. break;
  3415. #endif /* FEATURE_VI_YANKMARK */
  3416. #if ENABLE_FEATURE_VI_UNDO
  3417. case 'u': // u- undo last operation
  3418. undo_pop();
  3419. break;
  3420. #endif
  3421. case '$': // $- goto end of line
  3422. case KEYCODE_END: // Cursor Key End
  3423. for (;;) {
  3424. dot = end_line(dot);
  3425. if (--cmdcnt <= 0)
  3426. break;
  3427. dot_next();
  3428. }
  3429. break;
  3430. case '%': // %- find matching char of pair () [] {}
  3431. for (q = dot; q < end && *q != '\n'; q++) {
  3432. if (strchr("()[]{}", *q) != NULL) {
  3433. // we found half of a pair
  3434. p = find_pair(q, *q);
  3435. if (p == NULL) {
  3436. indicate_error();
  3437. } else {
  3438. dot = p;
  3439. }
  3440. break;
  3441. }
  3442. }
  3443. if (*q == '\n')
  3444. indicate_error();
  3445. break;
  3446. case 'f': // f- forward to a user specified char
  3447. last_forward_char = get_one_char(); // get the search char
  3448. //
  3449. // dont separate these two commands. 'f' depends on ';'
  3450. //
  3451. //**** fall through to ... ';'
  3452. case ';': // ;- look at rest of line for last forward char
  3453. do {
  3454. if (last_forward_char == 0)
  3455. break;
  3456. q = dot + 1;
  3457. while (q < end - 1 && *q != '\n' && *q != last_forward_char) {
  3458. q++;
  3459. }
  3460. if (*q == last_forward_char)
  3461. dot = q;
  3462. } while (--cmdcnt > 0);
  3463. break;
  3464. case ',': // repeat latest 'f' in opposite direction
  3465. if (last_forward_char == 0)
  3466. break;
  3467. do {
  3468. q = dot - 1;
  3469. while (q >= text && *q != '\n' && *q != last_forward_char) {
  3470. q--;
  3471. }
  3472. if (q >= text && *q == last_forward_char)
  3473. dot = q;
  3474. } while (--cmdcnt > 0);
  3475. break;
  3476. case '-': // -- goto prev line
  3477. do {
  3478. dot_prev();
  3479. dot_skip_over_ws();
  3480. } while (--cmdcnt > 0);
  3481. break;
  3482. #if ENABLE_FEATURE_VI_DOT_CMD
  3483. case '.': // .- repeat the last modifying command
  3484. // Stuff the last_modifying_cmd back into stdin
  3485. // and let it be re-executed.
  3486. if (lmc_len > 0) {
  3487. last_modifying_cmd[lmc_len] = 0;
  3488. ioq = ioq_start = xstrdup(last_modifying_cmd);
  3489. }
  3490. break;
  3491. #endif
  3492. #if ENABLE_FEATURE_VI_SEARCH
  3493. case '?': // /- search for a pattern
  3494. case '/': // /- search for a pattern
  3495. buf[0] = c;
  3496. buf[1] = '\0';
  3497. q = get_input_line(buf); // get input line- use "status line"
  3498. if (q[0] && !q[1]) {
  3499. if (last_search_pattern[0])
  3500. last_search_pattern[0] = c;
  3501. goto dc3; // if no pat re-use old pat
  3502. }
  3503. if (q[0]) { // strlen(q) > 1: new pat- save it and find
  3504. // there is a new pat
  3505. free(last_search_pattern);
  3506. last_search_pattern = xstrdup(q);
  3507. goto dc3; // now find the pattern
  3508. }
  3509. // user changed mind and erased the "/"- do nothing
  3510. break;
  3511. case 'N': // N- backward search for last pattern
  3512. dir = BACK; // assume BACKWARD search
  3513. p = dot - 1;
  3514. if (last_search_pattern[0] == '?') {
  3515. dir = FORWARD;
  3516. p = dot + 1;
  3517. }
  3518. goto dc4; // now search for pattern
  3519. break;
  3520. case 'n': // n- repeat search for last pattern
  3521. // search rest of text[] starting at next char
  3522. // if search fails return orignal "p" not the "p+1" address
  3523. do {
  3524. const char *msg;
  3525. dc3:
  3526. dir = FORWARD; // assume FORWARD search
  3527. p = dot + 1;
  3528. if (last_search_pattern[0] == '?') {
  3529. dir = BACK;
  3530. p = dot - 1;
  3531. }
  3532. dc4:
  3533. q = char_search(p, last_search_pattern + 1, dir, FULL);
  3534. if (q != NULL) {
  3535. dot = q; // good search, update "dot"
  3536. msg = NULL;
  3537. goto dc2;
  3538. }
  3539. // no pattern found between "dot" and "end"- continue at top
  3540. p = text;
  3541. if (dir == BACK) {
  3542. p = end - 1;
  3543. }
  3544. q = char_search(p, last_search_pattern + 1, dir, FULL);
  3545. if (q != NULL) { // found something
  3546. dot = q; // found new pattern- goto it
  3547. msg = "search hit BOTTOM, continuing at TOP";
  3548. if (dir == BACK) {
  3549. msg = "search hit TOP, continuing at BOTTOM";
  3550. }
  3551. } else {
  3552. msg = "Pattern not found";
  3553. }
  3554. dc2:
  3555. if (msg)
  3556. status_line_bold("%s", msg);
  3557. } while (--cmdcnt > 0);
  3558. break;
  3559. case '{': // {- move backward paragraph
  3560. q = char_search(dot, "\n\n", BACK, FULL);
  3561. if (q != NULL) { // found blank line
  3562. dot = next_line(q); // move to next blank line
  3563. }
  3564. break;
  3565. case '}': // }- move forward paragraph
  3566. q = char_search(dot, "\n\n", FORWARD, FULL);
  3567. if (q != NULL) { // found blank line
  3568. dot = next_line(q); // move to next blank line
  3569. }
  3570. break;
  3571. #endif /* FEATURE_VI_SEARCH */
  3572. case '0': // 0- goto beginning of line
  3573. case '1': // 1-
  3574. case '2': // 2-
  3575. case '3': // 3-
  3576. case '4': // 4-
  3577. case '5': // 5-
  3578. case '6': // 6-
  3579. case '7': // 7-
  3580. case '8': // 8-
  3581. case '9': // 9-
  3582. if (c == '0' && cmdcnt < 1) {
  3583. dot_begin(); // this was a standalone zero
  3584. } else {
  3585. cmdcnt = cmdcnt * 10 + (c - '0'); // this 0 is part of a number
  3586. }
  3587. break;
  3588. case ':': // :- the colon mode commands
  3589. p = get_input_line(":"); // get input line- use "status line"
  3590. colon(p); // execute the command
  3591. break;
  3592. case '<': // <- Left shift something
  3593. case '>': // >- Right shift something
  3594. cnt = count_lines(text, dot); // remember what line we are on
  3595. c1 = get_one_char(); // get the type of thing to delete
  3596. find_range(&p, &q, c1);
  3597. yank_delete(p, q, 1, YANKONLY, NO_UNDO); // save copy before change
  3598. p = begin_line(p);
  3599. q = end_line(q);
  3600. i = count_lines(p, q); // # of lines we are shifting
  3601. for ( ; i > 0; i--, p = next_line(p)) {
  3602. if (c == '<') {
  3603. // shift left- remove tab or 8 spaces
  3604. if (*p == '\t') {
  3605. // shrink buffer 1 char
  3606. text_hole_delete(p, p, NO_UNDO);
  3607. } else if (*p == ' ') {
  3608. // we should be calculating columns, not just SPACE
  3609. for (j = 0; *p == ' ' && j < tabstop; j++) {
  3610. text_hole_delete(p, p, NO_UNDO);
  3611. }
  3612. }
  3613. } else if (c == '>') {
  3614. // shift right -- add tab or 8 spaces
  3615. char_insert(p, '\t', ALLOW_UNDO);
  3616. }
  3617. }
  3618. dot = find_line(cnt); // what line were we on
  3619. dot_skip_over_ws();
  3620. end_cmd_q(); // stop adding to q
  3621. break;
  3622. case 'A': // A- append at e-o-l
  3623. dot_end(); // go to e-o-l
  3624. //**** fall through to ... 'a'
  3625. case 'a': // a- append after current char
  3626. if (*dot != '\n')
  3627. dot++;
  3628. goto dc_i;
  3629. break;
  3630. case 'B': // B- back a blank-delimited Word
  3631. case 'E': // E- end of a blank-delimited word
  3632. case 'W': // W- forward a blank-delimited word
  3633. dir = FORWARD;
  3634. if (c == 'B')
  3635. dir = BACK;
  3636. do {
  3637. if (c == 'W' || isspace(dot[dir])) {
  3638. dot = skip_thing(dot, 1, dir, S_TO_WS);
  3639. dot = skip_thing(dot, 2, dir, S_OVER_WS);
  3640. }
  3641. if (c != 'W')
  3642. dot = skip_thing(dot, 1, dir, S_BEFORE_WS);
  3643. } while (--cmdcnt > 0);
  3644. break;
  3645. case 'C': // C- Change to e-o-l
  3646. case 'D': // D- delete to e-o-l
  3647. save_dot = dot;
  3648. dot = dollar_line(dot); // move to before NL
  3649. // copy text into a register and delete
  3650. dot = yank_delete(save_dot, dot, 0, YANKDEL, ALLOW_UNDO); // delete to e-o-l
  3651. if (c == 'C')
  3652. goto dc_i; // start inserting
  3653. #if ENABLE_FEATURE_VI_DOT_CMD
  3654. if (c == 'D')
  3655. end_cmd_q(); // stop adding to q
  3656. #endif
  3657. break;
  3658. case 'g': // 'gg' goto a line number (vim) (default: very first line)
  3659. c1 = get_one_char();
  3660. if (c1 != 'g') {
  3661. buf[0] = 'g';
  3662. buf[1] = c1; // TODO: if Unicode?
  3663. buf[2] = '\0';
  3664. not_implemented(buf);
  3665. break;
  3666. }
  3667. if (cmdcnt == 0)
  3668. cmdcnt = 1;
  3669. /* fall through */
  3670. case 'G': // G- goto to a line number (default= E-O-F)
  3671. dot = end - 1; // assume E-O-F
  3672. if (cmdcnt > 0) {
  3673. dot = find_line(cmdcnt); // what line is #cmdcnt
  3674. }
  3675. dot_skip_over_ws();
  3676. break;
  3677. case 'H': // H- goto top line on screen
  3678. dot = screenbegin;
  3679. if (cmdcnt > (rows - 1)) {
  3680. cmdcnt = (rows - 1);
  3681. }
  3682. if (--cmdcnt > 0) {
  3683. do_cmd('+');
  3684. }
  3685. dot_skip_over_ws();
  3686. break;
  3687. case 'I': // I- insert before first non-blank
  3688. dot_begin(); // 0
  3689. dot_skip_over_ws();
  3690. //**** fall through to ... 'i'
  3691. case 'i': // i- insert before current char
  3692. case KEYCODE_INSERT: // Cursor Key Insert
  3693. dc_i:
  3694. cmd_mode = 1; // start inserting
  3695. undo_queue_commit(); // commit queue when cmd_mode changes
  3696. break;
  3697. case 'J': // J- join current and next lines together
  3698. do {
  3699. dot_end(); // move to NL
  3700. if (dot < end - 1) { // make sure not last char in text[]
  3701. #if ENABLE_FEATURE_VI_UNDO
  3702. undo_push(dot, 1, UNDO_DEL);
  3703. *dot++ = ' '; // replace NL with space
  3704. undo_push((dot - 1), 1, UNDO_INS_CHAIN);
  3705. #else
  3706. *dot++ = ' ';
  3707. modified_count++;
  3708. #endif
  3709. while (isblank(*dot)) { // delete leading WS
  3710. text_hole_delete(dot, dot, ALLOW_UNDO_CHAIN);
  3711. }
  3712. }
  3713. } while (--cmdcnt > 0);
  3714. end_cmd_q(); // stop adding to q
  3715. break;
  3716. case 'L': // L- goto bottom line on screen
  3717. dot = end_screen();
  3718. if (cmdcnt > (rows - 1)) {
  3719. cmdcnt = (rows - 1);
  3720. }
  3721. if (--cmdcnt > 0) {
  3722. do_cmd('-');
  3723. }
  3724. dot_begin();
  3725. dot_skip_over_ws();
  3726. break;
  3727. case 'M': // M- goto middle line on screen
  3728. dot = screenbegin;
  3729. for (cnt = 0; cnt < (rows-1) / 2; cnt++)
  3730. dot = next_line(dot);
  3731. break;
  3732. case 'O': // O- open a empty line above
  3733. // 0i\n ESC -i
  3734. p = begin_line(dot);
  3735. if (p[-1] == '\n') {
  3736. dot_prev();
  3737. case 'o': // o- open a empty line below; Yes, I know it is in the middle of the "if (..."
  3738. dot_end();
  3739. dot = char_insert(dot, '\n', ALLOW_UNDO);
  3740. } else {
  3741. dot_begin(); // 0
  3742. dot = char_insert(dot, '\n', ALLOW_UNDO); // i\n ESC
  3743. dot_prev(); // -
  3744. }
  3745. goto dc_i;
  3746. break;
  3747. case 'R': // R- continuous Replace char
  3748. dc5:
  3749. cmd_mode = 2;
  3750. undo_queue_commit();
  3751. break;
  3752. case KEYCODE_DELETE:
  3753. if (dot < end - 1)
  3754. dot = yank_delete(dot, dot, 1, YANKDEL, ALLOW_UNDO);
  3755. break;
  3756. case 'X': // X- delete char before dot
  3757. case 'x': // x- delete the current char
  3758. case 's': // s- substitute the current char
  3759. dir = 0;
  3760. if (c == 'X')
  3761. dir = -1;
  3762. do {
  3763. if (dot[dir] != '\n') {
  3764. if (c == 'X')
  3765. dot--; // delete prev char
  3766. dot = yank_delete(dot, dot, 0, YANKDEL, ALLOW_UNDO); // delete char
  3767. }
  3768. } while (--cmdcnt > 0);
  3769. end_cmd_q(); // stop adding to q
  3770. if (c == 's')
  3771. goto dc_i; // start inserting
  3772. break;
  3773. case 'Z': // Z- if modified, {write}; exit
  3774. // ZZ means to save file (if necessary), then exit
  3775. c1 = get_one_char();
  3776. if (c1 != 'Z') {
  3777. indicate_error();
  3778. break;
  3779. }
  3780. if (modified_count) {
  3781. if (ENABLE_FEATURE_VI_READONLY && readonly_mode) {
  3782. status_line_bold("'%s' is read only", current_filename);
  3783. break;
  3784. }
  3785. cnt = file_write(current_filename, text, end - 1);
  3786. if (cnt < 0) {
  3787. if (cnt == -1)
  3788. status_line_bold("Write error: %s", strerror(errno));
  3789. } else if (cnt == (end - 1 - text + 1)) {
  3790. editing = 0;
  3791. }
  3792. } else {
  3793. editing = 0;
  3794. }
  3795. break;
  3796. case '^': // ^- move to first non-blank on line
  3797. dot_begin();
  3798. dot_skip_over_ws();
  3799. break;
  3800. case 'b': // b- back a word
  3801. case 'e': // e- end of word
  3802. dir = FORWARD;
  3803. if (c == 'b')
  3804. dir = BACK;
  3805. do {
  3806. if ((dot + dir) < text || (dot + dir) > end - 1)
  3807. break;
  3808. dot += dir;
  3809. if (isspace(*dot)) {
  3810. dot = skip_thing(dot, (c == 'e') ? 2 : 1, dir, S_OVER_WS);
  3811. }
  3812. if (isalnum(*dot) || *dot == '_') {
  3813. dot = skip_thing(dot, 1, dir, S_END_ALNUM);
  3814. } else if (ispunct(*dot)) {
  3815. dot = skip_thing(dot, 1, dir, S_END_PUNCT);
  3816. }
  3817. } while (--cmdcnt > 0);
  3818. break;
  3819. case 'c': // c- change something
  3820. case 'd': // d- delete something
  3821. #if ENABLE_FEATURE_VI_YANKMARK
  3822. case 'y': // y- yank something
  3823. case 'Y': // Y- Yank a line
  3824. #endif
  3825. {
  3826. int yf, ml, whole = 0;
  3827. yf = YANKDEL; // assume either "c" or "d"
  3828. #if ENABLE_FEATURE_VI_YANKMARK
  3829. if (c == 'y' || c == 'Y')
  3830. yf = YANKONLY;
  3831. #endif
  3832. c1 = 'y';
  3833. if (c != 'Y')
  3834. c1 = get_one_char(); // get the type of thing to delete
  3835. // determine range, and whether it spans lines
  3836. ml = find_range(&p, &q, c1);
  3837. place_cursor(0, 0);
  3838. if (c1 == 27) { // ESC- user changed mind and wants out
  3839. c = c1 = 27; // Escape- do nothing
  3840. } else if (strchr("wW", c1)) {
  3841. if (c == 'c') {
  3842. // don't include trailing WS as part of word
  3843. while (isblank(*q)) {
  3844. if (q <= text || q[-1] == '\n')
  3845. break;
  3846. q--;
  3847. }
  3848. }
  3849. dot = yank_delete(p, q, ml, yf, ALLOW_UNDO); // delete word
  3850. } else if (strchr("^0bBeEft%$ lh\b\177", c1)) {
  3851. // partial line copy text into a register and delete
  3852. dot = yank_delete(p, q, ml, yf, ALLOW_UNDO); // delete word
  3853. } else if (strchr("cdykjHL+-{}\r\n", c1)) {
  3854. // whole line copy text into a register and delete
  3855. dot = yank_delete(p, q, ml, yf, ALLOW_UNDO); // delete lines
  3856. whole = 1;
  3857. } else {
  3858. // could not recognize object
  3859. c = c1 = 27; // error-
  3860. ml = 0;
  3861. indicate_error();
  3862. }
  3863. if (ml && whole) {
  3864. if (c == 'c') {
  3865. dot = char_insert(dot, '\n', ALLOW_UNDO_CHAIN);
  3866. // on the last line of file don't move to prev line
  3867. if (whole && dot != (end-1)) {
  3868. dot_prev();
  3869. }
  3870. } else if (c == 'd') {
  3871. dot_begin();
  3872. dot_skip_over_ws();
  3873. }
  3874. }
  3875. if (c1 != 27) {
  3876. // if CHANGING, not deleting, start inserting after the delete
  3877. if (c == 'c') {
  3878. strcpy(buf, "Change");
  3879. goto dc_i; // start inserting
  3880. }
  3881. if (c == 'd') {
  3882. strcpy(buf, "Delete");
  3883. }
  3884. #if ENABLE_FEATURE_VI_YANKMARK
  3885. if (c == 'y' || c == 'Y') {
  3886. strcpy(buf, "Yank");
  3887. }
  3888. p = reg[YDreg];
  3889. q = p + strlen(p);
  3890. for (cnt = 0; p <= q; p++) {
  3891. if (*p == '\n')
  3892. cnt++;
  3893. }
  3894. status_line("%s %d lines (%d chars) using [%c]",
  3895. buf, cnt, strlen(reg[YDreg]), what_reg());
  3896. #endif
  3897. end_cmd_q(); // stop adding to q
  3898. }
  3899. break;
  3900. }
  3901. case 'k': // k- goto prev line, same col
  3902. case KEYCODE_UP: // cursor key Up
  3903. do {
  3904. dot_prev();
  3905. dot = move_to_col(dot, ccol + offset); // try stay in same col
  3906. } while (--cmdcnt > 0);
  3907. break;
  3908. case 'r': // r- replace the current char with user input
  3909. c1 = get_one_char(); // get the replacement char
  3910. if (*dot != '\n') {
  3911. #if ENABLE_FEATURE_VI_UNDO
  3912. undo_push(dot, 1, UNDO_DEL);
  3913. *dot = c1;
  3914. undo_push(dot, 1, UNDO_INS_CHAIN);
  3915. #else
  3916. *dot = c1;
  3917. modified_count++;
  3918. #endif
  3919. }
  3920. end_cmd_q(); // stop adding to q
  3921. break;
  3922. case 't': // t- move to char prior to next x
  3923. last_forward_char = get_one_char();
  3924. do_cmd(';');
  3925. if (*dot == last_forward_char)
  3926. dot_left();
  3927. last_forward_char = 0;
  3928. break;
  3929. case 'w': // w- forward a word
  3930. do {
  3931. if (isalnum(*dot) || *dot == '_') { // we are on ALNUM
  3932. dot = skip_thing(dot, 1, FORWARD, S_END_ALNUM);
  3933. } else if (ispunct(*dot)) { // we are on PUNCT
  3934. dot = skip_thing(dot, 1, FORWARD, S_END_PUNCT);
  3935. }
  3936. if (dot < end - 1)
  3937. dot++; // move over word
  3938. if (isspace(*dot)) {
  3939. dot = skip_thing(dot, 2, FORWARD, S_OVER_WS);
  3940. }
  3941. } while (--cmdcnt > 0);
  3942. break;
  3943. case 'z': // z-
  3944. c1 = get_one_char(); // get the replacement char
  3945. cnt = 0;
  3946. if (c1 == '.')
  3947. cnt = (rows - 2) / 2; // put dot at center
  3948. if (c1 == '-')
  3949. cnt = rows - 2; // put dot at bottom
  3950. screenbegin = begin_line(dot); // start dot at top
  3951. dot_scroll(cnt, -1);
  3952. break;
  3953. case '|': // |- move to column "cmdcnt"
  3954. dot = move_to_col(dot, cmdcnt - 1); // try to move to column
  3955. break;
  3956. case '~': // ~- flip the case of letters a-z -> A-Z
  3957. do {
  3958. #if ENABLE_FEATURE_VI_UNDO
  3959. if (islower(*dot)) {
  3960. undo_push(dot, 1, UNDO_DEL);
  3961. *dot = toupper(*dot);
  3962. undo_push(dot, 1, UNDO_INS_CHAIN);
  3963. } else if (isupper(*dot)) {
  3964. undo_push(dot, 1, UNDO_DEL);
  3965. *dot = tolower(*dot);
  3966. undo_push(dot, 1, UNDO_INS_CHAIN);
  3967. }
  3968. #else
  3969. if (islower(*dot)) {
  3970. *dot = toupper(*dot);
  3971. modified_count++;
  3972. } else if (isupper(*dot)) {
  3973. *dot = tolower(*dot);
  3974. modified_count++;
  3975. }
  3976. #endif
  3977. dot_right();
  3978. } while (--cmdcnt > 0);
  3979. end_cmd_q(); // stop adding to q
  3980. break;
  3981. //----- The Cursor and Function Keys -----------------------------
  3982. case KEYCODE_HOME: // Cursor Key Home
  3983. dot_begin();
  3984. break;
  3985. // The Fn keys could point to do_macro which could translate them
  3986. #if 0
  3987. case KEYCODE_FUN1: // Function Key F1
  3988. case KEYCODE_FUN2: // Function Key F2
  3989. case KEYCODE_FUN3: // Function Key F3
  3990. case KEYCODE_FUN4: // Function Key F4
  3991. case KEYCODE_FUN5: // Function Key F5
  3992. case KEYCODE_FUN6: // Function Key F6
  3993. case KEYCODE_FUN7: // Function Key F7
  3994. case KEYCODE_FUN8: // Function Key F8
  3995. case KEYCODE_FUN9: // Function Key F9
  3996. case KEYCODE_FUN10: // Function Key F10
  3997. case KEYCODE_FUN11: // Function Key F11
  3998. case KEYCODE_FUN12: // Function Key F12
  3999. break;
  4000. #endif
  4001. }
  4002. dc1:
  4003. // if text[] just became empty, add back an empty line
  4004. if (end == text) {
  4005. char_insert(text, '\n', NO_UNDO); // start empty buf with dummy line
  4006. dot = text;
  4007. }
  4008. // it is OK for dot to exactly equal to end, otherwise check dot validity
  4009. if (dot != end) {
  4010. dot = bound_dot(dot); // make sure "dot" is valid
  4011. }
  4012. #if ENABLE_FEATURE_VI_YANKMARK
  4013. check_context(c); // update the current context
  4014. #endif
  4015. if (!isdigit(c))
  4016. cmdcnt = 0; // cmd was not a number, reset cmdcnt
  4017. cnt = dot - begin_line(dot);
  4018. // Try to stay off of the Newline
  4019. if (*dot == '\n' && cnt > 0 && cmd_mode == 0)
  4020. dot--;
  4021. }
  4022. /* NB! the CRASHME code is unmaintained, and doesn't currently build */
  4023. #if ENABLE_FEATURE_VI_CRASHME
  4024. static int totalcmds = 0;
  4025. static int Mp = 85; // Movement command Probability
  4026. static int Np = 90; // Non-movement command Probability
  4027. static int Dp = 96; // Delete command Probability
  4028. static int Ip = 97; // Insert command Probability
  4029. static int Yp = 98; // Yank command Probability
  4030. static int Pp = 99; // Put command Probability
  4031. static int M = 0, N = 0, I = 0, D = 0, Y = 0, P = 0, U = 0;
  4032. static const char chars[20] = "\t012345 abcdABCD-=.$";
  4033. static const char *const words[20] = {
  4034. "this", "is", "a", "test",
  4035. "broadcast", "the", "emergency", "of",
  4036. "system", "quick", "brown", "fox",
  4037. "jumped", "over", "lazy", "dogs",
  4038. "back", "January", "Febuary", "March"
  4039. };
  4040. static const char *const lines[20] = {
  4041. "You should have received a copy of the GNU General Public License\n",
  4042. "char c, cm, *cmd, *cmd1;\n",
  4043. "generate a command by percentages\n",
  4044. "Numbers may be typed as a prefix to some commands.\n",
  4045. "Quit, discarding changes!\n",
  4046. "Forced write, if permission originally not valid.\n",
  4047. "In general, any ex or ed command (such as substitute or delete).\n",
  4048. "I have tickets available for the Blazers vs LA Clippers for Monday, Janurary 1 at 1:00pm.\n",
  4049. "Please get w/ me and I will go over it with you.\n",
  4050. "The following is a list of scheduled, committed changes.\n",
  4051. "1. Launch Norton Antivirus (Start, Programs, Norton Antivirus)\n",
  4052. "Reminder....Town Meeting in Central Perk cafe today at 3:00pm.\n",
  4053. "Any question about transactions please contact Sterling Huxley.\n",
  4054. "I will try to get back to you by Friday, December 31.\n",
  4055. "This Change will be implemented on Friday.\n",
  4056. "Let me know if you have problems accessing this;\n",
  4057. "Sterling Huxley recently added you to the access list.\n",
  4058. "Would you like to go to lunch?\n",
  4059. "The last command will be automatically run.\n",
  4060. "This is too much english for a computer geek.\n",
  4061. };
  4062. static char *multilines[20] = {
  4063. "You should have received a copy of the GNU General Public License\n",
  4064. "char c, cm, *cmd, *cmd1;\n",
  4065. "generate a command by percentages\n",
  4066. "Numbers may be typed as a prefix to some commands.\n",
  4067. "Quit, discarding changes!\n",
  4068. "Forced write, if permission originally not valid.\n",
  4069. "In general, any ex or ed command (such as substitute or delete).\n",
  4070. "I have tickets available for the Blazers vs LA Clippers for Monday, Janurary 1 at 1:00pm.\n",
  4071. "Please get w/ me and I will go over it with you.\n",
  4072. "The following is a list of scheduled, committed changes.\n",
  4073. "1. Launch Norton Antivirus (Start, Programs, Norton Antivirus)\n",
  4074. "Reminder....Town Meeting in Central Perk cafe today at 3:00pm.\n",
  4075. "Any question about transactions please contact Sterling Huxley.\n",
  4076. "I will try to get back to you by Friday, December 31.\n",
  4077. "This Change will be implemented on Friday.\n",
  4078. "Let me know if you have problems accessing this;\n",
  4079. "Sterling Huxley recently added you to the access list.\n",
  4080. "Would you like to go to lunch?\n",
  4081. "The last command will be automatically run.\n",
  4082. "This is too much english for a computer geek.\n",
  4083. };
  4084. // create a random command to execute
  4085. static void crash_dummy()
  4086. {
  4087. static int sleeptime; // how long to pause between commands
  4088. char c, cm, *cmd, *cmd1;
  4089. int i, cnt, thing, rbi, startrbi, percent;
  4090. // "dot" movement commands
  4091. cmd1 = " \n\r\002\004\005\006\025\0310^$-+wWeEbBhjklHL";
  4092. // is there already a command running?
  4093. if (readbuffer[0] > 0)
  4094. goto cd1;
  4095. cd0:
  4096. readbuffer[0] = 'X';
  4097. startrbi = rbi = 1;
  4098. sleeptime = 0; // how long to pause between commands
  4099. memset(readbuffer, '\0', sizeof(readbuffer));
  4100. // generate a command by percentages
  4101. percent = (int) lrand48() % 100; // get a number from 0-99
  4102. if (percent < Mp) { // Movement commands
  4103. // available commands
  4104. cmd = cmd1;
  4105. M++;
  4106. } else if (percent < Np) { // non-movement commands
  4107. cmd = "mz<>\'\""; // available commands
  4108. N++;
  4109. } else if (percent < Dp) { // Delete commands
  4110. cmd = "dx"; // available commands
  4111. D++;
  4112. } else if (percent < Ip) { // Inset commands
  4113. cmd = "iIaAsrJ"; // available commands
  4114. I++;
  4115. } else if (percent < Yp) { // Yank commands
  4116. cmd = "yY"; // available commands
  4117. Y++;
  4118. } else if (percent < Pp) { // Put commands
  4119. cmd = "pP"; // available commands
  4120. P++;
  4121. } else {
  4122. // We do not know how to handle this command, try again
  4123. U++;
  4124. goto cd0;
  4125. }
  4126. // randomly pick one of the available cmds from "cmd[]"
  4127. i = (int) lrand48() % strlen(cmd);
  4128. cm = cmd[i];
  4129. if (strchr(":\024", cm))
  4130. goto cd0; // dont allow colon or ctrl-T commands
  4131. readbuffer[rbi++] = cm; // put cmd into input buffer
  4132. // now we have the command-
  4133. // there are 1, 2, and multi char commands
  4134. // find out which and generate the rest of command as necessary
  4135. if (strchr("dmryz<>\'\"", cm)) { // 2-char commands
  4136. cmd1 = " \n\r0$^-+wWeEbBhjklHL";
  4137. if (cm == 'm' || cm == '\'' || cm == '\"') { // pick a reg[]
  4138. cmd1 = "abcdefghijklmnopqrstuvwxyz";
  4139. }
  4140. thing = (int) lrand48() % strlen(cmd1); // pick a movement command
  4141. c = cmd1[thing];
  4142. readbuffer[rbi++] = c; // add movement to input buffer
  4143. }
  4144. if (strchr("iIaAsc", cm)) { // multi-char commands
  4145. if (cm == 'c') {
  4146. // change some thing
  4147. thing = (int) lrand48() % strlen(cmd1); // pick a movement command
  4148. c = cmd1[thing];
  4149. readbuffer[rbi++] = c; // add movement to input buffer
  4150. }
  4151. thing = (int) lrand48() % 4; // what thing to insert
  4152. cnt = (int) lrand48() % 10; // how many to insert
  4153. for (i = 0; i < cnt; i++) {
  4154. if (thing == 0) { // insert chars
  4155. readbuffer[rbi++] = chars[((int) lrand48() % strlen(chars))];
  4156. } else if (thing == 1) { // insert words
  4157. strcat(readbuffer, words[(int) lrand48() % 20]);
  4158. strcat(readbuffer, " ");
  4159. sleeptime = 0; // how fast to type
  4160. } else if (thing == 2) { // insert lines
  4161. strcat(readbuffer, lines[(int) lrand48() % 20]);
  4162. sleeptime = 0; // how fast to type
  4163. } else { // insert multi-lines
  4164. strcat(readbuffer, multilines[(int) lrand48() % 20]);
  4165. sleeptime = 0; // how fast to type
  4166. }
  4167. }
  4168. strcat(readbuffer, "\033");
  4169. }
  4170. readbuffer[0] = strlen(readbuffer + 1);
  4171. cd1:
  4172. totalcmds++;
  4173. if (sleeptime > 0)
  4174. mysleep(sleeptime); // sleep 1/100 sec
  4175. }
  4176. // test to see if there are any errors
  4177. static void crash_test()
  4178. {
  4179. static time_t oldtim;
  4180. time_t tim;
  4181. char d[2], msg[80];
  4182. msg[0] = '\0';
  4183. if (end < text) {
  4184. strcat(msg, "end<text ");
  4185. }
  4186. if (end > textend) {
  4187. strcat(msg, "end>textend ");
  4188. }
  4189. if (dot < text) {
  4190. strcat(msg, "dot<text ");
  4191. }
  4192. if (dot > end) {
  4193. strcat(msg, "dot>end ");
  4194. }
  4195. if (screenbegin < text) {
  4196. strcat(msg, "screenbegin<text ");
  4197. }
  4198. if (screenbegin > end - 1) {
  4199. strcat(msg, "screenbegin>end-1 ");
  4200. }
  4201. if (msg[0]) {
  4202. printf("\n\n%d: \'%c\' %s\n\n\n%s[Hit return to continue]%s",
  4203. totalcmds, last_input_char, msg, ESC_BOLD_TEXT, ESC_NORM_TEXT);
  4204. fflush_all();
  4205. while (safe_read(STDIN_FILENO, d, 1) > 0) {
  4206. if (d[0] == '\n' || d[0] == '\r')
  4207. break;
  4208. }
  4209. }
  4210. tim = time(NULL);
  4211. if (tim >= (oldtim + 3)) {
  4212. sprintf(status_buffer,
  4213. "Tot=%d: M=%d N=%d I=%d D=%d Y=%d P=%d U=%d size=%d",
  4214. totalcmds, M, N, I, D, Y, P, U, end - text + 1);
  4215. oldtim = tim;
  4216. }
  4217. }
  4218. #endif