TextView.cs 187 KB

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