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. Added += TextView_Added!;
  1569. LayoutComplete += 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.A.WithCtrl, Command.LeftStart);
  1918. KeyBindings.Add (Key.Home.WithShift, Command.LeftStartExtend);
  1919. KeyBindings.Add (Key.Delete, Command.DeleteCharRight);
  1920. KeyBindings.Add (Key.D.WithCtrl, Command.DeleteCharRight);
  1921. KeyBindings.Add (Key.End, Command.RightEnd);
  1922. KeyBindings.Add (Key.E.WithCtrl, Command.RightEnd);
  1923. KeyBindings.Add (Key.End.WithShift, Command.RightEndExtend);
  1924. KeyBindings.Add (Key.K.WithCtrl, Command.CutToEndLine); // kill-to-end
  1925. KeyBindings.Add (Key.Delete.WithCtrl.WithShift, Command.CutToEndLine); // kill-to-end
  1926. KeyBindings.Add (Key.Backspace.WithCtrl.WithShift, Command.CutToStartLine); // kill-to-start
  1927. KeyBindings.Add (Key.Y.WithCtrl, Command.Paste); // Control-y, yank
  1928. KeyBindings.Add (Key.Space.WithCtrl, Command.ToggleExtend);
  1929. KeyBindings.Add (Key.C.WithCtrl, Command.Copy);
  1930. KeyBindings.Add (Key.W.WithCtrl, Command.Cut); // Move to Unix?
  1931. KeyBindings.Add (Key.X.WithCtrl, Command.Cut);
  1932. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.WordLeft);
  1933. KeyBindings.Add (Key.CursorLeft.WithCtrl.WithShift, Command.WordLeftExtend);
  1934. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.WordRight);
  1935. KeyBindings.Add (Key.CursorRight.WithCtrl.WithShift, Command.WordRightExtend);
  1936. KeyBindings.Add (Key.Delete.WithCtrl, Command.KillWordForwards); // kill-word-forwards
  1937. KeyBindings.Add (Key.Backspace.WithCtrl, Command.KillWordBackwards); // kill-word-backwards
  1938. KeyBindings.Add (Key.End.WithCtrl, Command.End);
  1939. KeyBindings.Add (Key.End.WithCtrl.WithShift, Command.EndExtend);
  1940. KeyBindings.Add (Key.Home.WithCtrl, Command.Start);
  1941. KeyBindings.Add (Key.Home.WithCtrl.WithShift, Command.StartExtend);
  1942. KeyBindings.Add (Key.T.WithCtrl, Command.SelectAll);
  1943. KeyBindings.Add (Key.InsertChar, Command.ToggleOverwrite);
  1944. KeyBindings.Add (Key.Tab, Command.Tab);
  1945. KeyBindings.Add (Key.Tab.WithShift, Command.BackTab);
  1946. KeyBindings.Add (Key.Z.WithCtrl, Command.Undo);
  1947. KeyBindings.Add (Key.R.WithCtrl, Command.Redo);
  1948. KeyBindings.Add (Key.G.WithCtrl, Command.DeleteAll);
  1949. KeyBindings.Add (Key.D.WithCtrl.WithShift, Command.DeleteAll);
  1950. KeyBindings.Add (Key.L.WithCtrl, Command.Open);
  1951. #if UNIX_KEY_BINDINGS
  1952. KeyBindings.Add (Key.C.WithAlt, Command.Copy);
  1953. KeyBindings.Add (Key.B.WithAlt, Command.WordLeft);
  1954. KeyBindings.Add (Key.W.WithAlt, Command.Cut);
  1955. KeyBindings.Add (Key.V.WithAlt, Command.PageUp);
  1956. KeyBindings.Add (Key.F.WithAlt, Command.WordRight);
  1957. KeyBindings.Add (Key.K.WithAlt, Command.CutToStartLine); // kill-to-start
  1958. #endif
  1959. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1960. ContextMenu = new ();
  1961. ContextMenu.KeyChanged += ContextMenu_KeyChanged!;
  1962. KeyBindings.Add ((KeyCode)ContextMenu.Key, KeyBindingScope.HotKey, Command.Context);
  1963. }
  1964. private void TextView_Added1 (object? sender, SuperViewChangedEventArgs e) { throw new NotImplementedException (); }
  1965. // BUGBUG: AllowsReturn is mis-named. It should be EnterKeyAccepts.
  1966. /// <summary>
  1967. /// Gets or sets whether pressing ENTER in a <see cref="TextView"/> creates a new line of text
  1968. /// in the view or invokes the <see cref="View.Accepting"/> event.
  1969. /// </summary>
  1970. /// <remarks>
  1971. /// <para>
  1972. /// Setting this property alters <see cref="Multiline"/>.
  1973. /// If <see cref="AllowsReturn"/> is set to <see langword="true"/>, then <see cref="Multiline"/> is also set to
  1974. /// `true` and
  1975. /// vice-versa.
  1976. /// </para>
  1977. /// <para>
  1978. /// If <see cref="AllowsReturn"/> is set to <see langword="false"/>, then <see cref="AllowsTab"/> gets set to
  1979. /// <see langword="false"/>.
  1980. /// </para>
  1981. /// </remarks>
  1982. public bool AllowsReturn
  1983. {
  1984. get => _allowsReturn;
  1985. set
  1986. {
  1987. _allowsReturn = value;
  1988. if (_allowsReturn && !_multiline)
  1989. {
  1990. // BUGBUG: Setting properties should not have side-effects like this. Multiline and AllowsReturn should be independent.
  1991. Multiline = true;
  1992. }
  1993. if (!_allowsReturn && _multiline)
  1994. {
  1995. Multiline = false;
  1996. // BUGBUG: Setting properties should not have side-effects like this. Multiline and AllowsTab should be independent.
  1997. AllowsTab = false;
  1998. }
  1999. SetNeedsDisplay ();
  2000. }
  2001. }
  2002. /// <summary>
  2003. /// Gets or sets whether the <see cref="TextView"/> inserts a tab character into the text or ignores tab input. If
  2004. /// set to `false` and the user presses the tab key (or shift-tab) the focus will move to the next view (or previous
  2005. /// with shift-tab). The default is `true`; if the user presses the tab key, a tab character will be inserted into the
  2006. /// text.
  2007. /// </summary>
  2008. public bool AllowsTab
  2009. {
  2010. get => _allowsTab;
  2011. set
  2012. {
  2013. _allowsTab = value;
  2014. if (_allowsTab && _tabWidth == 0)
  2015. {
  2016. _tabWidth = 4;
  2017. }
  2018. if (_allowsTab && !_multiline)
  2019. {
  2020. Multiline = true;
  2021. }
  2022. if (!_allowsTab && _tabWidth > 0)
  2023. {
  2024. _tabWidth = 0;
  2025. }
  2026. SetNeedsDisplay ();
  2027. }
  2028. }
  2029. /// <summary>
  2030. /// Provides autocomplete context menu based on suggestions at the current cursor position. Configure
  2031. /// <see cref="IAutocomplete.SuggestionGenerator"/> to enable this feature
  2032. /// </summary>
  2033. public IAutocomplete Autocomplete { get; protected set; } = new TextViewAutocomplete ();
  2034. /// <summary>Get the <see cref="ContextMenu"/> for this view.</summary>
  2035. public ContextMenu? ContextMenu { get; }
  2036. /// <summary>Gets the cursor column.</summary>
  2037. /// <value>The cursor column.</value>
  2038. public int CurrentColumn { get; private set; }
  2039. /// <summary>Gets the current cursor row.</summary>
  2040. public int CurrentRow { get; private set; }
  2041. /// <summary>Sets or gets the current cursor position.</summary>
  2042. public Point CursorPosition
  2043. {
  2044. get => new (CurrentColumn, CurrentRow);
  2045. set
  2046. {
  2047. List<Cell> line = _model.GetLine (Math.Max (Math.Min (value.Y, _model.Count - 1), 0));
  2048. CurrentColumn = value.X < 0 ? 0 :
  2049. value.X > line.Count ? line.Count : value.X;
  2050. CurrentRow = value.Y < 0 ? 0 :
  2051. value.Y > _model.Count - 1 ? Math.Max (_model.Count - 1, 0) : value.Y;
  2052. SetNeedsDisplay ();
  2053. Adjust ();
  2054. }
  2055. }
  2056. /// <summary>
  2057. /// Indicates whatever the text has history changes or not. <see langword="true"/> if the text has history changes
  2058. /// <see langword="false"/> otherwise.
  2059. /// </summary>
  2060. public bool HasHistoryChanges => _historyText.HasHistoryChanges;
  2061. /// <summary>
  2062. /// If <see langword="true"/> and the current <see cref="Cell.Attribute"/> is null will inherit from the
  2063. /// previous, otherwise if <see langword="false"/> (default) do nothing. If the text is load with
  2064. /// <see cref="Load(List{Cell})"/> this property is automatically sets to <see langword="true"/>.
  2065. /// </summary>
  2066. public bool InheritsPreviousAttribute { get; set; }
  2067. /// <summary>
  2068. /// Indicates whatever the text was changed or not. <see langword="true"/> if the text was changed
  2069. /// <see langword="false"/> otherwise.
  2070. /// </summary>
  2071. public bool IsDirty
  2072. {
  2073. get => _historyText.IsDirty (_model.GetAllLines ());
  2074. set => _historyText.Clear (_model.GetAllLines ());
  2075. }
  2076. /// <summary>Gets or sets the left column.</summary>
  2077. public int LeftColumn
  2078. {
  2079. get => _leftColumn;
  2080. set
  2081. {
  2082. if (value > 0 && _wordWrap)
  2083. {
  2084. return;
  2085. }
  2086. _leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0);
  2087. }
  2088. }
  2089. /// <summary>Gets the number of lines.</summary>
  2090. public int Lines => _model.Count;
  2091. /// <summary>Gets the maximum visible length line.</summary>
  2092. public int Maxlength => _model.GetMaxVisibleLine (_topRow, _topRow + Viewport.Height, TabWidth);
  2093. /// <summary>Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.</summary>
  2094. public bool Multiline
  2095. {
  2096. get => _multiline;
  2097. set
  2098. {
  2099. _multiline = value;
  2100. if (_multiline && !_allowsTab)
  2101. {
  2102. AllowsTab = true;
  2103. }
  2104. if (_multiline && !_allowsReturn)
  2105. {
  2106. AllowsReturn = true;
  2107. }
  2108. if (!_multiline)
  2109. {
  2110. AllowsReturn = false;
  2111. AllowsTab = false;
  2112. WordWrap = false;
  2113. CurrentColumn = 0;
  2114. CurrentRow = 0;
  2115. _savedHeight = Height;
  2116. Height = Dim.Auto (DimAutoStyle.Text, 1);
  2117. if (!IsInitialized)
  2118. {
  2119. _model.LoadString (Text);
  2120. }
  2121. SetNeedsDisplay ();
  2122. }
  2123. else if (_multiline && _savedHeight is { })
  2124. {
  2125. Height = _savedHeight;
  2126. SetNeedsDisplay ();
  2127. }
  2128. KeyBindings.Remove (Key.Enter);
  2129. KeyBindings.Add (Key.Enter, Multiline ? Command.NewLine : Command.Accept);
  2130. }
  2131. }
  2132. /// <summary>Gets or sets whether the <see cref="TextView"/> is in read-only mode or not</summary>
  2133. /// <value>Boolean value(Default false)</value>
  2134. public bool ReadOnly
  2135. {
  2136. get => _isReadOnly;
  2137. set
  2138. {
  2139. if (value != _isReadOnly)
  2140. {
  2141. _isReadOnly = value;
  2142. SetNeedsDisplay ();
  2143. WrapTextModel ();
  2144. Adjust ();
  2145. }
  2146. }
  2147. }
  2148. /// <summary>Length of the selected text.</summary>
  2149. public int SelectedLength => GetSelectedLength ();
  2150. /// <summary>
  2151. /// Gets the selected text as
  2152. /// <see>
  2153. /// <cref>List{List{Cell}}</cref>
  2154. /// </see>
  2155. /// </summary>
  2156. public List<List<Cell>> SelectedCellsList
  2157. {
  2158. get
  2159. {
  2160. GetRegion (out List<List<Cell>> selectedCellsList);
  2161. return selectedCellsList;
  2162. }
  2163. }
  2164. /// <summary>The selected text.</summary>
  2165. public string SelectedText
  2166. {
  2167. get
  2168. {
  2169. if (!IsSelecting || (_model.Count == 1 && _model.GetLine (0).Count == 0))
  2170. {
  2171. return string.Empty;
  2172. }
  2173. return GetSelectedRegion ();
  2174. }
  2175. }
  2176. /// <summary>Get or sets whether the user is currently selecting text.</summary>
  2177. public bool IsSelecting { get; set; }
  2178. /// <summary>Start column position of the selected text.</summary>
  2179. public int SelectionStartColumn
  2180. {
  2181. get => _selectionStartColumn;
  2182. set
  2183. {
  2184. List<Cell> line = _model.GetLine (_selectionStartRow);
  2185. _selectionStartColumn = value < 0 ? 0 :
  2186. value > line.Count ? line.Count : value;
  2187. IsSelecting = true;
  2188. SetNeedsDisplay ();
  2189. Adjust ();
  2190. }
  2191. }
  2192. /// <summary>Start row position of the selected text.</summary>
  2193. public int SelectionStartRow
  2194. {
  2195. get => _selectionStartRow;
  2196. set
  2197. {
  2198. _selectionStartRow = value < 0 ? 0 :
  2199. value > _model.Count - 1 ? Math.Max (_model.Count - 1, 0) : value;
  2200. IsSelecting = true;
  2201. SetNeedsDisplay ();
  2202. Adjust ();
  2203. }
  2204. }
  2205. /// <summary>Gets or sets a value indicating the number of whitespace when pressing the TAB key.</summary>
  2206. public int TabWidth
  2207. {
  2208. get => _tabWidth;
  2209. set
  2210. {
  2211. _tabWidth = Math.Max (value, 0);
  2212. if (_tabWidth > 0 && !AllowsTab)
  2213. {
  2214. AllowsTab = true;
  2215. }
  2216. SetNeedsDisplay ();
  2217. }
  2218. }
  2219. /// <summary>Sets or gets the text in the <see cref="TextView"/>.</summary>
  2220. /// <remarks>
  2221. /// The <see cref="View.TextChanged"/> event is fired whenever this property is set. Note, however, that Text is not
  2222. /// set by <see cref="TextView"/> as the user types.
  2223. /// </remarks>
  2224. public override string Text
  2225. {
  2226. get
  2227. {
  2228. if (_wordWrap)
  2229. {
  2230. return _wrapManager!.Model.ToString ();
  2231. }
  2232. return _model.ToString ();
  2233. }
  2234. set
  2235. {
  2236. ResetPosition ();
  2237. _model.LoadString (value);
  2238. if (_wordWrap)
  2239. {
  2240. _wrapManager = new (_model);
  2241. _model = _wrapManager.WrapModel (Viewport.Width, out _, out _, out _, out _);
  2242. }
  2243. OnTextChanged ();
  2244. SetNeedsDisplay ();
  2245. _historyText.Clear (_model.GetAllLines ());
  2246. }
  2247. }
  2248. /// <summary>Gets or sets the top row.</summary>
  2249. public int TopRow
  2250. {
  2251. get => _topRow;
  2252. set => _topRow = Math.Max (Math.Min (value, Lines - 1), 0);
  2253. }
  2254. /// <summary>
  2255. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry, so
  2256. /// new input should be appended at the cursor position, rather than clearing the entry
  2257. /// </summary>
  2258. public bool Used { get; set; }
  2259. /// <summary>Allows word wrap the to fit the available container width.</summary>
  2260. public bool WordWrap
  2261. {
  2262. get => _wordWrap;
  2263. set
  2264. {
  2265. if (value == _wordWrap)
  2266. {
  2267. return;
  2268. }
  2269. if (value && !_multiline)
  2270. {
  2271. return;
  2272. }
  2273. _wordWrap = value;
  2274. ResetPosition ();
  2275. if (_wordWrap)
  2276. {
  2277. _wrapManager = new (_model);
  2278. WrapTextModel ();
  2279. }
  2280. else if (!_wordWrap && _wrapManager is { })
  2281. {
  2282. _model = _wrapManager.Model;
  2283. }
  2284. SetNeedsDisplay ();
  2285. }
  2286. }
  2287. /// <summary>Allows clearing the <see cref="HistoryText.HistoryTextItemEventArgs"/> items updating the original text.</summary>
  2288. public void ClearHistoryChanges () { _historyText?.Clear (_model.GetAllLines ()); }
  2289. /// <summary>Closes the contents of the stream into the <see cref="TextView"/>.</summary>
  2290. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  2291. public bool CloseFile ()
  2292. {
  2293. SetWrapModel ();
  2294. bool res = _model.CloseFile ();
  2295. ResetPosition ();
  2296. SetNeedsDisplay ();
  2297. UpdateWrapModel ();
  2298. return res;
  2299. }
  2300. /// <summary>Raised when the contents of the <see cref="TextView"/> are changed.</summary>
  2301. /// <remarks>
  2302. /// Unlike the <see cref="View.TextChanged"/> event, this event is raised whenever the user types or otherwise changes
  2303. /// the contents of the <see cref="TextView"/>.
  2304. /// </remarks>
  2305. public event EventHandler<ContentsChangedEventArgs>? ContentsChanged;
  2306. internal void ApplyCellsAttribute (Attribute attribute)
  2307. {
  2308. if (!ReadOnly && SelectedLength > 0)
  2309. {
  2310. int startRow = Math.Min (SelectionStartRow, CurrentRow);
  2311. int endRow = Math.Max (CurrentRow, SelectionStartRow);
  2312. int startCol = SelectionStartRow <= CurrentRow ? SelectionStartColumn : CurrentColumn;
  2313. int endCol = CurrentRow >= SelectionStartRow ? CurrentColumn : SelectionStartColumn;
  2314. List<List<Cell>> selectedCellsOriginal = [];
  2315. List<List<Cell>> selectedCellsChanged = [];
  2316. for (int r = startRow; r <= endRow; r++)
  2317. {
  2318. List<Cell> line = GetLine (r);
  2319. selectedCellsOriginal.Add ([.. line]);
  2320. for (int c = r == startRow ? startCol : 0;
  2321. c < (r == endRow ? endCol : line.Count);
  2322. c++)
  2323. {
  2324. Cell cell = line [c]; // Copy value to a new variable
  2325. cell.Attribute = attribute; // Modify the copy
  2326. line [c] = cell; // Assign the modified copy back
  2327. }
  2328. selectedCellsChanged.Add ([.. GetLine (r)]);
  2329. }
  2330. GetSelectedRegion ();
  2331. IsSelecting = false;
  2332. _historyText.Add (
  2333. [.. selectedCellsOriginal],
  2334. new (startCol, startRow)
  2335. );
  2336. _historyText.Add (
  2337. [.. selectedCellsChanged],
  2338. new (startCol, startRow),
  2339. HistoryText.LineStatus.Attribute
  2340. );
  2341. }
  2342. }
  2343. private Attribute? GetSelectedCellAttribute ()
  2344. {
  2345. List<Cell> line;
  2346. if (SelectedLength > 0)
  2347. {
  2348. line = GetLine (SelectionStartRow);
  2349. if (line [Math.Min (SelectionStartColumn, line.Count - 1)].Attribute is { } attributeSel)
  2350. {
  2351. return new (attributeSel);
  2352. }
  2353. return new (ColorScheme!.Focus);
  2354. }
  2355. line = GetCurrentLine ();
  2356. if (line [Math.Min (CurrentColumn, line.Count - 1)].Attribute is { } attribute)
  2357. {
  2358. return new (attribute);
  2359. }
  2360. return new (ColorScheme!.Focus);
  2361. }
  2362. /// <summary>
  2363. /// Open a dialog to set the foreground and background colors.
  2364. /// </summary>
  2365. public void PromptForColors ()
  2366. {
  2367. if (!ColorPicker.Prompt (
  2368. "Colors",
  2369. GetSelectedCellAttribute (),
  2370. out Attribute newAttribute
  2371. ))
  2372. {
  2373. return;
  2374. }
  2375. var attribute = new Attribute (
  2376. newAttribute.Foreground,
  2377. newAttribute.Background
  2378. );
  2379. ApplyCellsAttribute (attribute);
  2380. }
  2381. private string? _copiedText;
  2382. private List<List<Cell>> _copiedCellsList = [];
  2383. /// <summary>Copy the selected text to the clipboard contents.</summary>
  2384. public void Copy ()
  2385. {
  2386. SetWrapModel ();
  2387. if (IsSelecting)
  2388. {
  2389. _copiedText = GetRegion (out _copiedCellsList);
  2390. SetClipboard (_copiedText);
  2391. _copyWithoutSelection = false;
  2392. }
  2393. else
  2394. {
  2395. List<Cell> currentLine = GetCurrentLine ();
  2396. _copiedCellsList.Add (currentLine);
  2397. _copiedText = Cell.ToString (currentLine);
  2398. SetClipboard (_copiedText);
  2399. _copyWithoutSelection = true;
  2400. }
  2401. UpdateWrapModel ();
  2402. DoNeededAction ();
  2403. }
  2404. /// <summary>Cut the selected text to the clipboard contents.</summary>
  2405. public void Cut ()
  2406. {
  2407. SetWrapModel ();
  2408. _copiedText = GetRegion (out _copiedCellsList);
  2409. SetClipboard (_copiedText);
  2410. if (!_isReadOnly)
  2411. {
  2412. ClearRegion ();
  2413. _historyText.Add (
  2414. [new (GetCurrentLine ())],
  2415. CursorPosition,
  2416. HistoryText.LineStatus.Replaced
  2417. );
  2418. }
  2419. UpdateWrapModel ();
  2420. IsSelecting = false;
  2421. DoNeededAction ();
  2422. OnContentsChanged ();
  2423. }
  2424. /// <summary>Deletes all text.</summary>
  2425. public void DeleteAll ()
  2426. {
  2427. if (Lines == 0)
  2428. {
  2429. return;
  2430. }
  2431. _selectionStartColumn = 0;
  2432. _selectionStartRow = 0;
  2433. MoveBottomEndExtend ();
  2434. DeleteCharLeft ();
  2435. SetNeedsDisplay ();
  2436. }
  2437. /// <summary>Deletes all the selected or a single character at left from the position of the cursor.</summary>
  2438. public void DeleteCharLeft ()
  2439. {
  2440. if (_isReadOnly)
  2441. {
  2442. return;
  2443. }
  2444. SetWrapModel ();
  2445. if (IsSelecting)
  2446. {
  2447. _historyText.Add (new () { new (GetCurrentLine ()) }, CursorPosition);
  2448. ClearSelectedRegion ();
  2449. List<Cell> currentLine = GetCurrentLine ();
  2450. _historyText.Add (
  2451. new () { new (currentLine) },
  2452. CursorPosition,
  2453. HistoryText.LineStatus.Replaced
  2454. );
  2455. UpdateWrapModel ();
  2456. OnContentsChanged ();
  2457. return;
  2458. }
  2459. if (DeleteTextBackwards ())
  2460. {
  2461. UpdateWrapModel ();
  2462. OnContentsChanged ();
  2463. return;
  2464. }
  2465. UpdateWrapModel ();
  2466. DoNeededAction ();
  2467. OnContentsChanged ();
  2468. }
  2469. /// <summary>Deletes all the selected or a single character at right from the position of the cursor.</summary>
  2470. public void DeleteCharRight ()
  2471. {
  2472. if (_isReadOnly)
  2473. {
  2474. return;
  2475. }
  2476. SetWrapModel ();
  2477. if (IsSelecting)
  2478. {
  2479. _historyText.Add (new () { new (GetCurrentLine ()) }, CursorPosition);
  2480. ClearSelectedRegion ();
  2481. List<Cell> currentLine = GetCurrentLine ();
  2482. _historyText.Add (
  2483. new () { new (currentLine) },
  2484. CursorPosition,
  2485. HistoryText.LineStatus.Replaced
  2486. );
  2487. UpdateWrapModel ();
  2488. OnContentsChanged ();
  2489. return;
  2490. }
  2491. if (DeleteTextForwards ())
  2492. {
  2493. UpdateWrapModel ();
  2494. OnContentsChanged ();
  2495. return;
  2496. }
  2497. UpdateWrapModel ();
  2498. DoNeededAction ();
  2499. OnContentsChanged ();
  2500. }
  2501. /// <summary>Invoked when the normal color is drawn.</summary>
  2502. public event EventHandler<CellEventArgs>? DrawNormalColor;
  2503. /// <summary>Invoked when the ready only color is drawn.</summary>
  2504. public event EventHandler<CellEventArgs>? DrawReadOnlyColor;
  2505. /// <summary>Invoked when the selection color is drawn.</summary>
  2506. public event EventHandler<CellEventArgs>? DrawSelectionColor;
  2507. /// <summary>
  2508. /// Invoked when the used color is drawn. The Used Color is used to indicate if the <see cref="Key.InsertChar"/>
  2509. /// was pressed and enabled.
  2510. /// </summary>
  2511. public event EventHandler<CellEventArgs>? DrawUsedColor;
  2512. /// <summary>Find the next text based on the match case with the option to replace it.</summary>
  2513. /// <param name="textToFind">The text to find.</param>
  2514. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  2515. /// <param name="matchCase">The match case setting.</param>
  2516. /// <param name="matchWholeWord">The match whole word setting.</param>
  2517. /// <param name="textToReplace">The text to replace.</param>
  2518. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  2519. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  2520. public bool FindNextText (
  2521. string textToFind,
  2522. out bool gaveFullTurn,
  2523. bool matchCase = false,
  2524. bool matchWholeWord = false,
  2525. string? textToReplace = null,
  2526. bool replace = false
  2527. )
  2528. {
  2529. if (_model.Count == 0)
  2530. {
  2531. gaveFullTurn = false;
  2532. return false;
  2533. }
  2534. SetWrapModel ();
  2535. ResetContinuousFind ();
  2536. (Point current, bool found) foundPos =
  2537. _model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  2538. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  2539. }
  2540. /// <summary>Find the previous text based on the match case with the option to replace it.</summary>
  2541. /// <param name="textToFind">The text to find.</param>
  2542. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  2543. /// <param name="matchCase">The match case setting.</param>
  2544. /// <param name="matchWholeWord">The match whole word setting.</param>
  2545. /// <param name="textToReplace">The text to replace.</param>
  2546. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  2547. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  2548. public bool FindPreviousText (
  2549. string textToFind,
  2550. out bool gaveFullTurn,
  2551. bool matchCase = false,
  2552. bool matchWholeWord = false,
  2553. string? textToReplace = null,
  2554. bool replace = false
  2555. )
  2556. {
  2557. if (_model.Count == 0)
  2558. {
  2559. gaveFullTurn = false;
  2560. return false;
  2561. }
  2562. SetWrapModel ();
  2563. ResetContinuousFind ();
  2564. (Point current, bool found) foundPos =
  2565. _model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  2566. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  2567. }
  2568. /// <summary>Reset the flag to stop continuous find.</summary>
  2569. public void FindTextChanged () { _continuousFind = false; }
  2570. /// <summary>Gets all lines of characters.</summary>
  2571. /// <returns></returns>
  2572. public List<List<Cell>> GetAllLines () { return _model.GetAllLines (); }
  2573. /// <summary>
  2574. /// Returns the characters on the current line (where the cursor is positioned). Use <see cref="CurrentColumn"/>
  2575. /// to determine the position of the cursor within that line
  2576. /// </summary>
  2577. /// <returns></returns>
  2578. public List<Cell> GetCurrentLine () { return _model.GetLine (CurrentRow); }
  2579. /// <summary>Returns the characters on the <paramref name="line"/>.</summary>
  2580. /// <param name="line">The intended line.</param>
  2581. /// <returns></returns>
  2582. public List<Cell> GetLine (int line) { return _model.GetLine (line); }
  2583. /// <inheritdoc/>
  2584. public override Attribute GetNormalColor () { return GetFocusColor (); }
  2585. /// <summary>
  2586. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position exactly as if the user had just
  2587. /// typed it
  2588. /// </summary>
  2589. /// <param name="toAdd">Text to add</param>
  2590. public void InsertText (string toAdd)
  2591. {
  2592. foreach (char ch in toAdd)
  2593. {
  2594. Key key;
  2595. try
  2596. {
  2597. key = new (ch);
  2598. }
  2599. catch (Exception)
  2600. {
  2601. throw new ArgumentException (
  2602. $"Cannot insert character '{ch}' because it does not map to a Key"
  2603. );
  2604. }
  2605. InsertText (key);
  2606. if (NeedsDisplay)
  2607. {
  2608. Adjust ();
  2609. }
  2610. else
  2611. {
  2612. PositionCursor ();
  2613. }
  2614. }
  2615. }
  2616. /// <summary>Loads the contents of the file into the <see cref="TextView"/>.</summary>
  2617. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  2618. /// <param name="path">Path to the file to load.</param>
  2619. public bool Load (string path)
  2620. {
  2621. SetWrapModel ();
  2622. bool res;
  2623. try
  2624. {
  2625. SetWrapModel ();
  2626. res = _model.LoadFile (path);
  2627. _historyText.Clear (_model.GetAllLines ());
  2628. ResetPosition ();
  2629. }
  2630. finally
  2631. {
  2632. UpdateWrapModel ();
  2633. SetNeedsDisplay ();
  2634. Adjust ();
  2635. }
  2636. UpdateWrapModel ();
  2637. return res;
  2638. }
  2639. /// <summary>Loads the contents of the stream into the <see cref="TextView"/>.</summary>
  2640. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  2641. /// <param name="stream">Stream to load the contents from.</param>
  2642. public void Load (Stream stream)
  2643. {
  2644. SetWrapModel ();
  2645. _model.LoadStream (stream);
  2646. _historyText.Clear (_model.GetAllLines ());
  2647. ResetPosition ();
  2648. SetNeedsDisplay ();
  2649. UpdateWrapModel ();
  2650. }
  2651. /// <summary>Loads the contents of the <see cref="Cell"/> list into the <see cref="TextView"/>.</summary>
  2652. /// <param name="cells">Rune cells list to load the contents from.</param>
  2653. public void Load (List<Cell> cells)
  2654. {
  2655. SetWrapModel ();
  2656. _model.LoadCells (cells, ColorScheme?.Focus);
  2657. _historyText.Clear (_model.GetAllLines ());
  2658. ResetPosition ();
  2659. SetNeedsDisplay ();
  2660. UpdateWrapModel ();
  2661. InheritsPreviousAttribute = true;
  2662. }
  2663. /// <summary>Loads the contents of the list of <see cref="Cell"/> list into the <see cref="TextView"/>.</summary>
  2664. /// <param name="cellsList">List of rune cells list to load the contents from.</param>
  2665. public void Load (List<List<Cell>> cellsList)
  2666. {
  2667. SetWrapModel ();
  2668. InheritsPreviousAttribute = true;
  2669. _model.LoadListCells (cellsList, ColorScheme?.Focus);
  2670. _historyText.Clear (_model.GetAllLines ());
  2671. ResetPosition ();
  2672. SetNeedsDisplay ();
  2673. UpdateWrapModel ();
  2674. }
  2675. /// <inheritdoc/>
  2676. protected override bool OnMouseEvent (MouseEvent ev)
  2677. {
  2678. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked)
  2679. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  2680. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  2681. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  2682. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  2683. && !ev.Flags.HasFlag (MouseFlags.WheeledDown)
  2684. && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  2685. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  2686. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)
  2687. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  2688. && !ev.Flags.HasFlag (ContextMenu!.MouseFlags))
  2689. {
  2690. return false;
  2691. }
  2692. if (!CanFocus)
  2693. {
  2694. return true;
  2695. }
  2696. if (!HasFocus)
  2697. {
  2698. SetFocus ();
  2699. }
  2700. _continuousFind = false;
  2701. // Give autocomplete first opportunity to respond to mouse clicks
  2702. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  2703. {
  2704. return true;
  2705. }
  2706. if (ev.Flags == MouseFlags.Button1Clicked)
  2707. {
  2708. if (_isButtonReleased)
  2709. {
  2710. _isButtonReleased = false;
  2711. return true;
  2712. }
  2713. if (_shiftSelecting && !_isButtonShift)
  2714. {
  2715. StopSelecting ();
  2716. }
  2717. ProcessMouseClick (ev, out _);
  2718. if (Used)
  2719. {
  2720. PositionCursor ();
  2721. }
  2722. else
  2723. {
  2724. SetNeedsDisplay ();
  2725. }
  2726. _lastWasKill = false;
  2727. _columnTrack = CurrentColumn;
  2728. }
  2729. else if (ev.Flags == MouseFlags.WheeledDown)
  2730. {
  2731. _lastWasKill = false;
  2732. _columnTrack = CurrentColumn;
  2733. ScrollTo (_topRow + 1);
  2734. }
  2735. else if (ev.Flags == MouseFlags.WheeledUp)
  2736. {
  2737. _lastWasKill = false;
  2738. _columnTrack = CurrentColumn;
  2739. ScrollTo (_topRow - 1);
  2740. }
  2741. else if (ev.Flags == MouseFlags.WheeledRight)
  2742. {
  2743. _lastWasKill = false;
  2744. _columnTrack = CurrentColumn;
  2745. ScrollTo (_leftColumn + 1, false);
  2746. }
  2747. else if (ev.Flags == MouseFlags.WheeledLeft)
  2748. {
  2749. _lastWasKill = false;
  2750. _columnTrack = CurrentColumn;
  2751. ScrollTo (_leftColumn - 1, false);
  2752. }
  2753. else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  2754. {
  2755. ProcessMouseClick (ev, out List<Cell> line);
  2756. PositionCursor ();
  2757. if (_model.Count > 0 && _shiftSelecting && IsSelecting)
  2758. {
  2759. if (CurrentRow - _topRow >= Viewport.Height - 1 && _model.Count > _topRow + CurrentRow)
  2760. {
  2761. ScrollTo (_topRow + Viewport.Height);
  2762. }
  2763. else if (_topRow > 0 && CurrentRow <= _topRow)
  2764. {
  2765. ScrollTo (_topRow - Viewport.Height);
  2766. }
  2767. else if (ev.Position.Y >= Viewport.Height)
  2768. {
  2769. ScrollTo (_model.Count);
  2770. }
  2771. else if (ev.Position.Y < 0 && _topRow > 0)
  2772. {
  2773. ScrollTo (0);
  2774. }
  2775. if (CurrentColumn - _leftColumn >= Viewport.Width - 1 && line.Count > _leftColumn + CurrentColumn)
  2776. {
  2777. ScrollTo (_leftColumn + Viewport.Width, false);
  2778. }
  2779. else if (_leftColumn > 0 && CurrentColumn <= _leftColumn)
  2780. {
  2781. ScrollTo (_leftColumn - Viewport.Width, false);
  2782. }
  2783. else if (ev.Position.X >= Viewport.Width)
  2784. {
  2785. ScrollTo (line.Count, false);
  2786. }
  2787. else if (ev.Position.X < 0 && _leftColumn > 0)
  2788. {
  2789. ScrollTo (0, false);
  2790. }
  2791. }
  2792. _lastWasKill = false;
  2793. _columnTrack = CurrentColumn;
  2794. }
  2795. else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift))
  2796. {
  2797. if (!_shiftSelecting)
  2798. {
  2799. _isButtonShift = true;
  2800. StartSelecting ();
  2801. }
  2802. ProcessMouseClick (ev, out _);
  2803. PositionCursor ();
  2804. _lastWasKill = false;
  2805. _columnTrack = CurrentColumn;
  2806. }
  2807. else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed))
  2808. {
  2809. if (_shiftSelecting)
  2810. {
  2811. _clickWithSelecting = true;
  2812. StopSelecting ();
  2813. }
  2814. ProcessMouseClick (ev, out _);
  2815. PositionCursor ();
  2816. if (!IsSelecting)
  2817. {
  2818. StartSelecting ();
  2819. }
  2820. _lastWasKill = false;
  2821. _columnTrack = CurrentColumn;
  2822. if (Application.MouseGrabView is null)
  2823. {
  2824. Application.GrabMouse (this);
  2825. }
  2826. }
  2827. else if (ev.Flags.HasFlag (MouseFlags.Button1Released))
  2828. {
  2829. _isButtonReleased = true;
  2830. Application.UngrabMouse ();
  2831. }
  2832. else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked))
  2833. {
  2834. if (ev.Flags.HasFlag (MouseFlags.ButtonShift))
  2835. {
  2836. if (!IsSelecting)
  2837. {
  2838. StartSelecting ();
  2839. }
  2840. }
  2841. else if (IsSelecting)
  2842. {
  2843. StopSelecting ();
  2844. }
  2845. ProcessMouseClick (ev, out List<Cell> line);
  2846. (int col, int row)? newPos;
  2847. if (CurrentColumn == line.Count
  2848. || (CurrentColumn > 0 && (line [CurrentColumn - 1].Rune.Value != ' ' || line [CurrentColumn].Rune.Value == ' ')))
  2849. {
  2850. newPos = _model.WordBackward (CurrentColumn, CurrentRow);
  2851. if (newPos.HasValue)
  2852. {
  2853. CurrentColumn = CurrentRow == newPos.Value.row ? newPos.Value.col : 0;
  2854. }
  2855. }
  2856. if (!IsSelecting)
  2857. {
  2858. StartSelecting ();
  2859. }
  2860. newPos = _model.WordForward (CurrentColumn, CurrentRow);
  2861. if (newPos is { } && newPos.HasValue)
  2862. {
  2863. CurrentColumn = CurrentRow == newPos.Value.row ? newPos.Value.col : line.Count;
  2864. }
  2865. PositionCursor ();
  2866. _lastWasKill = false;
  2867. _columnTrack = CurrentColumn;
  2868. }
  2869. else if (ev.Flags.HasFlag (MouseFlags.Button1TripleClicked))
  2870. {
  2871. if (IsSelecting)
  2872. {
  2873. StopSelecting ();
  2874. }
  2875. ProcessMouseClick (ev, out List<Cell> line);
  2876. CurrentColumn = 0;
  2877. if (!IsSelecting)
  2878. {
  2879. StartSelecting ();
  2880. }
  2881. CurrentColumn = line.Count;
  2882. PositionCursor ();
  2883. _lastWasKill = false;
  2884. _columnTrack = CurrentColumn;
  2885. }
  2886. else if (ev.Flags == ContextMenu!.MouseFlags)
  2887. {
  2888. ContextMenu.Position = ViewportToScreen ((Viewport with { X = ev.Position.X, Y = ev.Position.Y }).Location);
  2889. ShowContextMenu ();
  2890. }
  2891. return true;
  2892. }
  2893. /// <summary>Will scroll the <see cref="TextView"/> to the last line and position the cursor there.</summary>
  2894. public void MoveEnd ()
  2895. {
  2896. CurrentRow = _model.Count - 1;
  2897. List<Cell> line = GetCurrentLine ();
  2898. CurrentColumn = line.Count;
  2899. TrackColumn ();
  2900. PositionCursor ();
  2901. }
  2902. /// <summary>Will scroll the <see cref="TextView"/> to the first line and position the cursor there.</summary>
  2903. public void MoveHome ()
  2904. {
  2905. CurrentRow = 0;
  2906. _topRow = 0;
  2907. CurrentColumn = 0;
  2908. _leftColumn = 0;
  2909. TrackColumn ();
  2910. PositionCursor ();
  2911. SetNeedsDisplay ();
  2912. }
  2913. /// <summary>
  2914. /// Called when the contents of the TextView change. E.g. when the user types text or deletes text. Raises the
  2915. /// <see cref="ContentsChanged"/> event.
  2916. /// </summary>
  2917. public virtual void OnContentsChanged ()
  2918. {
  2919. ContentsChanged?.Invoke (this, new (CurrentRow, CurrentColumn));
  2920. ProcessInheritsPreviousColorScheme (CurrentRow, CurrentColumn);
  2921. ProcessAutocomplete ();
  2922. }
  2923. /// <inheritdoc/>
  2924. public override void OnDrawContent (Rectangle viewport)
  2925. {
  2926. _isDrawing = true;
  2927. SetNormalColor ();
  2928. (int width, int height) offB = OffSetBackground ();
  2929. int right = Viewport.Width + offB.width;
  2930. int bottom = Viewport.Height + offB.height;
  2931. var row = 0;
  2932. for (int idxRow = _topRow; idxRow < _model.Count; idxRow++)
  2933. {
  2934. List<Cell> line = _model.GetLine (idxRow);
  2935. int lineRuneCount = line.Count;
  2936. var col = 0;
  2937. Move (0, row);
  2938. for (int idxCol = _leftColumn; idxCol < lineRuneCount; idxCol++)
  2939. {
  2940. Rune rune = idxCol >= lineRuneCount ? (Rune)' ' : line [idxCol].Rune;
  2941. int cols = rune.GetColumns ();
  2942. if (idxCol < line.Count && IsSelecting && PointInSelection (idxCol, idxRow))
  2943. {
  2944. OnDrawSelectionColor (line, idxCol, idxRow);
  2945. }
  2946. else if (idxCol == CurrentColumn && idxRow == CurrentRow && !IsSelecting && !Used && HasFocus && idxCol < lineRuneCount)
  2947. {
  2948. OnDrawUsedColor (line, idxCol, idxRow);
  2949. }
  2950. else if (ReadOnly)
  2951. {
  2952. OnDrawReadOnlyColor (line, idxCol, idxRow);
  2953. }
  2954. else
  2955. {
  2956. OnDrawNormalColor (line, idxCol, idxRow);
  2957. }
  2958. if (rune.Value == '\t')
  2959. {
  2960. cols += TabWidth + 1;
  2961. if (col + cols > right)
  2962. {
  2963. cols = right - col;
  2964. }
  2965. for (var i = 0; i < cols; i++)
  2966. {
  2967. if (col + i < right)
  2968. {
  2969. AddRune (col + i, row, (Rune)' ');
  2970. }
  2971. }
  2972. }
  2973. else
  2974. {
  2975. AddRune (col, row, rune);
  2976. // Ensures that cols less than 0 to be 1 because it will be converted to a printable rune
  2977. cols = Math.Max (cols, 1);
  2978. }
  2979. if (!TextModel.SetCol (ref col, viewport.Right, cols))
  2980. {
  2981. break;
  2982. }
  2983. if (idxCol + 1 < lineRuneCount && col + line [idxCol + 1].Rune.GetColumns () > right)
  2984. {
  2985. break;
  2986. }
  2987. }
  2988. if (col < right)
  2989. {
  2990. SetNormalColor ();
  2991. ClearRegion (col, row, right, row + 1);
  2992. }
  2993. row++;
  2994. }
  2995. if (row < bottom)
  2996. {
  2997. SetNormalColor ();
  2998. ClearRegion (viewport.Left, row, right, bottom);
  2999. }
  3000. //PositionCursor ();
  3001. _isDrawing = false;
  3002. }
  3003. /// <inheritdoc/>
  3004. protected override void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? view)
  3005. {
  3006. if (Application.MouseGrabView is { } && Application.MouseGrabView == this)
  3007. {
  3008. Application.UngrabMouse ();
  3009. }
  3010. }
  3011. /// <inheritdoc/>
  3012. protected override bool OnKeyDown (Key key)
  3013. {
  3014. if (!key.IsValid)
  3015. {
  3016. return false;
  3017. }
  3018. // Give autocomplete first opportunity to respond to key presses
  3019. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (key))
  3020. {
  3021. return true;
  3022. }
  3023. return false;
  3024. }
  3025. /// <inheritdoc/>
  3026. protected override bool OnKeyDownNotHandled (Key a)
  3027. {
  3028. if (!CanFocus)
  3029. {
  3030. return true;
  3031. }
  3032. ResetColumnTrack ();
  3033. // Ignore control characters and other special keys
  3034. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  3035. {
  3036. return false;
  3037. }
  3038. InsertText (a);
  3039. DoNeededAction ();
  3040. return true;
  3041. }
  3042. /// <inheritdoc/>
  3043. public override bool OnKeyUp (Key key)
  3044. {
  3045. if (key == Key.Space.WithCtrl)
  3046. {
  3047. return true;
  3048. }
  3049. return false;
  3050. }
  3051. /// <summary>Invoke the <see cref="UnwrappedCursorPosition"/> event with the unwrapped <see cref="CursorPosition"/>.</summary>
  3052. public virtual void OnUnwrappedCursorPosition (int? cRow = null, int? cCol = null)
  3053. {
  3054. int? row = cRow is null ? CurrentRow : cRow;
  3055. int? col = cCol is null ? CurrentColumn : cCol;
  3056. if (cRow is null && cCol is null && _wordWrap)
  3057. {
  3058. row = _wrapManager!.GetModelLineFromWrappedLines (CurrentRow);
  3059. col = _wrapManager.GetModelColFromWrappedLines (CurrentRow, CurrentColumn);
  3060. }
  3061. UnwrappedCursorPosition?.Invoke (this, new (new ((int)col, (int)row)));
  3062. }
  3063. /// <summary>Paste the clipboard contents into the current selected position.</summary>
  3064. public void Paste ()
  3065. {
  3066. if (_isReadOnly)
  3067. {
  3068. return;
  3069. }
  3070. SetWrapModel ();
  3071. string? contents = Clipboard.Contents;
  3072. if (_copyWithoutSelection && contents.FirstOrDefault (x => x is '\n' or '\r') == 0)
  3073. {
  3074. List<Cell> runeList = contents is null ? [] : Cell.ToCellList (contents);
  3075. List<Cell> currentLine = GetCurrentLine ();
  3076. _historyText.Add ([new (currentLine)], CursorPosition);
  3077. List<List<Cell>> addedLine = [new (currentLine), runeList];
  3078. _historyText.Add (
  3079. [.. addedLine],
  3080. CursorPosition,
  3081. HistoryText.LineStatus.Added
  3082. );
  3083. _model.AddLine (CurrentRow, runeList);
  3084. CurrentRow++;
  3085. _historyText.Add (
  3086. [new (GetCurrentLine ())],
  3087. CursorPosition,
  3088. HistoryText.LineStatus.Replaced
  3089. );
  3090. SetNeedsDisplay ();
  3091. OnContentsChanged ();
  3092. }
  3093. else
  3094. {
  3095. if (IsSelecting)
  3096. {
  3097. ClearRegion ();
  3098. }
  3099. _copyWithoutSelection = false;
  3100. InsertAllText (contents, true);
  3101. if (IsSelecting)
  3102. {
  3103. _historyText.ReplaceLast (
  3104. [new (GetCurrentLine ())],
  3105. CursorPosition,
  3106. HistoryText.LineStatus.Original
  3107. );
  3108. }
  3109. SetNeedsDisplay ();
  3110. }
  3111. UpdateWrapModel ();
  3112. IsSelecting = false;
  3113. DoNeededAction ();
  3114. }
  3115. /// <summary>Positions the cursor on the current row and column</summary>
  3116. public override Point? PositionCursor ()
  3117. {
  3118. ProcessAutocomplete ();
  3119. if (!CanFocus || !Enabled || Application.Driver is null)
  3120. {
  3121. return null;
  3122. }
  3123. if (Application.MouseGrabView == this && IsSelecting)
  3124. {
  3125. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3126. //var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Viewport.Height);
  3127. //var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Viewport.Height);
  3128. //SetNeedsDisplay (new (0, minRow, Viewport.Width, maxRow));
  3129. SetNeedsDisplay ();
  3130. }
  3131. List<Cell> line = _model.GetLine (CurrentRow);
  3132. var col = 0;
  3133. if (line.Count > 0)
  3134. {
  3135. for (int idx = _leftColumn; idx < line.Count; idx++)
  3136. {
  3137. if (idx >= CurrentColumn)
  3138. {
  3139. break;
  3140. }
  3141. int cols = line [idx].Rune.GetColumns ();
  3142. if (line [idx].Rune.Value == '\t')
  3143. {
  3144. cols += TabWidth + 1;
  3145. }
  3146. else
  3147. {
  3148. // Ensures that cols less than 0 to be 1 because it will be converted to a printable rune
  3149. cols = Math.Max (cols, 1);
  3150. }
  3151. if (!TextModel.SetCol (ref col, Viewport.Width, cols))
  3152. {
  3153. col = CurrentColumn;
  3154. break;
  3155. }
  3156. }
  3157. }
  3158. int posX = CurrentColumn - _leftColumn;
  3159. int posY = CurrentRow - _topRow;
  3160. if (posX > -1 && col >= posX && posX < Viewport.Width && _topRow <= CurrentRow && posY < Viewport.Height)
  3161. {
  3162. Move (col, CurrentRow - _topRow);
  3163. return new (col, CurrentRow - _topRow);
  3164. }
  3165. return null; // Hide cursor
  3166. }
  3167. /// <summary>Redoes the latest changes.</summary>
  3168. public void Redo ()
  3169. {
  3170. if (ReadOnly)
  3171. {
  3172. return;
  3173. }
  3174. _historyText.Redo ();
  3175. }
  3176. /// <summary>Replaces all the text based on the match case.</summary>
  3177. /// <param name="textToFind">The text to find.</param>
  3178. /// <param name="matchCase">The match case setting.</param>
  3179. /// <param name="matchWholeWord">The match whole word setting.</param>
  3180. /// <param name="textToReplace">The text to replace.</param>
  3181. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  3182. public bool ReplaceAllText (
  3183. string textToFind,
  3184. bool matchCase = false,
  3185. bool matchWholeWord = false,
  3186. string? textToReplace = null
  3187. )
  3188. {
  3189. if (_isReadOnly || _model.Count == 0)
  3190. {
  3191. return false;
  3192. }
  3193. SetWrapModel ();
  3194. ResetContinuousFind ();
  3195. (Point current, bool found) foundPos =
  3196. _model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  3197. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  3198. }
  3199. /// <summary>
  3200. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is
  3201. /// true or will scroll the <see cref="TextView"/> to display the specified column at the left if
  3202. /// <paramref name="isRow"/> is false.
  3203. /// </summary>
  3204. /// <param name="idx">
  3205. /// Row that should be displayed at the top or Column that should be displayed at the left, if the value
  3206. /// is negative it will be reset to zero
  3207. /// </param>
  3208. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  3209. public void ScrollTo (int idx, bool isRow = true)
  3210. {
  3211. if (idx < 0)
  3212. {
  3213. idx = 0;
  3214. }
  3215. if (isRow)
  3216. {
  3217. _topRow = Math.Max (idx > _model.Count - 1 ? _model.Count - 1 : idx, 0);
  3218. }
  3219. else if (!_wordWrap)
  3220. {
  3221. int maxlength =
  3222. _model.GetMaxVisibleLine (_topRow, _topRow + Viewport.Height, TabWidth);
  3223. _leftColumn = Math.Max (!_wordWrap && idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  3224. }
  3225. SetNeedsDisplay ();
  3226. }
  3227. /// <summary>Select all text.</summary>
  3228. public void SelectAll ()
  3229. {
  3230. if (_model.Count == 0)
  3231. {
  3232. return;
  3233. }
  3234. StartSelecting ();
  3235. _selectionStartColumn = 0;
  3236. _selectionStartRow = 0;
  3237. CurrentColumn = _model.GetLine (_model.Count - 1).Count;
  3238. CurrentRow = _model.Count - 1;
  3239. SetNeedsDisplay ();
  3240. }
  3241. ///// <summary>Raised when the <see cref="Text"/> property of the <see cref="TextView"/> changes.</summary>
  3242. ///// <remarks>
  3243. ///// The <see cref="Text"/> property of <see cref="TextView"/> only changes when it is explicitly set, not as the
  3244. ///// user types. To be notified as the user changes the contents of the TextView see <see cref="IsDirty"/>.
  3245. ///// </remarks>
  3246. //public event EventHandler? TextChanged;
  3247. /// <summary>Undoes the latest changes.</summary>
  3248. public void Undo ()
  3249. {
  3250. if (ReadOnly)
  3251. {
  3252. return;
  3253. }
  3254. _historyText.Undo ();
  3255. }
  3256. /// <summary>Invoked with the unwrapped <see cref="CursorPosition"/>.</summary>
  3257. public event EventHandler<PointEventArgs>? UnwrappedCursorPosition;
  3258. /// <summary>
  3259. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3260. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3261. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.Normal"/>.
  3262. /// </summary>
  3263. /// <param name="line">The line.</param>
  3264. /// <param name="idxCol">The col index.</param>
  3265. /// <param name="idxRow">The row index.</param>
  3266. protected virtual void OnDrawNormalColor (List<Cell> line, int idxCol, int idxRow)
  3267. {
  3268. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3269. var ev = new CellEventArgs (line, idxCol, unwrappedPos);
  3270. DrawNormalColor?.Invoke (this, ev);
  3271. if (line [idxCol].Attribute is { })
  3272. {
  3273. Attribute? attribute = line [idxCol].Attribute;
  3274. Driver.SetAttribute ((Attribute)attribute!);
  3275. }
  3276. else
  3277. {
  3278. Driver.SetAttribute (GetNormalColor ());
  3279. }
  3280. }
  3281. /// <summary>
  3282. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3283. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3284. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.Focus"/>.
  3285. /// </summary>
  3286. /// <param name="line">The line.</param>
  3287. /// <param name="idxCol">The col index.</param>
  3288. /// ///
  3289. /// <param name="idxRow">The row index.</param>
  3290. protected virtual void OnDrawReadOnlyColor (List<Cell> line, int idxCol, int idxRow)
  3291. {
  3292. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3293. var ev = new CellEventArgs (line, idxCol, unwrappedPos);
  3294. DrawReadOnlyColor?.Invoke (this, ev);
  3295. Attribute? cellAttribute = line [idxCol].Attribute is { } ? line [idxCol].Attribute : ColorScheme?.Disabled;
  3296. Attribute attribute;
  3297. if (cellAttribute!.Value.Foreground == cellAttribute.Value.Background)
  3298. {
  3299. attribute = new (cellAttribute.Value.Foreground, cellAttribute.Value.Background);
  3300. }
  3301. else
  3302. {
  3303. attribute = new (cellAttribute.Value.Foreground, ColorScheme!.Focus.Background);
  3304. }
  3305. Driver.SetAttribute (attribute);
  3306. }
  3307. /// <summary>
  3308. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3309. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3310. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.Focus"/>.
  3311. /// </summary>
  3312. /// <param name="line">The line.</param>
  3313. /// <param name="idxCol">The col index.</param>
  3314. /// ///
  3315. /// <param name="idxRow">The row index.</param>
  3316. protected virtual void OnDrawSelectionColor (List<Cell> line, int idxCol, int idxRow)
  3317. {
  3318. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3319. var ev = new CellEventArgs (line, idxCol, unwrappedPos);
  3320. DrawSelectionColor?.Invoke (this, ev);
  3321. if (line [idxCol].Attribute is { })
  3322. {
  3323. Attribute? attribute = line [idxCol].Attribute;
  3324. Driver.SetAttribute (
  3325. new (attribute!.Value.Background, attribute.Value.Foreground)
  3326. );
  3327. }
  3328. else
  3329. {
  3330. Driver.SetAttribute (
  3331. new (
  3332. ColorScheme!.Focus.Background,
  3333. ColorScheme!.Focus.Foreground
  3334. )
  3335. );
  3336. }
  3337. }
  3338. /// <summary>
  3339. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idxCol"/>
  3340. /// of the current <paramref name="line"/>. Override to provide custom coloring by calling
  3341. /// <see cref="ConsoleDriver.SetAttribute(Attribute)"/> Defaults to <see cref="ColorScheme.HotFocus"/>.
  3342. /// </summary>
  3343. /// <param name="line">The line.</param>
  3344. /// <param name="idxCol">The col index.</param>
  3345. /// ///
  3346. /// <param name="idxRow">The row index.</param>
  3347. protected virtual void OnDrawUsedColor (List<Cell> line, int idxCol, int idxRow)
  3348. {
  3349. (int Row, int Col) unwrappedPos = GetUnwrappedPosition (idxRow, idxCol);
  3350. var ev = new CellEventArgs (line, idxCol, unwrappedPos);
  3351. DrawUsedColor?.Invoke (this, ev);
  3352. if (line [idxCol].Attribute is { })
  3353. {
  3354. Attribute? attribute = line [idxCol].Attribute;
  3355. SetValidUsedColor (attribute!);
  3356. }
  3357. else
  3358. {
  3359. SetValidUsedColor (ColorScheme?.Focus);
  3360. }
  3361. }
  3362. /// <summary>
  3363. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to
  3364. /// <see cref="ColorScheme.Normal"/>.
  3365. /// </summary>
  3366. protected virtual void SetNormalColor () { Driver.SetAttribute (GetNormalColor ()); }
  3367. private void Adjust ()
  3368. {
  3369. (int width, int height) offB = OffSetBackground ();
  3370. List<Cell> line = GetCurrentLine ();
  3371. bool need = NeedsDisplay || _wrapNeeded || !Used;
  3372. (int size, int length) tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  3373. (int size, int length) dSize = TextModel.DisplaySize (line, _leftColumn, CurrentColumn, true, TabWidth);
  3374. if (!_wordWrap && CurrentColumn < _leftColumn)
  3375. {
  3376. _leftColumn = CurrentColumn;
  3377. need = true;
  3378. }
  3379. else if (!_wordWrap
  3380. && (CurrentColumn - _leftColumn + 1 > Viewport.Width + offB.width || dSize.size + 1 >= Viewport.Width + offB.width))
  3381. {
  3382. _leftColumn = TextModel.CalculateLeftColumn (
  3383. line,
  3384. _leftColumn,
  3385. CurrentColumn,
  3386. Viewport.Width + offB.width,
  3387. TabWidth
  3388. );
  3389. need = true;
  3390. }
  3391. else if ((_wordWrap && _leftColumn > 0) || (dSize.size < Viewport.Width + offB.width && tSize.size < Viewport.Width + offB.width))
  3392. {
  3393. if (_leftColumn > 0)
  3394. {
  3395. _leftColumn = 0;
  3396. need = true;
  3397. }
  3398. }
  3399. if (CurrentRow < _topRow)
  3400. {
  3401. _topRow = CurrentRow;
  3402. need = true;
  3403. }
  3404. else if (CurrentRow - _topRow >= Viewport.Height + offB.height)
  3405. {
  3406. _topRow = Math.Min (Math.Max (CurrentRow - Viewport.Height + 1, 0), CurrentRow);
  3407. need = true;
  3408. }
  3409. else if (_topRow > 0 && CurrentRow < _topRow)
  3410. {
  3411. _topRow = Math.Max (_topRow - 1, 0);
  3412. need = true;
  3413. }
  3414. if (need)
  3415. {
  3416. if (_wrapNeeded)
  3417. {
  3418. WrapTextModel ();
  3419. _wrapNeeded = false;
  3420. }
  3421. SetNeedsDisplay ();
  3422. }
  3423. else
  3424. {
  3425. if (IsInitialized)
  3426. {
  3427. PositionCursor ();
  3428. }
  3429. }
  3430. OnUnwrappedCursorPosition ();
  3431. }
  3432. private void AppendClipboard (string text) { Clipboard.Contents += text; }
  3433. private MenuBarItem? BuildContextMenuBarItem ()
  3434. {
  3435. return new (
  3436. new MenuItem []
  3437. {
  3438. new (
  3439. Strings.ctxSelectAll,
  3440. "",
  3441. SelectAll,
  3442. null,
  3443. null,
  3444. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  3445. ),
  3446. new (
  3447. Strings.ctxDeleteAll,
  3448. "",
  3449. DeleteAll,
  3450. null,
  3451. null,
  3452. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  3453. ),
  3454. new (
  3455. Strings.ctxCopy,
  3456. "",
  3457. Copy,
  3458. null,
  3459. null,
  3460. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  3461. ),
  3462. new (
  3463. Strings.ctxCut,
  3464. "",
  3465. Cut,
  3466. null,
  3467. null,
  3468. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  3469. ),
  3470. new (
  3471. Strings.ctxPaste,
  3472. "",
  3473. Paste,
  3474. null,
  3475. null,
  3476. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  3477. ),
  3478. new (
  3479. Strings.ctxUndo,
  3480. "",
  3481. Undo,
  3482. null,
  3483. null,
  3484. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  3485. ),
  3486. new (
  3487. Strings.ctxRedo,
  3488. "",
  3489. Redo,
  3490. null,
  3491. null,
  3492. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  3493. ),
  3494. new (
  3495. Strings.ctxColors,
  3496. "",
  3497. () => PromptForColors (),
  3498. null,
  3499. null,
  3500. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Open)
  3501. )
  3502. }
  3503. );
  3504. }
  3505. private void ClearRegion (int left, int top, int right, int bottom)
  3506. {
  3507. for (int row = top; row < bottom; row++)
  3508. {
  3509. Move (left, row);
  3510. for (int col = left; col < right; col++)
  3511. {
  3512. AddRune (col, row, (Rune)' ');
  3513. }
  3514. }
  3515. }
  3516. //
  3517. // Clears the contents of the selected region
  3518. //
  3519. private void ClearRegion ()
  3520. {
  3521. SetWrapModel ();
  3522. long start, end;
  3523. long currentEncoded = ((long)(uint)CurrentRow << 32) | (uint)CurrentColumn;
  3524. GetEncodedRegionBounds (out start, out end);
  3525. var startRow = (int)(start >> 32);
  3526. var maxrow = (int)(end >> 32);
  3527. var startCol = (int)(start & 0xffffffff);
  3528. var endCol = (int)(end & 0xffffffff);
  3529. List<Cell> line = _model.GetLine (startRow);
  3530. _historyText.Add (new () { new (line) }, new (startCol, startRow));
  3531. List<List<Cell>> removedLines = new ();
  3532. if (startRow == maxrow)
  3533. {
  3534. removedLines.Add (new (line));
  3535. line.RemoveRange (startCol, endCol - startCol);
  3536. CurrentColumn = startCol;
  3537. if (_wordWrap)
  3538. {
  3539. SetNeedsDisplay ();
  3540. }
  3541. else
  3542. {
  3543. //QUESTION: Is the below comment still relevant?
  3544. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3545. //SetNeedsDisplay (new (0, startRow - topRow, Viewport.Width, startRow - topRow + 1));
  3546. SetNeedsDisplay ();
  3547. }
  3548. _historyText.Add (
  3549. new (removedLines),
  3550. CursorPosition,
  3551. HistoryText.LineStatus.Removed
  3552. );
  3553. UpdateWrapModel ();
  3554. return;
  3555. }
  3556. removedLines.Add (new (line));
  3557. line.RemoveRange (startCol, line.Count - startCol);
  3558. List<Cell> line2 = _model.GetLine (maxrow);
  3559. line.AddRange (line2.Skip (endCol));
  3560. for (int row = startRow + 1; row <= maxrow; row++)
  3561. {
  3562. removedLines.Add (new (_model.GetLine (startRow + 1)));
  3563. _model.RemoveLine (startRow + 1);
  3564. }
  3565. if (currentEncoded == end)
  3566. {
  3567. CurrentRow -= maxrow - startRow;
  3568. }
  3569. CurrentColumn = startCol;
  3570. _historyText.Add (
  3571. new (removedLines),
  3572. CursorPosition,
  3573. HistoryText.LineStatus.Removed
  3574. );
  3575. UpdateWrapModel ();
  3576. SetNeedsDisplay ();
  3577. }
  3578. private void ClearSelectedRegion ()
  3579. {
  3580. SetWrapModel ();
  3581. if (!_isReadOnly)
  3582. {
  3583. ClearRegion ();
  3584. }
  3585. UpdateWrapModel ();
  3586. IsSelecting = false;
  3587. DoNeededAction ();
  3588. }
  3589. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.ReplaceKey (e.OldKey, e.NewKey); }
  3590. private bool DeleteTextBackwards ()
  3591. {
  3592. SetWrapModel ();
  3593. if (CurrentColumn > 0)
  3594. {
  3595. // Delete backwards
  3596. List<Cell> currentLine = GetCurrentLine ();
  3597. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  3598. currentLine.RemoveAt (CurrentColumn - 1);
  3599. if (_wordWrap)
  3600. {
  3601. _wrapNeeded = true;
  3602. }
  3603. CurrentColumn--;
  3604. _historyText.Add (
  3605. new () { new (currentLine) },
  3606. CursorPosition,
  3607. HistoryText.LineStatus.Replaced
  3608. );
  3609. if (CurrentColumn < _leftColumn)
  3610. {
  3611. _leftColumn--;
  3612. SetNeedsDisplay ();
  3613. }
  3614. else
  3615. {
  3616. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3617. //SetNeedsDisplay (new (0, currentRow - topRow, 1, Viewport.Width));
  3618. SetNeedsDisplay ();
  3619. }
  3620. }
  3621. else
  3622. {
  3623. // Merges the current line with the previous one.
  3624. if (CurrentRow == 0)
  3625. {
  3626. return true;
  3627. }
  3628. int prowIdx = CurrentRow - 1;
  3629. List<Cell> prevRow = _model.GetLine (prowIdx);
  3630. _historyText.Add (new () { new (prevRow) }, CursorPosition);
  3631. List<List<Cell>> removedLines = new () { new (prevRow) };
  3632. removedLines.Add (new (GetCurrentLine ()));
  3633. _historyText.Add (
  3634. removedLines,
  3635. new (CurrentColumn, prowIdx),
  3636. HistoryText.LineStatus.Removed
  3637. );
  3638. int prevCount = prevRow.Count;
  3639. _model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  3640. _model.RemoveLine (CurrentRow);
  3641. if (_wordWrap)
  3642. {
  3643. _wrapNeeded = true;
  3644. }
  3645. CurrentRow--;
  3646. _historyText.Add (
  3647. new () { GetCurrentLine () },
  3648. new (CurrentColumn, prowIdx),
  3649. HistoryText.LineStatus.Replaced
  3650. );
  3651. CurrentColumn = prevCount;
  3652. SetNeedsDisplay ();
  3653. }
  3654. UpdateWrapModel ();
  3655. return false;
  3656. }
  3657. private bool DeleteTextForwards ()
  3658. {
  3659. SetWrapModel ();
  3660. List<Cell> currentLine = GetCurrentLine ();
  3661. if (CurrentColumn == currentLine.Count)
  3662. {
  3663. if (CurrentRow + 1 == _model.Count)
  3664. {
  3665. UpdateWrapModel ();
  3666. return true;
  3667. }
  3668. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  3669. List<List<Cell>> removedLines = new () { new (currentLine) };
  3670. List<Cell> nextLine = _model.GetLine (CurrentRow + 1);
  3671. removedLines.Add (new (nextLine));
  3672. _historyText.Add (removedLines, CursorPosition, HistoryText.LineStatus.Removed);
  3673. currentLine.AddRange (nextLine);
  3674. _model.RemoveLine (CurrentRow + 1);
  3675. _historyText.Add (
  3676. new () { new (currentLine) },
  3677. CursorPosition,
  3678. HistoryText.LineStatus.Replaced
  3679. );
  3680. if (_wordWrap)
  3681. {
  3682. _wrapNeeded = true;
  3683. }
  3684. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, CurrentRow - _topRow + 1));
  3685. }
  3686. else
  3687. {
  3688. _historyText.Add ([[.. currentLine]], CursorPosition);
  3689. currentLine.RemoveAt (CurrentColumn);
  3690. _historyText.Add (
  3691. [[.. currentLine]],
  3692. CursorPosition,
  3693. HistoryText.LineStatus.Replaced
  3694. );
  3695. if (_wordWrap)
  3696. {
  3697. _wrapNeeded = true;
  3698. }
  3699. DoSetNeedsDisplay (
  3700. new (
  3701. CurrentColumn - _leftColumn,
  3702. CurrentRow - _topRow,
  3703. Viewport.Width,
  3704. Math.Max (CurrentRow - _topRow + 1, 0)
  3705. )
  3706. );
  3707. }
  3708. UpdateWrapModel ();
  3709. return false;
  3710. }
  3711. private void DoNeededAction ()
  3712. {
  3713. if (NeedsDisplay)
  3714. {
  3715. Adjust ();
  3716. }
  3717. else
  3718. {
  3719. PositionCursor ();
  3720. }
  3721. }
  3722. private void DoSetNeedsDisplay (Rectangle rect)
  3723. {
  3724. if (_wrapNeeded)
  3725. {
  3726. SetNeedsDisplay ();
  3727. }
  3728. else
  3729. {
  3730. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3731. //SetNeedsDisplay (rect);
  3732. SetNeedsDisplay ();
  3733. }
  3734. }
  3735. private IEnumerable<(int col, int row, Cell rune)> ForwardIterator (int col, int row)
  3736. {
  3737. if (col < 0 || row < 0)
  3738. {
  3739. yield break;
  3740. }
  3741. if (row >= _model.Count)
  3742. {
  3743. yield break;
  3744. }
  3745. List<Cell> line = GetCurrentLine ();
  3746. if (col >= line.Count)
  3747. {
  3748. yield break;
  3749. }
  3750. while (row < _model.Count)
  3751. {
  3752. for (int c = col; c < line.Count; c++)
  3753. {
  3754. yield return (c, row, line [c]);
  3755. }
  3756. col = 0;
  3757. row++;
  3758. line = GetCurrentLine ();
  3759. }
  3760. }
  3761. private void GenerateSuggestions ()
  3762. {
  3763. List<Cell> currentLine = GetCurrentLine ();
  3764. int cursorPosition = Math.Min (CurrentColumn, currentLine.Count);
  3765. Autocomplete.Context = new (
  3766. currentLine,
  3767. cursorPosition,
  3768. Autocomplete.Context != null
  3769. ? Autocomplete.Context.Canceled
  3770. : false
  3771. );
  3772. Autocomplete.GenerateSuggestions (
  3773. Autocomplete.Context
  3774. );
  3775. }
  3776. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  3777. private void GetEncodedRegionBounds (
  3778. out long start,
  3779. out long end,
  3780. int? startRow = null,
  3781. int? startCol = null,
  3782. int? cRow = null,
  3783. int? cCol = null
  3784. )
  3785. {
  3786. long selection;
  3787. long point;
  3788. if (startRow is null || startCol is null || cRow is null || cCol is null)
  3789. {
  3790. selection = ((long)(uint)_selectionStartRow << 32) | (uint)_selectionStartColumn;
  3791. point = ((long)(uint)CurrentRow << 32) | (uint)CurrentColumn;
  3792. }
  3793. else
  3794. {
  3795. selection = ((long)(uint)startRow << 32) | (uint)startCol;
  3796. point = ((long)(uint)cRow << 32) | (uint)cCol;
  3797. }
  3798. if (selection > point)
  3799. {
  3800. start = point;
  3801. end = selection;
  3802. }
  3803. else
  3804. {
  3805. start = selection;
  3806. end = point;
  3807. }
  3808. }
  3809. //
  3810. // Returns a string with the text in the selected
  3811. // region.
  3812. //
  3813. internal string GetRegion (
  3814. out List<List<Cell>> cellsList,
  3815. int? sRow = null,
  3816. int? sCol = null,
  3817. int? cRow = null,
  3818. int? cCol = null,
  3819. TextModel? model = null
  3820. )
  3821. {
  3822. GetEncodedRegionBounds (out long start, out long end, sRow, sCol, cRow, cCol);
  3823. cellsList = [];
  3824. if (start == end)
  3825. {
  3826. return string.Empty;
  3827. }
  3828. var startRow = (int)(start >> 32);
  3829. var maxRow = (int)(end >> 32);
  3830. var startCol = (int)(start & 0xffffffff);
  3831. var endCol = (int)(end & 0xffffffff);
  3832. List<Cell> line = model is null ? _model.GetLine (startRow) : model.GetLine (startRow);
  3833. List<Cell> cells;
  3834. if (startRow == maxRow)
  3835. {
  3836. cells = line.GetRange (startCol, endCol - startCol);
  3837. cellsList.Add (cells);
  3838. return StringFromRunes (cells);
  3839. }
  3840. cells = line.GetRange (startCol, line.Count - startCol);
  3841. cellsList.Add (cells);
  3842. string res = StringFromRunes (cells);
  3843. for (int row = startRow + 1; row < maxRow; row++)
  3844. {
  3845. cellsList.AddRange ([]);
  3846. cells = model == null ? _model.GetLine (row) : model.GetLine (row);
  3847. cellsList.Add (cells);
  3848. res = res
  3849. + Environment.NewLine
  3850. + StringFromRunes (cells);
  3851. }
  3852. line = model is null ? _model.GetLine (maxRow) : model.GetLine (maxRow);
  3853. cellsList.AddRange ([]);
  3854. cells = line.GetRange (0, endCol);
  3855. cellsList.Add (cells);
  3856. res = res + Environment.NewLine + StringFromRunes (cells);
  3857. return res;
  3858. }
  3859. private int GetSelectedLength () { return SelectedText.Length; }
  3860. private string GetSelectedRegion ()
  3861. {
  3862. int cRow = CurrentRow;
  3863. int cCol = CurrentColumn;
  3864. int startRow = _selectionStartRow;
  3865. int startCol = _selectionStartColumn;
  3866. TextModel model = _model;
  3867. if (_wordWrap)
  3868. {
  3869. cRow = _wrapManager!.GetModelLineFromWrappedLines (CurrentRow);
  3870. cCol = _wrapManager.GetModelColFromWrappedLines (CurrentRow, CurrentColumn);
  3871. startRow = _wrapManager.GetModelLineFromWrappedLines (_selectionStartRow);
  3872. startCol = _wrapManager.GetModelColFromWrappedLines (_selectionStartRow, _selectionStartColumn);
  3873. model = _wrapManager.Model;
  3874. }
  3875. OnUnwrappedCursorPosition (cRow, cCol);
  3876. return GetRegion (out _, startRow, startCol, cRow, cCol, model);
  3877. }
  3878. private (int Row, int Col) GetUnwrappedPosition (int line, int col)
  3879. {
  3880. if (WordWrap)
  3881. {
  3882. return new ValueTuple<int, int> (
  3883. _wrapManager!.GetModelLineFromWrappedLines (line),
  3884. _wrapManager.GetModelColFromWrappedLines (line, col)
  3885. );
  3886. }
  3887. return new ValueTuple<int, int> (line, col);
  3888. }
  3889. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItemEventArgs obj)
  3890. {
  3891. SetWrapModel ();
  3892. if (obj is { })
  3893. {
  3894. int startLine = obj.CursorPosition.Y;
  3895. if (obj.RemovedOnAdded is { })
  3896. {
  3897. int offset;
  3898. if (obj.IsUndoing)
  3899. {
  3900. offset = Math.Max (obj.RemovedOnAdded.Lines.Count - obj.Lines.Count, 1);
  3901. }
  3902. else
  3903. {
  3904. offset = obj.RemovedOnAdded.Lines.Count - 1;
  3905. }
  3906. for (var i = 0; i < offset; i++)
  3907. {
  3908. if (Lines > obj.RemovedOnAdded.CursorPosition.Y)
  3909. {
  3910. _model.RemoveLine (obj.RemovedOnAdded.CursorPosition.Y);
  3911. }
  3912. else
  3913. {
  3914. break;
  3915. }
  3916. }
  3917. }
  3918. for (var i = 0; i < obj.Lines.Count; i++)
  3919. {
  3920. if (i == 0 || obj.LineStatus == HistoryText.LineStatus.Original || obj.LineStatus == HistoryText.LineStatus.Attribute)
  3921. {
  3922. _model.ReplaceLine (startLine, obj.Lines [i]);
  3923. }
  3924. else if (obj is { IsUndoing: true, LineStatus: HistoryText.LineStatus.Removed }
  3925. or { IsUndoing: false, LineStatus: HistoryText.LineStatus.Added })
  3926. {
  3927. _model.AddLine (startLine, obj.Lines [i]);
  3928. }
  3929. else if (Lines > obj.CursorPosition.Y + 1)
  3930. {
  3931. _model.RemoveLine (obj.CursorPosition.Y + 1);
  3932. }
  3933. startLine++;
  3934. }
  3935. CursorPosition = obj.FinalCursorPosition;
  3936. }
  3937. UpdateWrapModel ();
  3938. Adjust ();
  3939. OnContentsChanged ();
  3940. }
  3941. private void Insert (Cell cell)
  3942. {
  3943. List<Cell> line = GetCurrentLine ();
  3944. if (Used)
  3945. {
  3946. line.Insert (Math.Min (CurrentColumn, line.Count), cell);
  3947. }
  3948. else
  3949. {
  3950. if (CurrentColumn < line.Count)
  3951. {
  3952. line.RemoveAt (CurrentColumn);
  3953. }
  3954. line.Insert (Math.Min (CurrentColumn, line.Count), cell);
  3955. }
  3956. int prow = CurrentRow - _topRow;
  3957. if (!_wrapNeeded)
  3958. {
  3959. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  3960. //SetNeedsDisplay (new (0, prow, Math.Max (Viewport.Width, 0), Math.Max (prow + 1, 0)));
  3961. SetNeedsDisplay ();
  3962. }
  3963. }
  3964. private void InsertAllText (string text, bool fromClipboard = false)
  3965. {
  3966. if (string.IsNullOrEmpty (text))
  3967. {
  3968. return;
  3969. }
  3970. List<List<Cell>> lines;
  3971. if (fromClipboard && text == _copiedText)
  3972. {
  3973. lines = _copiedCellsList;
  3974. }
  3975. else
  3976. {
  3977. // Get selected attribute
  3978. Attribute? attribute = GetSelectedAttribute (CurrentRow, CurrentColumn);
  3979. lines = Cell.StringToLinesOfCells (text, attribute);
  3980. }
  3981. if (lines.Count == 0)
  3982. {
  3983. return;
  3984. }
  3985. SetWrapModel ();
  3986. List<Cell> line = GetCurrentLine ();
  3987. _historyText.Add ([new (line)], CursorPosition);
  3988. // Optimize single line
  3989. if (lines.Count == 1)
  3990. {
  3991. line.InsertRange (CurrentColumn, lines [0]);
  3992. CurrentColumn += lines [0].Count;
  3993. _historyText.Add (
  3994. [new (line)],
  3995. CursorPosition,
  3996. HistoryText.LineStatus.Replaced
  3997. );
  3998. if (!_wordWrap && CurrentColumn - _leftColumn > Viewport.Width)
  3999. {
  4000. _leftColumn = Math.Max (CurrentColumn - Viewport.Width + 1, 0);
  4001. }
  4002. if (_wordWrap)
  4003. {
  4004. SetNeedsDisplay ();
  4005. }
  4006. else
  4007. {
  4008. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  4009. //SetNeedsDisplay (new (0, currentRow - topRow, Viewport.Width, Math.Max (currentRow - topRow + 1, 0)));
  4010. SetNeedsDisplay ();
  4011. }
  4012. UpdateWrapModel ();
  4013. OnContentsChanged ();
  4014. return;
  4015. }
  4016. List<Cell>? rest = null;
  4017. var lastPosition = 0;
  4018. if (_model.Count > 0 && line.Count > 0 && !_copyWithoutSelection)
  4019. {
  4020. // Keep a copy of the rest of the line
  4021. int restCount = line.Count - CurrentColumn;
  4022. rest = line.GetRange (CurrentColumn, restCount);
  4023. line.RemoveRange (CurrentColumn, restCount);
  4024. }
  4025. // First line is inserted at the current location, the rest is appended
  4026. line.InsertRange (CurrentColumn, lines [0]);
  4027. //model.AddLine (currentRow, lines [0]);
  4028. List<List<Cell>> addedLines = [new (line)];
  4029. for (var i = 1; i < lines.Count; i++)
  4030. {
  4031. _model.AddLine (CurrentRow + i, lines [i]);
  4032. addedLines.Add ([.. lines [i]]);
  4033. }
  4034. if (rest is { })
  4035. {
  4036. List<Cell> last = _model.GetLine (CurrentRow + lines.Count - 1);
  4037. lastPosition = last.Count;
  4038. last.InsertRange (last.Count, rest);
  4039. addedLines.Last ().InsertRange (addedLines.Last ().Count, rest);
  4040. }
  4041. _historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  4042. // Now adjust column and row positions
  4043. CurrentRow += lines.Count - 1;
  4044. CurrentColumn = rest is { } ? lastPosition : lines [^1].Count;
  4045. Adjust ();
  4046. _historyText.Add (
  4047. [new (line)],
  4048. CursorPosition,
  4049. HistoryText.LineStatus.Replaced
  4050. );
  4051. UpdateWrapModel ();
  4052. OnContentsChanged ();
  4053. }
  4054. private bool InsertText (Key a, Attribute? attribute = null)
  4055. {
  4056. //So that special keys like tab can be processed
  4057. if (_isReadOnly)
  4058. {
  4059. return true;
  4060. }
  4061. SetWrapModel ();
  4062. _historyText.Add ([new (GetCurrentLine ())], CursorPosition);
  4063. if (IsSelecting)
  4064. {
  4065. ClearSelectedRegion ();
  4066. }
  4067. if ((uint)a.KeyCode == '\n')
  4068. {
  4069. _model.AddLine (CurrentRow + 1, []);
  4070. CurrentRow++;
  4071. CurrentColumn = 0;
  4072. }
  4073. else if ((uint)a.KeyCode == '\r')
  4074. {
  4075. CurrentColumn = 0;
  4076. }
  4077. else
  4078. {
  4079. if (Used)
  4080. {
  4081. Insert (new () { Rune = a.AsRune, Attribute = attribute });
  4082. CurrentColumn++;
  4083. if (CurrentColumn >= _leftColumn + Viewport.Width)
  4084. {
  4085. _leftColumn++;
  4086. SetNeedsDisplay ();
  4087. }
  4088. }
  4089. else
  4090. {
  4091. Insert (new () { Rune = a.AsRune, Attribute = attribute });
  4092. CurrentColumn++;
  4093. }
  4094. }
  4095. _historyText.Add (
  4096. [new (GetCurrentLine ())],
  4097. CursorPosition,
  4098. HistoryText.LineStatus.Replaced
  4099. );
  4100. UpdateWrapModel ();
  4101. OnContentsChanged ();
  4102. return true;
  4103. }
  4104. private void KillToEndOfLine ()
  4105. {
  4106. if (_isReadOnly)
  4107. {
  4108. return;
  4109. }
  4110. if (_model.Count == 1 && GetCurrentLine ().Count == 0)
  4111. {
  4112. // Prevents from adding line feeds if there is no more lines.
  4113. return;
  4114. }
  4115. SetWrapModel ();
  4116. List<Cell> currentLine = GetCurrentLine ();
  4117. var setLastWasKill = true;
  4118. if (currentLine.Count > 0 && CurrentColumn == currentLine.Count)
  4119. {
  4120. UpdateWrapModel ();
  4121. DeleteTextForwards ();
  4122. return;
  4123. }
  4124. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  4125. if (currentLine.Count == 0)
  4126. {
  4127. if (CurrentRow < _model.Count - 1)
  4128. {
  4129. List<List<Cell>> removedLines = new () { new (currentLine) };
  4130. _model.RemoveLine (CurrentRow);
  4131. removedLines.Add (new (GetCurrentLine ()));
  4132. _historyText.Add (
  4133. new (removedLines),
  4134. CursorPosition,
  4135. HistoryText.LineStatus.Removed
  4136. );
  4137. }
  4138. if (_model.Count > 0 || _lastWasKill)
  4139. {
  4140. string val = Environment.NewLine;
  4141. if (_lastWasKill)
  4142. {
  4143. AppendClipboard (val);
  4144. }
  4145. else
  4146. {
  4147. SetClipboard (val);
  4148. }
  4149. }
  4150. if (_model.Count == 0)
  4151. {
  4152. // Prevents from adding line feeds if there is no more lines.
  4153. setLastWasKill = false;
  4154. }
  4155. }
  4156. else
  4157. {
  4158. int restCount = currentLine.Count - CurrentColumn;
  4159. List<Cell> rest = currentLine.GetRange (CurrentColumn, restCount);
  4160. var val = string.Empty;
  4161. val += StringFromRunes (rest);
  4162. if (_lastWasKill)
  4163. {
  4164. AppendClipboard (val);
  4165. }
  4166. else
  4167. {
  4168. SetClipboard (val);
  4169. }
  4170. currentLine.RemoveRange (CurrentColumn, restCount);
  4171. }
  4172. _historyText.Add (
  4173. [[.. GetCurrentLine ()]],
  4174. CursorPosition,
  4175. HistoryText.LineStatus.Replaced
  4176. );
  4177. UpdateWrapModel ();
  4178. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4179. _lastWasKill = setLastWasKill;
  4180. DoNeededAction ();
  4181. }
  4182. private void KillToLeftStart ()
  4183. {
  4184. if (_isReadOnly)
  4185. {
  4186. return;
  4187. }
  4188. if (_model.Count == 1 && GetCurrentLine ().Count == 0)
  4189. {
  4190. // Prevents from adding line feeds if there is no more lines.
  4191. return;
  4192. }
  4193. SetWrapModel ();
  4194. List<Cell> currentLine = GetCurrentLine ();
  4195. var setLastWasKill = true;
  4196. if (currentLine.Count > 0 && CurrentColumn == 0)
  4197. {
  4198. UpdateWrapModel ();
  4199. DeleteTextBackwards ();
  4200. return;
  4201. }
  4202. _historyText.Add ([[.. currentLine]], CursorPosition);
  4203. if (currentLine.Count == 0)
  4204. {
  4205. if (CurrentRow > 0)
  4206. {
  4207. _model.RemoveLine (CurrentRow);
  4208. if (_model.Count > 0 || _lastWasKill)
  4209. {
  4210. string val = Environment.NewLine;
  4211. if (_lastWasKill)
  4212. {
  4213. AppendClipboard (val);
  4214. }
  4215. else
  4216. {
  4217. SetClipboard (val);
  4218. }
  4219. }
  4220. if (_model.Count == 0)
  4221. {
  4222. // Prevents from adding line feeds if there is no more lines.
  4223. setLastWasKill = false;
  4224. }
  4225. CurrentRow--;
  4226. currentLine = _model.GetLine (CurrentRow);
  4227. List<List<Cell>> removedLine =
  4228. [
  4229. [..currentLine],
  4230. []
  4231. ];
  4232. _historyText.Add (
  4233. [.. removedLine],
  4234. CursorPosition,
  4235. HistoryText.LineStatus.Removed
  4236. );
  4237. CurrentColumn = currentLine.Count;
  4238. }
  4239. }
  4240. else
  4241. {
  4242. int restCount = CurrentColumn;
  4243. List<Cell> rest = currentLine.GetRange (0, restCount);
  4244. var val = string.Empty;
  4245. val += StringFromRunes (rest);
  4246. if (_lastWasKill)
  4247. {
  4248. AppendClipboard (val);
  4249. }
  4250. else
  4251. {
  4252. SetClipboard (val);
  4253. }
  4254. currentLine.RemoveRange (0, restCount);
  4255. CurrentColumn = 0;
  4256. }
  4257. _historyText.Add (
  4258. [[.. GetCurrentLine ()]],
  4259. CursorPosition,
  4260. HistoryText.LineStatus.Replaced
  4261. );
  4262. UpdateWrapModel ();
  4263. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4264. _lastWasKill = setLastWasKill;
  4265. DoNeededAction ();
  4266. }
  4267. private void KillWordBackward ()
  4268. {
  4269. if (_isReadOnly)
  4270. {
  4271. return;
  4272. }
  4273. SetWrapModel ();
  4274. List<Cell> currentLine = GetCurrentLine ();
  4275. _historyText.Add ([[.. GetCurrentLine ()]], CursorPosition);
  4276. if (CurrentColumn == 0)
  4277. {
  4278. DeleteTextBackwards ();
  4279. _historyText.ReplaceLast (
  4280. [[.. GetCurrentLine ()]],
  4281. CursorPosition,
  4282. HistoryText.LineStatus.Replaced
  4283. );
  4284. UpdateWrapModel ();
  4285. return;
  4286. }
  4287. (int col, int row)? newPos = _model.WordBackward (CurrentColumn, CurrentRow);
  4288. if (newPos.HasValue && CurrentRow == newPos.Value.row)
  4289. {
  4290. int restCount = CurrentColumn - newPos.Value.col;
  4291. currentLine.RemoveRange (newPos.Value.col, restCount);
  4292. if (_wordWrap)
  4293. {
  4294. _wrapNeeded = true;
  4295. }
  4296. CurrentColumn = newPos.Value.col;
  4297. }
  4298. else if (newPos.HasValue)
  4299. {
  4300. int restCount = currentLine.Count - CurrentColumn;
  4301. currentLine.RemoveRange (CurrentColumn, restCount);
  4302. if (_wordWrap)
  4303. {
  4304. _wrapNeeded = true;
  4305. }
  4306. CurrentColumn = newPos.Value.col;
  4307. CurrentRow = newPos.Value.row;
  4308. }
  4309. _historyText.Add (
  4310. [[.. GetCurrentLine ()]],
  4311. CursorPosition,
  4312. HistoryText.LineStatus.Replaced
  4313. );
  4314. UpdateWrapModel ();
  4315. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4316. DoNeededAction ();
  4317. }
  4318. private void KillWordForward ()
  4319. {
  4320. if (_isReadOnly)
  4321. {
  4322. return;
  4323. }
  4324. SetWrapModel ();
  4325. List<Cell> currentLine = GetCurrentLine ();
  4326. _historyText.Add ([[.. GetCurrentLine ()]], CursorPosition);
  4327. if (currentLine.Count == 0 || CurrentColumn == currentLine.Count)
  4328. {
  4329. DeleteTextForwards ();
  4330. _historyText.ReplaceLast (
  4331. [[.. GetCurrentLine ()]],
  4332. CursorPosition,
  4333. HistoryText.LineStatus.Replaced
  4334. );
  4335. UpdateWrapModel ();
  4336. return;
  4337. }
  4338. (int col, int row)? newPos = _model.WordForward (CurrentColumn, CurrentRow);
  4339. var restCount = 0;
  4340. if (newPos.HasValue && CurrentRow == newPos.Value.row)
  4341. {
  4342. restCount = newPos.Value.col - CurrentColumn;
  4343. currentLine.RemoveRange (CurrentColumn, restCount);
  4344. }
  4345. else if (newPos.HasValue)
  4346. {
  4347. restCount = currentLine.Count - CurrentColumn;
  4348. currentLine.RemoveRange (CurrentColumn, restCount);
  4349. }
  4350. if (_wordWrap)
  4351. {
  4352. _wrapNeeded = true;
  4353. }
  4354. _historyText.Add (
  4355. [[.. GetCurrentLine ()]],
  4356. CursorPosition,
  4357. HistoryText.LineStatus.Replaced
  4358. );
  4359. UpdateWrapModel ();
  4360. DoSetNeedsDisplay (new (0, CurrentRow - _topRow, Viewport.Width, Viewport.Height));
  4361. DoNeededAction ();
  4362. }
  4363. private void Model_LinesLoaded (object sender, EventArgs e)
  4364. {
  4365. // This call is not needed. Model_LinesLoaded gets invoked when
  4366. // model.LoadString (value) is called. LoadString is called from one place
  4367. // (Text.set) and historyText.Clear() is called immediately after.
  4368. // If this call happens, HistoryText_ChangeText will get called multiple times
  4369. // when Text is set, which is wrong.
  4370. //historyText.Clear (Text);
  4371. if (!_multiline && !IsInitialized)
  4372. {
  4373. CurrentColumn = Text.GetRuneCount ();
  4374. _leftColumn = CurrentColumn > Viewport.Width + 1 ? CurrentColumn - Viewport.Width + 1 : 0;
  4375. }
  4376. }
  4377. private void MoveBottomEnd ()
  4378. {
  4379. ResetAllTrack ();
  4380. if (_shiftSelecting && IsSelecting)
  4381. {
  4382. StopSelecting ();
  4383. }
  4384. MoveEnd ();
  4385. }
  4386. private void MoveBottomEndExtend ()
  4387. {
  4388. ResetAllTrack ();
  4389. StartSelecting ();
  4390. MoveEnd ();
  4391. }
  4392. private bool MoveDown ()
  4393. {
  4394. if (CurrentRow + 1 < _model.Count)
  4395. {
  4396. if (_columnTrack == -1)
  4397. {
  4398. _columnTrack = CurrentColumn;
  4399. }
  4400. CurrentRow++;
  4401. if (CurrentRow >= _topRow + Viewport.Height)
  4402. {
  4403. _topRow++;
  4404. SetNeedsDisplay ();
  4405. }
  4406. TrackColumn ();
  4407. PositionCursor ();
  4408. }
  4409. else if (CurrentRow > Viewport.Height)
  4410. {
  4411. Adjust ();
  4412. }
  4413. else
  4414. {
  4415. return false;
  4416. }
  4417. DoNeededAction ();
  4418. return true;
  4419. }
  4420. private void MoveEndOfLine ()
  4421. {
  4422. List<Cell> currentLine = GetCurrentLine ();
  4423. CurrentColumn = Math.Max (currentLine.Count - (ReadOnly ? 1 : 0), 0);
  4424. Adjust ();
  4425. DoNeededAction ();
  4426. }
  4427. private bool MoveLeft ()
  4428. {
  4429. if (CurrentColumn > 0)
  4430. {
  4431. CurrentColumn--;
  4432. }
  4433. else
  4434. {
  4435. if (CurrentRow > 0)
  4436. {
  4437. CurrentRow--;
  4438. if (CurrentRow < _topRow)
  4439. {
  4440. _topRow--;
  4441. SetNeedsDisplay ();
  4442. }
  4443. List<Cell> currentLine = GetCurrentLine ();
  4444. CurrentColumn = Math.Max (currentLine.Count - (ReadOnly ? 1 : 0), 0);
  4445. }
  4446. else
  4447. {
  4448. return false;
  4449. }
  4450. }
  4451. Adjust ();
  4452. DoNeededAction ();
  4453. return true;
  4454. }
  4455. private void MovePageDown ()
  4456. {
  4457. int nPageDnShift = Viewport.Height - 1;
  4458. if (CurrentRow >= 0 && CurrentRow < _model.Count)
  4459. {
  4460. if (_columnTrack == -1)
  4461. {
  4462. _columnTrack = CurrentColumn;
  4463. }
  4464. CurrentRow = CurrentRow + nPageDnShift > _model.Count
  4465. ? _model.Count > 0 ? _model.Count - 1 : 0
  4466. : CurrentRow + nPageDnShift;
  4467. if (_topRow < CurrentRow - nPageDnShift)
  4468. {
  4469. _topRow = CurrentRow >= _model.Count
  4470. ? CurrentRow - nPageDnShift
  4471. : _topRow + nPageDnShift;
  4472. SetNeedsDisplay ();
  4473. }
  4474. TrackColumn ();
  4475. PositionCursor ();
  4476. }
  4477. DoNeededAction ();
  4478. }
  4479. private void MovePageUp ()
  4480. {
  4481. int nPageUpShift = Viewport.Height - 1;
  4482. if (CurrentRow > 0)
  4483. {
  4484. if (_columnTrack == -1)
  4485. {
  4486. _columnTrack = CurrentColumn;
  4487. }
  4488. CurrentRow = CurrentRow - nPageUpShift < 0 ? 0 : CurrentRow - nPageUpShift;
  4489. if (CurrentRow < _topRow)
  4490. {
  4491. _topRow = _topRow - nPageUpShift < 0 ? 0 : _topRow - nPageUpShift;
  4492. SetNeedsDisplay ();
  4493. }
  4494. TrackColumn ();
  4495. PositionCursor ();
  4496. }
  4497. DoNeededAction ();
  4498. }
  4499. private bool MoveRight ()
  4500. {
  4501. List<Cell> currentLine = GetCurrentLine ();
  4502. if ((ReadOnly ? CurrentColumn + 1 : CurrentColumn) < currentLine.Count)
  4503. {
  4504. CurrentColumn++;
  4505. }
  4506. else
  4507. {
  4508. if (CurrentRow + 1 < _model.Count)
  4509. {
  4510. CurrentRow++;
  4511. CurrentColumn = 0;
  4512. if (CurrentRow >= _topRow + Viewport.Height)
  4513. {
  4514. _topRow++;
  4515. SetNeedsDisplay ();
  4516. }
  4517. else
  4518. {
  4519. return false;
  4520. }
  4521. }
  4522. else
  4523. {
  4524. return false;
  4525. }
  4526. }
  4527. Adjust ();
  4528. DoNeededAction ();
  4529. return true;
  4530. }
  4531. private void MoveLeftStart ()
  4532. {
  4533. if (_leftColumn > 0)
  4534. {
  4535. SetNeedsDisplay ();
  4536. }
  4537. CurrentColumn = 0;
  4538. _leftColumn = 0;
  4539. Adjust ();
  4540. DoNeededAction ();
  4541. }
  4542. private void MoveTopHome ()
  4543. {
  4544. ResetAllTrack ();
  4545. if (_shiftSelecting && IsSelecting)
  4546. {
  4547. StopSelecting ();
  4548. }
  4549. MoveHome ();
  4550. }
  4551. private void MoveTopHomeExtend ()
  4552. {
  4553. ResetColumnTrack ();
  4554. StartSelecting ();
  4555. MoveHome ();
  4556. }
  4557. private bool MoveUp ()
  4558. {
  4559. if (CurrentRow > 0)
  4560. {
  4561. if (_columnTrack == -1)
  4562. {
  4563. _columnTrack = CurrentColumn;
  4564. }
  4565. CurrentRow--;
  4566. if (CurrentRow < _topRow)
  4567. {
  4568. _topRow--;
  4569. SetNeedsDisplay ();
  4570. }
  4571. TrackColumn ();
  4572. PositionCursor ();
  4573. }
  4574. else
  4575. {
  4576. return false;
  4577. }
  4578. DoNeededAction ();
  4579. return true;
  4580. }
  4581. private void MoveWordBackward ()
  4582. {
  4583. (int col, int row)? newPos = _model.WordBackward (CurrentColumn, CurrentRow);
  4584. if (newPos.HasValue)
  4585. {
  4586. CurrentColumn = newPos.Value.col;
  4587. CurrentRow = newPos.Value.row;
  4588. }
  4589. Adjust ();
  4590. DoNeededAction ();
  4591. }
  4592. private void MoveWordForward ()
  4593. {
  4594. (int col, int row)? newPos = _model.WordForward (CurrentColumn, CurrentRow);
  4595. if (newPos.HasValue)
  4596. {
  4597. CurrentColumn = newPos.Value.col;
  4598. CurrentRow = newPos.Value.row;
  4599. }
  4600. Adjust ();
  4601. DoNeededAction ();
  4602. }
  4603. private (int width, int height) OffSetBackground ()
  4604. {
  4605. var w = 0;
  4606. var h = 0;
  4607. if (SuperView?.Viewport.Right - Viewport.Right < 0)
  4608. {
  4609. w = SuperView!.Viewport.Right - Viewport.Right - 1;
  4610. }
  4611. if (SuperView?.Viewport.Bottom - Viewport.Bottom < 0)
  4612. {
  4613. h = SuperView!.Viewport.Bottom - Viewport.Bottom - 1;
  4614. }
  4615. return (w, h);
  4616. }
  4617. private bool PointInSelection (int col, int row)
  4618. {
  4619. long start, end;
  4620. GetEncodedRegionBounds (out start, out end);
  4621. long q = ((long)(uint)row << 32) | (uint)col;
  4622. return q >= start && q <= end - 1;
  4623. }
  4624. private void ProcessAutocomplete ()
  4625. {
  4626. if (_isDrawing)
  4627. {
  4628. return;
  4629. }
  4630. if (_clickWithSelecting)
  4631. {
  4632. _clickWithSelecting = false;
  4633. return;
  4634. }
  4635. if (SelectedLength > 0)
  4636. {
  4637. return;
  4638. }
  4639. // draw autocomplete
  4640. GenerateSuggestions ();
  4641. var renderAt = new Point (
  4642. Autocomplete.Context.CursorPosition,
  4643. Autocomplete.PopupInsideContainer
  4644. ? CursorPosition.Y + 1 - TopRow
  4645. : 0
  4646. );
  4647. Autocomplete.RenderOverlay (renderAt);
  4648. }
  4649. private bool ProcessBackTab ()
  4650. {
  4651. ResetColumnTrack ();
  4652. if (!AllowsTab || _isReadOnly)
  4653. {
  4654. return false;
  4655. }
  4656. if (CurrentColumn > 0)
  4657. {
  4658. SetWrapModel ();
  4659. List<Cell> currentLine = GetCurrentLine ();
  4660. if (currentLine.Count > 0 && currentLine [CurrentColumn - 1].Rune.Value == '\t')
  4661. {
  4662. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  4663. currentLine.RemoveAt (CurrentColumn - 1);
  4664. CurrentColumn--;
  4665. _historyText.Add (
  4666. new () { new (GetCurrentLine ()) },
  4667. CursorPosition,
  4668. HistoryText.LineStatus.Replaced
  4669. );
  4670. }
  4671. SetNeedsDisplay ();
  4672. UpdateWrapModel ();
  4673. }
  4674. DoNeededAction ();
  4675. return true;
  4676. }
  4677. private void ProcessCopy ()
  4678. {
  4679. ResetColumnTrack ();
  4680. Copy ();
  4681. }
  4682. private void ProcessCut ()
  4683. {
  4684. ResetColumnTrack ();
  4685. Cut ();
  4686. }
  4687. private void ProcessDeleteCharLeft ()
  4688. {
  4689. ResetColumnTrack ();
  4690. DeleteCharLeft ();
  4691. }
  4692. private void ProcessDeleteCharRight ()
  4693. {
  4694. ResetColumnTrack ();
  4695. DeleteCharRight ();
  4696. }
  4697. private Attribute? GetSelectedAttribute (int row, int col)
  4698. {
  4699. if (!InheritsPreviousAttribute || (Lines == 1 && GetLine (Lines).Count == 0))
  4700. {
  4701. return null;
  4702. }
  4703. List<Cell> line = GetLine (row);
  4704. int foundRow = row;
  4705. while (line.Count == 0)
  4706. {
  4707. if (foundRow == 0 && line.Count == 0)
  4708. {
  4709. return null;
  4710. }
  4711. foundRow--;
  4712. line = GetLine (foundRow);
  4713. }
  4714. int foundCol = foundRow < row ? line.Count - 1 : Math.Min (col, line.Count - 1);
  4715. Cell cell = line [foundCol];
  4716. return cell.Attribute;
  4717. }
  4718. // If InheritsPreviousColorScheme is enabled this method will check if the rune cell on
  4719. // the row and col location and around has a not null color scheme. If it's null will set it with
  4720. // the very most previous valid color scheme.
  4721. private void ProcessInheritsPreviousColorScheme (int row, int col)
  4722. {
  4723. if (!InheritsPreviousAttribute || (Lines == 1 && GetLine (Lines).Count == 0))
  4724. {
  4725. return;
  4726. }
  4727. List<Cell> line = GetLine (row);
  4728. List<Cell> lineToSet = line;
  4729. while (line.Count == 0)
  4730. {
  4731. if (row == 0 && line.Count == 0)
  4732. {
  4733. return;
  4734. }
  4735. row--;
  4736. line = GetLine (row);
  4737. lineToSet = line;
  4738. }
  4739. int colWithColor = Math.Max (Math.Min (col - 2, line.Count - 1), 0);
  4740. Cell cell = line [colWithColor];
  4741. int colWithoutColor = Math.Max (col - 1, 0);
  4742. Cell lineTo = lineToSet [colWithoutColor];
  4743. if (cell.Attribute is { } && colWithColor == 0 && lineTo.Attribute is { })
  4744. {
  4745. for (int r = row - 1; r > -1; r--)
  4746. {
  4747. List<Cell> l = GetLine (r);
  4748. for (int c = l.Count - 1; c > -1; c--)
  4749. {
  4750. Cell cell1 = l [c];
  4751. if (cell1.Attribute is null)
  4752. {
  4753. cell1.Attribute = cell.Attribute;
  4754. l [c] = cell1;
  4755. }
  4756. else
  4757. {
  4758. return;
  4759. }
  4760. }
  4761. }
  4762. return;
  4763. }
  4764. if (cell.Attribute is null)
  4765. {
  4766. for (int r = row; r > -1; r--)
  4767. {
  4768. List<Cell> l = GetLine (r);
  4769. colWithColor = l.FindLastIndex (
  4770. colWithColor > -1 ? colWithColor : l.Count - 1,
  4771. c => c.Attribute != null
  4772. );
  4773. if (colWithColor > -1 && l [colWithColor].Attribute is { })
  4774. {
  4775. cell = l [colWithColor];
  4776. break;
  4777. }
  4778. }
  4779. }
  4780. else
  4781. {
  4782. int cRow = row;
  4783. while (cell.Attribute is null)
  4784. {
  4785. if ((colWithColor == 0 || cell.Attribute is null) && cRow > 0)
  4786. {
  4787. line = GetLine (--cRow);
  4788. colWithColor = line.Count - 1;
  4789. cell = line [colWithColor];
  4790. }
  4791. else if (cRow == 0 && colWithColor < line.Count)
  4792. {
  4793. cell = line [colWithColor + 1];
  4794. }
  4795. }
  4796. }
  4797. if (cell.Attribute is { } && colWithColor > -1 && colWithoutColor < lineToSet.Count && lineTo.Attribute is null)
  4798. {
  4799. while (lineTo.Attribute is null)
  4800. {
  4801. lineTo.Attribute = cell.Attribute;
  4802. lineToSet [colWithoutColor] = lineTo;
  4803. colWithoutColor--;
  4804. if (colWithoutColor == -1 && row > 0)
  4805. {
  4806. lineToSet = GetLine (--row);
  4807. colWithoutColor = lineToSet.Count - 1;
  4808. }
  4809. }
  4810. }
  4811. }
  4812. private void ProcessKillWordBackward ()
  4813. {
  4814. ResetColumnTrack ();
  4815. KillWordBackward ();
  4816. }
  4817. private void ProcessKillWordForward ()
  4818. {
  4819. ResetColumnTrack ();
  4820. KillWordForward ();
  4821. }
  4822. private void ProcessMouseClick (MouseEvent ev, out List<Cell> line)
  4823. {
  4824. List<Cell>? r = null;
  4825. if (_model.Count > 0)
  4826. {
  4827. int maxCursorPositionableLine = Math.Max (_model.Count - 1 - _topRow, 0);
  4828. if (Math.Max (ev.Position.Y, 0) > maxCursorPositionableLine)
  4829. {
  4830. CurrentRow = maxCursorPositionableLine + _topRow;
  4831. }
  4832. else
  4833. {
  4834. CurrentRow = Math.Max (ev.Position.Y + _topRow, 0);
  4835. }
  4836. r = GetCurrentLine ();
  4837. int idx = TextModel.GetColFromX (r, _leftColumn, Math.Max (ev.Position.X, 0), TabWidth);
  4838. if (idx - _leftColumn >= r.Count)
  4839. {
  4840. CurrentColumn = Math.Max (r.Count - _leftColumn - (ReadOnly ? 1 : 0), 0);
  4841. }
  4842. else
  4843. {
  4844. CurrentColumn = idx + _leftColumn;
  4845. }
  4846. }
  4847. line = r!;
  4848. }
  4849. private bool ProcessMoveDown ()
  4850. {
  4851. ResetContinuousFindTrack ();
  4852. if (_shiftSelecting && IsSelecting)
  4853. {
  4854. StopSelecting ();
  4855. }
  4856. return MoveDown ();
  4857. }
  4858. private void ProcessMoveDownExtend ()
  4859. {
  4860. ResetColumnTrack ();
  4861. StartSelecting ();
  4862. MoveDown ();
  4863. }
  4864. private void ProcessMoveEndOfLine ()
  4865. {
  4866. ResetAllTrack ();
  4867. if (_shiftSelecting && IsSelecting)
  4868. {
  4869. StopSelecting ();
  4870. }
  4871. MoveEndOfLine ();
  4872. }
  4873. private void ProcessMoveRightEndExtend ()
  4874. {
  4875. ResetAllTrack ();
  4876. StartSelecting ();
  4877. MoveEndOfLine ();
  4878. }
  4879. private bool ProcessMoveLeft ()
  4880. {
  4881. // if the user presses Left (without any control keys) and they are at the start of the text
  4882. if (CurrentColumn == 0 && CurrentRow == 0)
  4883. {
  4884. if (IsSelecting)
  4885. {
  4886. StopSelecting ();
  4887. return true;
  4888. }
  4889. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  4890. return false;
  4891. }
  4892. ResetAllTrack ();
  4893. if (_shiftSelecting && IsSelecting)
  4894. {
  4895. StopSelecting ();
  4896. }
  4897. MoveLeft ();
  4898. return true;
  4899. }
  4900. private void ProcessMoveLeftExtend ()
  4901. {
  4902. ResetAllTrack ();
  4903. StartSelecting ();
  4904. MoveLeft ();
  4905. }
  4906. private bool ProcessMoveRight ()
  4907. {
  4908. // if the user presses Right (without any control keys)
  4909. // determine where the last cursor position in the text is
  4910. int lastRow = _model.Count - 1;
  4911. int lastCol = _model.GetLine (lastRow).Count;
  4912. // 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)
  4913. if (CurrentColumn == lastCol && CurrentRow == lastRow)
  4914. {
  4915. // Unless they have text selected
  4916. if (IsSelecting)
  4917. {
  4918. // In which case clear
  4919. StopSelecting ();
  4920. return true;
  4921. }
  4922. return false;
  4923. }
  4924. ResetAllTrack ();
  4925. if (_shiftSelecting && IsSelecting)
  4926. {
  4927. StopSelecting ();
  4928. }
  4929. MoveRight ();
  4930. return true;
  4931. }
  4932. private void ProcessMoveRightExtend ()
  4933. {
  4934. ResetAllTrack ();
  4935. StartSelecting ();
  4936. MoveRight ();
  4937. }
  4938. private void ProcessMoveLeftStart ()
  4939. {
  4940. ResetAllTrack ();
  4941. if (_shiftSelecting && IsSelecting)
  4942. {
  4943. StopSelecting ();
  4944. }
  4945. MoveLeftStart ();
  4946. }
  4947. private void ProcessMoveLeftStartExtend ()
  4948. {
  4949. ResetAllTrack ();
  4950. StartSelecting ();
  4951. MoveLeftStart ();
  4952. }
  4953. private bool ProcessMoveUp ()
  4954. {
  4955. ResetContinuousFindTrack ();
  4956. if (_shiftSelecting && IsSelecting)
  4957. {
  4958. StopSelecting ();
  4959. }
  4960. return MoveUp ();
  4961. }
  4962. private void ProcessMoveUpExtend ()
  4963. {
  4964. ResetColumnTrack ();
  4965. StartSelecting ();
  4966. MoveUp ();
  4967. }
  4968. private void ProcessMoveWordBackward ()
  4969. {
  4970. ResetAllTrack ();
  4971. if (_shiftSelecting && IsSelecting)
  4972. {
  4973. StopSelecting ();
  4974. }
  4975. MoveWordBackward ();
  4976. }
  4977. private void ProcessMoveWordBackwardExtend ()
  4978. {
  4979. ResetAllTrack ();
  4980. StartSelecting ();
  4981. MoveWordBackward ();
  4982. }
  4983. private void ProcessMoveWordForward ()
  4984. {
  4985. ResetAllTrack ();
  4986. if (_shiftSelecting && IsSelecting)
  4987. {
  4988. StopSelecting ();
  4989. }
  4990. MoveWordForward ();
  4991. }
  4992. private void ProcessMoveWordForwardExtend ()
  4993. {
  4994. ResetAllTrack ();
  4995. StartSelecting ();
  4996. MoveWordForward ();
  4997. }
  4998. private void ProcessPageDown ()
  4999. {
  5000. ResetColumnTrack ();
  5001. if (_shiftSelecting && IsSelecting)
  5002. {
  5003. StopSelecting ();
  5004. }
  5005. MovePageDown ();
  5006. }
  5007. private void ProcessPageDownExtend ()
  5008. {
  5009. ResetColumnTrack ();
  5010. StartSelecting ();
  5011. MovePageDown ();
  5012. }
  5013. private void ProcessPageUp ()
  5014. {
  5015. ResetColumnTrack ();
  5016. if (_shiftSelecting && IsSelecting)
  5017. {
  5018. StopSelecting ();
  5019. }
  5020. MovePageUp ();
  5021. }
  5022. private void ProcessPageUpExtend ()
  5023. {
  5024. ResetColumnTrack ();
  5025. StartSelecting ();
  5026. MovePageUp ();
  5027. }
  5028. private void ProcessPaste ()
  5029. {
  5030. ResetColumnTrack ();
  5031. if (_isReadOnly)
  5032. {
  5033. return;
  5034. }
  5035. Paste ();
  5036. }
  5037. private bool ProcessEnterKey (CommandContext ctx)
  5038. {
  5039. ResetColumnTrack ();
  5040. if (_isReadOnly)
  5041. {
  5042. return false;
  5043. }
  5044. if (!AllowsReturn)
  5045. {
  5046. // By Default pressing ENTER should be ignored (OnAccept will return false or null). Only cancel if the
  5047. // event was fired and set Cancel = true.
  5048. return RaiseAccepting (ctx) is null or false;
  5049. }
  5050. SetWrapModel ();
  5051. List<Cell> currentLine = GetCurrentLine ();
  5052. _historyText.Add (new () { new (currentLine) }, CursorPosition);
  5053. if (IsSelecting)
  5054. {
  5055. ClearSelectedRegion ();
  5056. currentLine = GetCurrentLine ();
  5057. }
  5058. int restCount = currentLine.Count - CurrentColumn;
  5059. List<Cell> rest = currentLine.GetRange (CurrentColumn, restCount);
  5060. currentLine.RemoveRange (CurrentColumn, restCount);
  5061. List<List<Cell>> addedLines = new () { new (currentLine) };
  5062. _model.AddLine (CurrentRow + 1, rest);
  5063. addedLines.Add (new (_model.GetLine (CurrentRow + 1)));
  5064. _historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  5065. CurrentRow++;
  5066. var fullNeedsDisplay = false;
  5067. if (CurrentRow >= _topRow + Viewport.Height)
  5068. {
  5069. _topRow++;
  5070. fullNeedsDisplay = true;
  5071. }
  5072. CurrentColumn = 0;
  5073. _historyText.Add (
  5074. new () { new (GetCurrentLine ()) },
  5075. CursorPosition,
  5076. HistoryText.LineStatus.Replaced
  5077. );
  5078. if (!_wordWrap && CurrentColumn < _leftColumn)
  5079. {
  5080. fullNeedsDisplay = true;
  5081. _leftColumn = 0;
  5082. }
  5083. if (fullNeedsDisplay)
  5084. {
  5085. SetNeedsDisplay ();
  5086. }
  5087. else
  5088. {
  5089. // BUGBUG: customized rect aren't supported now because the Redraw isn't using the Intersect method.
  5090. //SetNeedsDisplay (new (0, currentRow - topRow, 2, Viewport.Height));
  5091. SetNeedsDisplay ();
  5092. }
  5093. UpdateWrapModel ();
  5094. DoNeededAction ();
  5095. OnContentsChanged ();
  5096. return true;
  5097. }
  5098. private void ProcessSelectAll ()
  5099. {
  5100. ResetColumnTrack ();
  5101. SelectAll ();
  5102. }
  5103. private void ProcessSetOverwrite ()
  5104. {
  5105. ResetColumnTrack ();
  5106. SetOverwrite (!Used);
  5107. }
  5108. private bool ProcessTab ()
  5109. {
  5110. ResetColumnTrack ();
  5111. if (!AllowsTab || _isReadOnly)
  5112. {
  5113. return false;
  5114. }
  5115. InsertText (new Key ((KeyCode)'\t'));
  5116. DoNeededAction ();
  5117. return true;
  5118. }
  5119. private void ResetAllTrack ()
  5120. {
  5121. // Handle some state here - whether the last command was a kill
  5122. // operation and the column tracking (up/down)
  5123. _lastWasKill = false;
  5124. _columnTrack = -1;
  5125. _continuousFind = false;
  5126. }
  5127. private void ResetColumnTrack ()
  5128. {
  5129. // Handle some state here - whether the last command was a kill
  5130. // operation and the column tracking (up/down)
  5131. _lastWasKill = false;
  5132. _columnTrack = -1;
  5133. }
  5134. private void ResetContinuousFind ()
  5135. {
  5136. if (!_continuousFind)
  5137. {
  5138. int col = IsSelecting ? _selectionStartColumn : CurrentColumn;
  5139. int row = IsSelecting ? _selectionStartRow : CurrentRow;
  5140. _model.ResetContinuousFind (new (col, row));
  5141. }
  5142. }
  5143. private void ResetContinuousFindTrack ()
  5144. {
  5145. // Handle some state here - whether the last command was a kill
  5146. // operation and the column tracking (up/down)
  5147. _lastWasKill = false;
  5148. _continuousFind = false;
  5149. }
  5150. private void ResetPosition ()
  5151. {
  5152. _topRow = _leftColumn = CurrentRow = CurrentColumn = 0;
  5153. StopSelecting ();
  5154. }
  5155. private void SetClipboard (string text)
  5156. {
  5157. if (text is { })
  5158. {
  5159. Clipboard.Contents = text;
  5160. }
  5161. }
  5162. private bool SetFoundText (
  5163. string text,
  5164. (Point current, bool found) foundPos,
  5165. string? textToReplace = null,
  5166. bool replace = false,
  5167. bool replaceAll = false
  5168. )
  5169. {
  5170. if (foundPos.found)
  5171. {
  5172. StartSelecting ();
  5173. _selectionStartColumn = foundPos.current.X;
  5174. _selectionStartRow = foundPos.current.Y;
  5175. if (!replaceAll)
  5176. {
  5177. CurrentColumn = _selectionStartColumn + text.GetRuneCount ();
  5178. }
  5179. else
  5180. {
  5181. CurrentColumn = _selectionStartColumn + textToReplace!.GetRuneCount ();
  5182. }
  5183. CurrentRow = foundPos.current.Y;
  5184. if (!_isReadOnly && replace)
  5185. {
  5186. Adjust ();
  5187. ClearSelectedRegion ();
  5188. InsertAllText (textToReplace!);
  5189. StartSelecting ();
  5190. _selectionStartColumn = CurrentColumn - textToReplace!.GetRuneCount ();
  5191. }
  5192. else
  5193. {
  5194. UpdateWrapModel ();
  5195. SetNeedsDisplay ();
  5196. Adjust ();
  5197. }
  5198. _continuousFind = true;
  5199. return foundPos.found;
  5200. }
  5201. UpdateWrapModel ();
  5202. _continuousFind = false;
  5203. return foundPos.found;
  5204. }
  5205. private void SetOverwrite (bool overwrite)
  5206. {
  5207. Used = overwrite;
  5208. SetNeedsDisplay ();
  5209. DoNeededAction ();
  5210. }
  5211. private static void SetValidUsedColor (Attribute? attribute)
  5212. {
  5213. // BUGBUG: (v2 truecolor) This code depends on 8-bit color names; disabling for now
  5214. //if ((colorScheme!.HotNormal.Foreground & colorScheme.Focus.Background) == colorScheme.Focus.Foreground) {
  5215. Driver.SetAttribute (new (attribute!.Value.Background, attribute!.Value.Foreground));
  5216. }
  5217. /// <summary>Restore from original model.</summary>
  5218. private void SetWrapModel ([CallerMemberName] string? caller = null)
  5219. {
  5220. if (_currentCaller is { })
  5221. {
  5222. return;
  5223. }
  5224. if (_wordWrap)
  5225. {
  5226. _currentCaller = caller;
  5227. CurrentColumn = _wrapManager!.GetModelColFromWrappedLines (CurrentRow, CurrentColumn);
  5228. CurrentRow = _wrapManager.GetModelLineFromWrappedLines (CurrentRow);
  5229. _selectionStartColumn =
  5230. _wrapManager.GetModelColFromWrappedLines (_selectionStartRow, _selectionStartColumn);
  5231. _selectionStartRow = _wrapManager.GetModelLineFromWrappedLines (_selectionStartRow);
  5232. _model = _wrapManager.Model;
  5233. }
  5234. }
  5235. private void ShowContextMenu ()
  5236. {
  5237. if (!Equals (_currentCulture, Thread.CurrentThread.CurrentUICulture))
  5238. {
  5239. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  5240. }
  5241. ContextMenu!.Show (BuildContextMenuBarItem ());
  5242. }
  5243. private void StartSelecting ()
  5244. {
  5245. if (_shiftSelecting && IsSelecting)
  5246. {
  5247. return;
  5248. }
  5249. _shiftSelecting = true;
  5250. IsSelecting = true;
  5251. _selectionStartColumn = CurrentColumn;
  5252. _selectionStartRow = CurrentRow;
  5253. }
  5254. private void StopSelecting ()
  5255. {
  5256. _shiftSelecting = false;
  5257. IsSelecting = false;
  5258. _isButtonShift = false;
  5259. }
  5260. private string StringFromRunes (List<Cell> cells)
  5261. {
  5262. if (cells is null)
  5263. {
  5264. throw new ArgumentNullException (nameof (cells));
  5265. }
  5266. var size = 0;
  5267. foreach (Cell cell in cells)
  5268. {
  5269. size += cell.Rune.GetEncodingLength ();
  5270. }
  5271. var encoded = new byte [size];
  5272. var offset = 0;
  5273. foreach (Cell cell in cells)
  5274. {
  5275. offset += cell.Rune.Encode (encoded, offset);
  5276. }
  5277. return StringExtensions.ToString (encoded);
  5278. }
  5279. private void TextView_Added (object sender, SuperViewChangedEventArgs e)
  5280. {
  5281. if (Autocomplete.HostControl is null)
  5282. {
  5283. Autocomplete.HostControl = this;
  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. SetNeedsDisplay ();
  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. SetNeedsDisplay ();
  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. }