TextView.cs 125 KB

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