vi.c 136 KB

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