vi.c 147 KB

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