vi.c 152 KB

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