vi.c 110 KB

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