TextView.cs 142 KB

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