2
0

TextView.cs 187 KB

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