TextView.cs 138 KB

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