TextView.cs 188 KB

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