vi.c 137 KB

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