vi.c 107 KB

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