vi.c 145 KB

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