TextView.cs 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486
  1. #nullable enable
  2. // TextView.cs: multi-line text editing
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.Runtime.CompilerServices;
  6. using System.Text.Json.Serialization;
  7. using Terminal.Gui.Resources;
  8. namespace Terminal.Gui;
  9. /// <summary>
  10. /// Represents a single row/column within the <see cref="TextView"/>. Includes the glyph and the
  11. /// foreground/background colors.
  12. /// </summary>
  13. [DebuggerDisplay ("{ColorSchemeDebuggerDisplay}")]
  14. public class RuneCell : IEquatable<RuneCell>
  15. {
  16. /// <summary>The <see cref="Terminal.Gui.ColorScheme"/> color sets to draw the glyph with.</summary>
  17. [JsonConverter (typeof (ColorSchemeJsonConverter))]
  18. public ColorScheme? ColorScheme { get; set; }
  19. /// <summary>The glyph to draw.</summary>
  20. [JsonConverter (typeof (RuneJsonConverter))]
  21. public Rune Rune { get; set; }
  22. private string ColorSchemeDebuggerDisplay => ToString ();
  23. /// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
  24. /// <param name="other">An object to compare with this object.</param>
  25. /// <returns>
  26. /// <see langword="true"/> if the current object is equal to the <paramref name="other"/> parameter; otherwise,
  27. /// <see langword="false"/>.
  28. /// </returns>
  29. public bool Equals (RuneCell? other) { return other is { } && Rune.Equals (other.Rune) && ColorScheme == other.ColorScheme; }
  30. /// <summary>Returns a string that represents the current object.</summary>
  31. /// <returns>A string that represents the current object.</returns>
  32. public override string ToString ()
  33. {
  34. string colorSchemeStr = ColorScheme?.ToString () ?? "null";
  35. return $"U+{Rune.Value:X4} '{Rune.ToString ()}'; {colorSchemeStr}";
  36. }
  37. }
  38. internal class TextModel
  39. {
  40. private List<List<RuneCell>> _lines = new ();
  41. private (Point startPointToFind, Point currentPointToFind, bool found) _toFind;
  42. /// <summary>The number of text lines in the model</summary>
  43. public int Count => _lines.Count;
  44. public string? FilePath { get; set; }
  45. /// <summary>Adds a line to the model at the specified position.</summary>
  46. /// <param name="pos">Line number where the line will be inserted.</param>
  47. /// <param name="cells">The line of text and color, as a List of RuneCell.</param>
  48. public void AddLine (int pos, List<RuneCell> cells) { _lines.Insert (pos, cells); }
  49. public bool CloseFile ()
  50. {
  51. if (FilePath is null)
  52. {
  53. throw new ArgumentNullException (nameof (FilePath));
  54. }
  55. FilePath = null;
  56. _lines = new ();
  57. return true;
  58. }
  59. public List<List<RuneCell>> GetAllLines () { return _lines; }
  60. /// <summary>Returns the specified line as a List of Rune</summary>
  61. /// <returns>The line.</returns>
  62. /// <param name="line">Line number to retrieve.</param>
  63. public List<RuneCell> GetLine (int line)
  64. {
  65. if (_lines.Count > 0)
  66. {
  67. if (line < Count)
  68. {
  69. return _lines [line];
  70. }
  71. return _lines [Count - 1];
  72. }
  73. _lines.Add (new ());
  74. return _lines [0];
  75. }
  76. /// <summary>Returns the maximum line length of the visible lines.</summary>
  77. /// <param name="first">The first line.</param>
  78. /// <param name="last">The last line.</param>
  79. /// <param name="tabWidth">The tab width.</param>
  80. public int GetMaxVisibleLine (int first, int last, int tabWidth)
  81. {
  82. var maxLength = 0;
  83. last = last < _lines.Count ? last : _lines.Count;
  84. for (int i = first; i < last; i++)
  85. {
  86. List<RuneCell> line = GetLine (i);
  87. int tabSum = line.Sum (c => c.Rune.Value == '\t' ? Math.Max (tabWidth - 1, 0) : 0);
  88. int l = line.Count + tabSum;
  89. if (l > maxLength)
  90. {
  91. maxLength = l;
  92. }
  93. }
  94. return maxLength;
  95. }
  96. public event EventHandler? LinesLoaded;
  97. public bool LoadFile (string file)
  98. {
  99. FilePath = file ?? throw new ArgumentNullException (nameof (file));
  100. using (FileStream stream = File.OpenRead (file))
  101. {
  102. LoadStream (stream);
  103. return true;
  104. }
  105. }
  106. public void LoadListRuneCells (List<List<RuneCell>> cellsList, ColorScheme? colorScheme)
  107. {
  108. _lines = cellsList;
  109. SetColorSchemes (colorScheme);
  110. OnLinesLoaded ();
  111. }
  112. public void LoadRuneCells (List<RuneCell> cells, ColorScheme? colorScheme)
  113. {
  114. _lines = ToRuneCells (cells);
  115. SetColorSchemes (colorScheme);
  116. OnLinesLoaded ();
  117. }
  118. public void LoadStream (Stream input)
  119. {
  120. if (input is null)
  121. {
  122. throw new ArgumentNullException (nameof (input));
  123. }
  124. _lines = new ();
  125. var buff = new BufferedStream (input);
  126. int v;
  127. List<byte> line = new ();
  128. var wasNewLine = false;
  129. while ((v = buff.ReadByte ()) != -1)
  130. {
  131. if (v == 13)
  132. {
  133. continue;
  134. }
  135. if (v == 10)
  136. {
  137. Append (line);
  138. line.Clear ();
  139. wasNewLine = true;
  140. continue;
  141. }
  142. line.Add ((byte)v);
  143. wasNewLine = false;
  144. }
  145. if (line.Count > 0 || wasNewLine)
  146. {
  147. Append (line);
  148. }
  149. buff.Dispose ();
  150. OnLinesLoaded ();
  151. }
  152. public void LoadString (string content)
  153. {
  154. _lines = StringToLinesOfRuneCells (content);
  155. OnLinesLoaded ();
  156. }
  157. /// <summary>Removes the line at the specified position</summary>
  158. /// <param name="pos">Position.</param>
  159. public void RemoveLine (int pos)
  160. {
  161. if (_lines.Count > 0)
  162. {
  163. if (_lines.Count == 1 && _lines [0].Count == 0)
  164. {
  165. return;
  166. }
  167. _lines.RemoveAt (pos);
  168. }
  169. }
  170. public void ReplaceLine (int pos, List<RuneCell> runes)
  171. {
  172. if (_lines.Count > 0 && pos < _lines.Count)
  173. {
  174. _lines [pos] = new (runes);
  175. }
  176. else if (_lines.Count == 0 || (_lines.Count > 0 && pos >= _lines.Count))
  177. {
  178. _lines.Add (runes);
  179. }
  180. }
  181. // Splits a string into a List that contains a List<RuneCell> for each line
  182. public static List<List<RuneCell>> StringToLinesOfRuneCells (string content, ColorScheme? colorScheme = null)
  183. {
  184. List<RuneCell> cells = content.EnumerateRunes ()
  185. .Select (x => new RuneCell { Rune = x, ColorScheme = colorScheme })
  186. .ToList ();
  187. return SplitNewLines (cells);
  188. }
  189. /// <summary>Converts the string into a <see cref="List{RuneCell}"/>.</summary>
  190. /// <param name="str">The string to convert.</param>
  191. /// <param name="colorScheme">The <see cref="ColorScheme"/> to use.</param>
  192. /// <returns></returns>
  193. public static List<RuneCell> ToRuneCellList (string str, ColorScheme? colorScheme = null)
  194. {
  195. List<RuneCell> cells = new ();
  196. foreach (Rune rune in str.EnumerateRunes ())
  197. {
  198. cells.Add (new () { Rune = rune, ColorScheme = colorScheme });
  199. }
  200. return cells;
  201. }
  202. public override string ToString ()
  203. {
  204. var sb = new StringBuilder ();
  205. for (var i = 0; i < _lines.Count; i++)
  206. {
  207. sb.Append (ToString (_lines [i]));
  208. if (i + 1 < _lines.Count)
  209. {
  210. sb.AppendLine ();
  211. }
  212. }
  213. return sb.ToString ();
  214. }
  215. /// <summary>Converts a <see cref="RuneCell"/> generic collection into a string.</summary>
  216. /// <param name="cells">The enumerable cell to convert.</param>
  217. /// <returns></returns>
  218. public static string ToString (IEnumerable<RuneCell> cells)
  219. {
  220. var str = string.Empty;
  221. foreach (RuneCell cell in cells)
  222. {
  223. str += cell.Rune.ToString ();
  224. }
  225. return str;
  226. }
  227. public (int col, int row)? WordBackward (int fromCol, int fromRow)
  228. {
  229. if (fromRow == 0 && fromCol == 0)
  230. {
  231. return null;
  232. }
  233. int col = Math.Max (fromCol - 1, 0);
  234. int row = fromRow;
  235. try
  236. {
  237. RuneCell? cell = RuneAt (col, row);
  238. Rune rune;
  239. if (cell is { })
  240. {
  241. rune = cell.Rune;
  242. }
  243. else
  244. {
  245. if (col > 0)
  246. {
  247. return (col, row);
  248. }
  249. if (col == 0 && row > 0)
  250. {
  251. row--;
  252. List<RuneCell> line = GetLine (row);
  253. return (line.Count, row);
  254. }
  255. return null;
  256. }
  257. RuneType runeType = GetRuneType (rune);
  258. int lastValidCol = IsSameRuneType (rune, runeType) && (Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) || Rune.IsSymbol (rune))
  259. ? col
  260. : -1;
  261. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  262. {
  263. if (Rune.IsWhiteSpace (nRune))
  264. {
  265. while (MovePrev (ref nCol, ref nRow, out nRune))
  266. {
  267. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune))
  268. {
  269. lastValidCol = nCol;
  270. if (runeType == RuneType.IsWhiteSpace || runeType == RuneType.IsUnknown)
  271. {
  272. runeType = GetRuneType (nRune);
  273. }
  274. break;
  275. }
  276. }
  277. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune)))
  278. {
  279. if (lastValidCol > -1)
  280. {
  281. nCol = lastValidCol;
  282. }
  283. return;
  284. }
  285. while (MovePrev (ref nCol, ref nRow, out nRune))
  286. {
  287. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune) && !Rune.IsSymbol (nRune))
  288. {
  289. break;
  290. }
  291. if (nRow != fromRow)
  292. {
  293. break;
  294. }
  295. lastValidCol =
  296. (IsSameRuneType (nRune, runeType) && Rune.IsLetterOrDigit (nRune)) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune)
  297. ? nCol
  298. : lastValidCol;
  299. }
  300. if (lastValidCol > -1)
  301. {
  302. nCol = lastValidCol;
  303. nRow = fromRow;
  304. }
  305. }
  306. else
  307. {
  308. if (!MovePrev (ref nCol, ref nRow, out nRune))
  309. {
  310. return;
  311. }
  312. List<RuneCell> line = GetLine (nRow);
  313. if (nCol == 0
  314. && nRow == fromRow
  315. && (Rune.IsLetterOrDigit (line [0].Rune) || Rune.IsPunctuation (line [0].Rune) || Rune.IsSymbol (line [0].Rune)))
  316. {
  317. return;
  318. }
  319. lastValidCol =
  320. (IsSameRuneType (nRune, runeType) && Rune.IsLetterOrDigit (nRune)) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune)
  321. ? nCol
  322. : lastValidCol;
  323. if (lastValidCol > -1 && Rune.IsWhiteSpace (nRune))
  324. {
  325. nCol = lastValidCol;
  326. return;
  327. }
  328. if (fromRow != nRow)
  329. {
  330. nCol = line.Count;
  331. return;
  332. }
  333. ProcMovePrev (ref nCol, ref nRow, nRune);
  334. }
  335. }
  336. ProcMovePrev (ref col, ref row, rune);
  337. if (fromCol != col || fromRow != row)
  338. {
  339. return (col, row);
  340. }
  341. return null;
  342. }
  343. catch (Exception)
  344. {
  345. return null;
  346. }
  347. }
  348. public (int col, int row)? WordForward (int fromCol, int fromRow)
  349. {
  350. if (fromRow == _lines.Count - 1 && fromCol == GetLine (_lines.Count - 1).Count)
  351. {
  352. return null;
  353. }
  354. int col = fromCol;
  355. int row = fromRow;
  356. try
  357. {
  358. Rune rune = RuneAt (col, row).Rune;
  359. RuneType runeType = GetRuneType (rune);
  360. int lastValidCol = IsSameRuneType (rune, runeType) && (Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) || Rune.IsSymbol (rune))
  361. ? col
  362. : -1;
  363. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  364. {
  365. if (Rune.IsWhiteSpace (nRune))
  366. {
  367. while (MoveNext (ref nCol, ref nRow, out nRune))
  368. {
  369. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune))
  370. {
  371. lastValidCol = nCol;
  372. return;
  373. }
  374. }
  375. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune)))
  376. {
  377. if (lastValidCol > -1)
  378. {
  379. nCol = lastValidCol;
  380. }
  381. return;
  382. }
  383. while (MoveNext (ref nCol, ref nRow, out nRune))
  384. {
  385. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune) && !Rune.IsSymbol (nRune))
  386. {
  387. break;
  388. }
  389. if (nRow != fromRow)
  390. {
  391. break;
  392. }
  393. lastValidCol =
  394. (IsSameRuneType (nRune, runeType) && Rune.IsLetterOrDigit (nRune)) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune)
  395. ? nCol
  396. : lastValidCol;
  397. }
  398. if (lastValidCol > -1)
  399. {
  400. nCol = lastValidCol;
  401. nRow = fromRow;
  402. }
  403. }
  404. else
  405. {
  406. if (!MoveNext (ref nCol, ref nRow, out nRune))
  407. {
  408. return;
  409. }
  410. if (!IsSameRuneType (nRune, runeType) && !Rune.IsWhiteSpace (nRune))
  411. {
  412. return;
  413. }
  414. List<RuneCell> line = GetLine (nRow);
  415. if (nCol == line.Count
  416. && nRow == fromRow
  417. && (Rune.IsLetterOrDigit (line [0].Rune) || Rune.IsPunctuation (line [0].Rune) || Rune.IsSymbol (line [0].Rune)))
  418. {
  419. return;
  420. }
  421. lastValidCol =
  422. (IsSameRuneType (nRune, runeType) && Rune.IsLetterOrDigit (nRune)) || Rune.IsPunctuation (nRune) || Rune.IsSymbol (nRune)
  423. ? nCol
  424. : lastValidCol;
  425. if (fromRow != nRow)
  426. {
  427. nCol = 0;
  428. return;
  429. }
  430. ProcMoveNext (ref nCol, ref nRow, nRune);
  431. }
  432. }
  433. ProcMoveNext (ref col, ref row, rune);
  434. if (fromCol != col || fromRow != row)
  435. {
  436. return (col, row);
  437. }
  438. return null;
  439. }
  440. catch (Exception)
  441. {
  442. return null;
  443. }
  444. }
  445. internal static int CalculateLeftColumn (List<RuneCell> t, int start, int end, int width, int tabWidth = 0)
  446. {
  447. List<Rune> runes = new ();
  448. foreach (RuneCell cell in t)
  449. {
  450. runes.Add (cell.Rune);
  451. }
  452. return CalculateLeftColumn (runes, start, end, width, tabWidth);
  453. }
  454. // Returns the left column in a range of the string.
  455. internal static int CalculateLeftColumn (List<Rune> t, int start, int end, int width, int tabWidth = 0)
  456. {
  457. if (t is null || t.Count == 0)
  458. {
  459. return 0;
  460. }
  461. var size = 0;
  462. int tcount = end > t.Count - 1 ? t.Count - 1 : end;
  463. var col = 0;
  464. for (int i = tcount; i >= 0; i--)
  465. {
  466. Rune rune = t [i];
  467. size += rune.GetColumns ();
  468. if (rune.Value == '\t')
  469. {
  470. size += tabWidth + 1;
  471. }
  472. if (size > width)
  473. {
  474. if (col + width == end)
  475. {
  476. col++;
  477. }
  478. break;
  479. }
  480. if ((end < t.Count && col > 0 && start < end && col == start) || end - col == width - 1)
  481. {
  482. break;
  483. }
  484. col = i;
  485. }
  486. return col;
  487. }
  488. internal static (int size, int length) DisplaySize (
  489. List<RuneCell> t,
  490. int start = -1,
  491. int end = -1,
  492. bool checkNextRune = true,
  493. int tabWidth = 0
  494. )
  495. {
  496. List<Rune> runes = new ();
  497. foreach (RuneCell cell in t)
  498. {
  499. runes.Add (cell.Rune);
  500. }
  501. return DisplaySize (runes, start, end, checkNextRune, tabWidth);
  502. }
  503. // Returns the size and length in a range of the string.
  504. internal static (int size, int length) DisplaySize (
  505. List<Rune> t,
  506. int start = -1,
  507. int end = -1,
  508. bool checkNextRune = true,
  509. int tabWidth = 0
  510. )
  511. {
  512. if (t is null || t.Count == 0)
  513. {
  514. return (0, 0);
  515. }
  516. var size = 0;
  517. var len = 0;
  518. int tcount = end == -1 ? t.Count :
  519. end > t.Count ? t.Count : end;
  520. int i = start == -1 ? 0 : start;
  521. for (; i < tcount; i++)
  522. {
  523. Rune rune = t [i];
  524. size += rune.GetColumns ();
  525. len += rune.GetEncodingLength (Encoding.Unicode);
  526. if (rune.Value == '\t')
  527. {
  528. size += tabWidth + 1;
  529. len += tabWidth - 1;
  530. }
  531. if (checkNextRune && i == tcount - 1 && t.Count > tcount && IsWideRune (t [i + 1], tabWidth, out int s, out int l))
  532. {
  533. size += s;
  534. len += l;
  535. }
  536. }
  537. bool IsWideRune (Rune r, int tWidth, out int s, out int l)
  538. {
  539. s = r.GetColumns ();
  540. l = r.GetEncodingLength ();
  541. if (r.Value == '\t')
  542. {
  543. s += tWidth + 1;
  544. l += tWidth - 1;
  545. }
  546. return s > 1;
  547. }
  548. return (size, len);
  549. }
  550. internal Size GetDisplaySize ()
  551. {
  552. Size size = Size.Empty;
  553. return size;
  554. }
  555. internal (Point current, bool found) FindNextText (
  556. string text,
  557. out bool gaveFullTurn,
  558. bool matchCase = false,
  559. bool matchWholeWord = false
  560. )
  561. {
  562. if (text is null || _lines.Count == 0)
  563. {
  564. gaveFullTurn = false;
  565. return (Point.Empty, false);
  566. }
  567. if (_toFind.found)
  568. {
  569. _toFind.currentPointToFind.X++;
  570. }
  571. (Point current, bool found) foundPos = GetFoundNextTextPoint (
  572. text,
  573. _lines.Count,
  574. matchCase,
  575. matchWholeWord,
  576. _toFind.currentPointToFind
  577. );
  578. if (!foundPos.found && _toFind.currentPointToFind != _toFind.startPointToFind)
  579. {
  580. foundPos = GetFoundNextTextPoint (
  581. text,
  582. _toFind.startPointToFind.Y + 1,
  583. matchCase,
  584. matchWholeWord,
  585. Point.Empty
  586. );
  587. }
  588. gaveFullTurn = ApplyToFind (foundPos);
  589. return foundPos;
  590. }
  591. internal (Point current, bool found) FindPreviousText (
  592. string text,
  593. out bool gaveFullTurn,
  594. bool matchCase = false,
  595. bool matchWholeWord = false
  596. )
  597. {
  598. if (text is null || _lines.Count == 0)
  599. {
  600. gaveFullTurn = false;
  601. return (Point.Empty, false);
  602. }
  603. if (_toFind.found)
  604. {
  605. _toFind.currentPointToFind.X++;
  606. }
  607. int linesCount = _toFind.currentPointToFind.IsEmpty ? _lines.Count - 1 : _toFind.currentPointToFind.Y;
  608. (Point current, bool found) foundPos = GetFoundPreviousTextPoint (
  609. text,
  610. linesCount,
  611. matchCase,
  612. matchWholeWord,
  613. _toFind.currentPointToFind
  614. );
  615. if (!foundPos.found && _toFind.currentPointToFind != _toFind.startPointToFind)
  616. {
  617. foundPos = GetFoundPreviousTextPoint (
  618. text,
  619. _lines.Count - 1,
  620. matchCase,
  621. matchWholeWord,
  622. new (_lines [_lines.Count - 1].Count, _lines.Count)
  623. );
  624. }
  625. gaveFullTurn = ApplyToFind (foundPos);
  626. return foundPos;
  627. }
  628. internal static int GetColFromX (List<RuneCell> t, int start, int x, int tabWidth = 0)
  629. {
  630. List<Rune> runes = new ();
  631. foreach (RuneCell cell in t)
  632. {
  633. runes.Add (cell.Rune);
  634. }
  635. return GetColFromX (runes, start, x, tabWidth);
  636. }
  637. internal static int GetColFromX (List<Rune> t, int start, int x, int tabWidth = 0)
  638. {
  639. if (x < 0)
  640. {
  641. return x;
  642. }
  643. int size = start;
  644. int pX = x + start;
  645. for (int i = start; i < t.Count; i++)
  646. {
  647. Rune r = t [i];
  648. size += r.GetColumns ();
  649. if (r.Value == '\t')
  650. {
  651. size += tabWidth + 1;
  652. }
  653. if (i == pX || size > pX)
  654. {
  655. return i - start;
  656. }
  657. }
  658. return t.Count - start;
  659. }
  660. internal (Point current, bool found) ReplaceAllText (
  661. string text,
  662. bool matchCase = false,
  663. bool matchWholeWord = false,
  664. string? textToReplace = null
  665. )
  666. {
  667. var found = false;
  668. var pos = Point.Empty;
  669. for (var i = 0; i < _lines.Count; i++)
  670. {
  671. List<RuneCell> x = _lines [i];
  672. string txt = GetText (x);
  673. string matchText = !matchCase ? text.ToUpper () : text;
  674. int col = txt.IndexOf (matchText);
  675. while (col > -1)
  676. {
  677. if (matchWholeWord && !MatchWholeWord (txt, matchText, col))
  678. {
  679. if (col + 1 > txt.Length)
  680. {
  681. break;
  682. }
  683. col = txt.IndexOf (matchText, col + 1);
  684. continue;
  685. }
  686. if (col > -1)
  687. {
  688. if (!found)
  689. {
  690. found = true;
  691. }
  692. _lines [i] = ToRuneCellList (ReplaceText (x, textToReplace!, matchText, col));
  693. x = _lines [i];
  694. txt = GetText (x);
  695. pos = new (col, i);
  696. col += textToReplace!.Length - matchText.Length;
  697. }
  698. if (col < 0 || col + 1 > txt.Length)
  699. {
  700. break;
  701. }
  702. col = txt.IndexOf (matchText, col + 1);
  703. }
  704. }
  705. string GetText (List<RuneCell> x)
  706. {
  707. string txt = ToString (x);
  708. if (!matchCase)
  709. {
  710. txt = txt.ToUpper ();
  711. }
  712. return txt;
  713. }
  714. return (pos, found);
  715. }
  716. /// <summary>Redefine column and line tracking.</summary>
  717. /// <param name="point">Contains the column and line.</param>
  718. internal void ResetContinuousFind (Point point)
  719. {
  720. _toFind.startPointToFind = _toFind.currentPointToFind = point;
  721. _toFind.found = false;
  722. }
  723. internal static bool SetCol (ref int col, int width, int cols)
  724. {
  725. if (col + cols <= width)
  726. {
  727. col += cols;
  728. return true;
  729. }
  730. return false;
  731. }
  732. // Turns the string into cells, this does not split the
  733. // contents on a newline if it is present.
  734. internal static List<RuneCell> StringToRuneCells (string str, ColorScheme? colorScheme = null)
  735. {
  736. List<RuneCell> cells = new ();
  737. foreach (Rune rune in str.ToRunes ())
  738. {
  739. cells.Add (new () { Rune = rune, ColorScheme = colorScheme });
  740. }
  741. return cells;
  742. }
  743. internal static List<RuneCell> ToRuneCells (IEnumerable<Rune> runes, ColorScheme? colorScheme = null)
  744. {
  745. List<RuneCell> cells = new ();
  746. foreach (Rune rune in runes)
  747. {
  748. cells.Add (new () { Rune = rune, ColorScheme = colorScheme });
  749. }
  750. return cells;
  751. }
  752. private void Append (List<byte> line)
  753. {
  754. var str = StringExtensions.ToString (line.ToArray ());
  755. _lines.Add (StringToRuneCells (str));
  756. }
  757. private bool ApplyToFind ((Point current, bool found) foundPos)
  758. {
  759. var gaveFullTurn = false;
  760. if (foundPos.found)
  761. {
  762. _toFind.currentPointToFind = foundPos.current;
  763. if (_toFind.found && _toFind.currentPointToFind == _toFind.startPointToFind)
  764. {
  765. gaveFullTurn = true;
  766. }
  767. if (!_toFind.found)
  768. {
  769. _toFind.startPointToFind = _toFind.currentPointToFind = foundPos.current;
  770. _toFind.found = foundPos.found;
  771. }
  772. }
  773. return gaveFullTurn;
  774. }
  775. private (Point current, bool found) GetFoundNextTextPoint (
  776. string text,
  777. int linesCount,
  778. bool matchCase,
  779. bool matchWholeWord,
  780. Point start
  781. )
  782. {
  783. for (int i = start.Y; i < linesCount; i++)
  784. {
  785. List<RuneCell> x = _lines [i];
  786. string txt = ToString (x);
  787. if (!matchCase)
  788. {
  789. txt = txt.ToUpper ();
  790. }
  791. string matchText = !matchCase ? text.ToUpper () : text;
  792. int col = txt.IndexOf (matchText, Math.Min (start.X, txt.Length));
  793. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col))
  794. {
  795. continue;
  796. }
  797. if (col > -1 && ((i == start.Y && col >= start.X) || i > start.Y) && txt.Contains (matchText))
  798. {
  799. return (new (col, i), true);
  800. }
  801. if (col == -1 && start.X > 0)
  802. {
  803. start.X = 0;
  804. }
  805. }
  806. return (Point.Empty, false);
  807. }
  808. private (Point current, bool found) GetFoundPreviousTextPoint (
  809. string text,
  810. int linesCount,
  811. bool matchCase,
  812. bool matchWholeWord,
  813. Point start
  814. )
  815. {
  816. for (int i = linesCount; i >= 0; i--)
  817. {
  818. List<RuneCell> x = _lines [i];
  819. string txt = ToString (x);
  820. if (!matchCase)
  821. {
  822. txt = txt.ToUpper ();
  823. }
  824. if (start.Y != i)
  825. {
  826. start.X = Math.Max (x.Count - 1, 0);
  827. }
  828. string matchText = !matchCase ? text.ToUpper () : text;
  829. int col = txt.LastIndexOf (matchText, _toFind.found ? start.X - 1 : start.X);
  830. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col))
  831. {
  832. continue;
  833. }
  834. if (col > -1 && ((i <= linesCount && col <= start.X) || i < start.Y) && txt.Contains (matchText))
  835. {
  836. return (new (col, i), true);
  837. }
  838. }
  839. return (Point.Empty, false);
  840. }
  841. private RuneType GetRuneType (Rune rune)
  842. {
  843. if (Rune.IsSymbol (rune))
  844. {
  845. return RuneType.IsSymbol;
  846. }
  847. if (Rune.IsWhiteSpace (rune))
  848. {
  849. return RuneType.IsWhiteSpace;
  850. }
  851. if (Rune.IsLetterOrDigit (rune))
  852. {
  853. return RuneType.IsLetterOrDigit;
  854. }
  855. if (Rune.IsPunctuation (rune))
  856. {
  857. return RuneType.IsPunctuation;
  858. }
  859. return RuneType.IsUnknown;
  860. }
  861. private bool IsSameRuneType (Rune newRune, RuneType runeType)
  862. {
  863. RuneType rt = GetRuneType (newRune);
  864. return rt == runeType;
  865. }
  866. private bool MatchWholeWord (string source, string matchText, int index = 0)
  867. {
  868. if (string.IsNullOrEmpty (source) || string.IsNullOrEmpty (matchText))
  869. {
  870. return false;
  871. }
  872. string txt = matchText.Trim ();
  873. int start = index > 0 ? index - 1 : 0;
  874. int end = index + txt.Length;
  875. if ((start == 0 || Rune.IsWhiteSpace ((Rune)source [start])) && (end == source.Length || Rune.IsWhiteSpace ((Rune)source [end])))
  876. {
  877. return true;
  878. }
  879. return false;
  880. }
  881. private bool MoveNext (ref int col, ref int row, out Rune rune)
  882. {
  883. List<RuneCell> line = GetLine (row);
  884. if (col + 1 < line.Count)
  885. {
  886. col++;
  887. rune = line [col].Rune;
  888. if (col + 1 == line.Count && !Rune.IsLetterOrDigit (rune) && !Rune.IsWhiteSpace (line [col - 1].Rune))
  889. {
  890. col++;
  891. }
  892. return true;
  893. }
  894. if (col + 1 == line.Count)
  895. {
  896. col++;
  897. }
  898. while (row + 1 < Count)
  899. {
  900. col = 0;
  901. row++;
  902. line = GetLine (row);
  903. if (line.Count > 0)
  904. {
  905. rune = line [0].Rune;
  906. return true;
  907. }
  908. }
  909. rune = default (Rune);
  910. return false;
  911. }
  912. private bool MovePrev (ref int col, ref int row, out Rune rune)
  913. {
  914. List<RuneCell> line = GetLine (row);
  915. if (col > 0)
  916. {
  917. col--;
  918. rune = line [col].Rune;
  919. return true;
  920. }
  921. if (row == 0)
  922. {
  923. rune = default (Rune);
  924. return false;
  925. }
  926. while (row > 0)
  927. {
  928. row--;
  929. line = GetLine (row);
  930. col = line.Count - 1;
  931. if (col >= 0)
  932. {
  933. rune = line [col].Rune;
  934. return true;
  935. }
  936. }
  937. rune = default (Rune);
  938. return false;
  939. }
  940. private void OnLinesLoaded () { LinesLoaded?.Invoke (this, EventArgs.Empty); }
  941. private string ReplaceText (List<RuneCell> source, string textToReplace, string matchText, int col)
  942. {
  943. string origTxt = ToString (source);
  944. (_, int len) = DisplaySize (source, 0, col, false);
  945. (_, int len2) = DisplaySize (source, col, col + matchText.Length, false);
  946. (_, int len3) = DisplaySize (source, col + matchText.Length, origTxt.GetRuneCount (), false);
  947. return origTxt [..len] + textToReplace + origTxt.Substring (len + len2, len3);
  948. }
  949. private RuneCell RuneAt (int col, int row)
  950. {
  951. List<RuneCell> line = GetLine (row);
  952. if (line.Count > 0)
  953. {
  954. return line [col > line.Count - 1 ? line.Count - 1 : col];
  955. }
  956. return default (RuneCell)!;
  957. }
  958. private void SetColorSchemes (ColorScheme? colorScheme)
  959. {
  960. foreach (List<RuneCell> line in _lines)
  961. {
  962. foreach (RuneCell cell in line)
  963. {
  964. cell.ColorScheme ??= colorScheme;
  965. }
  966. }
  967. }
  968. private static List<List<RuneCell>> SplitNewLines (List<RuneCell> cells)
  969. {
  970. List<List<RuneCell>> lines = new ();
  971. int start = 0, i = 0;
  972. var hasCR = false;
  973. // ASCII code 13 = Carriage Return.
  974. // ASCII code 10 = Line Feed.
  975. for (; i < cells.Count; i++)
  976. {
  977. if (cells [i].Rune.Value == 13)
  978. {
  979. hasCR = true;
  980. continue;
  981. }
  982. if (cells [i].Rune.Value == 10)
  983. {
  984. if (i - start > 0)
  985. {
  986. lines.Add (cells.GetRange (start, hasCR ? i - 1 - start : i - start));
  987. }
  988. else
  989. {
  990. lines.Add (StringToRuneCells (string.Empty));
  991. }
  992. start = i + 1;
  993. hasCR = false;
  994. }
  995. }
  996. if (i - start >= 0)
  997. {
  998. lines.Add (cells.GetRange (start, i - start));
  999. }
  1000. return lines;
  1001. }
  1002. private static List<List<RuneCell>> ToRuneCells (List<RuneCell> cells) { return SplitNewLines (cells); }
  1003. private enum RuneType
  1004. {
  1005. IsSymbol,
  1006. IsWhiteSpace,
  1007. IsLetterOrDigit,
  1008. IsPunctuation,
  1009. IsUnknown
  1010. }
  1011. }
  1012. internal partial class HistoryText
  1013. {
  1014. public enum LineStatus
  1015. {
  1016. Original,
  1017. Replaced,
  1018. Removed,
  1019. Added
  1020. }
  1021. private readonly List<HistoryTextItemEventArgs> _historyTextItems = new ();
  1022. private int _idxHistoryText = -1;
  1023. private string? _originalText;
  1024. public bool HasHistoryChanges => _idxHistoryText > -1;
  1025. public bool IsFromHistory { get; private set; }
  1026. public void Add (List<List<RuneCell>> lines, Point curPos, LineStatus lineStatus = LineStatus.Original)
  1027. {
  1028. if (lineStatus == LineStatus.Original && _historyTextItems.Count > 0 && _historyTextItems.Last ().LineStatus == LineStatus.Original)
  1029. {
  1030. return;
  1031. }
  1032. if (lineStatus == LineStatus.Replaced && _historyTextItems.Count > 0 && _historyTextItems.Last ().LineStatus == LineStatus.Replaced)
  1033. {
  1034. return;
  1035. }
  1036. if (_historyTextItems.Count == 0 && lineStatus != LineStatus.Original)
  1037. {
  1038. throw new ArgumentException ("The first item must be the original.");
  1039. }
  1040. if (_idxHistoryText >= 0 && _idxHistoryText + 1 < _historyTextItems.Count)
  1041. {
  1042. _historyTextItems.RemoveRange (
  1043. _idxHistoryText + 1,
  1044. _historyTextItems.Count - _idxHistoryText - 1
  1045. );
  1046. }
  1047. _historyTextItems.Add (new (lines, curPos, lineStatus));
  1048. _idxHistoryText++;
  1049. }
  1050. public event EventHandler<HistoryTextItemEventArgs>? ChangeText;
  1051. public void Clear (string text)
  1052. {
  1053. _historyTextItems.Clear ();
  1054. _idxHistoryText = -1;
  1055. _originalText = text;
  1056. OnChangeText (null);
  1057. }
  1058. public bool IsDirty (string text) { return _originalText != text; }
  1059. public void Redo ()
  1060. {
  1061. if (_historyTextItems?.Count > 0 && _idxHistoryText < _historyTextItems.Count - 1)
  1062. {
  1063. IsFromHistory = true;
  1064. _idxHistoryText++;
  1065. var historyTextItem = new HistoryTextItemEventArgs (_historyTextItems [_idxHistoryText]) { IsUndoing = false };
  1066. ProcessChanges (ref historyTextItem);
  1067. IsFromHistory = false;
  1068. }
  1069. }
  1070. public void ReplaceLast (List<List<RuneCell>> lines, Point curPos, LineStatus lineStatus)
  1071. {
  1072. HistoryTextItemEventArgs? found = _historyTextItems.FindLast (x => x.LineStatus == lineStatus);
  1073. if (found is { })
  1074. {
  1075. found.Lines = lines;
  1076. found.CursorPosition = curPos;
  1077. }
  1078. }
  1079. public void Undo ()
  1080. {
  1081. if (_historyTextItems?.Count > 0 && _idxHistoryText > 0)
  1082. {
  1083. IsFromHistory = true;
  1084. _idxHistoryText--;
  1085. var historyTextItem = new HistoryTextItemEventArgs (_historyTextItems [_idxHistoryText]) { IsUndoing = true };
  1086. ProcessChanges (ref historyTextItem);
  1087. IsFromHistory = false;
  1088. }
  1089. }
  1090. private void OnChangeText (HistoryTextItemEventArgs? lines) { ChangeText?.Invoke (this, lines!); }
  1091. private void ProcessChanges (ref HistoryTextItemEventArgs historyTextItem)
  1092. {
  1093. if (historyTextItem.IsUndoing)
  1094. {
  1095. if (_idxHistoryText - 1 > -1
  1096. && (_historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Added
  1097. || _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Removed
  1098. || (historyTextItem.LineStatus == LineStatus.Replaced && _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Original)))
  1099. {
  1100. _idxHistoryText--;
  1101. while (_historyTextItems [_idxHistoryText].LineStatus == LineStatus.Added
  1102. && _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Removed)
  1103. {
  1104. _idxHistoryText--;
  1105. }
  1106. historyTextItem = new (_historyTextItems [_idxHistoryText]);
  1107. historyTextItem.IsUndoing = true;
  1108. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  1109. }
  1110. if (historyTextItem.LineStatus == LineStatus.Removed && _historyTextItems [_idxHistoryText + 1].LineStatus == LineStatus.Added)
  1111. {
  1112. historyTextItem.RemovedOnAdded =
  1113. new (_historyTextItems [_idxHistoryText + 1]);
  1114. }
  1115. if ((historyTextItem.LineStatus == LineStatus.Added && _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Original)
  1116. || (historyTextItem.LineStatus == LineStatus.Removed && _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Original)
  1117. || (historyTextItem.LineStatus == LineStatus.Added && _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Removed))
  1118. {
  1119. if (!historyTextItem.Lines [0]
  1120. .SequenceEqual (_historyTextItems [_idxHistoryText - 1].Lines [0])
  1121. && historyTextItem.CursorPosition == _historyTextItems [_idxHistoryText - 1].CursorPosition)
  1122. {
  1123. historyTextItem.Lines [0] =
  1124. new (_historyTextItems [_idxHistoryText - 1].Lines [0]);
  1125. }
  1126. if (historyTextItem.LineStatus == LineStatus.Added && _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Removed)
  1127. {
  1128. historyTextItem.FinalCursorPosition =
  1129. _historyTextItems [_idxHistoryText - 2].CursorPosition;
  1130. }
  1131. else
  1132. {
  1133. historyTextItem.FinalCursorPosition =
  1134. _historyTextItems [_idxHistoryText - 1].CursorPosition;
  1135. }
  1136. }
  1137. else
  1138. {
  1139. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  1140. }
  1141. OnChangeText (historyTextItem);
  1142. while (_historyTextItems [_idxHistoryText].LineStatus == LineStatus.Removed
  1143. || _historyTextItems [_idxHistoryText].LineStatus == LineStatus.Added)
  1144. {
  1145. _idxHistoryText--;
  1146. }
  1147. }
  1148. else if (!historyTextItem.IsUndoing)
  1149. {
  1150. if (_idxHistoryText + 1 < _historyTextItems.Count
  1151. && (historyTextItem.LineStatus == LineStatus.Original
  1152. || _historyTextItems [_idxHistoryText + 1].LineStatus == LineStatus.Added
  1153. || _historyTextItems [_idxHistoryText + 1].LineStatus == LineStatus.Removed))
  1154. {
  1155. _idxHistoryText++;
  1156. historyTextItem = new (_historyTextItems [_idxHistoryText]);
  1157. historyTextItem.IsUndoing = false;
  1158. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  1159. }
  1160. if (historyTextItem.LineStatus == LineStatus.Added && _historyTextItems [_idxHistoryText - 1].LineStatus == LineStatus.Removed)
  1161. {
  1162. historyTextItem.RemovedOnAdded =
  1163. new (_historyTextItems [_idxHistoryText - 1]);
  1164. }
  1165. if ((historyTextItem.LineStatus == LineStatus.Removed && _historyTextItems [_idxHistoryText + 1].LineStatus == LineStatus.Replaced)
  1166. || (historyTextItem.LineStatus == LineStatus.Removed && _historyTextItems [_idxHistoryText + 1].LineStatus == LineStatus.Original)
  1167. || (historyTextItem.LineStatus == LineStatus.Added && _historyTextItems [_idxHistoryText + 1].LineStatus == LineStatus.Replaced))
  1168. {
  1169. if (historyTextItem.LineStatus == LineStatus.Removed
  1170. && !historyTextItem.Lines [0]
  1171. .SequenceEqual (_historyTextItems [_idxHistoryText + 1].Lines [0]))
  1172. {
  1173. historyTextItem.Lines [0] =
  1174. new (_historyTextItems [_idxHistoryText + 1].Lines [0]);
  1175. }
  1176. historyTextItem.FinalCursorPosition =
  1177. _historyTextItems [_idxHistoryText + 1].CursorPosition;
  1178. }
  1179. else
  1180. {
  1181. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  1182. }
  1183. OnChangeText (historyTextItem);
  1184. while (_historyTextItems [_idxHistoryText].LineStatus == LineStatus.Removed
  1185. || _historyTextItems [_idxHistoryText].LineStatus == LineStatus.Added)
  1186. {
  1187. _idxHistoryText++;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. internal class WordWrapManager
  1193. {
  1194. private int _frameWidth;
  1195. private bool _isWrapModelRefreshing;
  1196. private List<WrappedLine> _wrappedModelLines = new ();
  1197. public WordWrapManager (TextModel model) { Model = model; }
  1198. public TextModel Model { get; private set; }
  1199. public void AddLine (int row, int col)
  1200. {
  1201. int modelRow = GetModelLineFromWrappedLines (row);
  1202. int modelCol = GetModelColFromWrappedLines (row, col);
  1203. List<RuneCell> line = GetCurrentLine (modelRow);
  1204. int restCount = line.Count - modelCol;
  1205. List<RuneCell> rest = line.GetRange (modelCol, restCount);
  1206. line.RemoveRange (modelCol, restCount);
  1207. Model.AddLine (modelRow + 1, rest);
  1208. _isWrapModelRefreshing = true;
  1209. WrapModel (_frameWidth, out _, out _, out _, out _, modelRow + 1);
  1210. _isWrapModelRefreshing = false;
  1211. }
  1212. public int GetModelColFromWrappedLines (int line, int col)
  1213. {
  1214. if (_wrappedModelLines?.Count == 0)
  1215. {
  1216. return 0;
  1217. }
  1218. int modelLine = GetModelLineFromWrappedLines (line);
  1219. int firstLine = _wrappedModelLines.IndexOf (r => r.ModelLine == modelLine);
  1220. var modelCol = 0;
  1221. for (int i = firstLine; i <= Math.Min (line, _wrappedModelLines!.Count - 1); i++)
  1222. {
  1223. WrappedLine wLine = _wrappedModelLines [i];
  1224. if (i < line)
  1225. {
  1226. modelCol += wLine.ColWidth;
  1227. }
  1228. else
  1229. {
  1230. modelCol += col;
  1231. }
  1232. }
  1233. return modelCol;
  1234. }
  1235. public int GetModelLineFromWrappedLines (int line)
  1236. {
  1237. return _wrappedModelLines.Count > 0
  1238. ? _wrappedModelLines [Math.Min (
  1239. line,
  1240. _wrappedModelLines.Count - 1
  1241. )].ModelLine
  1242. : 0;
  1243. }
  1244. public int GetWrappedLineColWidth (int line, int col, WordWrapManager wrapManager)
  1245. {
  1246. if (_wrappedModelLines?.Count == 0)
  1247. {
  1248. return 0;
  1249. }
  1250. List<WrappedLine> wModelLines = wrapManager._wrappedModelLines;
  1251. int modelLine = GetModelLineFromWrappedLines (line);
  1252. int firstLine = _wrappedModelLines.IndexOf (r => r.ModelLine == modelLine);
  1253. var modelCol = 0;
  1254. var colWidthOffset = 0;
  1255. int i = firstLine;
  1256. while (modelCol < col)
  1257. {
  1258. WrappedLine wLine = _wrappedModelLines! [i];
  1259. WrappedLine wLineToCompare = wModelLines [i];
  1260. if (wLine.ModelLine != modelLine || wLineToCompare.ModelLine != modelLine)
  1261. {
  1262. break;
  1263. }
  1264. modelCol += Math.Max (wLine.ColWidth, wLineToCompare.ColWidth);
  1265. colWidthOffset += wLine.ColWidth - wLineToCompare.ColWidth;
  1266. if (modelCol > col)
  1267. {
  1268. modelCol += col - modelCol;
  1269. }
  1270. i++;
  1271. }
  1272. return modelCol - colWidthOffset;
  1273. }
  1274. public bool Insert (int row, int col, RuneCell cell)
  1275. {
  1276. List<RuneCell> line = GetCurrentLine (GetModelLineFromWrappedLines (row));
  1277. line.Insert (GetModelColFromWrappedLines (row, col), cell);
  1278. if (line.Count > _frameWidth)
  1279. {
  1280. return true;
  1281. }
  1282. return false;
  1283. }
  1284. public bool RemoveAt (int row, int col)
  1285. {
  1286. int modelRow = GetModelLineFromWrappedLines (row);
  1287. List<RuneCell> line = GetCurrentLine (modelRow);
  1288. int modelCol = GetModelColFromWrappedLines (row, col);
  1289. if (modelCol > line.Count)
  1290. {
  1291. Model.RemoveLine (modelRow);
  1292. RemoveAt (row, 0);
  1293. return false;
  1294. }
  1295. if (modelCol < line.Count)
  1296. {
  1297. line.RemoveAt (modelCol);
  1298. }
  1299. if (line.Count > _frameWidth || (row + 1 < _wrappedModelLines.Count && _wrappedModelLines [row + 1].ModelLine == modelRow))
  1300. {
  1301. return true;
  1302. }
  1303. return false;
  1304. }
  1305. public bool RemoveLine (int row, int col, out bool lineRemoved, bool forward = true)
  1306. {
  1307. lineRemoved = false;
  1308. int modelRow = GetModelLineFromWrappedLines (row);
  1309. List<RuneCell> line = GetCurrentLine (modelRow);
  1310. int modelCol = GetModelColFromWrappedLines (row, col);
  1311. if (modelCol == 0 && line.Count == 0)
  1312. {
  1313. Model.RemoveLine (modelRow);
  1314. return false;
  1315. }
  1316. if (modelCol < line.Count)
  1317. {
  1318. if (forward)
  1319. {
  1320. line.RemoveAt (modelCol);
  1321. return true;
  1322. }
  1323. if (modelCol - 1 > -1)
  1324. {
  1325. line.RemoveAt (modelCol - 1);
  1326. return true;
  1327. }
  1328. }
  1329. lineRemoved = true;
  1330. if (forward)
  1331. {
  1332. if (modelRow + 1 == Model.Count)
  1333. {
  1334. return false;
  1335. }
  1336. List<RuneCell> nextLine = Model.GetLine (modelRow + 1);
  1337. line.AddRange (nextLine);
  1338. Model.RemoveLine (modelRow + 1);
  1339. if (line.Count > _frameWidth)
  1340. {
  1341. return true;
  1342. }
  1343. }
  1344. else
  1345. {
  1346. if (modelRow == 0)
  1347. {
  1348. return false;
  1349. }
  1350. List<RuneCell> prevLine = Model.GetLine (modelRow - 1);
  1351. prevLine.AddRange (line);
  1352. Model.RemoveLine (modelRow);
  1353. if (prevLine.Count > _frameWidth)
  1354. {
  1355. return true;
  1356. }
  1357. }
  1358. return false;
  1359. }
  1360. public bool RemoveRange (int row, int index, int count)
  1361. {
  1362. int modelRow = GetModelLineFromWrappedLines (row);
  1363. List<RuneCell> line = GetCurrentLine (modelRow);
  1364. int modelCol = GetModelColFromWrappedLines (row, index);
  1365. try
  1366. {
  1367. line.RemoveRange (modelCol, count);
  1368. }
  1369. catch (Exception)
  1370. {
  1371. return false;
  1372. }
  1373. return true;
  1374. }
  1375. public List<List<RuneCell>> ToListRune (List<string> textList)
  1376. {
  1377. List<List<RuneCell>> runesList = new ();
  1378. foreach (string text in textList)
  1379. {
  1380. runesList.Add (TextModel.ToRuneCellList (text));
  1381. }
  1382. return runesList;
  1383. }
  1384. public void UpdateModel (
  1385. TextModel model,
  1386. out int nRow,
  1387. out int nCol,
  1388. out int nStartRow,
  1389. out int nStartCol,
  1390. int row,
  1391. int col,
  1392. int startRow,
  1393. int startCol,
  1394. bool preserveTrailingSpaces
  1395. )
  1396. {
  1397. _isWrapModelRefreshing = true;
  1398. Model = model;
  1399. WrapModel (
  1400. _frameWidth,
  1401. out nRow,
  1402. out nCol,
  1403. out nStartRow,
  1404. out nStartCol,
  1405. row,
  1406. col,
  1407. startRow,
  1408. startCol,
  1409. 0,
  1410. preserveTrailingSpaces
  1411. );
  1412. _isWrapModelRefreshing = false;
  1413. }
  1414. public TextModel WrapModel (
  1415. int width,
  1416. out int nRow,
  1417. out int nCol,
  1418. out int nStartRow,
  1419. out int nStartCol,
  1420. int row = 0,
  1421. int col = 0,
  1422. int startRow = 0,
  1423. int startCol = 0,
  1424. int tabWidth = 0,
  1425. bool preserveTrailingSpaces = true
  1426. )
  1427. {
  1428. _frameWidth = width;
  1429. int modelRow = _isWrapModelRefreshing ? row : GetModelLineFromWrappedLines (row);
  1430. int modelCol = _isWrapModelRefreshing ? col : GetModelColFromWrappedLines (row, col);
  1431. int modelStartRow = _isWrapModelRefreshing ? startRow : GetModelLineFromWrappedLines (startRow);
  1432. int modelStartCol =
  1433. _isWrapModelRefreshing ? startCol : GetModelColFromWrappedLines (startRow, startCol);
  1434. var wrappedModel = new TextModel ();
  1435. var lines = 0;
  1436. nRow = 0;
  1437. nCol = 0;
  1438. nStartRow = 0;
  1439. nStartCol = 0;
  1440. bool isRowAndColSet = row == 0 && col == 0;
  1441. bool isStartRowAndColSet = startRow == 0 && startCol == 0;
  1442. List<WrappedLine> wModelLines = new ();
  1443. for (var i = 0; i < Model.Count; i++)
  1444. {
  1445. List<RuneCell> line = Model.GetLine (i);
  1446. List<List<RuneCell>> wrappedLines = ToListRune (
  1447. TextFormatter.Format (
  1448. TextModel.ToString (line),
  1449. width,
  1450. Alignment.Start,
  1451. true,
  1452. preserveTrailingSpaces,
  1453. tabWidth
  1454. )
  1455. );
  1456. var sumColWidth = 0;
  1457. for (var j = 0; j < wrappedLines.Count; j++)
  1458. {
  1459. List<RuneCell> wrapLine = wrappedLines [j];
  1460. if (!isRowAndColSet && modelRow == i)
  1461. {
  1462. if (nCol + wrapLine.Count <= modelCol)
  1463. {
  1464. nCol += wrapLine.Count;
  1465. nRow = lines;
  1466. if (nCol == modelCol)
  1467. {
  1468. nCol = wrapLine.Count;
  1469. isRowAndColSet = true;
  1470. }
  1471. else if (j == wrappedLines.Count - 1)
  1472. {
  1473. nCol = wrapLine.Count - j + modelCol - nCol;
  1474. isRowAndColSet = true;
  1475. }
  1476. }
  1477. else
  1478. {
  1479. int offset = nCol + wrapLine.Count - modelCol;
  1480. nCol = wrapLine.Count - offset;
  1481. nRow = lines;
  1482. isRowAndColSet = true;
  1483. }
  1484. }
  1485. if (!isStartRowAndColSet && modelStartRow == i)
  1486. {
  1487. if (nStartCol + wrapLine.Count <= modelStartCol)
  1488. {
  1489. nStartCol += wrapLine.Count;
  1490. nStartRow = lines;
  1491. if (nStartCol == modelStartCol)
  1492. {
  1493. nStartCol = wrapLine.Count;
  1494. isStartRowAndColSet = true;
  1495. }
  1496. else if (j == wrappedLines.Count - 1)
  1497. {
  1498. nStartCol = wrapLine.Count - j + modelStartCol - nStartCol;
  1499. isStartRowAndColSet = true;
  1500. }
  1501. }
  1502. else
  1503. {
  1504. int offset = nStartCol + wrapLine.Count - modelStartCol;
  1505. nStartCol = wrapLine.Count - offset;
  1506. nStartRow = lines;
  1507. isStartRowAndColSet = true;
  1508. }
  1509. }
  1510. for (int k = j; k < wrapLine.Count; k++)
  1511. {
  1512. wrapLine [k].ColorScheme = line [k].ColorScheme;
  1513. }
  1514. wrappedModel.AddLine (lines, wrapLine);
  1515. sumColWidth += wrapLine.Count;
  1516. var wrappedLine = new WrappedLine
  1517. {
  1518. ModelLine = i, Row = lines, RowIndex = j, ColWidth = wrapLine.Count
  1519. };
  1520. wModelLines.Add (wrappedLine);
  1521. lines++;
  1522. }
  1523. }
  1524. _wrappedModelLines = wModelLines;
  1525. return wrappedModel;
  1526. }
  1527. private List<RuneCell> GetCurrentLine (int row) { return Model.GetLine (row); }
  1528. private class WrappedLine
  1529. {
  1530. public int ColWidth;
  1531. public int ModelLine;
  1532. public int Row;
  1533. public int RowIndex;
  1534. }
  1535. }
  1536. /// <summary>Multi-line text editing <see cref="View"/>.</summary>
  1537. /// <remarks>
  1538. /// <para>
  1539. /// <see cref="TextView"/> provides a multi-line text editor. Users interact with it with the standard Windows,
  1540. /// Mac, and Linux (Emacs) commands.
  1541. /// </para>
  1542. /// <list type="table">
  1543. /// <listheader>
  1544. /// <term>Shortcut</term> <description>Action performed</description>
  1545. /// </listheader>
  1546. /// <item>
  1547. /// <term>Left cursor, Control-b</term> <description>Moves the editing point left.</description>
  1548. /// </item>
  1549. /// <item>
  1550. /// <term>Right cursor, Control-f</term> <description>Moves the editing point right.</description>
  1551. /// </item>
  1552. /// <item>
  1553. /// <term>Alt-b</term> <description>Moves one word back.</description>
  1554. /// </item>
  1555. /// <item>
  1556. /// <term>Alt-f</term> <description>Moves one word forward.</description>
  1557. /// </item>
  1558. /// <item>
  1559. /// <term>Up cursor, Control-p</term> <description>Moves the editing point one line up.</description>
  1560. /// </item>
  1561. /// <item>
  1562. /// <term>Down cursor, Control-n</term> <description>Moves the editing point one line down</description>
  1563. /// </item>
  1564. /// <item>
  1565. /// <term>Home key, Control-a</term> <description>Moves the cursor to the beginning of the line.</description>
  1566. /// </item>
  1567. /// <item>
  1568. /// <term>End key, Control-e</term> <description>Moves the cursor to the end of the line.</description>
  1569. /// </item>
  1570. /// <item>
  1571. /// <term>Control-Home</term> <description>Scrolls to the first line and moves the cursor there.</description>
  1572. /// </item>
  1573. /// <item>
  1574. /// <term>Control-End</term> <description>Scrolls to the last line and moves the cursor there.</description>
  1575. /// </item>
  1576. /// <item>
  1577. /// <term>Delete, Control-d</term> <description>Deletes the character in front of the cursor.</description>
  1578. /// </item>
  1579. /// <item>
  1580. /// <term>Backspace</term> <description>Deletes the character behind the cursor.</description>
  1581. /// </item>
  1582. /// <item>
  1583. /// <term>Control-k</term>
  1584. /// <description>
  1585. /// Deletes the text until the end of the line and replaces the kill buffer with the deleted text.
  1586. /// You can paste this text in a different place by using Control-y.
  1587. /// </description>
  1588. /// </item>
  1589. /// <item>
  1590. /// <term>Control-y</term>
  1591. /// <description>Pastes the content of the kill ring into the current position.</description>
  1592. /// </item>
  1593. /// <item>
  1594. /// <term>Alt-d</term>
  1595. /// <description>
  1596. /// Deletes the word above the cursor and adds it to the kill ring. You can paste the contents of
  1597. /// the kill ring with Control-y.
  1598. /// </description>
  1599. /// </item>
  1600. /// <item>
  1601. /// <term>Control-q</term>
  1602. /// <description>
  1603. /// Quotes the next input character, to prevent the normal processing of key handling to take
  1604. /// place.
  1605. /// </description>
  1606. /// </item>
  1607. /// </list>
  1608. /// </remarks>
  1609. public class TextView : View
  1610. {
  1611. private readonly HistoryText _historyText = new ();
  1612. private bool _allowsReturn = true;
  1613. private bool _allowsTab = true;
  1614. private bool _clickWithSelecting;
  1615. // The column we are tracking, or -1 if we are not tracking any column
  1616. private int _columnTrack = -1;
  1617. private bool _continuousFind;
  1618. private bool _copyWithoutSelection;
  1619. private string? _currentCaller;
  1620. private CultureInfo? _currentCulture;
  1621. private bool _isButtonShift;
  1622. private bool _isButtonReleased;
  1623. private bool _isDrawing;
  1624. private bool _isReadOnly;
  1625. private bool _lastWasKill;
  1626. private int _leftColumn;
  1627. private TextModel _model = new ();
  1628. private bool _multiline = true;
  1629. private Dim? _savedHeight;
  1630. private int _selectionStartColumn, _selectionStartRow;
  1631. private bool _shiftSelecting;
  1632. private int _tabWidth = 4;
  1633. private int _topRow;
  1634. private bool _wordWrap;
  1635. private WordWrapManager? _wrapManager;
  1636. private bool _wrapNeeded;
  1637. /// <summary>
  1638. /// Initializes a <see cref="TextView"/> on the specified area, with dimensions controlled with the X, Y, Width
  1639. /// and Height properties.
  1640. /// </summary>
  1641. public TextView ()
  1642. {
  1643. CanFocus = true;
  1644. CursorVisibility = CursorVisibility.Default;
  1645. Used = true;
  1646. // By default, disable hotkeys (in case someome sets Title)
  1647. HotKeySpecifier = new ('\xffff');
  1648. _model.LinesLoaded += Model_LinesLoaded!;
  1649. _historyText.ChangeText += HistoryText_ChangeText!;
  1650. Initialized += TextView_Initialized!;
  1651. Added += TextView_Added!;
  1652. LayoutComplete += TextView_LayoutComplete;
  1653. // Things this view knows how to do
  1654. // Note - NewLine is only bound to Enter if Multiline is true
  1655. AddCommand (Command.NewLine, (ctx) => ProcessEnterKey (ctx));
  1656. AddCommand (
  1657. Command.PageDown,
  1658. () =>
  1659. {
  1660. ProcessPageDown ();
  1661. return true;
  1662. }
  1663. );
  1664. AddCommand (
  1665. Command.PageDownExtend,
  1666. () =>
  1667. {
  1668. ProcessPageDownExtend ();
  1669. return true;
  1670. }
  1671. );
  1672. AddCommand (
  1673. Command.PageUp,
  1674. () =>
  1675. {
  1676. ProcessPageUp ();
  1677. return true;
  1678. }
  1679. );
  1680. AddCommand (
  1681. Command.PageUpExtend,
  1682. () =>
  1683. {
  1684. ProcessPageUpExtend ();
  1685. return true;
  1686. }
  1687. );
  1688. AddCommand (Command.Down, () => ProcessMoveDown ());
  1689. AddCommand (
  1690. Command.DownExtend,
  1691. () =>
  1692. {
  1693. ProcessMoveDownExtend ();
  1694. return true;
  1695. }
  1696. );
  1697. AddCommand (Command.Up, () => ProcessMoveUp ());
  1698. AddCommand (
  1699. Command.UpExtend,
  1700. () =>
  1701. {
  1702. ProcessMoveUpExtend ();
  1703. return true;
  1704. }
  1705. );
  1706. AddCommand (Command.Right, () => ProcessMoveRight ());
  1707. AddCommand (
  1708. Command.RightExtend,
  1709. () =>
  1710. {
  1711. ProcessMoveRightExtend ();
  1712. return true;
  1713. }
  1714. );
  1715. AddCommand (Command.Left, () => ProcessMoveLeft ());
  1716. AddCommand (
  1717. Command.LeftExtend,
  1718. () =>
  1719. {
  1720. ProcessMoveLeftExtend ();
  1721. return true;
  1722. }
  1723. );
  1724. AddCommand (
  1725. Command.DeleteCharLeft,
  1726. () =>
  1727. {
  1728. ProcessDeleteCharLeft ();
  1729. return true;
  1730. }
  1731. );
  1732. AddCommand (
  1733. Command.LeftStart,
  1734. () =>
  1735. {
  1736. ProcessMoveLeftStart ();
  1737. return true;
  1738. }
  1739. );
  1740. AddCommand (
  1741. Command.LeftStartExtend,
  1742. () =>
  1743. {
  1744. ProcessMoveLeftStartExtend ();
  1745. return true;
  1746. }
  1747. );
  1748. AddCommand (
  1749. Command.DeleteCharRight,
  1750. () =>
  1751. {
  1752. ProcessDeleteCharRight ();
  1753. return true;
  1754. }
  1755. );
  1756. AddCommand (
  1757. Command.RightEnd,
  1758. () =>
  1759. {
  1760. ProcessMoveEndOfLine ();
  1761. return true;
  1762. }
  1763. );
  1764. AddCommand (
  1765. Command.RightEndExtend,
  1766. () =>
  1767. {
  1768. ProcessMoveRightEndExtend ();
  1769. return true;
  1770. }
  1771. );
  1772. AddCommand (
  1773. Command.CutToEndLine,
  1774. () =>
  1775. {
  1776. KillToEndOfLine ();
  1777. return true;
  1778. }
  1779. );
  1780. AddCommand (
  1781. Command.CutToStartLine,
  1782. () =>
  1783. {
  1784. KillToLeftStart ();
  1785. return true;
  1786. }
  1787. );
  1788. AddCommand (
  1789. Command.Paste,
  1790. () =>
  1791. {
  1792. ProcessPaste ();
  1793. return true;
  1794. }
  1795. );
  1796. AddCommand (
  1797. Command.ToggleExtend,
  1798. () =>
  1799. {
  1800. ToggleSelecting ();
  1801. return true;
  1802. }
  1803. );
  1804. AddCommand (
  1805. Command.Copy,
  1806. () =>
  1807. {
  1808. ProcessCopy ();
  1809. return true;
  1810. }
  1811. );
  1812. AddCommand (
  1813. Command.Cut,
  1814. () =>
  1815. {
  1816. ProcessCut ();
  1817. return true;
  1818. }
  1819. );
  1820. AddCommand (
  1821. Command.WordLeft,
  1822. () =>
  1823. {
  1824. ProcessMoveWordBackward ();
  1825. return true;
  1826. }
  1827. );
  1828. AddCommand (
  1829. Command.WordLeftExtend,
  1830. () =>
  1831. {
  1832. ProcessMoveWordBackwardExtend ();
  1833. return true;
  1834. }
  1835. );
  1836. AddCommand (
  1837. Command.WordRight,
  1838. () =>
  1839. {
  1840. ProcessMoveWordForward ();
  1841. return true;
  1842. }
  1843. );
  1844. AddCommand (
  1845. Command.WordRightExtend,
  1846. () =>
  1847. {
  1848. ProcessMoveWordForwardExtend ();
  1849. return true;
  1850. }
  1851. );
  1852. AddCommand (
  1853. Command.KillWordForwards,
  1854. () =>
  1855. {
  1856. ProcessKillWordForward ();
  1857. return true;
  1858. }
  1859. );
  1860. AddCommand (
  1861. Command.KillWordBackwards,
  1862. () =>
  1863. {
  1864. ProcessKillWordBackward ();
  1865. return true;
  1866. }
  1867. );
  1868. AddCommand (
  1869. Command.End,
  1870. () =>
  1871. {
  1872. MoveBottomEnd ();
  1873. return true;
  1874. }
  1875. );
  1876. AddCommand (
  1877. Command.EndExtend,
  1878. () =>
  1879. {
  1880. MoveBottomEndExtend ();
  1881. return true;
  1882. }
  1883. );
  1884. AddCommand (
  1885. Command.Start,
  1886. () =>
  1887. {
  1888. MoveTopHome ();
  1889. return true;
  1890. }
  1891. );
  1892. AddCommand (
  1893. Command.StartExtend,
  1894. () =>
  1895. {
  1896. MoveTopHomeExtend ();
  1897. return true;
  1898. }
  1899. );
  1900. AddCommand (
  1901. Command.SelectAll,
  1902. () =>
  1903. {
  1904. ProcessSelectAll ();
  1905. return true;
  1906. }
  1907. );
  1908. AddCommand (
  1909. Command.ToggleOverwrite,
  1910. () =>
  1911. {
  1912. ProcessSetOverwrite ();
  1913. return true;
  1914. }
  1915. );
  1916. AddCommand (
  1917. Command.EnableOverwrite,
  1918. () =>
  1919. {
  1920. SetOverwrite (true);
  1921. return true;
  1922. }
  1923. );
  1924. AddCommand (
  1925. Command.DisableOverwrite,
  1926. () =>
  1927. {
  1928. SetOverwrite (false);
  1929. return true;
  1930. }
  1931. );
  1932. AddCommand (Command.Tab, () => ProcessTab ());
  1933. AddCommand (Command.BackTab, () => ProcessBackTab ());
  1934. AddCommand (
  1935. Command.Undo,
  1936. () =>
  1937. {
  1938. Undo ();
  1939. return true;
  1940. }
  1941. );
  1942. AddCommand (
  1943. Command.Redo,
  1944. () =>
  1945. {
  1946. Redo ();
  1947. return true;
  1948. }
  1949. );
  1950. AddCommand (
  1951. Command.DeleteAll,
  1952. () =>
  1953. {
  1954. DeleteAll ();
  1955. return true;
  1956. }
  1957. );
  1958. AddCommand (
  1959. Command.Context,
  1960. () =>
  1961. {
  1962. ContextMenu!.Position = new (
  1963. CursorPosition.X - _leftColumn + 2,
  1964. CursorPosition.Y - _topRow + 2
  1965. );
  1966. ShowContextMenu ();
  1967. return true;
  1968. }
  1969. );
  1970. KeyBindings.Remove (Key.Space);
  1971. KeyBindings.Remove (Key.Enter);
  1972. KeyBindings.Add (Key.Enter, Multiline ? Command.NewLine : Command.Accept);
  1973. KeyBindings.Add (Key.PageDown, Command.PageDown);
  1974. KeyBindings.Add (Key.V.WithCtrl, Command.PageDown);
  1975. KeyBindings.Add (Key.PageDown.WithShift, Command.PageDownExtend);
  1976. KeyBindings.Add (Key.PageUp, Command.PageUp);
  1977. KeyBindings.Add (Key.PageUp.WithShift, Command.PageUpExtend);
  1978. KeyBindings.Add (Key.N.WithCtrl, Command.Down);
  1979. KeyBindings.Add (Key.CursorDown, Command.Down);
  1980. KeyBindings.Add (Key.CursorDown.WithShift, Command.DownExtend);
  1981. KeyBindings.Add (Key.P.WithCtrl, Command.Up);
  1982. KeyBindings.Add (Key.CursorUp, Command.Up);
  1983. KeyBindings.Add (Key.CursorUp.WithShift, Command.UpExtend);
  1984. KeyBindings.Add (Key.F.WithCtrl, Command.Right);
  1985. KeyBindings.Add (Key.CursorRight, Command.Right);
  1986. KeyBindings.Add (Key.CursorRight.WithShift, Command.RightExtend);
  1987. KeyBindings.Add (Key.B.WithCtrl, Command.Left);
  1988. KeyBindings.Add (Key.CursorLeft, Command.Left);
  1989. KeyBindings.Add (Key.CursorLeft.WithShift, Command.LeftExtend);
  1990. KeyBindings.Add (Key.Backspace, Command.DeleteCharLeft);
  1991. KeyBindings.Add (Key.Home, Command.LeftStart);
  1992. KeyBindings.Add (Key.A.WithCtrl, Command.LeftStart);
  1993. KeyBindings.Add (Key.Home.WithShift, Command.LeftStartExtend);
  1994. KeyBindings.Add (Key.Delete, Command.DeleteCharRight);
  1995. KeyBindings.Add (Key.D.WithCtrl, Command.DeleteCharRight);
  1996. KeyBindings.Add (Key.End, Command.RightEnd);
  1997. KeyBindings.Add (Key.E.WithCtrl, Command.RightEnd);
  1998. KeyBindings.Add (Key.End.WithShift, Command.RightEndExtend);
  1999. KeyBindings.Add (Key.K.WithCtrl, Command.CutToEndLine); // kill-to-end
  2000. KeyBindings.Add (Key.Delete.WithCtrl.WithShift, Command.CutToEndLine); // kill-to-end
  2001. KeyBindings.Add (Key.Backspace.WithCtrl.WithShift, Command.CutToStartLine); // kill-to-start
  2002. KeyBindings.Add (Key.Y.WithCtrl, Command.Paste); // Control-y, yank
  2003. KeyBindings.Add (Key.Space.WithCtrl, Command.ToggleExtend);
  2004. KeyBindings.Add (Key.C.WithCtrl, Command.Copy);
  2005. KeyBindings.Add (Key.W.WithCtrl, Command.Cut); // Move to Unix?
  2006. KeyBindings.Add (Key.X.WithCtrl, Command.Cut);
  2007. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.WordLeft);
  2008. KeyBindings.Add (Key.CursorLeft.WithCtrl.WithShift, Command.WordLeftExtend);
  2009. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.WordRight);
  2010. KeyBindings.Add (Key.CursorRight.WithCtrl.WithShift, Command.WordRightExtend);
  2011. KeyBindings.Add (Key.Delete.WithCtrl, Command.KillWordForwards); // kill-word-forwards
  2012. KeyBindings.Add (Key.Backspace.WithCtrl, Command.KillWordBackwards); // kill-word-backwards
  2013. KeyBindings.Add (Key.End.WithCtrl, Command.End);
  2014. KeyBindings.Add (Key.End.WithCtrl.WithShift, Command.EndExtend);
  2015. KeyBindings.Add (Key.Home.WithCtrl, Command.Start);
  2016. KeyBindings.Add (Key.Home.WithCtrl.WithShift, Command.StartExtend);
  2017. KeyBindings.Add (Key.T.WithCtrl, Command.SelectAll);
  2018. KeyBindings.Add (Key.InsertChar, Command.ToggleOverwrite);
  2019. KeyBindings.Add (Key.Tab, Command.Tab);
  2020. KeyBindings.Add (Key.Tab.WithShift, Command.BackTab);
  2021. KeyBindings.Add (Key.Z.WithCtrl, Command.Undo);
  2022. KeyBindings.Add (Key.R.WithCtrl, Command.Redo);
  2023. KeyBindings.Add (Key.G.WithCtrl, Command.DeleteAll);
  2024. KeyBindings.Add (Key.D.WithCtrl.WithShift, Command.DeleteAll);
  2025. #if UNIX_KEY_BINDINGS
  2026. KeyBindings.Add (Key.C.WithAlt, Command.Copy);
  2027. KeyBindings.Add (Key.B.WithAlt, Command.WordLeft);
  2028. KeyBindings.Add (Key.W.WithAlt, Command.Cut);
  2029. KeyBindings.Add (Key.V.WithAlt, Command.PageUp);
  2030. KeyBindings.Add (Key.F.WithAlt, Command.WordRight);
  2031. KeyBindings.Add (Key.K.WithAlt, Command.CutToStartLine); // kill-to-start
  2032. #endif
  2033. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  2034. ContextMenu = new ();
  2035. ContextMenu.KeyChanged += ContextMenu_KeyChanged!;
  2036. KeyBindings.Add ((KeyCode)ContextMenu.Key, KeyBindingScope.HotKey, Command.Context);
  2037. }
  2038. private void TextView_Added1 (object? sender, SuperViewChangedEventArgs e)
  2039. {
  2040. throw new NotImplementedException ();
  2041. }
  2042. // BUGBUG: AllowsReturn is mis-named. It should be EnterKeyAccepts.
  2043. /// <summary>
  2044. /// Gets or sets whether pressing ENTER in a <see cref="TextView"/> creates a new line of text
  2045. /// in the view or invokes the <see cref="View.Accepting"/> event.
  2046. /// </summary>
  2047. /// <remarks>
  2048. /// <para>
  2049. /// Setting this property alters <see cref="Multiline"/>.
  2050. /// If <see cref="AllowsReturn"/> is set to <see langword="true"/>, then <see cref="Multiline"/> is also set to `true` and
  2051. /// vice-versa.
  2052. /// </para>
  2053. /// <para>
  2054. /// If <see cref="AllowsReturn"/> is set to <see langword="false"/>, then <see cref="AllowsTab"/> gets set to <see langword="false"/>.
  2055. /// </para>
  2056. /// </remarks>
  2057. public bool AllowsReturn
  2058. {
  2059. get => _allowsReturn;
  2060. set
  2061. {
  2062. _allowsReturn = value;
  2063. if (_allowsReturn && !_multiline)
  2064. {
  2065. // BUGBUG: Setting properties should not have side-effects like this. Multiline and AllowsReturn should be independent.
  2066. Multiline = true;
  2067. }
  2068. if (!_allowsReturn && _multiline)
  2069. {
  2070. Multiline = false;
  2071. // BUGBUG: Setting properties should not have side-effects like this. Multiline and AllowsTab should be independent.
  2072. AllowsTab = false;
  2073. }
  2074. SetNeedsDisplay ();
  2075. }
  2076. }
  2077. /// <summary>
  2078. /// Gets or sets whether the <see cref="TextView"/> inserts a tab character into the text or ignores tab input. If
  2079. /// set to `false` and the user presses the tab key (or shift-tab) the focus will move to the next view (or previous
  2080. /// with shift-tab). The default is `true`; if the user presses the tab key, a tab character will be inserted into the
  2081. /// text.
  2082. /// </summary>
  2083. public bool AllowsTab
  2084. {
  2085. get => _allowsTab;
  2086. set
  2087. {
  2088. _allowsTab = value;
  2089. if (_allowsTab && _tabWidth == 0)
  2090. {
  2091. _tabWidth = 4;
  2092. }
  2093. if (_allowsTab && !_multiline)
  2094. {
  2095. Multiline = true;
  2096. }
  2097. if (!_allowsTab && _tabWidth > 0)
  2098. {
  2099. _tabWidth = 0;
  2100. }
  2101. SetNeedsDisplay ();
  2102. }
  2103. }
  2104. /// <summary>
  2105. /// Provides autocomplete context menu based on suggestions at the current cursor position. Configure
  2106. /// <see cref="IAutocomplete.SuggestionGenerator"/> to enable this feature
  2107. /// </summary>
  2108. public IAutocomplete Autocomplete { get; protected set; } = new TextViewAutocomplete ();
  2109. /// <summary>Get the <see cref="ContextMenu"/> for this view.</summary>
  2110. public ContextMenu? ContextMenu { get; }
  2111. /// <summary>Gets the cursor column.</summary>
  2112. /// <value>The cursor column.</value>
  2113. public int CurrentColumn { get; private set; }
  2114. /// <summary>Gets the current cursor row.</summary>
  2115. public int CurrentRow { get; private set; }
  2116. /// <summary>Sets or gets the current cursor position.</summary>
  2117. public Point CursorPosition
  2118. {
  2119. get => new (CurrentColumn, CurrentRow);
  2120. set
  2121. {
  2122. List<RuneCell> line = _model.GetLine (Math.Max (Math.Min (value.Y, _model.Count - 1), 0));
  2123. CurrentColumn = value.X < 0 ? 0 :
  2124. value.X > line.Count ? line.Count : value.X;
  2125. CurrentRow = value.Y < 0 ? 0 :
  2126. value.Y > _model.Count - 1 ? Math.Max (_model.Count - 1, 0) : value.Y;
  2127. SetNeedsDisplay ();
  2128. Adjust ();
  2129. }
  2130. }
  2131. /// <summary>
  2132. /// Indicates whatever the text has history changes or not. <see langword="true"/> if the text has history changes
  2133. /// <see langword="false"/> otherwise.
  2134. /// </summary>
  2135. public bool HasHistoryChanges => _historyText.HasHistoryChanges;
  2136. /// <summary>
  2137. /// If <see langword="true"/> and the current <see cref="RuneCell.ColorScheme"/> is null will inherit from the
  2138. /// previous, otherwise if <see langword="false"/> (default) do nothing. If the text is load with
  2139. /// <see cref="Load(List{RuneCell})"/> this property is automatically sets to <see langword="true"/>.
  2140. /// </summary>
  2141. public bool InheritsPreviousColorScheme { get; set; }
  2142. /// <summary>
  2143. /// Indicates whatever the text was changed or not. <see langword="true"/> if the text was changed
  2144. /// <see langword="false"/> otherwise.
  2145. /// </summary>
  2146. public bool IsDirty
  2147. {
  2148. get => _historyText.IsDirty (Text);
  2149. set => _historyText.Clear (Text);
  2150. }
  2151. /// <summary>Gets or sets the left column.</summary>
  2152. public int LeftColumn
  2153. {
  2154. get => _leftColumn;
  2155. set
  2156. {
  2157. if (value > 0 && _wordWrap)
  2158. {
  2159. return;
  2160. }
  2161. _leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0);
  2162. }
  2163. }
  2164. /// <summary>Gets the number of lines.</summary>
  2165. public int Lines => _model.Count;
  2166. /// <summary>Gets the maximum visible length line.</summary>
  2167. public int Maxlength => _model.GetMaxVisibleLine (_topRow, _topRow + Viewport.Height, TabWidth);
  2168. /// <summary>Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.</summary>
  2169. public bool Multiline
  2170. {
  2171. get => _multiline;
  2172. set
  2173. {
  2174. _multiline = value;
  2175. if (_multiline && !_allowsTab)
  2176. {
  2177. AllowsTab = true;
  2178. }
  2179. if (_multiline && !_allowsReturn)
  2180. {
  2181. AllowsReturn = true;
  2182. }
  2183. if (!_multiline)
  2184. {
  2185. AllowsReturn = false;
  2186. AllowsTab = false;
  2187. WordWrap = false;
  2188. CurrentColumn = 0;
  2189. CurrentRow = 0;
  2190. _savedHeight = Height;
  2191. Height = Dim.Auto (DimAutoStyle.Text, minimumContentDim: 1);
  2192. if (!IsInitialized)
  2193. {
  2194. _model.LoadString (Text);
  2195. }
  2196. SetNeedsDisplay ();
  2197. }
  2198. else if (_multiline && _savedHeight is { })
  2199. {
  2200. Height = _savedHeight;
  2201. SetNeedsDisplay ();
  2202. }
  2203. KeyBindings.Remove (Key.Enter);
  2204. KeyBindings.Add (Key.Enter, Multiline ? Command.NewLine : Command.Accept);
  2205. }
  2206. }
  2207. /// <summary>Gets or sets whether the <see cref="TextView"/> is in read-only mode or not</summary>
  2208. /// <value>Boolean value(Default false)</value>
  2209. public bool ReadOnly
  2210. {
  2211. get => _isReadOnly;
  2212. set
  2213. {
  2214. if (value != _isReadOnly)
  2215. {
  2216. _isReadOnly = value;
  2217. SetNeedsDisplay ();
  2218. WrapTextModel ();
  2219. Adjust ();
  2220. }
  2221. }
  2222. }
  2223. /// <summary>Length of the selected text.</summary>
  2224. public int SelectedLength => GetSelectedLength ();
  2225. /// <summary>The selected text.</summary>
  2226. public string SelectedText
  2227. {
  2228. get
  2229. {
  2230. if (!IsSelecting || (_model.Count == 1 && _model.GetLine (0).Count == 0))
  2231. {
  2232. return string.Empty;
  2233. }
  2234. return GetSelectedRegion ();
  2235. }
  2236. }
  2237. /// <summary>Get or sets whether the user is currently selecting text.</summary>
  2238. public bool IsSelecting { get; set; }
  2239. /// <summary>Start column position of the selected text.</summary>
  2240. public int SelectionStartColumn
  2241. {
  2242. get => _selectionStartColumn;
  2243. set
  2244. {
  2245. List<RuneCell> line = _model.GetLine (_selectionStartRow);
  2246. _selectionStartColumn = value < 0 ? 0 :
  2247. value > line.Count ? line.Count : value;
  2248. IsSelecting = true;
  2249. SetNeedsDisplay ();
  2250. Adjust ();
  2251. }
  2252. }
  2253. /// <summary>Start row position of the selected text.</summary>
  2254. public int SelectionStartRow
  2255. {
  2256. get => _selectionStartRow;
  2257. set
  2258. {
  2259. _selectionStartRow = value < 0 ? 0 :
  2260. value > _model.Count - 1 ? Math.Max (_model.Count - 1, 0) : value;
  2261. IsSelecting = true;
  2262. SetNeedsDisplay ();
  2263. Adjust ();
  2264. }
  2265. }
  2266. /// <summary>Gets or sets a value indicating the number of whitespace when pressing the TAB key.</summary>
  2267. public int TabWidth
  2268. {
  2269. get => _tabWidth;
  2270. set
  2271. {
  2272. _tabWidth = Math.Max (value, 0);
  2273. if (_tabWidth > 0 && !AllowsTab)
  2274. {
  2275. AllowsTab = true;
  2276. }
  2277. SetNeedsDisplay ();
  2278. }
  2279. }
  2280. /// <summary>Sets or gets the text in the <see cref="TextView"/>.</summary>
  2281. /// <remarks>
  2282. /// The <see cref="View.TextChanged"/> event is fired whenever this property is set. Note, however, that Text is not
  2283. /// set by <see cref="TextView"/> as the user types.
  2284. /// </remarks>
  2285. public override string Text
  2286. {
  2287. get
  2288. {
  2289. if (_wordWrap)
  2290. {
  2291. return _wrapManager!.Model.ToString ();
  2292. }
  2293. return _model.ToString ();
  2294. }
  2295. set
  2296. {
  2297. ResetPosition ();
  2298. _model.LoadString (value);
  2299. if (_wordWrap)
  2300. {
  2301. _wrapManager = new (_model);
  2302. _model = _wrapManager.WrapModel (Viewport.Width, out _, out _, out _, out _);
  2303. }
  2304. OnTextChanged ();
  2305. SetNeedsDisplay ();
  2306. _historyText.Clear (Text);
  2307. }
  2308. }
  2309. /// <summary>Gets or sets the top row.</summary>
  2310. public int TopRow
  2311. {
  2312. get => _topRow;
  2313. set => _topRow = Math.Max (Math.Min (value, Lines - 1), 0);
  2314. }
  2315. /// <summary>
  2316. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry, so
  2317. /// new input should be appended at the cursor position, rather than clearing the entry
  2318. /// </summary>
  2319. public bool Used { get; set; }
  2320. /// <summary>Allows word wrap the to fit the available container width.</summary>
  2321. public bool WordWrap
  2322. {
  2323. get => _wordWrap;
  2324. set
  2325. {
  2326. if (value == _wordWrap)
  2327. {
  2328. return;
  2329. }
  2330. if (value && !_multiline)
  2331. {
  2332. return;
  2333. }
  2334. _wordWrap = value;
  2335. ResetPosition ();
  2336. if (_wordWrap)
  2337. {
  2338. _wrapManager = new (_model);
  2339. WrapTextModel ();
  2340. }
  2341. else if (!_wordWrap && _wrapManager is { })
  2342. {
  2343. _model = _wrapManager.Model;
  2344. }
  2345. SetNeedsDisplay ();
  2346. }
  2347. }
  2348. /// <summary>Allows clearing the <see cref="HistoryText.HistoryTextItemEventArgs"/> items updating the original text.</summary>
  2349. public void ClearHistoryChanges () { _historyText?.Clear (Text); }
  2350. /// <summary>Closes the contents of the stream into the <see cref="TextView"/>.</summary>
  2351. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  2352. public bool CloseFile ()
  2353. {
  2354. SetWrapModel ();
  2355. bool res = _model.CloseFile ();
  2356. ResetPosition ();
  2357. SetNeedsDisplay ();
  2358. UpdateWrapModel ();
  2359. return res;
  2360. }
  2361. /// <summary>Raised when the contents of the <see cref="TextView"/> are changed.</summary>
  2362. /// <remarks>
  2363. /// Unlike the <see cref="View.TextChanged"/> event, this event is raised whenever the user types or otherwise changes
  2364. /// the contents of the <see cref="TextView"/>.
  2365. /// </remarks>
  2366. public event EventHandler<ContentsChangedEventArgs>? ContentsChanged;
  2367. /// <summary>Copy the selected text to the clipboard contents.</summary>
  2368. public void Copy ()
  2369. {
  2370. SetWrapModel ();
  2371. if (IsSelecting)
  2372. {
  2373. SetClipboard (GetRegion ());
  2374. _copyWithoutSelection = false;
  2375. }
  2376. else
  2377. {
  2378. List<RuneCell> currentLine = GetCurrentLine ();
  2379. SetClipboard (TextModel.ToString (currentLine));
  2380. _copyWithoutSelection = true;
  2381. }
  2382. UpdateWrapModel ();
  2383. DoNeededAction ();
  2384. }
  2385. /// <summary>Cut the selected text to the clipboard contents.</summary>
  2386. public void Cut ()
  2387. {
  2388. SetWrapModel ();
  2389. SetClipboard (GetRegion ());
  2390. if (!_isReadOnly)
  2391. {
  2392. ClearRegion ();
  2393. _historyText.Add (
  2394. new () { new (GetCurrentLine ()) },
  2395. CursorPosition,
  2396. HistoryText.LineStatus.Replaced
  2397. );
  2398. }
  2399. UpdateWrapModel ();
  2400. IsSelecting = false;
  2401. DoNeededAction ();
  2402. OnContentsChanged ();
  2403. }
  2404. /// <summary>Deletes all text.</summary>
  2405. public void DeleteAll ()
  2406. {
  2407. if (Lines == 0)
  2408. {
  2409. return;
  2410. }
  2411. _selectionStartColumn = 0;
  2412. _selectionStartRow = 0;
  2413. MoveBottomEndExtend ();
  2414. DeleteCharLeft ();
  2415. SetNeedsDisplay ();
  2416. }
  2417. /// <summary>Deletes all the selected or a single character at left from the position of the cursor.</summary>
  2418. public void DeleteCharLeft ()
  2419. {
  2420. if (_isReadOnly)
  2421. {
  2422. return;
  2423. }
  2424. SetWrapModel ();
  2425. if (IsSelecting)
  2426. {
  2427. _historyText.Add (new () { new (GetCurrentLine ()) }, CursorPosition);
  2428. ClearSelectedRegion ();
  2429. List<RuneCell> currentLine = GetCurrentLine ();
  2430. _historyText.Add (
  2431. new () { new (currentLine) },
  2432. CursorPosition,
  2433. HistoryText.LineStatus.Replaced
  2434. );
  2435. UpdateWrapModel ();
  2436. OnContentsChanged ();
  2437. return;
  2438. }
  2439. if (DeleteTextBackwards ())
  2440. {
  2441. UpdateWrapModel ();
  2442. OnContentsChanged ();
  2443. return;
  2444. }
  2445. UpdateWrapModel ();
  2446. DoNeededAction ();
  2447. OnContentsChanged ();
  2448. }
  2449. /// <summary>Deletes all the selected or a single character at right from the position of the cursor.</summary>
  2450. public void DeleteCharRight ()
  2451. {
  2452. if (_isReadOnly)
  2453. {
  2454. return;
  2455. }
  2456. SetWrapModel ();
  2457. if (IsSelecting)
  2458. {
  2459. _historyText.Add (new () { new (GetCurrentLine ()) }, CursorPosition);
  2460. ClearSelectedRegion ();
  2461. List<RuneCell> currentLine = GetCurrentLine ();
  2462. _historyText.Add (
  2463. new () { new (currentLine) },
  2464. CursorPosition,
  2465. HistoryText.LineStatus.Replaced
  2466. );
  2467. UpdateWrapModel ();
  2468. OnContentsChanged ();
  2469. return;
  2470. }
  2471. if (DeleteTextForwards ())
  2472. {
  2473. UpdateWrapModel ();
  2474. OnContentsChanged ();
  2475. return;
  2476. }
  2477. UpdateWrapModel ();
  2478. DoNeededAction ();
  2479. OnContentsChanged ();
  2480. }
  2481. /// <summary>Invoked when the normal color is drawn.</summary>
  2482. public event EventHandler<RuneCellEventArgs>? DrawNormalColor;
  2483. /// <summary>Invoked when the ready only color is drawn.</summary>
  2484. public event EventHandler<RuneCellEventArgs>? DrawReadOnlyColor;
  2485. /// <summary>Invoked when the selection color is drawn.</summary>
  2486. public event EventHandler<RuneCellEventArgs>? DrawSelectionColor;
  2487. /// <summary>
  2488. /// Invoked when the used color is drawn. The Used Color is used to indicate if the <see cref="Key.InsertChar"/>
  2489. /// was pressed and enabled.
  2490. /// </summary>
  2491. public event EventHandler<RuneCellEventArgs>? DrawUsedColor;
  2492. /// <summary>Find the next text based on the match case with the option to replace it.</summary>
  2493. /// <param name="textToFind">The text to find.</param>
  2494. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  2495. /// <param name="matchCase">The match case setting.</param>
  2496. /// <param name="matchWholeWord">The match whole word setting.</param>
  2497. /// <param name="textToReplace">The text to replace.</param>
  2498. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  2499. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  2500. public bool FindNextText (
  2501. string textToFind,
  2502. out bool gaveFullTurn,
  2503. bool matchCase = false,
  2504. bool matchWholeWord = false,
  2505. string? textToReplace = null,
  2506. bool replace = false
  2507. )
  2508. {
  2509. if (_model.Count == 0)
  2510. {
  2511. gaveFullTurn = false;
  2512. return false;
  2513. }
  2514. SetWrapModel ();
  2515. ResetContinuousFind ();
  2516. (Point current, bool found) foundPos =
  2517. _model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  2518. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  2519. }
  2520. /// <summary>Find the previous text based on the match case with the option to replace it.</summary>
  2521. /// <param name="textToFind">The text to find.</param>
  2522. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  2523. /// <param name="matchCase">The match case setting.</param>
  2524. /// <param name="matchWholeWord">The match whole word setting.</param>
  2525. /// <param name="textToReplace">The text to replace.</param>
  2526. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  2527. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  2528. public bool FindPreviousText (
  2529. string textToFind,
  2530. out bool gaveFullTurn,
  2531. bool matchCase = false,
  2532. bool matchWholeWord = false,
  2533. string? textToReplace = null,
  2534. bool replace = false
  2535. )
  2536. {
  2537. if (_model.Count == 0)
  2538. {
  2539. gaveFullTurn = false;
  2540. return false;
  2541. }
  2542. SetWrapModel ();
  2543. ResetContinuousFind ();
  2544. (Point current, bool found) foundPos =
  2545. _model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  2546. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  2547. }
  2548. /// <summary>Reset the flag to stop continuous find.</summary>
  2549. public void FindTextChanged () { _continuousFind = false; }
  2550. /// <summary>Gets all lines of characters.</summary>
  2551. /// <returns></returns>
  2552. public List<List<RuneCell>> GetAllLines () { return _model.GetAllLines (); }
  2553. /// <summary>
  2554. /// Returns the characters on the current line (where the cursor is positioned). Use <see cref="CurrentColumn"/>
  2555. /// to determine the position of the cursor within that line
  2556. /// </summary>
  2557. /// <returns></returns>
  2558. public List<RuneCell> GetCurrentLine () { return _model.GetLine (CurrentRow); }
  2559. /// <summary>Returns the characters on the <paramref name="line"/>.</summary>
  2560. /// <param name="line">The intended line.</param>
  2561. /// <returns></returns>
  2562. public List<RuneCell> GetLine (int line) { return _model.GetLine (line); }
  2563. /// <inheritdoc/>
  2564. public override Attribute GetNormalColor ()
  2565. {
  2566. return GetFocusColor ();
  2567. }
  2568. /// <summary>
  2569. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position exactly as if the user had just
  2570. /// typed it
  2571. /// </summary>
  2572. /// <param name="toAdd">Text to add</param>
  2573. public void InsertText (string toAdd)
  2574. {
  2575. foreach (char ch in toAdd)
  2576. {
  2577. Key key;
  2578. try
  2579. {
  2580. key = new (ch);
  2581. }
  2582. catch (Exception)
  2583. {
  2584. throw new ArgumentException (
  2585. $"Cannot insert character '{ch}' because it does not map to a Key"
  2586. );
  2587. }
  2588. InsertText (key);
  2589. if (NeedsDisplay)
  2590. {
  2591. Adjust ();
  2592. }
  2593. else
  2594. {
  2595. PositionCursor ();
  2596. }
  2597. }
  2598. }
  2599. /// <summary>Loads the contents of the file into the <see cref="TextView"/>.</summary>
  2600. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  2601. /// <param name="path">Path to the file to load.</param>
  2602. public bool Load (string path)
  2603. {
  2604. SetWrapModel ();
  2605. bool res;
  2606. try
  2607. {
  2608. SetWrapModel ();
  2609. res = _model.LoadFile (path);
  2610. _historyText.Clear (Text);
  2611. ResetPosition ();
  2612. }
  2613. finally
  2614. {
  2615. UpdateWrapModel ();
  2616. SetNeedsDisplay ();
  2617. Adjust ();
  2618. }
  2619. UpdateWrapModel ();
  2620. return res;
  2621. }
  2622. /// <summary>Loads the contents of the stream into the <see cref="TextView"/>.</summary>
  2623. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  2624. /// <param name="stream">Stream to load the contents from.</param>
  2625. public void Load (Stream stream)
  2626. {
  2627. SetWrapModel ();
  2628. _model.LoadStream (stream);
  2629. _historyText.Clear (Text);
  2630. ResetPosition ();
  2631. SetNeedsDisplay ();
  2632. UpdateWrapModel ();
  2633. }
  2634. /// <summary>Loads the contents of the <see cref="RuneCell"/> list into the <see cref="TextView"/>.</summary>
  2635. /// <param name="cells">Rune cells list to load the contents from.</param>
  2636. public void Load (List<RuneCell> cells)
  2637. {
  2638. SetWrapModel ();
  2639. _model.LoadRuneCells (cells, ColorScheme);
  2640. _historyText.Clear (Text);
  2641. ResetPosition ();
  2642. SetNeedsDisplay ();
  2643. UpdateWrapModel ();
  2644. InheritsPreviousColorScheme = true;
  2645. }
  2646. /// <summary>Loads the contents of the list of <see cref="RuneCell"/> list into the <see cref="TextView"/>.</summary>
  2647. /// <param name="cellsList">List of rune cells list to load the contents from.</param>
  2648. public void Load (List<List<RuneCell>> cellsList)
  2649. {
  2650. SetWrapModel ();
  2651. InheritsPreviousColorScheme = true;
  2652. _model.LoadListRuneCells (cellsList, ColorScheme);
  2653. _historyText.Clear (Text);
  2654. ResetPosition ();
  2655. SetNeedsDisplay ();
  2656. UpdateWrapModel ();
  2657. }
  2658. /// <inheritdoc/>
  2659. protected internal override bool OnMouseEvent (MouseEvent ev)
  2660. {
  2661. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked)
  2662. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  2663. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  2664. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  2665. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  2666. && !ev.Flags.HasFlag (MouseFlags.WheeledDown)
  2667. && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  2668. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  2669. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)
  2670. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  2671. && !ev.Flags.HasFlag (ContextMenu!.MouseFlags))
  2672. {
  2673. return base.OnMouseEvent (ev);
  2674. }
  2675. if (!CanFocus)
  2676. {
  2677. return true;
  2678. }
  2679. if (!HasFocus)
  2680. {
  2681. SetFocus ();
  2682. }
  2683. _continuousFind = false;
  2684. // Give autocomplete first opportunity to respond to mouse clicks
  2685. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  2686. {
  2687. return true;
  2688. }
  2689. if (ev.Flags == MouseFlags.Button1Clicked)
  2690. {
  2691. if (_isButtonReleased)
  2692. {
  2693. _isButtonReleased = false;
  2694. return true;
  2695. }
  2696. if (_shiftSelecting && !_isButtonShift)
  2697. {
  2698. StopSelecting ();
  2699. }
  2700. ProcessMouseClick (ev, out _);
  2701. if (Used)
  2702. {
  2703. PositionCursor ();
  2704. }
  2705. else
  2706. {
  2707. SetNeedsDisplay ();
  2708. }
  2709. _lastWasKill = false;
  2710. _columnTrack = CurrentColumn;
  2711. }
  2712. else if (ev.Flags == MouseFlags.WheeledDown)
  2713. {
  2714. _lastWasKill = false;
  2715. _columnTrack = CurrentColumn;
  2716. ScrollTo (_topRow + 1);
  2717. }
  2718. else if (ev.Flags == MouseFlags.WheeledUp)
  2719. {
  2720. _lastWasKill = false;
  2721. _columnTrack = CurrentColumn;
  2722. ScrollTo (_topRow - 1);
  2723. }
  2724. else if (ev.Flags == MouseFlags.WheeledRight)
  2725. {
  2726. _lastWasKill = false;
  2727. _columnTrack = CurrentColumn;
  2728. ScrollTo (_leftColumn + 1, false);
  2729. }
  2730. else if (ev.Flags == MouseFlags.WheeledLeft)
  2731. {
  2732. _lastWasKill = false;
  2733. _columnTrack = CurrentColumn;
  2734. ScrollTo (_leftColumn - 1, false);
  2735. }
  2736. else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  2737. {
  2738. ProcessMouseClick (ev, out List<RuneCell> line);
  2739. PositionCursor ();
  2740. if (_model.Count > 0 && _shiftSelecting && IsSelecting)
  2741. {
  2742. if (CurrentRow - _topRow >= Viewport.Height - 1 && _model.Count > _topRow + CurrentRow)
  2743. {
  2744. ScrollTo (_topRow + Viewport.Height);
  2745. }
  2746. else if (_topRow > 0 && CurrentRow <= _topRow)
  2747. {
  2748. ScrollTo (_topRow - Viewport.Height);
  2749. }
  2750. else if (ev.Position.Y >= Viewport.Height)
  2751. {
  2752. ScrollTo (_model.Count);
  2753. }
  2754. else if (ev.Position.Y < 0 && _topRow > 0)
  2755. {
  2756. ScrollTo (0);
  2757. }
  2758. if (CurrentColumn - _leftColumn >= Viewport.Width - 1 && line.Count > _leftColumn + CurrentColumn)
  2759. {
  2760. ScrollTo (_leftColumn + Viewport.Width, false);
  2761. }
  2762. else if (_leftColumn > 0 && CurrentColumn <= _leftColumn)
  2763. {
  2764. ScrollTo (_leftColumn - Viewport.Width, false);
  2765. }
  2766. else if (ev.Position.X >= Viewport.Width)
  2767. {
  2768. ScrollTo (line.Count, false);
  2769. }
  2770. else if (ev.Position.X < 0 && _leftColumn > 0)
  2771. {
  2772. ScrollTo (0, false);
  2773. }
  2774. }
  2775. _lastWasKill = false;
  2776. _columnTrack = CurrentColumn;
  2777. }
  2778. else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift))
  2779. {
  2780. if (!_shiftSelecting)
  2781. {
  2782. _isButtonShift = true;
  2783. StartSelecting ();
  2784. }
  2785. ProcessMouseClick (ev, out _);
  2786. PositionCursor ();
  2787. _lastWasKill = false;
  2788. _columnTrack = CurrentColumn;
  2789. }
  2790. else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed))
  2791. {
  2792. if (_shiftSelecting)
  2793. {
  2794. _clickWithSelecting = true;
  2795. StopSelecting ();
  2796. }
  2797. ProcessMouseClick (ev, out _);
  2798. PositionCursor ();
  2799. if (!IsSelecting)
  2800. {
  2801. StartSelecting ();
  2802. }
  2803. _lastWasKill = false;
  2804. _columnTrack = CurrentColumn;
  2805. if (Application.MouseGrabView is null)
  2806. {
  2807. Application.GrabMouse (this);
  2808. }
  2809. }
  2810. else if (ev.Flags.HasFlag (MouseFlags.Button1Released))
  2811. {
  2812. _isButtonReleased = true;
  2813. Application.UngrabMouse ();
  2814. }
  2815. else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked))
  2816. {
  2817. if (ev.Flags.HasFlag (MouseFlags.ButtonShift))
  2818. {
  2819. if (!IsSelecting)
  2820. {
  2821. StartSelecting ();
  2822. }
  2823. }
  2824. else if (IsSelecting)
  2825. {
  2826. StopSelecting ();
  2827. }
  2828. ProcessMouseClick (ev, out List<RuneCell> line);
  2829. (int col, int row)? newPos;
  2830. if (CurrentColumn == line.Count
  2831. || (CurrentColumn > 0 && (line [CurrentColumn - 1].Rune.Value != ' ' || line [CurrentColumn].Rune.Value == ' ')))
  2832. {
  2833. newPos = _model.WordBackward (CurrentColumn, CurrentRow);
  2834. if (newPos.HasValue)
  2835. {
  2836. CurrentColumn = CurrentRow == newPos.Value.row ? newPos.Value.col : 0;
  2837. }
  2838. }
  2839. if (!IsSelecting)
  2840. {
  2841. StartSelecting ();
  2842. }
  2843. newPos = _model.WordForward (CurrentColumn, CurrentRow);
  2844. if (newPos is { } && newPos.HasValue)
  2845. {
  2846. CurrentColumn = CurrentRow == newPos.Value.row ? newPos.Value.col : line.Count;
  2847. }
  2848. PositionCursor ();
  2849. _lastWasKill = false;
  2850. _columnTrack = CurrentColumn;
  2851. }
  2852. else if (ev.Flags.HasFlag (MouseFlags.Button1TripleClicked))
  2853. {
  2854. if (IsSelecting)
  2855. {
  2856. StopSelecting ();
  2857. }
  2858. ProcessMouseClick (ev, out List<RuneCell> line);
  2859. CurrentColumn = 0;
  2860. if (!IsSelecting)
  2861. {
  2862. StartSelecting ();
  2863. }
  2864. CurrentColumn = line.Count;
  2865. PositionCursor ();
  2866. _lastWasKill = false;
  2867. _columnTrack = CurrentColumn;
  2868. }
  2869. else if (ev.Flags == ContextMenu!.MouseFlags)
  2870. {
  2871. ContextMenu.Position = ViewportToScreen ((Viewport with { X = ev.Position.X, Y = ev.Position.Y }).Location);
  2872. ShowContextMenu ();
  2873. }
  2874. return true;
  2875. }
  2876. /// <summary>Will scroll the <see cref="TextView"/> to the last line and position the cursor there.</summary>
  2877. public void MoveEnd ()
  2878. {
  2879. CurrentRow = _model.Count - 1;
  2880. List<RuneCell> line = GetCurrentLine ();
  2881. CurrentColumn = line.Count;
  2882. TrackColumn ();
  2883. PositionCursor ();
  2884. }
  2885. /// <summary>Will scroll the <see cref="TextView"/> to the first line and position the cursor there.</summary>
  2886. public void MoveHome ()
  2887. {
  2888. CurrentRow = 0;
  2889. _topRow = 0;
  2890. CurrentColumn = 0;
  2891. _leftColumn = 0;
  2892. TrackColumn ();
  2893. PositionCursor ();
  2894. SetNeedsDisplay ();
  2895. }
  2896. /// <summary>
  2897. /// Called when the contents of the TextView change. E.g. when the user types text or deletes text. Raises the
  2898. /// <see cref="ContentsChanged"/> event.
  2899. /// </summary>
  2900. public virtual void OnContentsChanged ()
  2901. {
  2902. ContentsChanged?.Invoke (this, new (CurrentRow, CurrentColumn));
  2903. ProcessInheritsPreviousColorScheme (CurrentRow, CurrentColumn);
  2904. ProcessAutocomplete ();
  2905. }
  2906. /// <inheritdoc/>
  2907. public override void OnDrawContent (Rectangle viewport)
  2908. {
  2909. _isDrawing = true;
  2910. SetNormalColor ();
  2911. (int width, int height) offB = OffSetBackground ();
  2912. int right = Viewport.Width + offB.width;
  2913. int bottom = Viewport.Height + offB.height;
  2914. var row = 0;
  2915. for (int idxRow = _topRow; idxRow < _model.Count; idxRow++)
  2916. {
  2917. List<RuneCell> line = _model.GetLine (idxRow);
  2918. int lineRuneCount = line.Count;
  2919. var col = 0;
  2920. Move (0, row);
  2921. for (int idxCol = _leftColumn; idxCol < lineRuneCount; idxCol++)
  2922. {
  2923. Rune rune = idxCol >= lineRuneCount ? (Rune)' ' : line [idxCol].Rune;
  2924. int cols = rune.GetColumns ();
  2925. if (idxCol < line.Count && IsSelecting && PointInSelection (idxCol, idxRow))
  2926. {
  2927. OnDrawSelectionColor (line, idxCol, idxRow);
  2928. }
  2929. else if (idxCol == CurrentColumn && idxRow == CurrentRow && !IsSelecting && !Used && HasFocus && idxCol < lineRuneCount)
  2930. {
  2931. OnDrawUsedColor (line, idxCol, idxRow);
  2932. }
  2933. else if (ReadOnly)
  2934. {
  2935. OnDrawReadOnlyColor (line, idxCol, idxRow);
  2936. }
  2937. else
  2938. {
  2939. OnDrawNormalColor (line, idxCol, idxRow);
  2940. }
  2941. if (rune.Value == '\t')
  2942. {
  2943. cols += TabWidth + 1;
  2944. if (col + cols > right)
  2945. {
  2946. cols = right - col;
  2947. }
  2948. for (var i = 0; i < cols; i++)
  2949. {
  2950. if (col + i < right)
  2951. {
  2952. AddRune (col + i, row, (Rune)' ');
  2953. }
  2954. }
  2955. }
  2956. else
  2957. {
  2958. AddRune (col, row, rune);
  2959. }
  2960. if (!TextModel.SetCol (ref col, viewport.Right, cols))
  2961. {
  2962. break;
  2963. }
  2964. if (idxCol + 1 < lineRuneCount && col + line [idxCol + 1].Rune.GetColumns () > right)
  2965. {
  2966. break;
  2967. }
  2968. }
  2969. if (col < right)
  2970. {
  2971. SetNormalColor ();
  2972. ClearRegion (col, row, right, row + 1);
  2973. }
  2974. row++;
  2975. }
  2976. if (row < bottom)
  2977. {
  2978. SetNormalColor ();
  2979. ClearRegion (viewport.Left, row, right, bottom);
  2980. }
  2981. //PositionCursor ();
  2982. _isDrawing = false;
  2983. }
  2984. /// <inheritdoc/>
  2985. public override bool? OnInvokingKeyBindings (Key a, KeyBindingScope scope)
  2986. {
  2987. if (!a.IsValid)
  2988. {
  2989. return false;
  2990. }
  2991. // Give autocomplete first opportunity to respond to key presses
  2992. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (a))
  2993. {
  2994. return true;
  2995. }
  2996. return base.OnInvokingKeyBindings (a, scope);
  2997. }
  2998. /// <inheritdoc/>
  2999. public override bool OnKeyUp (Key key)
  3000. {
  3001. if (key == Key.Space.WithCtrl)
  3002. {
  3003. return true;
  3004. }
  3005. return base.OnKeyUp (key);
  3006. }
  3007. /// <inheritdoc/>
  3008. protected override void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? view)
  3009. {
  3010. if (Application.MouseGrabView is { } && Application.MouseGrabView == this)
  3011. {
  3012. Application.UngrabMouse ();
  3013. }
  3014. return;
  3015. }
  3016. /// <inheritdoc/>
  3017. public override bool OnProcessKeyDown (Key a)
  3018. {
  3019. if (!CanFocus)
  3020. {
  3021. return true;
  3022. }
  3023. ResetColumnTrack ();
  3024. // Ignore control characters and other special keys
  3025. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  3026. {
  3027. return false;
  3028. }
  3029. InsertText (a);
  3030. DoNeededAction ();
  3031. return true;
  3032. }
  3033. /// <summary>Invoke the <see cref="UnwrappedCursorPosition"/> event with the unwrapped <see cref="CursorPosition"/>.</summary>
  3034. public virtual void OnUnwrappedCursorPosition (int? cRow = null, int? cCol = null)
  3035. {
  3036. int? row = cRow is null ? CurrentRow : cRow;
  3037. int? col = cCol is null ? CurrentColumn : cCol;
  3038. if (cRow is null && cCol is null && _wordWrap)
  3039. {
  3040. row = _wrapManager!.GetModelLineFromWrappedLines (CurrentRow);
  3041. col = _wrapManager.GetModelColFromWrappedLines (CurrentRow, CurrentColumn);
  3042. }
  3043. UnwrappedCursorPosition?.Invoke (this, new (new ((int)col, (int)row)));
  3044. }
  3045. /// <summary>Paste the clipboard contents into the current selected position.</summary>
  3046. public void Paste ()
  3047. {
  3048. if (_isReadOnly)
  3049. {
  3050. return;
  3051. }
  3052. SetWrapModel ();
  3053. string? contents = Clipboard.Contents;
  3054. if (_copyWithoutSelection && contents.FirstOrDefault (x => x == '\n' || x == '\r') == 0)
  3055. {
  3056. List<RuneCell> runeList = contents is null ? new () : TextModel.ToRuneCellList (contents);
  3057. List<RuneCell> currentLine = GetCurrentLine ();
  3058. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  3059. List<List<RuneCell>> addedLine = new () { new (currentLine), runeList };
  3060. _historyText.Add (
  3061. new (addedLine),
  3062. CursorPosition,
  3063. HistoryText.LineStatus.Added
  3064. );
  3065. _model.AddLine (CurrentRow, runeList);
  3066. CurrentRow++;
  3067. _historyText.Add (
  3068. new () { new (GetCurrentLine ()) },
  3069. CursorPosition,
  3070. HistoryText.LineStatus.Replaced
  3071. );
  3072. SetNeedsDisplay ();
  3073. OnContentsChanged ();
  3074. }
  3075. else
  3076. {
  3077. if (IsSelecting)
  3078. {
  3079. ClearRegion ();
  3080. }
  3081. _copyWithoutSelection = false;
  3082. InsertAllText (contents);
  3083. if (IsSelecting)
  3084. {
  3085. _historyText.ReplaceLast (
  3086. new () { new (GetCurrentLine ()) },
  3087. CursorPosition,
  3088. HistoryText.LineStatus.Original
  3089. );
  3090. }
  3091. SetNeedsDisplay ();
  3092. }
  3093. UpdateWrapModel ();
  3094. IsSelecting = false;
  3095. DoNeededAction ();
  3096. }
  3097. /// <summary>Positions the cursor on the current row and column</summary>
  3098. public override Point? PositionCursor ()
  3099. {
  3100. ProcessAutocomplete ();
  3101. if (!CanFocus || !Enabled || Application.Driver is null)
  3102. {
  3103. return null;
  3104. }
  3105. if (Application.MouseGrabView == this && IsSelecting)
  3106. {
  3107. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3108. //var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Viewport.Height);
  3109. //var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Viewport.Height);
  3110. //SetNeedsDisplay (new (0, minRow, Viewport.Width, maxRow));
  3111. SetNeedsDisplay ();
  3112. }
  3113. List<RuneCell> line = _model.GetLine (CurrentRow);
  3114. var col = 0;
  3115. if (line.Count > 0)
  3116. {
  3117. for (int idx = _leftColumn; idx < line.Count; idx++)
  3118. {
  3119. if (idx >= CurrentColumn)
  3120. {
  3121. break;
  3122. }
  3123. int cols = line [idx].Rune.GetColumns ();
  3124. if (line [idx].Rune.Value == '\t')
  3125. {
  3126. cols += TabWidth + 1;
  3127. }
  3128. if (!TextModel.SetCol (ref col, Viewport.Width, cols))
  3129. {
  3130. col = CurrentColumn;
  3131. break;
  3132. }
  3133. }
  3134. }
  3135. int posX = CurrentColumn - _leftColumn;
  3136. int posY = CurrentRow - _topRow;
  3137. if (posX > -1 && col >= posX && posX < Viewport.Width && _topRow <= CurrentRow && posY < Viewport.Height)
  3138. {
  3139. Move (col, CurrentRow - _topRow);
  3140. return new (col, CurrentRow - _topRow);
  3141. }
  3142. return null; // Hide cursor
  3143. }
  3144. /// <summary>Redoes the latest changes.</summary>
  3145. public void Redo ()
  3146. {
  3147. if (ReadOnly)
  3148. {
  3149. return;
  3150. }
  3151. _historyText.Redo ();
  3152. }
  3153. /// <summary>Replaces all the text based on the match case.</summary>
  3154. /// <param name="textToFind">The text to find.</param>
  3155. /// <param name="matchCase">The match case setting.</param>
  3156. /// <param name="matchWholeWord">The match whole word setting.</param>
  3157. /// <param name="textToReplace">The text to replace.</param>
  3158. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  3159. public bool ReplaceAllText (
  3160. string textToFind,
  3161. bool matchCase = false,
  3162. bool matchWholeWord = false,
  3163. string? textToReplace = null
  3164. )
  3165. {
  3166. if (_isReadOnly || _model.Count == 0)
  3167. {
  3168. return false;
  3169. }
  3170. SetWrapModel ();
  3171. ResetContinuousFind ();
  3172. (Point current, bool found) foundPos =
  3173. _model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  3174. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  3175. }
  3176. /// <summary>
  3177. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is
  3178. /// true or will scroll the <see cref="TextView"/> to display the specified column at the left if
  3179. /// <paramref name="isRow"/> is false.
  3180. /// </summary>
  3181. /// <param name="idx">
  3182. /// Row that should be displayed at the top or Column that should be displayed at the left, if the value
  3183. /// is negative it will be reset to zero
  3184. /// </param>
  3185. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  3186. public void ScrollTo (int idx, bool isRow = true)
  3187. {
  3188. if (idx < 0)
  3189. {
  3190. idx = 0;
  3191. }
  3192. if (isRow)
  3193. {
  3194. _topRow = Math.Max (idx > _model.Count - 1 ? _model.Count - 1 : idx, 0);
  3195. }
  3196. else if (!_wordWrap)
  3197. {
  3198. int maxlength =
  3199. _model.GetMaxVisibleLine (_topRow, _topRow + Viewport.Height, TabWidth);
  3200. _leftColumn = Math.Max (!_wordWrap && idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  3201. }
  3202. SetNeedsDisplay ();
  3203. }
  3204. /// <summary>Select all text.</summary>
  3205. public void SelectAll ()
  3206. {
  3207. if (_model.Count == 0)
  3208. {
  3209. return;
  3210. }
  3211. StartSelecting ();
  3212. _selectionStartColumn = 0;
  3213. _selectionStartRow = 0;
  3214. CurrentColumn = _model.GetLine (_model.Count - 1).Count;
  3215. CurrentRow = _model.Count - 1;
  3216. SetNeedsDisplay ();
  3217. }
  3218. ///// <summary>Raised when the <see cref="Text"/> property of the <see cref="TextView"/> changes.</summary>
  3219. ///// <remarks>
  3220. ///// The <see cref="Text"/> property of <see cref="TextView"/> only changes when it is explicitly set, not as the
  3221. ///// user types. To be notified as the user changes the contents of the TextView see <see cref="IsDirty"/>.
  3222. ///// </remarks>
  3223. //public event EventHandler? TextChanged;
  3224. /// <summary>Undoes the latest changes.</summary>
  3225. public void Undo ()
  3226. {
  3227. if (ReadOnly)
  3228. {
  3229. return;
  3230. }
  3231. _historyText.Undo ();
  3232. }
  3233. /// <summary>Invoked with the unwrapped <see cref="CursorPosition"/>.</summary>
  3234. public event EventHandler<PointEventArgs>? UnwrappedCursorPosition;
  3235. /// <summary>
  3236. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3237. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3238. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.Normal"/>.
  3239. /// </summary>
  3240. /// <param name="line">The line.</param>
  3241. /// <param name="idxCol">The col index.</param>
  3242. /// <param name="idxRow">The row index.</param>
  3243. protected virtual void OnDrawNormalColor (List<RuneCell> line, int idxCol, int idxRow)
  3244. {
  3245. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3246. var ev = new RuneCellEventArgs (line, idxCol, unwrappedPos);
  3247. DrawNormalColor?.Invoke (this, ev);
  3248. if (line [idxCol].ColorScheme is { })
  3249. {
  3250. ColorScheme? colorScheme = line [idxCol].ColorScheme;
  3251. Driver.SetAttribute (Enabled ? colorScheme!.Focus : colorScheme!.Disabled);
  3252. }
  3253. else
  3254. {
  3255. Driver.SetAttribute (GetNormalColor ());
  3256. }
  3257. }
  3258. /// <summary>
  3259. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3260. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3261. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.Focus"/>.
  3262. /// </summary>
  3263. /// <param name="line">The line.</param>
  3264. /// <param name="idxCol">The col index.</param>
  3265. /// ///
  3266. /// <param name="idxRow">The row index.</param>
  3267. protected virtual void OnDrawReadOnlyColor (List<RuneCell> line, int idxCol, int idxRow)
  3268. {
  3269. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3270. var ev = new RuneCellEventArgs (line, idxCol, unwrappedPos);
  3271. DrawReadOnlyColor?.Invoke (this, ev);
  3272. ColorScheme? colorScheme = line [idxCol].ColorScheme is { } ? line [idxCol].ColorScheme : ColorScheme;
  3273. Attribute attribute;
  3274. if (colorScheme!.Disabled.Foreground == colorScheme.Focus.Background)
  3275. {
  3276. attribute = new (colorScheme.Focus.Foreground, colorScheme.Focus.Background);
  3277. }
  3278. else
  3279. {
  3280. attribute = new (colorScheme.Disabled.Foreground, colorScheme.Focus.Background);
  3281. }
  3282. Driver.SetAttribute (attribute);
  3283. }
  3284. /// <summary>
  3285. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3286. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3287. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.Focus"/>.
  3288. /// </summary>
  3289. /// <param name="line">The line.</param>
  3290. /// <param name="idxCol">The col index.</param>
  3291. /// ///
  3292. /// <param name="idxRow">The row index.</param>
  3293. protected virtual void OnDrawSelectionColor (List<RuneCell> line, int idxCol, int idxRow)
  3294. {
  3295. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3296. var ev = new RuneCellEventArgs (line, idxCol, unwrappedPos);
  3297. DrawSelectionColor?.Invoke (this, ev);
  3298. if (line [idxCol].ColorScheme is { })
  3299. {
  3300. ColorScheme? colorScheme = line [idxCol].ColorScheme;
  3301. Driver.SetAttribute (
  3302. new (colorScheme!.Focus.Background, colorScheme.Focus.Foreground)
  3303. );
  3304. }
  3305. else
  3306. {
  3307. Driver.SetAttribute (
  3308. new (
  3309. ColorScheme!.Focus.Background,
  3310. ColorScheme!.Focus.Foreground
  3311. )
  3312. );
  3313. }
  3314. }
  3315. /// <summary>
  3316. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3317. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3318. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.HotFocus"/>.
  3319. /// </summary>
  3320. /// <param name="line">The line.</param>
  3321. /// <param name="idxCol">The col index.</param>
  3322. /// ///
  3323. /// <param name="idxRow">The row index.</param>
  3324. protected virtual void OnDrawUsedColor (List<RuneCell> line, int idxCol, int idxRow)
  3325. {
  3326. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3327. var ev = new RuneCellEventArgs (line, idxCol, unwrappedPos);
  3328. DrawUsedColor?.Invoke (this, ev);
  3329. if (line [idxCol].ColorScheme is { })
  3330. {
  3331. ColorScheme? colorScheme = line [idxCol].ColorScheme;
  3332. SetValidUsedColor (colorScheme!);
  3333. }
  3334. else
  3335. {
  3336. SetValidUsedColor (ColorScheme);
  3337. }
  3338. }
  3339. /// <summary>
  3340. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to
  3341. /// <see cref="ColorScheme.Normal"/>.
  3342. /// </summary>
  3343. protected virtual void SetNormalColor () { Driver.SetAttribute (GetNormalColor ()); }
  3344. private void Adjust ()
  3345. {
  3346. (int width, int height) offB = OffSetBackground ();
  3347. List<RuneCell> line = GetCurrentLine ();
  3348. bool need = NeedsDisplay || _wrapNeeded || !Used;
  3349. (int size, int length) tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  3350. (int size, int length) dSize = TextModel.DisplaySize (line, _leftColumn, CurrentColumn, true, TabWidth);
  3351. if (!_wordWrap && CurrentColumn < _leftColumn)
  3352. {
  3353. _leftColumn = CurrentColumn;
  3354. need = true;
  3355. }
  3356. else if (!_wordWrap
  3357. && (CurrentColumn - _leftColumn + 1 > Viewport.Width + offB.width || dSize.size + 1 >= Viewport.Width + offB.width))
  3358. {
  3359. _leftColumn = TextModel.CalculateLeftColumn (
  3360. line,
  3361. _leftColumn,
  3362. CurrentColumn,
  3363. Viewport.Width + offB.width,
  3364. TabWidth
  3365. );
  3366. need = true;
  3367. }
  3368. else if ((_wordWrap && _leftColumn > 0) || (dSize.size < Viewport.Width + offB.width && tSize.size < Viewport.Width + offB.width))
  3369. {
  3370. if (_leftColumn > 0)
  3371. {
  3372. _leftColumn = 0;
  3373. need = true;
  3374. }
  3375. }
  3376. if (CurrentRow < _topRow)
  3377. {
  3378. _topRow = CurrentRow;
  3379. need = true;
  3380. }
  3381. else if (CurrentRow - _topRow >= Viewport.Height + offB.height)
  3382. {
  3383. _topRow = Math.Min (Math.Max (CurrentRow - Viewport.Height + 1, 0), CurrentRow);
  3384. need = true;
  3385. }
  3386. else if (_topRow > 0 && CurrentRow < _topRow)
  3387. {
  3388. _topRow = Math.Max (_topRow - 1, 0);
  3389. need = true;
  3390. }
  3391. if (need)
  3392. {
  3393. if (_wrapNeeded)
  3394. {
  3395. WrapTextModel ();
  3396. _wrapNeeded = false;
  3397. }
  3398. SetNeedsDisplay ();
  3399. }
  3400. else
  3401. {
  3402. if (IsInitialized)
  3403. {
  3404. PositionCursor ();
  3405. }
  3406. }
  3407. OnUnwrappedCursorPosition ();
  3408. }
  3409. private void AppendClipboard (string text) { Clipboard.Contents += text; }
  3410. private MenuBarItem? BuildContextMenuBarItem ()
  3411. {
  3412. return new (
  3413. new MenuItem []
  3414. {
  3415. new (
  3416. Strings.ctxSelectAll,
  3417. "",
  3418. SelectAll,
  3419. null,
  3420. null,
  3421. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  3422. ),
  3423. new (
  3424. Strings.ctxDeleteAll,
  3425. "",
  3426. DeleteAll,
  3427. null,
  3428. null,
  3429. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  3430. ),
  3431. new (
  3432. Strings.ctxCopy,
  3433. "",
  3434. Copy,
  3435. null,
  3436. null,
  3437. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  3438. ),
  3439. new (
  3440. Strings.ctxCut,
  3441. "",
  3442. Cut,
  3443. null,
  3444. null,
  3445. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  3446. ),
  3447. new (
  3448. Strings.ctxPaste,
  3449. "",
  3450. Paste,
  3451. null,
  3452. null,
  3453. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  3454. ),
  3455. new (
  3456. Strings.ctxUndo,
  3457. "",
  3458. Undo,
  3459. null,
  3460. null,
  3461. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  3462. ),
  3463. new (
  3464. Strings.ctxRedo,
  3465. "",
  3466. Redo,
  3467. null,
  3468. null,
  3469. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  3470. )
  3471. }
  3472. );
  3473. }
  3474. private void ClearRegion (int left, int top, int right, int bottom)
  3475. {
  3476. for (int row = top; row < bottom; row++)
  3477. {
  3478. Move (left, row);
  3479. for (int col = left; col < right; col++)
  3480. {
  3481. AddRune (col, row, (Rune)' ');
  3482. }
  3483. }
  3484. }
  3485. //
  3486. // Clears the contents of the selected region
  3487. //
  3488. private void ClearRegion ()
  3489. {
  3490. SetWrapModel ();
  3491. long start, end;
  3492. long currentEncoded = ((long)(uint)CurrentRow << 32) | (uint)CurrentColumn;
  3493. GetEncodedRegionBounds (out start, out end);
  3494. var startRow = (int)(start >> 32);
  3495. var maxrow = (int)(end >> 32);
  3496. var startCol = (int)(start & 0xffffffff);
  3497. var endCol = (int)(end & 0xffffffff);
  3498. List<RuneCell> line = _model.GetLine (startRow);
  3499. _historyText.Add (new () { new (line) }, new (startCol, startRow));
  3500. List<List<RuneCell>> removedLines = new ();
  3501. if (startRow == maxrow)
  3502. {
  3503. removedLines.Add (new (line));
  3504. line.RemoveRange (startCol, endCol - startCol);
  3505. CurrentColumn = startCol;
  3506. if (_wordWrap)
  3507. {
  3508. SetNeedsDisplay ();
  3509. }
  3510. else
  3511. {
  3512. //QUESTION: Is the below comment still relevant?
  3513. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3514. //SetNeedsDisplay (new (0, startRow - topRow, Viewport.Width, startRow - topRow + 1));
  3515. SetNeedsDisplay ();
  3516. }
  3517. _historyText.Add (
  3518. new (removedLines),
  3519. CursorPosition,
  3520. HistoryText.LineStatus.Removed
  3521. );
  3522. UpdateWrapModel ();
  3523. return;
  3524. }
  3525. removedLines.Add (new (line));
  3526. line.RemoveRange (startCol, line.Count - startCol);
  3527. List<RuneCell> line2 = _model.GetLine (maxrow);
  3528. line.AddRange (line2.Skip (endCol));
  3529. for (int row = startRow + 1; row <= maxrow; row++)
  3530. {
  3531. removedLines.Add (new (_model.GetLine (startRow + 1)));
  3532. _model.RemoveLine (startRow + 1);
  3533. }
  3534. if (currentEncoded == end)
  3535. {
  3536. CurrentRow -= maxrow - startRow;
  3537. }
  3538. CurrentColumn = startCol;
  3539. _historyText.Add (
  3540. new (removedLines),
  3541. CursorPosition,
  3542. HistoryText.LineStatus.Removed
  3543. );
  3544. UpdateWrapModel ();
  3545. SetNeedsDisplay ();
  3546. }
  3547. private void ClearSelectedRegion ()
  3548. {
  3549. SetWrapModel ();
  3550. if (!_isReadOnly)
  3551. {
  3552. ClearRegion ();
  3553. }
  3554. UpdateWrapModel ();
  3555. IsSelecting = false;
  3556. DoNeededAction ();
  3557. }
  3558. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.ReplaceKey (e.OldKey, e.NewKey); }
  3559. private bool DeleteTextBackwards ()
  3560. {
  3561. SetWrapModel ();
  3562. if (CurrentColumn > 0)
  3563. {
  3564. // Delete backwards
  3565. List<RuneCell> currentLine = GetCurrentLine ();
  3566. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  3567. currentLine.RemoveAt (CurrentColumn - 1);
  3568. if (_wordWrap)
  3569. {
  3570. _wrapNeeded = true;
  3571. }
  3572. CurrentColumn--;
  3573. _historyText.Add (
  3574. new () { new (currentLine) },
  3575. CursorPosition,
  3576. HistoryText.LineStatus.Replaced
  3577. );
  3578. if (CurrentColumn < _leftColumn)
  3579. {
  3580. _leftColumn--;
  3581. SetNeedsDisplay ();
  3582. }
  3583. else
  3584. {
  3585. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3586. //SetNeedsDisplay (new (0, currentRow - topRow, 1, Viewport.Width));
  3587. SetNeedsDisplay ();
  3588. }
  3589. }
  3590. else
  3591. {
  3592. // Merges the current line with the previous one.
  3593. if (CurrentRow == 0)
  3594. {
  3595. return true;
  3596. }
  3597. int prowIdx = CurrentRow - 1;
  3598. List<RuneCell> prevRow = _model.GetLine (prowIdx);
  3599. _historyText.Add (new () { new (prevRow) }, CursorPosition);
  3600. List<List<RuneCell>> removedLines = new () { new (prevRow) };
  3601. removedLines.Add (new (GetCurrentLine ()));
  3602. _historyText.Add (
  3603. removedLines,
  3604. new (CurrentColumn, prowIdx),
  3605. HistoryText.LineStatus.Removed
  3606. );
  3607. int prevCount = prevRow.Count;
  3608. _model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  3609. _model.RemoveLine (CurrentRow);
  3610. if (_wordWrap)
  3611. {
  3612. _wrapNeeded = true;
  3613. }
  3614. CurrentRow--;
  3615. _historyText.Add (
  3616. new () { GetCurrentLine () },
  3617. new (CurrentColumn, prowIdx),
  3618. HistoryText.LineStatus.Replaced
  3619. );
  3620. CurrentColumn = prevCount;
  3621. SetNeedsDisplay ();
  3622. }
  3623. UpdateWrapModel ();
  3624. return false;
  3625. }
  3626. private bool DeleteTextForwards ()
  3627. {
  3628. SetWrapModel ();
  3629. List<RuneCell> currentLine = GetCurrentLine ();
  3630. if (CurrentColumn == currentLine.Count)
  3631. {
  3632. if (CurrentRow + 1 == _model.Count)
  3633. {
  3634. UpdateWrapModel ();
  3635. return true;
  3636. }
  3637. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  3638. List<List<RuneCell>> removedLines = new () { new (currentLine) };
  3639. List<RuneCell> nextLine = _model.GetLine (CurrentRow + 1);
  3640. removedLines.Add (new (nextLine));
  3641. _historyText.Add (removedLines, CursorPosition, HistoryText.LineStatus.Removed);
  3642. currentLine.AddRange (nextLine);
  3643. _model.RemoveLine (CurrentRow + 1);
  3644. _historyText.Add (
  3645. new () { new (currentLine) },
  3646. CursorPosition,
  3647. HistoryText.LineStatus.Replaced
  3648. );
  3649. if (_wordWrap)
  3650. {
  3651. _wrapNeeded = true;
  3652. }
  3653. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, CurrentRow - _topRow + 1));
  3654. }
  3655. else
  3656. {
  3657. _historyText.Add ([ [.. currentLine]], CursorPosition);
  3658. currentLine.RemoveAt (CurrentColumn);
  3659. _historyText.Add (
  3660. [ [.. currentLine]],
  3661. CursorPosition,
  3662. HistoryText.LineStatus.Replaced
  3663. );
  3664. if (_wordWrap)
  3665. {
  3666. _wrapNeeded = true;
  3667. }
  3668. DoSetNeedsDisplay (
  3669. new (
  3670. CurrentColumn - _leftColumn,
  3671. CurrentRow - _topRow,
  3672. Viewport.Width,
  3673. Math.Max (CurrentRow - _topRow + 1, 0)
  3674. )
  3675. );
  3676. }
  3677. UpdateWrapModel ();
  3678. return false;
  3679. }
  3680. private void DoNeededAction ()
  3681. {
  3682. if (NeedsDisplay)
  3683. {
  3684. Adjust ();
  3685. }
  3686. else
  3687. {
  3688. PositionCursor ();
  3689. }
  3690. }
  3691. private void DoSetNeedsDisplay (Rectangle rect)
  3692. {
  3693. if (_wrapNeeded)
  3694. {
  3695. SetNeedsDisplay ();
  3696. }
  3697. else
  3698. {
  3699. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3700. //SetNeedsDisplay (rect);
  3701. SetNeedsDisplay ();
  3702. }
  3703. }
  3704. private IEnumerable<(int col, int row, RuneCell rune)> ForwardIterator (int col, int row)
  3705. {
  3706. if (col < 0 || row < 0)
  3707. {
  3708. yield break;
  3709. }
  3710. if (row >= _model.Count)
  3711. {
  3712. yield break;
  3713. }
  3714. List<RuneCell> line = GetCurrentLine ();
  3715. if (col >= line.Count)
  3716. {
  3717. yield break;
  3718. }
  3719. while (row < _model.Count)
  3720. {
  3721. for (int c = col; c < line.Count; c++)
  3722. {
  3723. yield return (c, row, line [c]);
  3724. }
  3725. col = 0;
  3726. row++;
  3727. line = GetCurrentLine ();
  3728. }
  3729. }
  3730. private void GenerateSuggestions ()
  3731. {
  3732. List<RuneCell> currentLine = GetCurrentLine ();
  3733. int cursorPosition = Math.Min (CurrentColumn, currentLine.Count);
  3734. Autocomplete.Context = new (
  3735. currentLine,
  3736. cursorPosition,
  3737. Autocomplete.Context != null
  3738. ? Autocomplete.Context.Canceled
  3739. : false
  3740. );
  3741. Autocomplete.GenerateSuggestions (
  3742. Autocomplete.Context
  3743. );
  3744. }
  3745. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  3746. private void GetEncodedRegionBounds (
  3747. out long start,
  3748. out long end,
  3749. int? startRow = null,
  3750. int? startCol = null,
  3751. int? cRow = null,
  3752. int? cCol = null
  3753. )
  3754. {
  3755. long selection;
  3756. long point;
  3757. if (startRow is null || startCol is null || cRow is null || cCol is null)
  3758. {
  3759. selection = ((long)(uint)_selectionStartRow << 32) | (uint)_selectionStartColumn;
  3760. point = ((long)(uint)CurrentRow << 32) | (uint)CurrentColumn;
  3761. }
  3762. else
  3763. {
  3764. selection = ((long)(uint)startRow << 32) | (uint)startCol;
  3765. point = ((long)(uint)cRow << 32) | (uint)cCol;
  3766. }
  3767. if (selection > point)
  3768. {
  3769. start = point;
  3770. end = selection;
  3771. }
  3772. else
  3773. {
  3774. start = selection;
  3775. end = point;
  3776. }
  3777. }
  3778. //
  3779. // Returns a string with the text in the selected
  3780. // region.
  3781. //
  3782. private string GetRegion (
  3783. int? sRow = null,
  3784. int? sCol = null,
  3785. int? cRow = null,
  3786. int? cCol = null,
  3787. TextModel? model = null
  3788. )
  3789. {
  3790. long start, end;
  3791. GetEncodedRegionBounds (out start, out end, sRow, sCol, cRow, cCol);
  3792. if (start == end)
  3793. {
  3794. return string.Empty;
  3795. }
  3796. var startRow = (int)(start >> 32);
  3797. var maxrow = (int)(end >> 32);
  3798. var startCol = (int)(start & 0xffffffff);
  3799. var endCol = (int)(end & 0xffffffff);
  3800. List<RuneCell> line = model is null ? _model.GetLine (startRow) : model.GetLine (startRow);
  3801. if (startRow == maxrow)
  3802. {
  3803. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  3804. }
  3805. string res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  3806. for (int row = startRow + 1; row < maxrow; row++)
  3807. {
  3808. res = res
  3809. + Environment.NewLine
  3810. + StringFromRunes (
  3811. model == null
  3812. ? _model.GetLine (row)
  3813. : model.GetLine (row)
  3814. );
  3815. }
  3816. line = model is null ? _model.GetLine (maxrow) : model.GetLine (maxrow);
  3817. res = res + Environment.NewLine + StringFromRunes (line.GetRange (0, endCol));
  3818. return res;
  3819. }
  3820. private int GetSelectedLength () { return SelectedText.Length; }
  3821. private string GetSelectedRegion ()
  3822. {
  3823. int cRow = CurrentRow;
  3824. int cCol = CurrentColumn;
  3825. int startRow = _selectionStartRow;
  3826. int startCol = _selectionStartColumn;
  3827. TextModel model = _model;
  3828. if (_wordWrap)
  3829. {
  3830. cRow = _wrapManager!.GetModelLineFromWrappedLines (CurrentRow);
  3831. cCol = _wrapManager.GetModelColFromWrappedLines (CurrentRow, CurrentColumn);
  3832. startRow = _wrapManager.GetModelLineFromWrappedLines (_selectionStartRow);
  3833. startCol = _wrapManager.GetModelColFromWrappedLines (_selectionStartRow, _selectionStartColumn);
  3834. model = _wrapManager.Model;
  3835. }
  3836. OnUnwrappedCursorPosition (cRow, cCol);
  3837. return GetRegion (startRow, startCol, cRow, cCol, model);
  3838. }
  3839. private (int Row, int Col) GetUnwrappedPosition (int line, int col)
  3840. {
  3841. if (WordWrap)
  3842. {
  3843. return new ValueTuple<int, int> (
  3844. _wrapManager!.GetModelLineFromWrappedLines (line),
  3845. _wrapManager.GetModelColFromWrappedLines (line, col)
  3846. );
  3847. }
  3848. return new ValueTuple<int, int> (line, col);
  3849. }
  3850. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItemEventArgs obj)
  3851. {
  3852. SetWrapModel ();
  3853. if (obj is { })
  3854. {
  3855. int startLine = obj.CursorPosition.Y;
  3856. if (obj.RemovedOnAdded is { })
  3857. {
  3858. int offset;
  3859. if (obj.IsUndoing)
  3860. {
  3861. offset = Math.Max (obj.RemovedOnAdded.Lines.Count - obj.Lines.Count, 1);
  3862. }
  3863. else
  3864. {
  3865. offset = obj.RemovedOnAdded.Lines.Count - 1;
  3866. }
  3867. for (var i = 0; i < offset; i++)
  3868. {
  3869. if (Lines > obj.RemovedOnAdded.CursorPosition.Y)
  3870. {
  3871. _model.RemoveLine (obj.RemovedOnAdded.CursorPosition.Y);
  3872. }
  3873. else
  3874. {
  3875. break;
  3876. }
  3877. }
  3878. }
  3879. for (var i = 0; i < obj.Lines.Count; i++)
  3880. {
  3881. if (i == 0)
  3882. {
  3883. _model.ReplaceLine (startLine, obj.Lines [i]);
  3884. }
  3885. else if ((obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Removed)
  3886. || (!obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Added))
  3887. {
  3888. _model.AddLine (startLine, obj.Lines [i]);
  3889. }
  3890. else if (Lines > obj.CursorPosition.Y + 1)
  3891. {
  3892. _model.RemoveLine (obj.CursorPosition.Y + 1);
  3893. }
  3894. startLine++;
  3895. }
  3896. CursorPosition = obj.FinalCursorPosition;
  3897. }
  3898. UpdateWrapModel ();
  3899. Adjust ();
  3900. OnContentsChanged ();
  3901. }
  3902. private void Insert (RuneCell cell)
  3903. {
  3904. List<RuneCell> line = GetCurrentLine ();
  3905. if (Used)
  3906. {
  3907. line.Insert (Math.Min (CurrentColumn, line.Count), cell);
  3908. }
  3909. else
  3910. {
  3911. if (CurrentColumn < line.Count)
  3912. {
  3913. line.RemoveAt (CurrentColumn);
  3914. }
  3915. line.Insert (Math.Min (CurrentColumn, line.Count), cell);
  3916. }
  3917. int prow = CurrentRow - _topRow;
  3918. if (!_wrapNeeded)
  3919. {
  3920. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3921. //SetNeedsDisplay (new (0, prow, Math.Max (Viewport.Width, 0), Math.Max (prow + 1, 0)));
  3922. SetNeedsDisplay ();
  3923. }
  3924. }
  3925. private void InsertAllText (string text)
  3926. {
  3927. if (string.IsNullOrEmpty (text))
  3928. {
  3929. return;
  3930. }
  3931. List<List<RuneCell>> lines = TextModel.StringToLinesOfRuneCells (text);
  3932. if (lines.Count == 0)
  3933. {
  3934. return;
  3935. }
  3936. SetWrapModel ();
  3937. List<RuneCell> line = GetCurrentLine ();
  3938. _historyText.Add (new () { new (line) }, CursorPosition);
  3939. // Optimize single line
  3940. if (lines.Count == 1)
  3941. {
  3942. line.InsertRange (CurrentColumn, lines [0]);
  3943. CurrentColumn += lines [0].Count;
  3944. _historyText.Add (
  3945. new () { new (line) },
  3946. CursorPosition,
  3947. HistoryText.LineStatus.Replaced
  3948. );
  3949. if (!_wordWrap && CurrentColumn - _leftColumn > Viewport.Width)
  3950. {
  3951. _leftColumn = Math.Max (CurrentColumn - Viewport.Width + 1, 0);
  3952. }
  3953. if (_wordWrap)
  3954. {
  3955. SetNeedsDisplay ();
  3956. }
  3957. else
  3958. {
  3959. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3960. //SetNeedsDisplay (new (0, currentRow - topRow, Viewport.Width, Math.Max (currentRow - topRow + 1, 0)));
  3961. SetNeedsDisplay ();
  3962. }
  3963. UpdateWrapModel ();
  3964. OnContentsChanged ();
  3965. return;
  3966. }
  3967. List<RuneCell>? rest = null;
  3968. var lastp = 0;
  3969. if (_model.Count > 0 && line.Count > 0 && !_copyWithoutSelection)
  3970. {
  3971. // Keep a copy of the rest of the line
  3972. int restCount = line.Count - CurrentColumn;
  3973. rest = line.GetRange (CurrentColumn, restCount);
  3974. line.RemoveRange (CurrentColumn, restCount);
  3975. }
  3976. // First line is inserted at the current location, the rest is appended
  3977. line.InsertRange (CurrentColumn, lines [0]);
  3978. //model.AddLine (currentRow, lines [0]);
  3979. List<List<RuneCell>> addedLines = new () { new (line) };
  3980. for (var i = 1; i < lines.Count; i++)
  3981. {
  3982. _model.AddLine (CurrentRow + i, lines [i]);
  3983. addedLines.Add (new (lines [i]));
  3984. }
  3985. if (rest is { })
  3986. {
  3987. List<RuneCell> last = _model.GetLine (CurrentRow + lines.Count - 1);
  3988. lastp = last.Count;
  3989. last.InsertRange (last.Count, rest);
  3990. addedLines.Last ().InsertRange (addedLines.Last ().Count, rest);
  3991. }
  3992. _historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  3993. // Now adjust column and row positions
  3994. CurrentRow += lines.Count - 1;
  3995. CurrentColumn = rest is { } ? lastp : lines [lines.Count - 1].Count;
  3996. Adjust ();
  3997. _historyText.Add (
  3998. new () { new (line) },
  3999. CursorPosition,
  4000. HistoryText.LineStatus.Replaced
  4001. );
  4002. UpdateWrapModel ();
  4003. OnContentsChanged ();
  4004. }
  4005. private bool InsertText (Key a, ColorScheme? colorScheme = null)
  4006. {
  4007. //So that special keys like tab can be processed
  4008. if (_isReadOnly)
  4009. {
  4010. return true;
  4011. }
  4012. SetWrapModel ();
  4013. _historyText.Add (new () { new (GetCurrentLine ()) }, CursorPosition);
  4014. if (IsSelecting)
  4015. {
  4016. ClearSelectedRegion ();
  4017. }
  4018. if ((uint)a.KeyCode == '\n')
  4019. {
  4020. _model.AddLine (CurrentRow + 1, new ());
  4021. CurrentRow++;
  4022. CurrentColumn = 0;
  4023. }
  4024. else if ((uint)a.KeyCode == '\r')
  4025. {
  4026. CurrentColumn = 0;
  4027. }
  4028. else
  4029. {
  4030. if (Used)
  4031. {
  4032. Insert (new () { Rune = a.AsRune, ColorScheme = colorScheme });
  4033. CurrentColumn++;
  4034. if (CurrentColumn >= _leftColumn + Viewport.Width)
  4035. {
  4036. _leftColumn++;
  4037. SetNeedsDisplay ();
  4038. }
  4039. }
  4040. else
  4041. {
  4042. Insert (new () { Rune = a.AsRune, ColorScheme = colorScheme });
  4043. CurrentColumn++;
  4044. }
  4045. }
  4046. _historyText.Add (
  4047. new () { new (GetCurrentLine ()) },
  4048. CursorPosition,
  4049. HistoryText.LineStatus.Replaced
  4050. );
  4051. UpdateWrapModel ();
  4052. OnContentsChanged ();
  4053. return true;
  4054. }
  4055. private void KillToEndOfLine ()
  4056. {
  4057. if (_isReadOnly)
  4058. {
  4059. return;
  4060. }
  4061. if (_model.Count == 1 && GetCurrentLine ().Count == 0)
  4062. {
  4063. // Prevents from adding line feeds if there is no more lines.
  4064. return;
  4065. }
  4066. SetWrapModel ();
  4067. List<RuneCell> currentLine = GetCurrentLine ();
  4068. var setLastWasKill = true;
  4069. if (currentLine.Count > 0 && CurrentColumn == currentLine.Count)
  4070. {
  4071. UpdateWrapModel ();
  4072. DeleteTextForwards ();
  4073. return;
  4074. }
  4075. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  4076. if (currentLine.Count == 0)
  4077. {
  4078. if (CurrentRow < _model.Count - 1)
  4079. {
  4080. List<List<RuneCell>> removedLines = new () { new (currentLine) };
  4081. _model.RemoveLine (CurrentRow);
  4082. removedLines.Add (new (GetCurrentLine ()));
  4083. _historyText.Add (
  4084. new (removedLines),
  4085. CursorPosition,
  4086. HistoryText.LineStatus.Removed
  4087. );
  4088. }
  4089. if (_model.Count > 0 || _lastWasKill)
  4090. {
  4091. string val = Environment.NewLine;
  4092. if (_lastWasKill)
  4093. {
  4094. AppendClipboard (val);
  4095. }
  4096. else
  4097. {
  4098. SetClipboard (val);
  4099. }
  4100. }
  4101. if (_model.Count == 0)
  4102. {
  4103. // Prevents from adding line feeds if there is no more lines.
  4104. setLastWasKill = false;
  4105. }
  4106. }
  4107. else
  4108. {
  4109. int restCount = currentLine.Count - CurrentColumn;
  4110. List<RuneCell> rest = currentLine.GetRange (CurrentColumn, restCount);
  4111. var val = string.Empty;
  4112. val += StringFromRunes (rest);
  4113. if (_lastWasKill)
  4114. {
  4115. AppendClipboard (val);
  4116. }
  4117. else
  4118. {
  4119. SetClipboard (val);
  4120. }
  4121. currentLine.RemoveRange (CurrentColumn, restCount);
  4122. }
  4123. _historyText.Add (
  4124. [ [.. GetCurrentLine ()]],
  4125. CursorPosition,
  4126. HistoryText.LineStatus.Replaced
  4127. );
  4128. UpdateWrapModel ();
  4129. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4130. _lastWasKill = setLastWasKill;
  4131. DoNeededAction ();
  4132. }
  4133. private void KillToLeftStart ()
  4134. {
  4135. if (_isReadOnly)
  4136. {
  4137. return;
  4138. }
  4139. if (_model.Count == 1 && GetCurrentLine ().Count == 0)
  4140. {
  4141. // Prevents from adding line feeds if there is no more lines.
  4142. return;
  4143. }
  4144. SetWrapModel ();
  4145. List<RuneCell> currentLine = GetCurrentLine ();
  4146. var setLastWasKill = true;
  4147. if (currentLine.Count > 0 && CurrentColumn == 0)
  4148. {
  4149. UpdateWrapModel ();
  4150. DeleteTextBackwards ();
  4151. return;
  4152. }
  4153. _historyText.Add ([ [.. currentLine]], CursorPosition);
  4154. if (currentLine.Count == 0)
  4155. {
  4156. if (CurrentRow > 0)
  4157. {
  4158. _model.RemoveLine (CurrentRow);
  4159. if (_model.Count > 0 || _lastWasKill)
  4160. {
  4161. string val = Environment.NewLine;
  4162. if (_lastWasKill)
  4163. {
  4164. AppendClipboard (val);
  4165. }
  4166. else
  4167. {
  4168. SetClipboard (val);
  4169. }
  4170. }
  4171. if (_model.Count == 0)
  4172. {
  4173. // Prevents from adding line feeds if there is no more lines.
  4174. setLastWasKill = false;
  4175. }
  4176. CurrentRow--;
  4177. currentLine = _model.GetLine (CurrentRow);
  4178. List<List<RuneCell>> removedLine =
  4179. [
  4180. [..currentLine],
  4181. []
  4182. ];
  4183. _historyText.Add (
  4184. [.. removedLine],
  4185. CursorPosition,
  4186. HistoryText.LineStatus.Removed
  4187. );
  4188. CurrentColumn = currentLine.Count;
  4189. }
  4190. }
  4191. else
  4192. {
  4193. int restCount = CurrentColumn;
  4194. List<RuneCell> rest = currentLine.GetRange (0, restCount);
  4195. var val = string.Empty;
  4196. val += StringFromRunes (rest);
  4197. if (_lastWasKill)
  4198. {
  4199. AppendClipboard (val);
  4200. }
  4201. else
  4202. {
  4203. SetClipboard (val);
  4204. }
  4205. currentLine.RemoveRange (0, restCount);
  4206. CurrentColumn = 0;
  4207. }
  4208. _historyText.Add (
  4209. [ [.. GetCurrentLine ()]],
  4210. CursorPosition,
  4211. HistoryText.LineStatus.Replaced
  4212. );
  4213. UpdateWrapModel ();
  4214. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4215. _lastWasKill = setLastWasKill;
  4216. DoNeededAction ();
  4217. }
  4218. private void KillWordBackward ()
  4219. {
  4220. if (_isReadOnly)
  4221. {
  4222. return;
  4223. }
  4224. SetWrapModel ();
  4225. List<RuneCell> currentLine = GetCurrentLine ();
  4226. _historyText.Add ([ [.. GetCurrentLine ()]], CursorPosition);
  4227. if (CurrentColumn == 0)
  4228. {
  4229. DeleteTextBackwards ();
  4230. _historyText.ReplaceLast (
  4231. [ [.. GetCurrentLine ()]],
  4232. CursorPosition,
  4233. HistoryText.LineStatus.Replaced
  4234. );
  4235. UpdateWrapModel ();
  4236. return;
  4237. }
  4238. (int col, int row)? newPos = _model.WordBackward (CurrentColumn, CurrentRow);
  4239. if (newPos.HasValue && CurrentRow == newPos.Value.row)
  4240. {
  4241. int restCount = CurrentColumn - newPos.Value.col;
  4242. currentLine.RemoveRange (newPos.Value.col, restCount);
  4243. if (_wordWrap)
  4244. {
  4245. _wrapNeeded = true;
  4246. }
  4247. CurrentColumn = newPos.Value.col;
  4248. }
  4249. else if (newPos.HasValue)
  4250. {
  4251. int restCount = currentLine.Count - CurrentColumn;
  4252. currentLine.RemoveRange (CurrentColumn, restCount);
  4253. if (_wordWrap)
  4254. {
  4255. _wrapNeeded = true;
  4256. }
  4257. CurrentColumn = newPos.Value.col;
  4258. CurrentRow = newPos.Value.row;
  4259. }
  4260. _historyText.Add (
  4261. [ [.. GetCurrentLine ()]],
  4262. CursorPosition,
  4263. HistoryText.LineStatus.Replaced
  4264. );
  4265. UpdateWrapModel ();
  4266. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4267. DoNeededAction ();
  4268. }
  4269. private void KillWordForward ()
  4270. {
  4271. if (_isReadOnly)
  4272. {
  4273. return;
  4274. }
  4275. SetWrapModel ();
  4276. List<RuneCell> currentLine = GetCurrentLine ();
  4277. _historyText.Add ([ [.. GetCurrentLine ()]], CursorPosition);
  4278. if (currentLine.Count == 0 || CurrentColumn == currentLine.Count)
  4279. {
  4280. DeleteTextForwards ();
  4281. _historyText.ReplaceLast (
  4282. [ [.. GetCurrentLine ()]],
  4283. CursorPosition,
  4284. HistoryText.LineStatus.Replaced
  4285. );
  4286. UpdateWrapModel ();
  4287. return;
  4288. }
  4289. (int col, int row)? newPos = _model.WordForward (CurrentColumn, CurrentRow);
  4290. var restCount = 0;
  4291. if (newPos.HasValue && CurrentRow == newPos.Value.row)
  4292. {
  4293. restCount = newPos.Value.col - CurrentColumn;
  4294. currentLine.RemoveRange (CurrentColumn, restCount);
  4295. }
  4296. else if (newPos.HasValue)
  4297. {
  4298. restCount = currentLine.Count - CurrentColumn;
  4299. currentLine.RemoveRange (CurrentColumn, restCount);
  4300. }
  4301. if (_wordWrap)
  4302. {
  4303. _wrapNeeded = true;
  4304. }
  4305. _historyText.Add (
  4306. [ [.. GetCurrentLine ()]],
  4307. CursorPosition,
  4308. HistoryText.LineStatus.Replaced
  4309. );
  4310. UpdateWrapModel ();
  4311. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4312. DoNeededAction ();
  4313. }
  4314. private void Model_LinesLoaded (object sender, EventArgs e)
  4315. {
  4316. // This call is not needed. Model_LinesLoaded gets invoked when
  4317. // model.LoadString (value) is called. LoadString is called from one place
  4318. // (Text.set) and historyText.Clear() is called immediately after.
  4319. // If this call happens, HistoryText_ChangeText will get called multiple times
  4320. // when Text is set, which is wrong.
  4321. //historyText.Clear (Text);
  4322. if (!_multiline && !IsInitialized)
  4323. {
  4324. CurrentColumn = Text.GetRuneCount ();
  4325. _leftColumn = CurrentColumn > Viewport.Width + 1 ? CurrentColumn - Viewport.Width + 1 : 0;
  4326. }
  4327. }
  4328. private void MoveBottomEnd ()
  4329. {
  4330. ResetAllTrack ();
  4331. if (_shiftSelecting && IsSelecting)
  4332. {
  4333. StopSelecting ();
  4334. }
  4335. MoveEnd ();
  4336. }
  4337. private void MoveBottomEndExtend ()
  4338. {
  4339. ResetAllTrack ();
  4340. StartSelecting ();
  4341. MoveEnd ();
  4342. }
  4343. private bool MoveDown ()
  4344. {
  4345. if (CurrentRow + 1 < _model.Count)
  4346. {
  4347. if (_columnTrack == -1)
  4348. {
  4349. _columnTrack = CurrentColumn;
  4350. }
  4351. CurrentRow++;
  4352. if (CurrentRow >= _topRow + Viewport.Height)
  4353. {
  4354. _topRow++;
  4355. SetNeedsDisplay ();
  4356. }
  4357. TrackColumn ();
  4358. PositionCursor ();
  4359. }
  4360. else if (CurrentRow > Viewport.Height)
  4361. {
  4362. Adjust ();
  4363. }
  4364. else
  4365. {
  4366. return false;
  4367. }
  4368. DoNeededAction ();
  4369. return true;
  4370. }
  4371. private void MoveEndOfLine ()
  4372. {
  4373. List<RuneCell> currentLine = GetCurrentLine ();
  4374. CurrentColumn = Math.Max (currentLine.Count - (ReadOnly ? 1 : 0), 0);
  4375. Adjust ();
  4376. DoNeededAction ();
  4377. }
  4378. private bool MoveLeft ()
  4379. {
  4380. if (CurrentColumn > 0)
  4381. {
  4382. CurrentColumn--;
  4383. }
  4384. else
  4385. {
  4386. if (CurrentRow > 0)
  4387. {
  4388. CurrentRow--;
  4389. if (CurrentRow < _topRow)
  4390. {
  4391. _topRow--;
  4392. SetNeedsDisplay ();
  4393. }
  4394. List<RuneCell> currentLine = GetCurrentLine ();
  4395. CurrentColumn = Math.Max (currentLine.Count - (ReadOnly ? 1 : 0), 0);
  4396. }
  4397. else
  4398. {
  4399. return false;
  4400. }
  4401. }
  4402. Adjust ();
  4403. DoNeededAction ();
  4404. return true;
  4405. }
  4406. private void MovePageDown ()
  4407. {
  4408. int nPageDnShift = Viewport.Height - 1;
  4409. if (CurrentRow >= 0 && CurrentRow < _model.Count)
  4410. {
  4411. if (_columnTrack == -1)
  4412. {
  4413. _columnTrack = CurrentColumn;
  4414. }
  4415. CurrentRow = CurrentRow + nPageDnShift > _model.Count
  4416. ? _model.Count > 0 ? _model.Count - 1 : 0
  4417. : CurrentRow + nPageDnShift;
  4418. if (_topRow < CurrentRow - nPageDnShift)
  4419. {
  4420. _topRow = CurrentRow >= _model.Count
  4421. ? CurrentRow - nPageDnShift
  4422. : _topRow + nPageDnShift;
  4423. SetNeedsDisplay ();
  4424. }
  4425. TrackColumn ();
  4426. PositionCursor ();
  4427. }
  4428. DoNeededAction ();
  4429. }
  4430. private void MovePageUp ()
  4431. {
  4432. int nPageUpShift = Viewport.Height - 1;
  4433. if (CurrentRow > 0)
  4434. {
  4435. if (_columnTrack == -1)
  4436. {
  4437. _columnTrack = CurrentColumn;
  4438. }
  4439. CurrentRow = CurrentRow - nPageUpShift < 0 ? 0 : CurrentRow - nPageUpShift;
  4440. if (CurrentRow < _topRow)
  4441. {
  4442. _topRow = _topRow - nPageUpShift < 0 ? 0 : _topRow - nPageUpShift;
  4443. SetNeedsDisplay ();
  4444. }
  4445. TrackColumn ();
  4446. PositionCursor ();
  4447. }
  4448. DoNeededAction ();
  4449. }
  4450. private bool MoveRight ()
  4451. {
  4452. List<RuneCell> currentLine = GetCurrentLine ();
  4453. if ((ReadOnly ? CurrentColumn + 1 : CurrentColumn) < currentLine.Count)
  4454. {
  4455. CurrentColumn++;
  4456. }
  4457. else
  4458. {
  4459. if (CurrentRow + 1 < _model.Count)
  4460. {
  4461. CurrentRow++;
  4462. CurrentColumn = 0;
  4463. if (CurrentRow >= _topRow + Viewport.Height)
  4464. {
  4465. _topRow++;
  4466. SetNeedsDisplay ();
  4467. }
  4468. else
  4469. {
  4470. return false;
  4471. }
  4472. }
  4473. else
  4474. {
  4475. return false;
  4476. }
  4477. }
  4478. Adjust ();
  4479. DoNeededAction ();
  4480. return true;
  4481. }
  4482. private void MoveLeftStart ()
  4483. {
  4484. if (_leftColumn > 0)
  4485. {
  4486. SetNeedsDisplay ();
  4487. }
  4488. CurrentColumn = 0;
  4489. _leftColumn = 0;
  4490. Adjust ();
  4491. DoNeededAction ();
  4492. }
  4493. private void MoveTopHome ()
  4494. {
  4495. ResetAllTrack ();
  4496. if (_shiftSelecting && IsSelecting)
  4497. {
  4498. StopSelecting ();
  4499. }
  4500. MoveHome ();
  4501. }
  4502. private void MoveTopHomeExtend ()
  4503. {
  4504. ResetColumnTrack ();
  4505. StartSelecting ();
  4506. MoveHome ();
  4507. }
  4508. private bool MoveUp ()
  4509. {
  4510. if (CurrentRow > 0)
  4511. {
  4512. if (_columnTrack == -1)
  4513. {
  4514. _columnTrack = CurrentColumn;
  4515. }
  4516. CurrentRow--;
  4517. if (CurrentRow < _topRow)
  4518. {
  4519. _topRow--;
  4520. SetNeedsDisplay ();
  4521. }
  4522. TrackColumn ();
  4523. PositionCursor ();
  4524. }
  4525. else
  4526. {
  4527. return false;
  4528. }
  4529. DoNeededAction ();
  4530. return true;
  4531. }
  4532. private void MoveWordBackward ()
  4533. {
  4534. (int col, int row)? newPos = _model.WordBackward (CurrentColumn, CurrentRow);
  4535. if (newPos.HasValue)
  4536. {
  4537. CurrentColumn = newPos.Value.col;
  4538. CurrentRow = newPos.Value.row;
  4539. }
  4540. Adjust ();
  4541. DoNeededAction ();
  4542. }
  4543. private void MoveWordForward ()
  4544. {
  4545. (int col, int row)? newPos = _model.WordForward (CurrentColumn, CurrentRow);
  4546. if (newPos.HasValue)
  4547. {
  4548. CurrentColumn = newPos.Value.col;
  4549. CurrentRow = newPos.Value.row;
  4550. }
  4551. Adjust ();
  4552. DoNeededAction ();
  4553. }
  4554. private (int width, int height) OffSetBackground ()
  4555. {
  4556. var w = 0;
  4557. var h = 0;
  4558. if (SuperView?.Viewport.Right - Viewport.Right < 0)
  4559. {
  4560. w = SuperView!.Viewport.Right - Viewport.Right - 1;
  4561. }
  4562. if (SuperView?.Viewport.Bottom - Viewport.Bottom < 0)
  4563. {
  4564. h = SuperView!.Viewport.Bottom - Viewport.Bottom - 1;
  4565. }
  4566. return (w, h);
  4567. }
  4568. private bool PointInSelection (int col, int row)
  4569. {
  4570. long start, end;
  4571. GetEncodedRegionBounds (out start, out end);
  4572. long q = ((long)(uint)row << 32) | (uint)col;
  4573. return q >= start && q <= end - 1;
  4574. }
  4575. private void ProcessAutocomplete ()
  4576. {
  4577. if (_isDrawing)
  4578. {
  4579. return;
  4580. }
  4581. if (_clickWithSelecting)
  4582. {
  4583. _clickWithSelecting = false;
  4584. return;
  4585. }
  4586. if (SelectedLength > 0)
  4587. {
  4588. return;
  4589. }
  4590. // draw autocomplete
  4591. GenerateSuggestions ();
  4592. var renderAt = new Point (
  4593. Autocomplete.Context.CursorPosition,
  4594. Autocomplete.PopupInsideContainer
  4595. ? CursorPosition.Y + 1 - TopRow
  4596. : 0
  4597. );
  4598. Autocomplete.RenderOverlay (renderAt);
  4599. }
  4600. private bool ProcessBackTab ()
  4601. {
  4602. ResetColumnTrack ();
  4603. if (!AllowsTab || _isReadOnly)
  4604. {
  4605. return false;
  4606. }
  4607. if (CurrentColumn > 0)
  4608. {
  4609. SetWrapModel ();
  4610. List<RuneCell> currentLine = GetCurrentLine ();
  4611. if (currentLine.Count > 0 && currentLine [CurrentColumn - 1].Rune.Value == '\t')
  4612. {
  4613. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  4614. currentLine.RemoveAt (CurrentColumn - 1);
  4615. CurrentColumn--;
  4616. _historyText.Add (
  4617. new () { new (GetCurrentLine ()) },
  4618. CursorPosition,
  4619. HistoryText.LineStatus.Replaced
  4620. );
  4621. }
  4622. SetNeedsDisplay ();
  4623. UpdateWrapModel ();
  4624. }
  4625. DoNeededAction ();
  4626. return true;
  4627. }
  4628. private void ProcessCopy ()
  4629. {
  4630. ResetColumnTrack ();
  4631. Copy ();
  4632. }
  4633. private void ProcessCut ()
  4634. {
  4635. ResetColumnTrack ();
  4636. Cut ();
  4637. }
  4638. private void ProcessDeleteCharLeft ()
  4639. {
  4640. ResetColumnTrack ();
  4641. DeleteCharLeft ();
  4642. }
  4643. private void ProcessDeleteCharRight ()
  4644. {
  4645. ResetColumnTrack ();
  4646. DeleteCharRight ();
  4647. }
  4648. // If InheritsPreviousColorScheme is enabled this method will check if the rune cell on
  4649. // the row and col location and around has a not null color scheme. If it's null will set it with
  4650. // the very most previous valid color scheme.
  4651. private void ProcessInheritsPreviousColorScheme (int row, int col)
  4652. {
  4653. if (!InheritsPreviousColorScheme || (Lines == 1 && GetLine (Lines).Count == 0))
  4654. {
  4655. return;
  4656. }
  4657. List<RuneCell> line = GetLine (row);
  4658. List<RuneCell> lineToSet = line;
  4659. while (line.Count == 0)
  4660. {
  4661. if (row == 0 && line.Count == 0)
  4662. {
  4663. return;
  4664. }
  4665. row--;
  4666. line = GetLine (row);
  4667. lineToSet = line;
  4668. }
  4669. int colWithColor = Math.Max (Math.Min (col - 2, line.Count - 1), 0);
  4670. RuneCell cell = line [colWithColor];
  4671. int colWithoutColor = Math.Max (col - 1, 0);
  4672. if (cell.ColorScheme is { } && colWithColor == 0 && lineToSet [colWithoutColor].ColorScheme is { })
  4673. {
  4674. for (int r = row - 1; r > -1; r--)
  4675. {
  4676. List<RuneCell> l = GetLine (r);
  4677. for (int c = l.Count - 1; c > -1; c--)
  4678. {
  4679. if (l [c].ColorScheme is null)
  4680. {
  4681. l [c].ColorScheme = cell.ColorScheme;
  4682. }
  4683. else
  4684. {
  4685. return;
  4686. }
  4687. }
  4688. }
  4689. return;
  4690. }
  4691. if (cell.ColorScheme is null)
  4692. {
  4693. for (int r = row; r > -1; r--)
  4694. {
  4695. List<RuneCell> l = GetLine (r);
  4696. colWithColor = l.FindLastIndex (
  4697. colWithColor > -1 ? colWithColor : l.Count - 1,
  4698. rc => rc.ColorScheme != null
  4699. );
  4700. if (colWithColor > -1 && l [colWithColor].ColorScheme is { })
  4701. {
  4702. cell = l [colWithColor];
  4703. break;
  4704. }
  4705. }
  4706. }
  4707. else
  4708. {
  4709. int cRow = row;
  4710. while (cell.ColorScheme is null)
  4711. {
  4712. if ((colWithColor == 0 || cell.ColorScheme is null) && cRow > 0)
  4713. {
  4714. line = GetLine (--cRow);
  4715. colWithColor = line.Count - 1;
  4716. cell = line [colWithColor];
  4717. }
  4718. else if (cRow == 0 && colWithColor < line.Count)
  4719. {
  4720. cell = line [colWithColor + 1];
  4721. }
  4722. }
  4723. }
  4724. if (cell.ColorScheme is { } && colWithColor > -1 && colWithoutColor < lineToSet.Count && lineToSet [colWithoutColor].ColorScheme is null)
  4725. {
  4726. while (lineToSet [colWithoutColor].ColorScheme is null)
  4727. {
  4728. lineToSet [colWithoutColor].ColorScheme = cell.ColorScheme;
  4729. colWithoutColor--;
  4730. if (colWithoutColor == -1 && row > 0)
  4731. {
  4732. lineToSet = GetLine (--row);
  4733. colWithoutColor = lineToSet.Count - 1;
  4734. }
  4735. }
  4736. }
  4737. }
  4738. private void ProcessKillWordBackward ()
  4739. {
  4740. ResetColumnTrack ();
  4741. KillWordBackward ();
  4742. }
  4743. private void ProcessKillWordForward ()
  4744. {
  4745. ResetColumnTrack ();
  4746. KillWordForward ();
  4747. }
  4748. private void ProcessMouseClick (MouseEvent ev, out List<RuneCell> line)
  4749. {
  4750. List<RuneCell>? r = null;
  4751. if (_model.Count > 0)
  4752. {
  4753. int maxCursorPositionableLine = Math.Max (_model.Count - 1 - _topRow, 0);
  4754. if (Math.Max (ev.Position.Y, 0) > maxCursorPositionableLine)
  4755. {
  4756. CurrentRow = maxCursorPositionableLine + _topRow;
  4757. }
  4758. else
  4759. {
  4760. CurrentRow = Math.Max (ev.Position.Y + _topRow, 0);
  4761. }
  4762. r = GetCurrentLine ();
  4763. int idx = TextModel.GetColFromX (r, _leftColumn, Math.Max (ev.Position.X, 0), TabWidth);
  4764. if (idx - _leftColumn >= r.Count)
  4765. {
  4766. CurrentColumn = Math.Max (r.Count - _leftColumn - (ReadOnly ? 1 : 0), 0);
  4767. }
  4768. else
  4769. {
  4770. CurrentColumn = idx + _leftColumn;
  4771. }
  4772. }
  4773. line = r!;
  4774. }
  4775. private bool ProcessMoveDown ()
  4776. {
  4777. ResetContinuousFindTrack ();
  4778. if (_shiftSelecting && IsSelecting)
  4779. {
  4780. StopSelecting ();
  4781. }
  4782. return MoveDown ();
  4783. }
  4784. private void ProcessMoveDownExtend ()
  4785. {
  4786. ResetColumnTrack ();
  4787. StartSelecting ();
  4788. MoveDown ();
  4789. }
  4790. private void ProcessMoveEndOfLine ()
  4791. {
  4792. ResetAllTrack ();
  4793. if (_shiftSelecting && IsSelecting)
  4794. {
  4795. StopSelecting ();
  4796. }
  4797. MoveEndOfLine ();
  4798. }
  4799. private void ProcessMoveRightEndExtend ()
  4800. {
  4801. ResetAllTrack ();
  4802. StartSelecting ();
  4803. MoveEndOfLine ();
  4804. }
  4805. private bool ProcessMoveLeft ()
  4806. {
  4807. // if the user presses Left (without any control keys) and they are at the start of the text
  4808. if (CurrentColumn == 0 && CurrentRow == 0)
  4809. {
  4810. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  4811. return false;
  4812. }
  4813. ResetAllTrack ();
  4814. if (_shiftSelecting && IsSelecting)
  4815. {
  4816. StopSelecting ();
  4817. }
  4818. MoveLeft ();
  4819. return true;
  4820. }
  4821. private void ProcessMoveLeftExtend ()
  4822. {
  4823. ResetAllTrack ();
  4824. StartSelecting ();
  4825. MoveLeft ();
  4826. }
  4827. private bool ProcessMoveRight ()
  4828. {
  4829. // if the user presses Right (without any control keys)
  4830. // determine where the last cursor position in the text is
  4831. int lastRow = _model.Count - 1;
  4832. int lastCol = _model.GetLine (lastRow).Count;
  4833. // if they are at the very end of all the text do not respond (this lets the key press fall through to navigation system - which usually changes focus forward)
  4834. if (CurrentColumn == lastCol && CurrentRow == lastRow)
  4835. {
  4836. return false;
  4837. }
  4838. ResetAllTrack ();
  4839. if (_shiftSelecting && IsSelecting)
  4840. {
  4841. StopSelecting ();
  4842. }
  4843. MoveRight ();
  4844. return true;
  4845. }
  4846. private void ProcessMoveRightExtend ()
  4847. {
  4848. ResetAllTrack ();
  4849. StartSelecting ();
  4850. MoveRight ();
  4851. }
  4852. private void ProcessMoveLeftStart ()
  4853. {
  4854. ResetAllTrack ();
  4855. if (_shiftSelecting && IsSelecting)
  4856. {
  4857. StopSelecting ();
  4858. }
  4859. MoveLeftStart ();
  4860. }
  4861. private void ProcessMoveLeftStartExtend ()
  4862. {
  4863. ResetAllTrack ();
  4864. StartSelecting ();
  4865. MoveLeftStart ();
  4866. }
  4867. private bool ProcessMoveUp ()
  4868. {
  4869. ResetContinuousFindTrack ();
  4870. if (_shiftSelecting && IsSelecting)
  4871. {
  4872. StopSelecting ();
  4873. }
  4874. return MoveUp ();
  4875. }
  4876. private void ProcessMoveUpExtend ()
  4877. {
  4878. ResetColumnTrack ();
  4879. StartSelecting ();
  4880. MoveUp ();
  4881. }
  4882. private void ProcessMoveWordBackward ()
  4883. {
  4884. ResetAllTrack ();
  4885. if (_shiftSelecting && IsSelecting)
  4886. {
  4887. StopSelecting ();
  4888. }
  4889. MoveWordBackward ();
  4890. }
  4891. private void ProcessMoveWordBackwardExtend ()
  4892. {
  4893. ResetAllTrack ();
  4894. StartSelecting ();
  4895. MoveWordBackward ();
  4896. }
  4897. private void ProcessMoveWordForward ()
  4898. {
  4899. ResetAllTrack ();
  4900. if (_shiftSelecting && IsSelecting)
  4901. {
  4902. StopSelecting ();
  4903. }
  4904. MoveWordForward ();
  4905. }
  4906. private void ProcessMoveWordForwardExtend ()
  4907. {
  4908. ResetAllTrack ();
  4909. StartSelecting ();
  4910. MoveWordForward ();
  4911. }
  4912. private void ProcessPageDown ()
  4913. {
  4914. ResetColumnTrack ();
  4915. if (_shiftSelecting && IsSelecting)
  4916. {
  4917. StopSelecting ();
  4918. }
  4919. MovePageDown ();
  4920. }
  4921. private void ProcessPageDownExtend ()
  4922. {
  4923. ResetColumnTrack ();
  4924. StartSelecting ();
  4925. MovePageDown ();
  4926. }
  4927. private void ProcessPageUp ()
  4928. {
  4929. ResetColumnTrack ();
  4930. if (_shiftSelecting && IsSelecting)
  4931. {
  4932. StopSelecting ();
  4933. }
  4934. MovePageUp ();
  4935. }
  4936. private void ProcessPageUpExtend ()
  4937. {
  4938. ResetColumnTrack ();
  4939. StartSelecting ();
  4940. MovePageUp ();
  4941. }
  4942. private void ProcessPaste ()
  4943. {
  4944. ResetColumnTrack ();
  4945. if (_isReadOnly)
  4946. {
  4947. return;
  4948. }
  4949. Paste ();
  4950. }
  4951. private bool ProcessEnterKey (CommandContext ctx)
  4952. {
  4953. ResetColumnTrack ();
  4954. if (_isReadOnly)
  4955. {
  4956. return false;
  4957. }
  4958. if (!AllowsReturn)
  4959. {
  4960. // By Default pressing ENTER should be ignored (OnAccept will return false or null). Only cancel if the
  4961. // event was fired and set Cancel = true.
  4962. return RaiseAccepting (ctx) is null or false;
  4963. }
  4964. SetWrapModel ();
  4965. List<RuneCell> currentLine = GetCurrentLine ();
  4966. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  4967. if (IsSelecting)
  4968. {
  4969. ClearSelectedRegion ();
  4970. currentLine = GetCurrentLine ();
  4971. }
  4972. int restCount = currentLine.Count - CurrentColumn;
  4973. List<RuneCell> rest = currentLine.GetRange (CurrentColumn, restCount);
  4974. currentLine.RemoveRange (CurrentColumn, restCount);
  4975. List<List<RuneCell>> addedLines = new () { new (currentLine) };
  4976. _model.AddLine (CurrentRow + 1, rest);
  4977. addedLines.Add (new (_model.GetLine (CurrentRow + 1)));
  4978. _historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  4979. CurrentRow++;
  4980. var fullNeedsDisplay = false;
  4981. if (CurrentRow >= _topRow + Viewport.Height)
  4982. {
  4983. _topRow++;
  4984. fullNeedsDisplay = true;
  4985. }
  4986. CurrentColumn = 0;
  4987. _historyText.Add (
  4988. new () { new (GetCurrentLine ()) },
  4989. CursorPosition,
  4990. HistoryText.LineStatus.Replaced
  4991. );
  4992. if (!_wordWrap && CurrentColumn < _leftColumn)
  4993. {
  4994. fullNeedsDisplay = true;
  4995. _leftColumn = 0;
  4996. }
  4997. if (fullNeedsDisplay)
  4998. {
  4999. SetNeedsDisplay ();
  5000. }
  5001. else
  5002. {
  5003. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  5004. //SetNeedsDisplay (new (0, currentRow - topRow, 2, Viewport.Height));
  5005. SetNeedsDisplay ();
  5006. }
  5007. UpdateWrapModel ();
  5008. DoNeededAction ();
  5009. OnContentsChanged ();
  5010. return true;
  5011. }
  5012. private void ProcessSelectAll ()
  5013. {
  5014. ResetColumnTrack ();
  5015. SelectAll ();
  5016. }
  5017. private void ProcessSetOverwrite ()
  5018. {
  5019. ResetColumnTrack ();
  5020. SetOverwrite (!Used);
  5021. }
  5022. private bool ProcessTab ()
  5023. {
  5024. ResetColumnTrack ();
  5025. if (!AllowsTab || _isReadOnly)
  5026. {
  5027. return false;
  5028. }
  5029. InsertText (new Key ((KeyCode)'\t'));
  5030. DoNeededAction ();
  5031. return true;
  5032. }
  5033. private void ResetAllTrack ()
  5034. {
  5035. // Handle some state here - whether the last command was a kill
  5036. // operation and the column tracking (up/down)
  5037. _lastWasKill = false;
  5038. _columnTrack = -1;
  5039. _continuousFind = false;
  5040. }
  5041. private void ResetColumnTrack ()
  5042. {
  5043. // Handle some state here - whether the last command was a kill
  5044. // operation and the column tracking (up/down)
  5045. _lastWasKill = false;
  5046. _columnTrack = -1;
  5047. }
  5048. private void ResetContinuousFind ()
  5049. {
  5050. if (!_continuousFind)
  5051. {
  5052. int col = IsSelecting ? _selectionStartColumn : CurrentColumn;
  5053. int row = IsSelecting ? _selectionStartRow : CurrentRow;
  5054. _model.ResetContinuousFind (new (col, row));
  5055. }
  5056. }
  5057. private void ResetContinuousFindTrack ()
  5058. {
  5059. // Handle some state here - whether the last command was a kill
  5060. // operation and the column tracking (up/down)
  5061. _lastWasKill = false;
  5062. _continuousFind = false;
  5063. }
  5064. private void ResetPosition ()
  5065. {
  5066. _topRow = _leftColumn = CurrentRow = CurrentColumn = 0;
  5067. StopSelecting ();
  5068. }
  5069. private void SetClipboard (string text)
  5070. {
  5071. if (text is { })
  5072. {
  5073. Clipboard.Contents = text;
  5074. }
  5075. }
  5076. private bool SetFoundText (
  5077. string text,
  5078. (Point current, bool found) foundPos,
  5079. string? textToReplace = null,
  5080. bool replace = false,
  5081. bool replaceAll = false
  5082. )
  5083. {
  5084. if (foundPos.found)
  5085. {
  5086. StartSelecting ();
  5087. _selectionStartColumn = foundPos.current.X;
  5088. _selectionStartRow = foundPos.current.Y;
  5089. if (!replaceAll)
  5090. {
  5091. CurrentColumn = _selectionStartColumn + text.GetRuneCount ();
  5092. }
  5093. else
  5094. {
  5095. CurrentColumn = _selectionStartColumn + textToReplace!.GetRuneCount ();
  5096. }
  5097. CurrentRow = foundPos.current.Y;
  5098. if (!_isReadOnly && replace)
  5099. {
  5100. Adjust ();
  5101. ClearSelectedRegion ();
  5102. InsertAllText (textToReplace!);
  5103. StartSelecting ();
  5104. _selectionStartColumn = CurrentColumn - textToReplace!.GetRuneCount ();
  5105. }
  5106. else
  5107. {
  5108. UpdateWrapModel ();
  5109. SetNeedsDisplay ();
  5110. Adjust ();
  5111. }
  5112. _continuousFind = true;
  5113. return foundPos.found;
  5114. }
  5115. UpdateWrapModel ();
  5116. _continuousFind = false;
  5117. return foundPos.found;
  5118. }
  5119. private void SetOverwrite (bool overwrite)
  5120. {
  5121. Used = overwrite;
  5122. SetNeedsDisplay ();
  5123. DoNeededAction ();
  5124. }
  5125. private static void SetValidUsedColor (ColorScheme? colorScheme)
  5126. {
  5127. // BUGBUG: (v2 truecolor) This code depends on 8-bit color names; disabling for now
  5128. //if ((colorScheme!.HotNormal.Foreground & colorScheme.Focus.Background) == colorScheme.Focus.Foreground) {
  5129. Driver.SetAttribute (new (colorScheme!.Focus.Background, colorScheme!.Focus.Foreground));
  5130. }
  5131. /// <summary>Restore from original model.</summary>
  5132. private void SetWrapModel ([CallerMemberName] string? caller = null)
  5133. {
  5134. if (_currentCaller is { })
  5135. {
  5136. return;
  5137. }
  5138. if (_wordWrap)
  5139. {
  5140. _currentCaller = caller;
  5141. CurrentColumn = _wrapManager!.GetModelColFromWrappedLines (CurrentRow, CurrentColumn);
  5142. CurrentRow = _wrapManager.GetModelLineFromWrappedLines (CurrentRow);
  5143. _selectionStartColumn =
  5144. _wrapManager.GetModelColFromWrappedLines (_selectionStartRow, _selectionStartColumn);
  5145. _selectionStartRow = _wrapManager.GetModelLineFromWrappedLines (_selectionStartRow);
  5146. _model = _wrapManager.Model;
  5147. }
  5148. }
  5149. private void ShowContextMenu ()
  5150. {
  5151. if (!Equals (_currentCulture, Thread.CurrentThread.CurrentUICulture))
  5152. {
  5153. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  5154. }
  5155. ContextMenu!.Show (BuildContextMenuBarItem ());
  5156. }
  5157. private void StartSelecting ()
  5158. {
  5159. if (_shiftSelecting && IsSelecting)
  5160. {
  5161. return;
  5162. }
  5163. _shiftSelecting = true;
  5164. IsSelecting = true;
  5165. _selectionStartColumn = CurrentColumn;
  5166. _selectionStartRow = CurrentRow;
  5167. }
  5168. private void StopSelecting ()
  5169. {
  5170. _shiftSelecting = false;
  5171. IsSelecting = false;
  5172. _isButtonShift = false;
  5173. }
  5174. private string StringFromRunes (List<RuneCell> cells)
  5175. {
  5176. if (cells is null)
  5177. {
  5178. throw new ArgumentNullException (nameof (cells));
  5179. }
  5180. var size = 0;
  5181. foreach (RuneCell cell in cells)
  5182. {
  5183. size += cell.Rune.GetEncodingLength ();
  5184. }
  5185. var encoded = new byte [size];
  5186. var offset = 0;
  5187. foreach (RuneCell cell in cells)
  5188. {
  5189. offset += cell.Rune.Encode (encoded, offset);
  5190. }
  5191. return StringExtensions.ToString (encoded);
  5192. }
  5193. private void TextView_Added (object sender, SuperViewChangedEventArgs e)
  5194. {
  5195. if (Autocomplete.HostControl is null)
  5196. {
  5197. Autocomplete.HostControl = this;
  5198. }
  5199. }
  5200. private void TextView_Initialized (object sender, EventArgs e)
  5201. {
  5202. if (Autocomplete.HostControl is null)
  5203. {
  5204. Autocomplete.HostControl = this;
  5205. }
  5206. OnContentsChanged ();
  5207. }
  5208. private void TextView_LayoutComplete (object? sender, LayoutEventArgs e)
  5209. {
  5210. WrapTextModel ();
  5211. Adjust ();
  5212. }
  5213. private void ToggleSelecting ()
  5214. {
  5215. ResetColumnTrack ();
  5216. IsSelecting = !IsSelecting;
  5217. _selectionStartColumn = CurrentColumn;
  5218. _selectionStartRow = CurrentRow;
  5219. }
  5220. // Tries to snap the cursor to the tracking column
  5221. private void TrackColumn ()
  5222. {
  5223. // Now track the column
  5224. List<RuneCell> line = GetCurrentLine ();
  5225. if (line.Count < _columnTrack)
  5226. {
  5227. CurrentColumn = line.Count;
  5228. }
  5229. else if (_columnTrack != -1)
  5230. {
  5231. CurrentColumn = _columnTrack;
  5232. }
  5233. else if (CurrentColumn > line.Count)
  5234. {
  5235. CurrentColumn = line.Count;
  5236. }
  5237. Adjust ();
  5238. }
  5239. /// <summary>Update the original model.</summary>
  5240. private void UpdateWrapModel ([CallerMemberName] string? caller = null)
  5241. {
  5242. if (_currentCaller is { } && _currentCaller != caller)
  5243. {
  5244. return;
  5245. }
  5246. if (_wordWrap)
  5247. {
  5248. _currentCaller = null;
  5249. _wrapManager!.UpdateModel (
  5250. _model,
  5251. out int nRow,
  5252. out int nCol,
  5253. out int nStartRow,
  5254. out int nStartCol,
  5255. CurrentRow,
  5256. CurrentColumn,
  5257. _selectionStartRow,
  5258. _selectionStartColumn,
  5259. true
  5260. );
  5261. CurrentRow = nRow;
  5262. CurrentColumn = nCol;
  5263. _selectionStartRow = nStartRow;
  5264. _selectionStartColumn = nStartCol;
  5265. _wrapNeeded = true;
  5266. SetNeedsDisplay ();
  5267. }
  5268. if (_currentCaller is { })
  5269. {
  5270. throw new InvalidOperationException (
  5271. $"WordWrap settings was changed after the {_currentCaller} call."
  5272. );
  5273. }
  5274. }
  5275. private void WrapTextModel ()
  5276. {
  5277. if (_wordWrap && _wrapManager is { })
  5278. {
  5279. _model = _wrapManager.WrapModel (
  5280. Math.Max (Viewport.Width - (ReadOnly ? 0 : 1), 0), // For the cursor on the last column of a line
  5281. out int nRow,
  5282. out int nCol,
  5283. out int nStartRow,
  5284. out int nStartCol,
  5285. CurrentRow,
  5286. CurrentColumn,
  5287. _selectionStartRow,
  5288. _selectionStartColumn,
  5289. _tabWidth
  5290. );
  5291. CurrentRow = nRow;
  5292. CurrentColumn = nCol;
  5293. _selectionStartRow = nStartRow;
  5294. _selectionStartColumn = nStartCol;
  5295. SetNeedsDisplay ();
  5296. }
  5297. }
  5298. }
  5299. /// <summary>
  5300. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  5301. /// options. An implementation on a TextView.
  5302. /// </summary>
  5303. public class TextViewAutocomplete : PopupAutocomplete
  5304. {
  5305. /// <inheritdoc/>
  5306. protected override void DeleteTextBackwards () { ((TextView)HostControl).DeleteCharLeft (); }
  5307. /// <inheritdoc/>
  5308. protected override void InsertText (string accepted) { ((TextView)HostControl).InsertText (accepted); }
  5309. /// <inheritdoc/>
  5310. protected override void SetCursorPosition (int column)
  5311. {
  5312. ((TextView)HostControl).CursorPosition =
  5313. new (column, ((TextView)HostControl).CurrentRow);
  5314. }
  5315. }