vi.c 145 KB

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