vi.c 121 KB

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