TextView.cs 187 KB

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