TextView.cs 187 KB

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