vi.c 121 KB

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