TextView.cs 185 KB

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