2
0

TextView.cs 182 KB

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