TextView.cs 186 KB

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