TextView.cs 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506
  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. Application.Top.AlternateForwardKeyChanged += Top_AlternateForwardKeyChanged;
  1249. Application.Top.AlternateBackwardKeyChanged += Top_AlternateBackwardKeyChanged;
  1250. OnContentsChanged ();
  1251. }
  1252. void Top_AlternateBackwardKeyChanged (Key obj)
  1253. {
  1254. ReplaceKeyBinding (obj, Application.AlternateBackwardKey);
  1255. }
  1256. void Top_AlternateForwardKeyChanged (Key obj)
  1257. {
  1258. ReplaceKeyBinding (obj, Application.AlternateForwardKey);
  1259. }
  1260. /// <summary>
  1261. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry,
  1262. /// so new input should be appended at the cursor position, rather than clearing the entry
  1263. /// </summary>
  1264. public bool Used { get; set; }
  1265. void ResetPosition ()
  1266. {
  1267. topRow = leftColumn = currentRow = currentColumn = 0;
  1268. StopSelecting ();
  1269. ResetCursorVisibility ();
  1270. }
  1271. /// <summary>
  1272. /// Sets or gets the text in the <see cref="TextView"/>.
  1273. /// </summary>
  1274. /// <remarks>
  1275. /// The <see cref="TextChanged"/> event is fired whenever this property is set. Note, however,
  1276. /// that Text is not set by <see cref="TextView"/> as the user types.
  1277. /// </remarks>
  1278. public override ustring Text {
  1279. get {
  1280. if (wordWrap) {
  1281. return wrapManager.Model.ToString ();
  1282. } else {
  1283. return model.ToString ();
  1284. }
  1285. }
  1286. set {
  1287. ResetPosition ();
  1288. model.LoadString (value);
  1289. if (wordWrap) {
  1290. wrapManager = new WordWrapManager (model);
  1291. model = wrapManager.WrapModel (frameWidth, out _, out _, out _, out _);
  1292. }
  1293. TextChanged?.Invoke ();
  1294. SetNeedsDisplay ();
  1295. historyText.Clear (Text);
  1296. }
  1297. }
  1298. ///<inheritdoc/>
  1299. public override Rect Frame {
  1300. get => base.Frame;
  1301. set {
  1302. base.Frame = value;
  1303. WrapTextModel ();
  1304. Adjust ();
  1305. }
  1306. }
  1307. void WrapTextModel ()
  1308. {
  1309. if (wordWrap && wrapManager != null) {
  1310. model = wrapManager.WrapModel (frameWidth,
  1311. out int nRow, out int nCol,
  1312. out int nStartRow, out int nStartCol,
  1313. currentRow, currentColumn,
  1314. selectionStartRow, selectionStartColumn,
  1315. tabWidth, preserveTrailingSpaces: true);
  1316. currentRow = nRow;
  1317. currentColumn = nCol;
  1318. selectionStartRow = nStartRow;
  1319. selectionStartColumn = nStartCol;
  1320. SetNeedsDisplay ();
  1321. }
  1322. }
  1323. int frameWidth => Math.Max (Frame.Width - (RightOffset != 0 ? 2 : 1), 0);
  1324. /// <summary>
  1325. /// Gets or sets the top row.
  1326. /// </summary>
  1327. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  1328. /// <summary>
  1329. /// Gets or sets the left column.
  1330. /// </summary>
  1331. public int LeftColumn {
  1332. get => leftColumn;
  1333. set {
  1334. if (value > 0 && wordWrap)
  1335. return;
  1336. leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0);
  1337. }
  1338. }
  1339. /// <summary>
  1340. /// Gets the maximum visible length line.
  1341. /// </summary>
  1342. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height, TabWidth);
  1343. /// <summary>
  1344. /// Gets the number of lines.
  1345. /// </summary>
  1346. public int Lines => model.Count;
  1347. /// <summary>
  1348. /// Sets or gets the current cursor position.
  1349. /// </summary>
  1350. public Point CursorPosition {
  1351. get => new Point (currentColumn, currentRow);
  1352. set {
  1353. var line = model.GetLine (Math.Max (Math.Min (value.Y, model.Count - 1), 0));
  1354. currentColumn = value.X < 0 ? 0 : value.X > line.Count ? line.Count : value.X;
  1355. currentRow = value.Y < 0 ? 0 : value.Y > model.Count - 1
  1356. ? Math.Max (model.Count - 1, 0) : value.Y;
  1357. SetNeedsDisplay ();
  1358. Adjust ();
  1359. }
  1360. }
  1361. /// <summary>
  1362. /// Start column position of the selected text.
  1363. /// </summary>
  1364. public int SelectionStartColumn {
  1365. get => selectionStartColumn;
  1366. set {
  1367. var line = model.GetLine (currentRow);
  1368. selectionStartColumn = value < 0 ? 0 : value > line.Count ? line.Count : value;
  1369. selecting = true;
  1370. SetNeedsDisplay ();
  1371. Adjust ();
  1372. }
  1373. }
  1374. /// <summary>
  1375. /// Start row position of the selected text.
  1376. /// </summary>
  1377. public int SelectionStartRow {
  1378. get => selectionStartRow;
  1379. set {
  1380. selectionStartRow = value < 0 ? 0 : value > model.Count - 1
  1381. ? Math.Max (model.Count - 1, 0) : value;
  1382. selecting = true;
  1383. SetNeedsDisplay ();
  1384. Adjust ();
  1385. }
  1386. }
  1387. /// <summary>
  1388. /// The selected text.
  1389. /// </summary>
  1390. public ustring SelectedText {
  1391. get {
  1392. if (!selecting || (model.Count == 1 && model.GetLine (0).Count == 0)) {
  1393. return ustring.Empty;
  1394. }
  1395. return GetSelectedRegion ();
  1396. }
  1397. }
  1398. /// <summary>
  1399. /// Length of the selected text.
  1400. /// </summary>
  1401. public int SelectedLength => GetSelectedLength ();
  1402. /// <summary>
  1403. /// Get or sets the selecting.
  1404. /// </summary>
  1405. public bool Selecting {
  1406. get => selecting;
  1407. set => selecting = value;
  1408. }
  1409. /// <summary>
  1410. /// Allows word wrap the to fit the available container width.
  1411. /// </summary>
  1412. public bool WordWrap {
  1413. get => wordWrap;
  1414. set {
  1415. if (value == wordWrap) {
  1416. return;
  1417. }
  1418. if (value && !multiline) {
  1419. return;
  1420. }
  1421. wordWrap = value;
  1422. ResetPosition ();
  1423. if (wordWrap) {
  1424. wrapManager = new WordWrapManager (model);
  1425. model = wrapManager.WrapModel (frameWidth, out _, out _, out _, out _);
  1426. } else if (!wordWrap && wrapManager != null) {
  1427. model = wrapManager.Model;
  1428. }
  1429. SetNeedsDisplay ();
  1430. }
  1431. }
  1432. /// <summary>
  1433. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  1434. /// This is only needed with the keyboard navigation.
  1435. /// </summary>
  1436. public int BottomOffset {
  1437. get => bottomOffset;
  1438. set {
  1439. if (currentRow == Lines - 1 && bottomOffset > 0 && value == 0) {
  1440. topRow = Math.Max (topRow - bottomOffset, 0);
  1441. }
  1442. bottomOffset = value;
  1443. Adjust ();
  1444. }
  1445. }
  1446. /// <summary>
  1447. /// The right offset needed to use a vertical scrollbar or for another reason.
  1448. /// This is only needed with the keyboard navigation.
  1449. /// </summary>
  1450. public int RightOffset {
  1451. get => rightOffset;
  1452. set {
  1453. if (!wordWrap && currentColumn == GetCurrentLine ().Count && rightOffset > 0 && value == 0) {
  1454. leftColumn = Math.Max (leftColumn - rightOffset, 0);
  1455. }
  1456. rightOffset = value;
  1457. Adjust ();
  1458. }
  1459. }
  1460. /// <summary>
  1461. /// Gets or sets a value indicating whether pressing ENTER in a <see cref="TextView"/>
  1462. /// creates a new line of text in the view or activates the default button for the toplevel.
  1463. /// </summary>
  1464. public bool AllowsReturn {
  1465. get => allowsReturn;
  1466. set {
  1467. allowsReturn = value;
  1468. if (allowsReturn && !multiline) {
  1469. Multiline = true;
  1470. }
  1471. if (!allowsReturn && multiline) {
  1472. Multiline = false;
  1473. AllowsTab = false;
  1474. }
  1475. SetNeedsDisplay ();
  1476. }
  1477. }
  1478. /// <summary>
  1479. /// Gets or sets whether the <see cref="TextView"/> inserts a tab character into the text or ignores
  1480. /// tab input. If set to `false` and the user presses the tab key (or shift-tab) the focus will move to the
  1481. /// next view (or previous with shift-tab). The default is `true`; if the user presses the tab key, a tab
  1482. /// character will be inserted into the text.
  1483. /// </summary>
  1484. public bool AllowsTab {
  1485. get => allowsTab;
  1486. set {
  1487. allowsTab = value;
  1488. if (allowsTab && tabWidth == 0) {
  1489. tabWidth = 4;
  1490. }
  1491. if (allowsTab && !multiline) {
  1492. Multiline = true;
  1493. }
  1494. if (!allowsTab && tabWidth > 0) {
  1495. tabWidth = 0;
  1496. }
  1497. SetNeedsDisplay ();
  1498. }
  1499. }
  1500. /// <summary>
  1501. /// Gets or sets a value indicating the number of whitespace when pressing the TAB key.
  1502. /// </summary>
  1503. public int TabWidth {
  1504. get => tabWidth;
  1505. set {
  1506. tabWidth = Math.Max (value, 0);
  1507. if (tabWidth > 0 && !AllowsTab) {
  1508. AllowsTab = true;
  1509. }
  1510. SetNeedsDisplay ();
  1511. }
  1512. }
  1513. Dim savedHeight = null;
  1514. /// <summary>
  1515. /// Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.
  1516. /// </summary>
  1517. public bool Multiline {
  1518. get => multiline;
  1519. set {
  1520. multiline = value;
  1521. if (multiline && !allowsTab) {
  1522. AllowsTab = true;
  1523. }
  1524. if (multiline && !allowsReturn) {
  1525. AllowsReturn = true;
  1526. }
  1527. if (!multiline) {
  1528. AllowsReturn = false;
  1529. AllowsTab = false;
  1530. WordWrap = false;
  1531. currentColumn = 0;
  1532. currentRow = 0;
  1533. savedHeight = Height;
  1534. var lyout = LayoutStyle;
  1535. if (LayoutStyle == LayoutStyle.Computed) {
  1536. LayoutStyle = LayoutStyle.Absolute;
  1537. }
  1538. Height = 1;
  1539. LayoutStyle = lyout;
  1540. Autocomplete.PopupInsideContainer = false;
  1541. SetNeedsDisplay ();
  1542. } else if (multiline && savedHeight != null) {
  1543. var lyout = LayoutStyle;
  1544. if (LayoutStyle == LayoutStyle.Computed) {
  1545. LayoutStyle = LayoutStyle.Absolute;
  1546. }
  1547. Height = savedHeight;
  1548. LayoutStyle = lyout;
  1549. Autocomplete.PopupInsideContainer = true;
  1550. SetNeedsDisplay ();
  1551. }
  1552. }
  1553. }
  1554. /// <summary>
  1555. /// Indicates whatever the text was changed or not.
  1556. /// <see langword="true"/> if the text was changed <see langword="false"/> otherwise.
  1557. /// </summary>
  1558. public bool IsDirty => historyText.IsDirty (Text);
  1559. /// <summary>
  1560. /// Indicates whatever the text has history changes or not.
  1561. /// <see langword="true"/> if the text has history changes <see langword="false"/> otherwise.
  1562. /// </summary>
  1563. public bool HasHistoryChanges => historyText.HasHistoryChanges;
  1564. /// <summary>
  1565. /// Get the <see cref="ContextMenu"/> for this view.
  1566. /// </summary>
  1567. public ContextMenu ContextMenu { get; private set; }
  1568. int GetSelectedLength ()
  1569. {
  1570. return SelectedText.Length;
  1571. }
  1572. CursorVisibility savedCursorVisibility;
  1573. void SaveCursorVisibility ()
  1574. {
  1575. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  1576. if (savedCursorVisibility == 0) {
  1577. savedCursorVisibility = desiredCursorVisibility;
  1578. }
  1579. DesiredCursorVisibility = CursorVisibility.Invisible;
  1580. }
  1581. }
  1582. void ResetCursorVisibility ()
  1583. {
  1584. if (savedCursorVisibility != 0) {
  1585. DesiredCursorVisibility = savedCursorVisibility;
  1586. savedCursorVisibility = 0;
  1587. }
  1588. }
  1589. /// <summary>
  1590. /// Loads the contents of the file into the <see cref="TextView"/>.
  1591. /// </summary>
  1592. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  1593. /// <param name="path">Path to the file to load.</param>
  1594. public bool LoadFile (string path)
  1595. {
  1596. bool res;
  1597. try {
  1598. SetWrapModel ();
  1599. res = model.LoadFile (path);
  1600. historyText.Clear (Text);
  1601. ResetPosition ();
  1602. } catch (Exception) {
  1603. throw;
  1604. } finally {
  1605. UpdateWrapModel ();
  1606. SetNeedsDisplay ();
  1607. Adjust ();
  1608. }
  1609. return res;
  1610. }
  1611. /// <summary>
  1612. /// Loads the contents of the stream into the <see cref="TextView"/>.
  1613. /// </summary>
  1614. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  1615. /// <param name="stream">Stream to load the contents from.</param>
  1616. public void LoadStream (Stream stream)
  1617. {
  1618. model.LoadStream (stream);
  1619. historyText.Clear (Text);
  1620. ResetPosition ();
  1621. SetNeedsDisplay ();
  1622. }
  1623. /// <summary>
  1624. /// Closes the contents of the stream into the <see cref="TextView"/>.
  1625. /// </summary>
  1626. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  1627. public bool CloseFile ()
  1628. {
  1629. var res = model.CloseFile ();
  1630. ResetPosition ();
  1631. SetNeedsDisplay ();
  1632. return res;
  1633. }
  1634. /// <summary>
  1635. /// Gets the current cursor row.
  1636. /// </summary>
  1637. public int CurrentRow => currentRow;
  1638. /// <summary>
  1639. /// Gets the cursor column.
  1640. /// </summary>
  1641. /// <value>The cursor column.</value>
  1642. public int CurrentColumn => currentColumn;
  1643. /// <summary>
  1644. /// Positions the cursor on the current row and column
  1645. /// </summary>
  1646. public override void PositionCursor ()
  1647. {
  1648. if (!CanFocus || !Enabled) {
  1649. return;
  1650. }
  1651. if (selecting) {
  1652. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1653. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1654. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  1655. }
  1656. var line = model.GetLine (currentRow);
  1657. var col = 0;
  1658. if (line.Count > 0) {
  1659. for (int idx = leftColumn; idx < line.Count; idx++) {
  1660. if (idx >= currentColumn)
  1661. break;
  1662. var cols = Rune.ColumnWidth (line [idx]);
  1663. if (line [idx] == '\t') {
  1664. cols += TabWidth + 1;
  1665. }
  1666. if (!TextModel.SetCol (ref col, Frame.Width, cols)) {
  1667. col = currentColumn;
  1668. break;
  1669. }
  1670. }
  1671. }
  1672. var posX = currentColumn - leftColumn;
  1673. var posY = currentRow - topRow;
  1674. if (posX > -1 && col >= posX && posX < Frame.Width - RightOffset
  1675. && topRow <= currentRow && posY < Frame.Height - BottomOffset) {
  1676. ResetCursorVisibility ();
  1677. Move (col, currentRow - topRow);
  1678. } else {
  1679. SaveCursorVisibility ();
  1680. }
  1681. }
  1682. void ClearRegion (int left, int top, int right, int bottom)
  1683. {
  1684. for (int row = top; row < bottom; row++) {
  1685. Move (left, row);
  1686. for (int col = left; col < right; col++)
  1687. AddRune (col, row, ' ');
  1688. }
  1689. }
  1690. /// <summary>
  1691. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to <see cref="ColorScheme.Normal"/>.
  1692. /// </summary>
  1693. protected virtual void SetNormalColor ()
  1694. {
  1695. Driver.SetAttribute (GetNormalColor ());
  1696. }
  1697. /// <summary>
  1698. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1699. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1700. /// Defaults to <see cref="ColorScheme.Normal"/>.
  1701. /// </summary>
  1702. /// <param name="line"></param>
  1703. /// <param name="idx"></param>
  1704. protected virtual void SetNormalColor (List<Rune> line, int idx)
  1705. {
  1706. Driver.SetAttribute (GetNormalColor ());
  1707. }
  1708. /// <summary>
  1709. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1710. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1711. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1712. /// </summary>
  1713. /// <param name="line"></param>
  1714. /// <param name="idx"></param>
  1715. protected virtual void SetSelectionColor (List<Rune> line, int idx)
  1716. {
  1717. Driver.SetAttribute (new Attribute (ColorScheme.Focus.Background, ColorScheme.Focus.Foreground));
  1718. }
  1719. /// <summary>
  1720. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1721. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1722. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1723. /// </summary>
  1724. /// <param name="line"></param>
  1725. /// <param name="idx"></param>
  1726. protected virtual void SetReadOnlyColor (List<Rune> line, int idx)
  1727. {
  1728. Attribute attribute;
  1729. if (ColorScheme.Disabled.Foreground == ColorScheme.Focus.Background) {
  1730. attribute = new Attribute (ColorScheme.Focus.Foreground, ColorScheme.Focus.Background);
  1731. } else {
  1732. attribute = new Attribute (ColorScheme.Disabled.Foreground, ColorScheme.Focus.Background);
  1733. }
  1734. Driver.SetAttribute (attribute);
  1735. }
  1736. /// <summary>
  1737. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1738. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1739. /// Defaults to <see cref="ColorScheme.HotFocus"/>.
  1740. /// </summary>
  1741. /// <param name="line"></param>
  1742. /// <param name="idx"></param>
  1743. protected virtual void SetUsedColor (List<Rune> line, int idx)
  1744. {
  1745. Driver.SetAttribute (ColorScheme.HotFocus);
  1746. }
  1747. bool isReadOnly = false;
  1748. /// <summary>
  1749. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1750. /// </summary>
  1751. /// <value>Boolean value(Default false)</value>
  1752. public bool ReadOnly {
  1753. get => isReadOnly;
  1754. set {
  1755. if (value != isReadOnly) {
  1756. isReadOnly = value;
  1757. SetNeedsDisplay ();
  1758. Adjust ();
  1759. }
  1760. }
  1761. }
  1762. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1763. /// <summary>
  1764. /// Get / Set the wished cursor when the field is focused
  1765. /// </summary>
  1766. public CursorVisibility DesiredCursorVisibility {
  1767. get => desiredCursorVisibility;
  1768. set {
  1769. if (HasFocus) {
  1770. Application.Driver.SetCursorVisibility (value);
  1771. }
  1772. desiredCursorVisibility = value;
  1773. SetNeedsDisplay ();
  1774. }
  1775. }
  1776. ///<inheritdoc/>
  1777. public override bool OnEnter (View view)
  1778. {
  1779. //TODO: Improve it by handling read only mode of the text field
  1780. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1781. return base.OnEnter (view);
  1782. }
  1783. ///<inheritdoc/>
  1784. public override bool OnLeave (View view)
  1785. {
  1786. if (Application.MouseGrabView != null && Application.MouseGrabView == this) {
  1787. Application.UngrabMouse ();
  1788. }
  1789. return base.OnLeave (view);
  1790. }
  1791. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1792. void GetEncodedRegionBounds (out long start, out long end,
  1793. int? startRow = null, int? startCol = null, int? cRow = null, int? cCol = null)
  1794. {
  1795. long selection;
  1796. long point;
  1797. if (startRow == null || startCol == null || cRow == null || cCol == null) {
  1798. selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1799. point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1800. } else {
  1801. selection = ((long)(uint)startRow << 32) | (uint)startCol;
  1802. point = ((long)(uint)cRow << 32) | (uint)cCol;
  1803. }
  1804. if (selection > point) {
  1805. start = point;
  1806. end = selection;
  1807. } else {
  1808. start = selection;
  1809. end = point;
  1810. }
  1811. }
  1812. bool PointInSelection (int col, int row)
  1813. {
  1814. long start, end;
  1815. GetEncodedRegionBounds (out start, out end);
  1816. var q = ((long)(uint)row << 32) | (uint)col;
  1817. return q >= start && q <= end - 1;
  1818. }
  1819. //
  1820. // Returns a ustring with the text in the selected
  1821. // region.
  1822. //
  1823. ustring GetRegion (int? sRow = null, int? sCol = null, int? cRow = null, int? cCol = null, TextModel model = null)
  1824. {
  1825. long start, end;
  1826. GetEncodedRegionBounds (out start, out end, sRow, sCol, cRow, cCol);
  1827. if (start == end) {
  1828. return ustring.Empty;
  1829. }
  1830. int startRow = (int)(start >> 32);
  1831. var maxrow = ((int)(end >> 32));
  1832. int startCol = (int)(start & 0xffffffff);
  1833. var endCol = (int)(end & 0xffffffff);
  1834. var line = model == null ? this.model.GetLine (startRow) : model.GetLine (startRow);
  1835. if (startRow == maxrow)
  1836. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1837. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1838. for (int row = startRow + 1; row < maxrow; row++) {
  1839. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (model == null
  1840. ? this.model.GetLine (row) : model.GetLine (row));
  1841. }
  1842. line = model == null ? this.model.GetLine (maxrow) : model.GetLine (maxrow);
  1843. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (line.GetRange (0, endCol));
  1844. return res;
  1845. }
  1846. //
  1847. // Clears the contents of the selected region
  1848. //
  1849. void ClearRegion ()
  1850. {
  1851. SetWrapModel ();
  1852. long start, end;
  1853. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1854. GetEncodedRegionBounds (out start, out end);
  1855. int startRow = (int)(start >> 32);
  1856. var maxrow = ((int)(end >> 32));
  1857. int startCol = (int)(start & 0xffffffff);
  1858. var endCol = (int)(end & 0xffffffff);
  1859. var line = model.GetLine (startRow);
  1860. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, new Point (startCol, startRow));
  1861. List<List<Rune>> removedLines = new List<List<Rune>> ();
  1862. if (startRow == maxrow) {
  1863. removedLines.Add (new List<Rune> (line));
  1864. line.RemoveRange (startCol, endCol - startCol);
  1865. currentColumn = startCol;
  1866. if (wordWrap) {
  1867. SetNeedsDisplay ();
  1868. } else {
  1869. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1870. }
  1871. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition, HistoryText.LineStatus.Removed);
  1872. UpdateWrapModel ();
  1873. return;
  1874. }
  1875. removedLines.Add (new List<Rune> (line));
  1876. line.RemoveRange (startCol, line.Count - startCol);
  1877. var line2 = model.GetLine (maxrow);
  1878. line.AddRange (line2.Skip (endCol));
  1879. for (int row = startRow + 1; row <= maxrow; row++) {
  1880. removedLines.Add (new List<Rune> (model.GetLine (startRow + 1)));
  1881. model.RemoveLine (startRow + 1);
  1882. }
  1883. if (currentEncoded == end) {
  1884. currentRow -= maxrow - (startRow);
  1885. }
  1886. currentColumn = startCol;
  1887. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  1888. HistoryText.LineStatus.Removed);
  1889. UpdateWrapModel ();
  1890. SetNeedsDisplay ();
  1891. }
  1892. /// <summary>
  1893. /// Select all text.
  1894. /// </summary>
  1895. public void SelectAll ()
  1896. {
  1897. if (model.Count == 0) {
  1898. return;
  1899. }
  1900. StartSelecting ();
  1901. selectionStartColumn = 0;
  1902. selectionStartRow = 0;
  1903. currentColumn = model.GetLine (model.Count - 1).Count;
  1904. currentRow = model.Count - 1;
  1905. SetNeedsDisplay ();
  1906. }
  1907. /// <summary>
  1908. /// Find the next text based on the match case with the option to replace it.
  1909. /// </summary>
  1910. /// <param name="textToFind">The text to find.</param>
  1911. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1912. /// <param name="matchCase">The match case setting.</param>
  1913. /// <param name="matchWholeWord">The match whole word setting.</param>
  1914. /// <param name="textToReplace">The text to replace.</param>
  1915. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1916. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1917. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1918. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1919. {
  1920. if (model.Count == 0) {
  1921. gaveFullTurn = false;
  1922. return false;
  1923. }
  1924. SetWrapModel ();
  1925. ResetContinuousFind ();
  1926. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1927. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1928. }
  1929. /// <summary>
  1930. /// Find the previous text based on the match case with the option to replace it.
  1931. /// </summary>
  1932. /// <param name="textToFind">The text to find.</param>
  1933. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  1934. /// <param name="matchCase">The match case setting.</param>
  1935. /// <param name="matchWholeWord">The match whole word setting.</param>
  1936. /// <param name="textToReplace">The text to replace.</param>
  1937. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1938. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1939. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1940. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1941. {
  1942. if (model.Count == 0) {
  1943. gaveFullTurn = false;
  1944. return false;
  1945. }
  1946. SetWrapModel ();
  1947. ResetContinuousFind ();
  1948. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1949. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1950. }
  1951. /// <summary>
  1952. /// Reset the flag to stop continuous find.
  1953. /// </summary>
  1954. public void FindTextChanged ()
  1955. {
  1956. continuousFind = false;
  1957. }
  1958. /// <summary>
  1959. /// Replaces all the text based on the match case.
  1960. /// </summary>
  1961. /// <param name="textToFind">The text to find.</param>
  1962. /// <param name="matchCase">The match case setting.</param>
  1963. /// <param name="matchWholeWord">The match whole word setting.</param>
  1964. /// <param name="textToReplace">The text to replace.</param>
  1965. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1966. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1967. ustring textToReplace = null)
  1968. {
  1969. if (isReadOnly || model.Count == 0) {
  1970. return false;
  1971. }
  1972. SetWrapModel ();
  1973. ResetContinuousFind ();
  1974. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1975. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1976. }
  1977. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1978. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1979. {
  1980. if (foundPos.found) {
  1981. StartSelecting ();
  1982. selectionStartColumn = foundPos.current.X;
  1983. selectionStartRow = foundPos.current.Y;
  1984. if (!replaceAll) {
  1985. currentColumn = selectionStartColumn + text.RuneCount;
  1986. } else {
  1987. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1988. }
  1989. currentRow = foundPos.current.Y;
  1990. if (!isReadOnly && replace) {
  1991. Adjust ();
  1992. ClearSelectedRegion ();
  1993. InsertText (textToReplace);
  1994. StartSelecting ();
  1995. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1996. } else {
  1997. UpdateWrapModel ();
  1998. SetNeedsDisplay ();
  1999. Adjust ();
  2000. }
  2001. continuousFind = true;
  2002. return foundPos.found;
  2003. }
  2004. UpdateWrapModel ();
  2005. continuousFind = false;
  2006. return foundPos.found;
  2007. }
  2008. void ResetContinuousFind ()
  2009. {
  2010. if (!continuousFind) {
  2011. var col = selecting ? selectionStartColumn : currentColumn;
  2012. var row = selecting ? selectionStartRow : currentRow;
  2013. model.ResetContinuousFind (new Point (col, row));
  2014. }
  2015. }
  2016. string currentCaller;
  2017. /// <summary>
  2018. /// Restore from original model.
  2019. /// </summary>
  2020. void SetWrapModel ([CallerMemberName] string caller = null)
  2021. {
  2022. if (currentCaller != null)
  2023. return;
  2024. if (wordWrap) {
  2025. currentCaller = caller;
  2026. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2027. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2028. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  2029. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  2030. model = wrapManager.Model;
  2031. }
  2032. }
  2033. /// <summary>
  2034. /// Update the original model.
  2035. /// </summary>
  2036. void UpdateWrapModel ([CallerMemberName] string caller = null)
  2037. {
  2038. if (currentCaller != null && currentCaller != caller)
  2039. return;
  2040. if (wordWrap) {
  2041. currentCaller = null;
  2042. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  2043. out int nStartRow, out int nStartCol,
  2044. currentRow, currentColumn,
  2045. selectionStartRow, selectionStartColumn, preserveTrailingSpaces: true);
  2046. currentRow = nRow;
  2047. currentColumn = nCol;
  2048. selectionStartRow = nStartRow;
  2049. selectionStartColumn = nStartCol;
  2050. wrapNeeded = true;
  2051. }
  2052. if (currentCaller != null)
  2053. throw new InvalidOperationException ($"WordWrap settings was changed after the {currentCaller} call.");
  2054. }
  2055. /// <summary>
  2056. /// Invoke the <see cref="UnwrappedCursorPosition"/> event with the unwrapped <see cref="CursorPosition"/>.
  2057. /// </summary>
  2058. public virtual void OnUnwrappedCursorPosition (int? cRow = null, int? cCol = null)
  2059. {
  2060. var row = cRow == null ? currentRow : cRow;
  2061. var col = cCol == null ? currentColumn : cCol;
  2062. if (cRow == null && cCol == null && wordWrap) {
  2063. row = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2064. col = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2065. }
  2066. UnwrappedCursorPosition?.Invoke (new Point ((int)col, (int)row));
  2067. }
  2068. ustring GetSelectedRegion ()
  2069. {
  2070. var cRow = currentRow;
  2071. var cCol = currentColumn;
  2072. var startRow = selectionStartRow;
  2073. var startCol = selectionStartColumn;
  2074. var model = this.model;
  2075. if (wordWrap) {
  2076. cRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2077. cCol = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2078. startRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  2079. startCol = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  2080. model = wrapManager.Model;
  2081. }
  2082. OnUnwrappedCursorPosition (cRow, cCol);
  2083. return GetRegion (startRow, startCol, cRow, cCol, model);
  2084. }
  2085. ///<inheritdoc/>
  2086. public override void Redraw (Rect bounds)
  2087. {
  2088. SetNormalColor ();
  2089. var offB = OffSetBackground ();
  2090. int right = Frame.Width + offB.width + RightOffset;
  2091. int bottom = Frame.Height + offB.height + BottomOffset;
  2092. var row = 0;
  2093. for (int idxRow = topRow; idxRow < model.Count; idxRow++) {
  2094. var line = model.GetLine (idxRow);
  2095. int lineRuneCount = line.Count;
  2096. var col = 0;
  2097. Move (0, row);
  2098. for (int idxCol = leftColumn; idxCol < lineRuneCount; idxCol++) {
  2099. var rune = idxCol >= lineRuneCount ? ' ' : line [idxCol];
  2100. var cols = Rune.ColumnWidth (rune);
  2101. if (idxCol < line.Count && selecting && PointInSelection (idxCol, idxRow)) {
  2102. SetSelectionColor (line, idxCol);
  2103. } else if (idxCol == currentColumn && idxRow == currentRow && !selecting && !Used
  2104. && HasFocus && idxCol < lineRuneCount) {
  2105. SetSelectionColor (line, idxCol);
  2106. } else if (ReadOnly) {
  2107. SetReadOnlyColor (line, idxCol);
  2108. } else {
  2109. SetNormalColor (line, idxCol);
  2110. }
  2111. if (rune == '\t') {
  2112. cols += TabWidth + 1;
  2113. if (col + cols > right) {
  2114. cols = right - col;
  2115. }
  2116. for (int i = 0; i < cols; i++) {
  2117. if (col + i < right) {
  2118. AddRune (col + i, row, ' ');
  2119. }
  2120. }
  2121. } else {
  2122. AddRune (col, row, rune);
  2123. }
  2124. if (!TextModel.SetCol (ref col, bounds.Right, cols)) {
  2125. break;
  2126. }
  2127. if (idxCol + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idxCol + 1]) > right) {
  2128. break;
  2129. }
  2130. }
  2131. if (col < right) {
  2132. SetNormalColor ();
  2133. ClearRegion (col, row, right, row + 1);
  2134. }
  2135. row++;
  2136. }
  2137. if (row < bottom) {
  2138. SetNormalColor ();
  2139. ClearRegion (bounds.Left, row, right, bottom);
  2140. }
  2141. PositionCursor ();
  2142. if (clickWithSelecting) {
  2143. clickWithSelecting = false;
  2144. return;
  2145. }
  2146. if (SelectedLength > 0)
  2147. return;
  2148. // draw autocomplete
  2149. Autocomplete.GenerateSuggestions ();
  2150. var renderAt = new Point (
  2151. CursorPosition.X - LeftColumn,
  2152. Autocomplete.PopupInsideContainer
  2153. ? (CursorPosition.Y + 1) - TopRow
  2154. : 0);
  2155. Autocomplete.RenderOverlay (renderAt);
  2156. }
  2157. /// <inheritdoc/>
  2158. public override Attribute GetNormalColor ()
  2159. {
  2160. return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  2161. }
  2162. ///<inheritdoc/>
  2163. public override bool CanFocus {
  2164. get => base.CanFocus;
  2165. set { base.CanFocus = value; }
  2166. }
  2167. void SetClipboard (ustring text)
  2168. {
  2169. if (text != null) {
  2170. Clipboard.Contents = text;
  2171. }
  2172. }
  2173. void AppendClipboard (ustring text)
  2174. {
  2175. Clipboard.Contents += text;
  2176. }
  2177. /// <summary>
  2178. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position
  2179. /// exactly as if the user had just typed it
  2180. /// </summary>
  2181. /// <param name="toAdd">Text to add</param>
  2182. public void InsertText (string toAdd)
  2183. {
  2184. foreach (var ch in toAdd) {
  2185. Key key;
  2186. try {
  2187. key = (Key)ch;
  2188. } catch (Exception) {
  2189. throw new ArgumentException ($"Cannot insert character '{ch}' because it does not map to a Key");
  2190. }
  2191. InsertText (new KeyEvent () { Key = key });
  2192. }
  2193. if (NeedDisplay.IsEmpty) {
  2194. PositionCursor ();
  2195. } else {
  2196. Adjust ();
  2197. }
  2198. }
  2199. void Insert (Rune rune)
  2200. {
  2201. var line = GetCurrentLine ();
  2202. if (Used) {
  2203. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2204. } else {
  2205. if (currentColumn < line.Count) {
  2206. line.RemoveAt (currentColumn);
  2207. }
  2208. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2209. }
  2210. var prow = currentRow - topRow;
  2211. if (!wrapNeeded) {
  2212. SetNeedsDisplay (new Rect (0, prow, Math.Max (Frame.Width, 0), Math.Max (prow + 1, 0)));
  2213. }
  2214. }
  2215. ustring StringFromRunes (List<Rune> runes)
  2216. {
  2217. if (runes == null)
  2218. throw new ArgumentNullException (nameof (runes));
  2219. int size = 0;
  2220. foreach (var rune in runes) {
  2221. size += Utf8.RuneLen (rune);
  2222. }
  2223. var encoded = new byte [size];
  2224. int offset = 0;
  2225. foreach (var rune in runes) {
  2226. offset += Utf8.EncodeRune (rune, encoded, offset);
  2227. }
  2228. return ustring.Make (encoded);
  2229. }
  2230. /// <summary>
  2231. /// Returns the characters on the current line (where the cursor is positioned).
  2232. /// Use <see cref="CurrentColumn"/> to determine the position of the cursor within
  2233. /// that line
  2234. /// </summary>
  2235. /// <returns></returns>
  2236. public List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  2237. void InsertText (ustring text)
  2238. {
  2239. if (ustring.IsNullOrEmpty (text)) {
  2240. return;
  2241. }
  2242. var lines = TextModel.StringToRunes (text);
  2243. if (lines.Count == 0) {
  2244. return;
  2245. }
  2246. SetWrapModel ();
  2247. var line = GetCurrentLine ();
  2248. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition);
  2249. // Optimize single line
  2250. if (lines.Count == 1) {
  2251. line.InsertRange (currentColumn, lines [0]);
  2252. currentColumn += lines [0].Count;
  2253. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2254. HistoryText.LineStatus.Replaced);
  2255. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  2256. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  2257. }
  2258. if (wordWrap) {
  2259. SetNeedsDisplay ();
  2260. } else {
  2261. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Math.Max (currentRow - topRow + 1, 0)));
  2262. }
  2263. UpdateWrapModel ();
  2264. OnContentsChanged ();
  2265. return;
  2266. }
  2267. List<Rune> rest = null;
  2268. int lastp = 0;
  2269. if (model.Count > 0 && line.Count > 0 && !copyWithoutSelection) {
  2270. // Keep a copy of the rest of the line
  2271. var restCount = line.Count - currentColumn;
  2272. rest = line.GetRange (currentColumn, restCount);
  2273. line.RemoveRange (currentColumn, restCount);
  2274. }
  2275. // First line is inserted at the current location, the rest is appended
  2276. line.InsertRange (currentColumn, lines [0]);
  2277. //model.AddLine (currentRow, lines [0]);
  2278. var addedLines = new List<List<Rune>> () { new List<Rune> (line) };
  2279. for (int i = 1; i < lines.Count; i++) {
  2280. model.AddLine (currentRow + i, lines [i]);
  2281. addedLines.Add (new List<Rune> (lines [i]));
  2282. }
  2283. if (rest != null) {
  2284. var last = model.GetLine (currentRow + lines.Count - 1);
  2285. lastp = last.Count;
  2286. last.InsertRange (last.Count, rest);
  2287. addedLines.Last ().InsertRange (addedLines.Last ().Count, rest);
  2288. }
  2289. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2290. // Now adjust column and row positions
  2291. currentRow += lines.Count - 1;
  2292. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  2293. Adjust ();
  2294. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2295. HistoryText.LineStatus.Replaced);
  2296. UpdateWrapModel ();
  2297. }
  2298. // The column we are tracking, or -1 if we are not tracking any column
  2299. int columnTrack = -1;
  2300. // Tries to snap the cursor to the tracking column
  2301. void TrackColumn ()
  2302. {
  2303. // Now track the column
  2304. var line = GetCurrentLine ();
  2305. if (line.Count < columnTrack)
  2306. currentColumn = line.Count;
  2307. else if (columnTrack != -1)
  2308. currentColumn = columnTrack;
  2309. else if (currentColumn > line.Count)
  2310. currentColumn = line.Count;
  2311. Adjust ();
  2312. }
  2313. void Adjust ()
  2314. {
  2315. var offB = OffSetBackground ();
  2316. var line = GetCurrentLine ();
  2317. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  2318. var tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  2319. var dSize = TextModel.DisplaySize (line, leftColumn, currentColumn, true, TabWidth);
  2320. if (!wordWrap && currentColumn < leftColumn) {
  2321. leftColumn = currentColumn;
  2322. need = true;
  2323. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width
  2324. || dSize.size + RightOffset >= Frame.Width + offB.width)) {
  2325. leftColumn = TextModel.CalculateLeftColumn (line, leftColumn, currentColumn,
  2326. Frame.Width + offB.width - RightOffset, TabWidth);
  2327. need = true;
  2328. } else if ((wordWrap && leftColumn > 0) || (dSize.size + RightOffset < Frame.Width + offB.width
  2329. && tSize.size + RightOffset < Frame.Width + offB.width)) {
  2330. if (leftColumn > 0) {
  2331. leftColumn = 0;
  2332. need = true;
  2333. }
  2334. }
  2335. if (currentRow < topRow) {
  2336. topRow = currentRow;
  2337. need = true;
  2338. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  2339. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  2340. need = true;
  2341. } else if (topRow > 0 && currentRow == topRow) {
  2342. topRow = Math.Max (topRow - 1, 0);
  2343. }
  2344. if (need) {
  2345. if (wrapNeeded) {
  2346. WrapTextModel ();
  2347. wrapNeeded = false;
  2348. }
  2349. SetNeedsDisplay ();
  2350. } else {
  2351. PositionCursor ();
  2352. }
  2353. OnUnwrappedCursorPosition ();
  2354. }
  2355. /// <summary>
  2356. /// Event arguments for events for when the contents of the TextView change. E.g. the <see cref="ContentsChanged"/> event.
  2357. /// </summary>
  2358. public class ContentsChangedEventArgs : EventArgs {
  2359. /// <summary>
  2360. /// Creates a new <see cref="ContentsChanged"/> instance.
  2361. /// </summary>
  2362. /// <param name="currentRow">Contains the row where the change occurred.</param>
  2363. /// <param name="currentColumn">Contains the column where the change occured.</param>
  2364. public ContentsChangedEventArgs (int currentRow, int currentColumn)
  2365. {
  2366. Row = currentRow;
  2367. Col = currentColumn;
  2368. }
  2369. /// <summary>
  2370. ///
  2371. /// Contains the row where the change occurred.
  2372. /// </summary>
  2373. public int Row { get; private set; }
  2374. /// <summary>
  2375. /// Contains the column where the change occurred.
  2376. /// </summary>
  2377. public int Col { get; private set; }
  2378. }
  2379. /// <summary>
  2380. /// Called when the contents of the TextView change. E.g. when the user types text or deletes text. Raises
  2381. /// the <see cref="ContentsChanged"/> event.
  2382. /// </summary>
  2383. public virtual void OnContentsChanged ()
  2384. {
  2385. ContentsChanged?.Invoke (new ContentsChangedEventArgs (CurrentRow, CurrentColumn));
  2386. }
  2387. (int width, int height) OffSetBackground ()
  2388. {
  2389. int w = 0;
  2390. int h = 0;
  2391. if (SuperView?.Frame.Right - Frame.Right < 0) {
  2392. w = SuperView.Frame.Right - Frame.Right - 1;
  2393. }
  2394. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  2395. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  2396. }
  2397. return (w, h);
  2398. }
  2399. /// <summary>
  2400. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  2401. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  2402. /// </summary>
  2403. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  2404. /// if the value is negative it will be reset to zero</param>
  2405. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  2406. public void ScrollTo (int idx, bool isRow = true)
  2407. {
  2408. if (idx < 0) {
  2409. idx = 0;
  2410. }
  2411. if (isRow) {
  2412. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  2413. } else if (!wordWrap) {
  2414. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset, TabWidth);
  2415. leftColumn = Math.Max (!wordWrap && idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  2416. }
  2417. SetNeedsDisplay ();
  2418. }
  2419. bool lastWasKill;
  2420. bool wrapNeeded;
  2421. bool shiftSelecting;
  2422. ///<inheritdoc/>
  2423. public override bool ProcessKey (KeyEvent kb)
  2424. {
  2425. if (!CanFocus) {
  2426. return true;
  2427. }
  2428. // Give autocomplete first opportunity to respond to key presses
  2429. if (SelectedLength == 0 && Autocomplete.ProcessKey (kb)) {
  2430. return true;
  2431. }
  2432. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (kb),
  2433. new KeyModifiers () { Alt = kb.IsAlt, Ctrl = kb.IsCtrl, Shift = kb.IsShift }));
  2434. if (result != null)
  2435. return (bool)result;
  2436. ResetColumnTrack ();
  2437. // Ignore control characters and other special keys
  2438. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  2439. return false;
  2440. InsertText (kb);
  2441. DoNeededAction ();
  2442. return true;
  2443. }
  2444. void RedoChanges ()
  2445. {
  2446. if (ReadOnly)
  2447. return;
  2448. historyText.Redo ();
  2449. }
  2450. void UndoChanges ()
  2451. {
  2452. if (ReadOnly)
  2453. return;
  2454. historyText.Undo ();
  2455. }
  2456. bool ProcessMovePreviousView ()
  2457. {
  2458. ResetColumnTrack ();
  2459. return MovePreviousView ();
  2460. }
  2461. bool ProcessMoveNextView ()
  2462. {
  2463. ResetColumnTrack ();
  2464. return MoveNextView ();
  2465. }
  2466. void ProcessSetOverwrite ()
  2467. {
  2468. ResetColumnTrack ();
  2469. SetOverwrite (!Used);
  2470. }
  2471. void ProcessSelectAll ()
  2472. {
  2473. ResetColumnTrack ();
  2474. SelectAll ();
  2475. }
  2476. void MoveTopHomeExtend ()
  2477. {
  2478. ResetColumnTrack ();
  2479. StartSelecting ();
  2480. MoveHome ();
  2481. }
  2482. void MoveTopHome ()
  2483. {
  2484. ResetAllTrack ();
  2485. if (shiftSelecting && selecting) {
  2486. StopSelecting ();
  2487. }
  2488. MoveHome ();
  2489. }
  2490. void MoveBottomEndExtend ()
  2491. {
  2492. ResetAllTrack ();
  2493. StartSelecting ();
  2494. MoveEnd ();
  2495. }
  2496. void MoveBottomEnd ()
  2497. {
  2498. ResetAllTrack ();
  2499. if (shiftSelecting && selecting) {
  2500. StopSelecting ();
  2501. }
  2502. MoveEnd ();
  2503. }
  2504. void ProcessKillWordBackward ()
  2505. {
  2506. ResetColumnTrack ();
  2507. KillWordBackward ();
  2508. }
  2509. void ProcessKillWordForward ()
  2510. {
  2511. ResetColumnTrack ();
  2512. KillWordForward ();
  2513. }
  2514. void ProcessMoveWordForwardExtend ()
  2515. {
  2516. ResetAllTrack ();
  2517. StartSelecting ();
  2518. MoveWordForward ();
  2519. }
  2520. void ProcessMoveWordForward ()
  2521. {
  2522. ResetAllTrack ();
  2523. if (shiftSelecting && selecting) {
  2524. StopSelecting ();
  2525. }
  2526. MoveWordForward ();
  2527. }
  2528. void ProcessMoveWordBackwardExtend ()
  2529. {
  2530. ResetAllTrack ();
  2531. StartSelecting ();
  2532. MoveWordBackward ();
  2533. }
  2534. void ProcessMoveWordBackward ()
  2535. {
  2536. ResetAllTrack ();
  2537. if (shiftSelecting && selecting) {
  2538. StopSelecting ();
  2539. }
  2540. MoveWordBackward ();
  2541. }
  2542. void ProcessCut ()
  2543. {
  2544. ResetColumnTrack ();
  2545. Cut ();
  2546. }
  2547. void ProcessCopy ()
  2548. {
  2549. ResetColumnTrack ();
  2550. Copy ();
  2551. }
  2552. void ToggleSelecting ()
  2553. {
  2554. ResetColumnTrack ();
  2555. selecting = !selecting;
  2556. selectionStartColumn = currentColumn;
  2557. selectionStartRow = currentRow;
  2558. }
  2559. void ProcessPaste ()
  2560. {
  2561. ResetColumnTrack ();
  2562. if (isReadOnly)
  2563. return;
  2564. Paste ();
  2565. }
  2566. void ProcessMoveEndOfLineExtend ()
  2567. {
  2568. ResetAllTrack ();
  2569. StartSelecting ();
  2570. MoveEndOfLine ();
  2571. }
  2572. void ProcessMoveEndOfLine ()
  2573. {
  2574. ResetAllTrack ();
  2575. if (shiftSelecting && selecting) {
  2576. StopSelecting ();
  2577. }
  2578. MoveEndOfLine ();
  2579. }
  2580. void ProcessDeleteCharRight ()
  2581. {
  2582. ResetColumnTrack ();
  2583. DeleteCharRight ();
  2584. }
  2585. void ProcessMoveStartOfLineExtend ()
  2586. {
  2587. ResetAllTrack ();
  2588. StartSelecting ();
  2589. MoveStartOfLine ();
  2590. }
  2591. void ProcessMoveStartOfLine ()
  2592. {
  2593. ResetAllTrack ();
  2594. if (shiftSelecting && selecting) {
  2595. StopSelecting ();
  2596. }
  2597. MoveStartOfLine ();
  2598. }
  2599. void ProcessDeleteCharLeft ()
  2600. {
  2601. ResetColumnTrack ();
  2602. DeleteCharLeft ();
  2603. }
  2604. void ProcessMoveLeftExtend ()
  2605. {
  2606. ResetAllTrack ();
  2607. StartSelecting ();
  2608. MoveLeft ();
  2609. }
  2610. bool ProcessMoveLeft ()
  2611. {
  2612. // if the user presses Left (without any control keys) and they are at the start of the text
  2613. if (currentColumn == 0 && currentRow == 0) {
  2614. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  2615. return false;
  2616. }
  2617. ResetAllTrack ();
  2618. if (shiftSelecting && selecting) {
  2619. StopSelecting ();
  2620. }
  2621. MoveLeft ();
  2622. return true;
  2623. }
  2624. void ProcessMoveRightExtend ()
  2625. {
  2626. ResetAllTrack ();
  2627. StartSelecting ();
  2628. MoveRight ();
  2629. }
  2630. bool ProcessMoveRight ()
  2631. {
  2632. // if the user presses Right (without any control keys)
  2633. // determine where the last cursor position in the text is
  2634. var lastRow = model.Count - 1;
  2635. var lastCol = model.GetLine (lastRow).Count;
  2636. // 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)
  2637. if (currentColumn == lastCol && currentRow == lastRow) {
  2638. return false;
  2639. }
  2640. ResetAllTrack ();
  2641. if (shiftSelecting && selecting) {
  2642. StopSelecting ();
  2643. }
  2644. MoveRight ();
  2645. return true;
  2646. }
  2647. void ProcessMoveUpExtend ()
  2648. {
  2649. ResetColumnTrack ();
  2650. StartSelecting ();
  2651. MoveUp ();
  2652. }
  2653. void ProcessMoveUp ()
  2654. {
  2655. ResetContinuousFindTrack ();
  2656. if (shiftSelecting && selecting) {
  2657. StopSelecting ();
  2658. }
  2659. MoveUp ();
  2660. }
  2661. void ProcessMoveDownExtend ()
  2662. {
  2663. ResetColumnTrack ();
  2664. StartSelecting ();
  2665. MoveDown ();
  2666. }
  2667. void ProcessMoveDown ()
  2668. {
  2669. ResetContinuousFindTrack ();
  2670. if (shiftSelecting && selecting) {
  2671. StopSelecting ();
  2672. }
  2673. MoveDown ();
  2674. }
  2675. void ProcessPageUpExtend ()
  2676. {
  2677. ResetColumnTrack ();
  2678. StartSelecting ();
  2679. MovePageUp ();
  2680. }
  2681. void ProcessPageUp ()
  2682. {
  2683. ResetColumnTrack ();
  2684. if (shiftSelecting && selecting) {
  2685. StopSelecting ();
  2686. }
  2687. MovePageUp ();
  2688. }
  2689. void ProcessPageDownExtend ()
  2690. {
  2691. ResetColumnTrack ();
  2692. StartSelecting ();
  2693. MovePageDown ();
  2694. }
  2695. void ProcessPageDown ()
  2696. {
  2697. ResetColumnTrack ();
  2698. if (shiftSelecting && selecting) {
  2699. StopSelecting ();
  2700. }
  2701. MovePageDown ();
  2702. }
  2703. bool MovePreviousView ()
  2704. {
  2705. if (Application.MdiTop != null) {
  2706. return SuperView?.FocusPrev () == true;
  2707. }
  2708. return false;
  2709. }
  2710. bool MoveNextView ()
  2711. {
  2712. if (Application.MdiTop != null) {
  2713. return SuperView?.FocusNext () == true;
  2714. }
  2715. return false;
  2716. }
  2717. bool ProcessBackTab ()
  2718. {
  2719. ResetColumnTrack ();
  2720. if (!AllowsTab || isReadOnly) {
  2721. return ProcessMovePreviousView ();
  2722. }
  2723. if (currentColumn > 0) {
  2724. SetWrapModel ();
  2725. var currentLine = GetCurrentLine ();
  2726. if (currentLine.Count > 0 && currentLine [currentColumn - 1] == '\t') {
  2727. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2728. currentLine.RemoveAt (currentColumn - 1);
  2729. currentColumn--;
  2730. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2731. HistoryText.LineStatus.Replaced);
  2732. }
  2733. UpdateWrapModel ();
  2734. }
  2735. DoNeededAction ();
  2736. return true;
  2737. }
  2738. bool ProcessTab ()
  2739. {
  2740. ResetColumnTrack ();
  2741. if (!AllowsTab || isReadOnly) {
  2742. return ProcessMoveNextView ();
  2743. }
  2744. InsertText (new KeyEvent ((Key)'\t', null));
  2745. DoNeededAction ();
  2746. return true;
  2747. }
  2748. void SetOverwrite (bool overwrite)
  2749. {
  2750. Used = overwrite;
  2751. SetNeedsDisplay ();
  2752. DoNeededAction ();
  2753. }
  2754. bool ProcessReturn ()
  2755. {
  2756. ResetColumnTrack ();
  2757. if (!AllowsReturn || isReadOnly) {
  2758. return false;
  2759. }
  2760. SetWrapModel ();
  2761. var currentLine = GetCurrentLine ();
  2762. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2763. if (selecting) {
  2764. ClearSelectedRegion ();
  2765. currentLine = GetCurrentLine ();
  2766. }
  2767. var restCount = currentLine.Count - currentColumn;
  2768. var rest = currentLine.GetRange (currentColumn, restCount);
  2769. currentLine.RemoveRange (currentColumn, restCount);
  2770. var addedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2771. model.AddLine (currentRow + 1, rest);
  2772. addedLines.Add (new List<Rune> (model.GetLine (currentRow + 1)));
  2773. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2774. currentRow++;
  2775. bool fullNeedsDisplay = false;
  2776. if (currentRow >= topRow + Frame.Height) {
  2777. topRow++;
  2778. fullNeedsDisplay = true;
  2779. }
  2780. currentColumn = 0;
  2781. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2782. HistoryText.LineStatus.Replaced);
  2783. if (!wordWrap && currentColumn < leftColumn) {
  2784. fullNeedsDisplay = true;
  2785. leftColumn = 0;
  2786. }
  2787. if (fullNeedsDisplay)
  2788. SetNeedsDisplay ();
  2789. else
  2790. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  2791. UpdateWrapModel ();
  2792. DoNeededAction ();
  2793. OnContentsChanged ();
  2794. return true;
  2795. }
  2796. void KillWordBackward ()
  2797. {
  2798. if (isReadOnly)
  2799. return;
  2800. SetWrapModel ();
  2801. var currentLine = GetCurrentLine ();
  2802. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2803. if (currentColumn == 0) {
  2804. DeleteTextBackwards ();
  2805. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2806. HistoryText.LineStatus.Replaced);
  2807. UpdateWrapModel ();
  2808. return;
  2809. }
  2810. var newPos = WordBackward (currentColumn, currentRow);
  2811. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2812. var restCount = currentColumn - newPos.Value.col;
  2813. currentLine.RemoveRange (newPos.Value.col, restCount);
  2814. if (wordWrap) {
  2815. wrapNeeded = true;
  2816. }
  2817. currentColumn = newPos.Value.col;
  2818. } else if (newPos.HasValue) {
  2819. var restCount = currentLine.Count - currentColumn;
  2820. currentLine.RemoveRange (currentColumn, restCount);
  2821. if (wordWrap) {
  2822. wrapNeeded = true;
  2823. }
  2824. currentColumn = newPos.Value.col;
  2825. currentRow = newPos.Value.row;
  2826. }
  2827. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2828. HistoryText.LineStatus.Replaced);
  2829. UpdateWrapModel ();
  2830. if (wrapNeeded) {
  2831. SetNeedsDisplay ();
  2832. } else {
  2833. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2834. }
  2835. DoNeededAction ();
  2836. }
  2837. void KillWordForward ()
  2838. {
  2839. if (isReadOnly)
  2840. return;
  2841. SetWrapModel ();
  2842. var currentLine = GetCurrentLine ();
  2843. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2844. if (currentLine.Count == 0 || currentColumn == currentLine.Count) {
  2845. DeleteTextForwards ();
  2846. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2847. HistoryText.LineStatus.Replaced);
  2848. UpdateWrapModel ();
  2849. return;
  2850. }
  2851. var newPos = WordForward (currentColumn, currentRow);
  2852. var restCount = 0;
  2853. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2854. restCount = newPos.Value.col - currentColumn;
  2855. currentLine.RemoveRange (currentColumn, restCount);
  2856. } else if (newPos.HasValue) {
  2857. restCount = currentLine.Count - currentColumn;
  2858. currentLine.RemoveRange (currentColumn, restCount);
  2859. }
  2860. if (wordWrap) {
  2861. wrapNeeded = true;
  2862. }
  2863. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2864. HistoryText.LineStatus.Replaced);
  2865. UpdateWrapModel ();
  2866. if (wrapNeeded) {
  2867. SetNeedsDisplay ();
  2868. } else {
  2869. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2870. }
  2871. DoNeededAction ();
  2872. }
  2873. void MoveWordForward ()
  2874. {
  2875. var newPos = WordForward (currentColumn, currentRow);
  2876. if (newPos.HasValue) {
  2877. currentColumn = newPos.Value.col;
  2878. currentRow = newPos.Value.row;
  2879. }
  2880. Adjust ();
  2881. DoNeededAction ();
  2882. }
  2883. void MoveWordBackward ()
  2884. {
  2885. var newPos = WordBackward (currentColumn, currentRow);
  2886. if (newPos.HasValue) {
  2887. currentColumn = newPos.Value.col;
  2888. currentRow = newPos.Value.row;
  2889. }
  2890. Adjust ();
  2891. DoNeededAction ();
  2892. }
  2893. void KillToStartOfLine ()
  2894. {
  2895. if (isReadOnly)
  2896. return;
  2897. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2898. // Prevents from adding line feeds if there is no more lines.
  2899. return;
  2900. }
  2901. SetWrapModel ();
  2902. var currentLine = GetCurrentLine ();
  2903. var setLastWasKill = true;
  2904. if (currentLine.Count > 0 && currentColumn == 0) {
  2905. UpdateWrapModel ();
  2906. DeleteTextBackwards ();
  2907. return;
  2908. }
  2909. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2910. if (currentLine.Count == 0) {
  2911. if (currentRow > 0) {
  2912. model.RemoveLine (currentRow);
  2913. if (model.Count > 0 || lastWasKill) {
  2914. var val = ustring.Make (Environment.NewLine);
  2915. if (lastWasKill) {
  2916. AppendClipboard (val);
  2917. } else {
  2918. SetClipboard (val);
  2919. }
  2920. }
  2921. if (model.Count == 0) {
  2922. // Prevents from adding line feeds if there is no more lines.
  2923. setLastWasKill = false;
  2924. }
  2925. currentRow--;
  2926. currentLine = model.GetLine (currentRow);
  2927. var removedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2928. removedLine.Add (new List<Rune> ());
  2929. historyText.Add (new List<List<Rune>> (removedLine), CursorPosition, HistoryText.LineStatus.Removed);
  2930. currentColumn = currentLine.Count;
  2931. }
  2932. } else {
  2933. var restCount = currentColumn;
  2934. var rest = currentLine.GetRange (0, restCount);
  2935. var val = ustring.Empty;
  2936. val += StringFromRunes (rest);
  2937. if (lastWasKill) {
  2938. AppendClipboard (val);
  2939. } else {
  2940. SetClipboard (val);
  2941. }
  2942. currentLine.RemoveRange (0, restCount);
  2943. currentColumn = 0;
  2944. }
  2945. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2946. HistoryText.LineStatus.Replaced);
  2947. UpdateWrapModel ();
  2948. if (wrapNeeded)
  2949. SetNeedsDisplay ();
  2950. else
  2951. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2952. lastWasKill = setLastWasKill;
  2953. DoNeededAction ();
  2954. }
  2955. void KillToEndOfLine ()
  2956. {
  2957. if (isReadOnly)
  2958. return;
  2959. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2960. // Prevents from adding line feeds if there is no more lines.
  2961. return;
  2962. }
  2963. SetWrapModel ();
  2964. var currentLine = GetCurrentLine ();
  2965. var setLastWasKill = true;
  2966. if (currentLine.Count > 0 && currentColumn == currentLine.Count) {
  2967. UpdateWrapModel ();
  2968. DeleteTextForwards ();
  2969. return;
  2970. }
  2971. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2972. if (currentLine.Count == 0) {
  2973. if (currentRow < model.Count - 1) {
  2974. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2975. model.RemoveLine (currentRow);
  2976. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  2977. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  2978. HistoryText.LineStatus.Removed);
  2979. }
  2980. if (model.Count > 0 || lastWasKill) {
  2981. var val = ustring.Make (Environment.NewLine);
  2982. if (lastWasKill) {
  2983. AppendClipboard (val);
  2984. } else {
  2985. SetClipboard (val);
  2986. }
  2987. }
  2988. if (model.Count == 0) {
  2989. // Prevents from adding line feeds if there is no more lines.
  2990. setLastWasKill = false;
  2991. }
  2992. } else {
  2993. var restCount = currentLine.Count - currentColumn;
  2994. var rest = currentLine.GetRange (currentColumn, restCount);
  2995. var val = ustring.Empty;
  2996. val += StringFromRunes (rest);
  2997. if (lastWasKill) {
  2998. AppendClipboard (val);
  2999. } else {
  3000. SetClipboard (val);
  3001. }
  3002. currentLine.RemoveRange (currentColumn, restCount);
  3003. }
  3004. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3005. HistoryText.LineStatus.Replaced);
  3006. UpdateWrapModel ();
  3007. if (wrapNeeded)
  3008. SetNeedsDisplay ();
  3009. else
  3010. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  3011. lastWasKill = setLastWasKill;
  3012. DoNeededAction ();
  3013. }
  3014. void MoveEndOfLine ()
  3015. {
  3016. var currentLine = GetCurrentLine ();
  3017. currentColumn = currentLine.Count;
  3018. Adjust ();
  3019. DoNeededAction ();
  3020. }
  3021. void MoveStartOfLine ()
  3022. {
  3023. currentColumn = 0;
  3024. leftColumn = 0;
  3025. Adjust ();
  3026. DoNeededAction ();
  3027. }
  3028. /// <summary>
  3029. /// Deletes all the selected or a single character at right from the position of the cursor.
  3030. /// </summary>
  3031. public void DeleteCharRight ()
  3032. {
  3033. if (isReadOnly)
  3034. return;
  3035. SetWrapModel ();
  3036. if (selecting) {
  3037. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3038. HistoryText.LineStatus.Original);
  3039. ClearSelectedRegion ();
  3040. var currentLine = GetCurrentLine ();
  3041. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3042. HistoryText.LineStatus.Replaced);
  3043. UpdateWrapModel ();
  3044. return;
  3045. }
  3046. if (DeleteTextForwards ()) {
  3047. UpdateWrapModel ();
  3048. return;
  3049. }
  3050. UpdateWrapModel ();
  3051. DoNeededAction ();
  3052. }
  3053. /// <summary>
  3054. /// Deletes all the selected or a single character at left from the position of the cursor.
  3055. /// </summary>
  3056. public void DeleteCharLeft ()
  3057. {
  3058. if (isReadOnly)
  3059. return;
  3060. SetWrapModel ();
  3061. if (selecting) {
  3062. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3063. HistoryText.LineStatus.Original);
  3064. ClearSelectedRegion ();
  3065. var currentLine = GetCurrentLine ();
  3066. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3067. HistoryText.LineStatus.Replaced);
  3068. UpdateWrapModel ();
  3069. return;
  3070. }
  3071. if (DeleteTextBackwards ()) {
  3072. UpdateWrapModel ();
  3073. return;
  3074. }
  3075. UpdateWrapModel ();
  3076. DoNeededAction ();
  3077. }
  3078. void MoveLeft ()
  3079. {
  3080. if (currentColumn > 0) {
  3081. currentColumn--;
  3082. } else {
  3083. if (currentRow > 0) {
  3084. currentRow--;
  3085. if (currentRow < topRow) {
  3086. topRow--;
  3087. SetNeedsDisplay ();
  3088. }
  3089. var currentLine = GetCurrentLine ();
  3090. currentColumn = currentLine.Count;
  3091. }
  3092. }
  3093. Adjust ();
  3094. DoNeededAction ();
  3095. }
  3096. void MoveRight ()
  3097. {
  3098. var currentLine = GetCurrentLine ();
  3099. if (currentColumn < currentLine.Count) {
  3100. currentColumn++;
  3101. } else {
  3102. if (currentRow + 1 < model.Count) {
  3103. currentRow++;
  3104. currentColumn = 0;
  3105. if (currentRow >= topRow + Frame.Height) {
  3106. topRow++;
  3107. SetNeedsDisplay ();
  3108. }
  3109. }
  3110. }
  3111. Adjust ();
  3112. DoNeededAction ();
  3113. }
  3114. void MovePageUp ()
  3115. {
  3116. int nPageUpShift = Frame.Height - 1;
  3117. if (currentRow > 0) {
  3118. if (columnTrack == -1)
  3119. columnTrack = currentColumn;
  3120. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  3121. if (currentRow < topRow) {
  3122. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  3123. SetNeedsDisplay ();
  3124. }
  3125. TrackColumn ();
  3126. PositionCursor ();
  3127. }
  3128. DoNeededAction ();
  3129. }
  3130. void MovePageDown ()
  3131. {
  3132. int nPageDnShift = Frame.Height - 1;
  3133. if (currentRow >= 0 && currentRow < model.Count) {
  3134. if (columnTrack == -1)
  3135. columnTrack = currentColumn;
  3136. currentRow = (currentRow + nPageDnShift) > model.Count
  3137. ? model.Count > 0 ? model.Count - 1 : 0
  3138. : currentRow + nPageDnShift;
  3139. if (topRow < currentRow - nPageDnShift) {
  3140. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  3141. SetNeedsDisplay ();
  3142. }
  3143. TrackColumn ();
  3144. PositionCursor ();
  3145. }
  3146. DoNeededAction ();
  3147. }
  3148. void ResetContinuousFindTrack ()
  3149. {
  3150. // Handle some state here - whether the last command was a kill
  3151. // operation and the column tracking (up/down)
  3152. lastWasKill = false;
  3153. continuousFind = false;
  3154. }
  3155. void ResetColumnTrack ()
  3156. {
  3157. // Handle some state here - whether the last command was a kill
  3158. // operation and the column tracking (up/down)
  3159. lastWasKill = false;
  3160. columnTrack = -1;
  3161. }
  3162. void ResetAllTrack ()
  3163. {
  3164. // Handle some state here - whether the last command was a kill
  3165. // operation and the column tracking (up/down)
  3166. lastWasKill = false;
  3167. columnTrack = -1;
  3168. continuousFind = false;
  3169. }
  3170. bool InsertText (KeyEvent kb)
  3171. {
  3172. //So that special keys like tab can be processed
  3173. if (isReadOnly)
  3174. return true;
  3175. SetWrapModel ();
  3176. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  3177. if (selecting) {
  3178. ClearSelectedRegion ();
  3179. }
  3180. if (kb.Key == Key.Enter) {
  3181. model.AddLine (currentRow + 1, new List<Rune> ());
  3182. currentRow++;
  3183. currentColumn = 0;
  3184. } else if ((uint)kb.Key == 13) {
  3185. currentColumn = 0;
  3186. } else {
  3187. if (Used) {
  3188. Insert ((uint)kb.Key);
  3189. currentColumn++;
  3190. if (currentColumn >= leftColumn + Frame.Width) {
  3191. leftColumn++;
  3192. SetNeedsDisplay ();
  3193. }
  3194. } else {
  3195. Insert ((uint)kb.Key);
  3196. currentColumn++;
  3197. }
  3198. }
  3199. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3200. HistoryText.LineStatus.Replaced);
  3201. UpdateWrapModel ();
  3202. OnContentsChanged ();
  3203. return true;
  3204. }
  3205. void ShowContextMenu ()
  3206. {
  3207. if (currentCulture != Thread.CurrentThread.CurrentUICulture) {
  3208. currentCulture = Thread.CurrentThread.CurrentUICulture;
  3209. ContextMenu.MenuItems = BuildContextMenuBarItem ();
  3210. }
  3211. ContextMenu.Show ();
  3212. }
  3213. /// <summary>
  3214. /// Deletes all text.
  3215. /// </summary>
  3216. public void DeleteAll ()
  3217. {
  3218. if (Lines == 0) {
  3219. return;
  3220. }
  3221. selectionStartColumn = 0;
  3222. selectionStartRow = 0;
  3223. MoveBottomEndExtend ();
  3224. DeleteCharLeft ();
  3225. SetNeedsDisplay ();
  3226. }
  3227. ///<inheritdoc/>
  3228. public override bool OnKeyUp (KeyEvent kb)
  3229. {
  3230. switch (kb.Key) {
  3231. case Key.Space | Key.CtrlMask:
  3232. return true;
  3233. }
  3234. return false;
  3235. }
  3236. void DoNeededAction ()
  3237. {
  3238. if (NeedDisplay.IsEmpty) {
  3239. PositionCursor ();
  3240. } else {
  3241. Adjust ();
  3242. }
  3243. }
  3244. bool DeleteTextForwards ()
  3245. {
  3246. SetWrapModel ();
  3247. var currentLine = GetCurrentLine ();
  3248. if (currentColumn == currentLine.Count) {
  3249. if (currentRow + 1 == model.Count) {
  3250. UpdateWrapModel ();
  3251. return true;
  3252. }
  3253. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3254. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  3255. var nextLine = model.GetLine (currentRow + 1);
  3256. removedLines.Add (new List<Rune> (nextLine));
  3257. historyText.Add (removedLines, CursorPosition, HistoryText.LineStatus.Removed);
  3258. currentLine.AddRange (nextLine);
  3259. model.RemoveLine (currentRow + 1);
  3260. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3261. HistoryText.LineStatus.Replaced);
  3262. if (wordWrap) {
  3263. wrapNeeded = true;
  3264. }
  3265. if (wrapNeeded) {
  3266. SetNeedsDisplay ();
  3267. } else {
  3268. var sr = currentRow - topRow;
  3269. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  3270. }
  3271. } else {
  3272. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3273. currentLine.RemoveAt (currentColumn);
  3274. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3275. HistoryText.LineStatus.Replaced);
  3276. if (wordWrap) {
  3277. wrapNeeded = true;
  3278. }
  3279. if (wrapNeeded) {
  3280. SetNeedsDisplay ();
  3281. } else {
  3282. var r = currentRow - topRow;
  3283. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  3284. }
  3285. }
  3286. UpdateWrapModel ();
  3287. return false;
  3288. }
  3289. bool DeleteTextBackwards ()
  3290. {
  3291. SetWrapModel ();
  3292. if (currentColumn > 0) {
  3293. // Delete backwards
  3294. var currentLine = GetCurrentLine ();
  3295. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3296. currentLine.RemoveAt (currentColumn - 1);
  3297. if (wordWrap) {
  3298. wrapNeeded = true;
  3299. }
  3300. currentColumn--;
  3301. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3302. HistoryText.LineStatus.Replaced);
  3303. if (currentColumn < leftColumn) {
  3304. leftColumn--;
  3305. SetNeedsDisplay ();
  3306. } else
  3307. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  3308. } else {
  3309. // Merges the current line with the previous one.
  3310. if (currentRow == 0)
  3311. return true;
  3312. var prowIdx = currentRow - 1;
  3313. var prevRow = model.GetLine (prowIdx);
  3314. historyText.Add (new List<List<Rune>> () { new List<Rune> (prevRow) }, CursorPosition);
  3315. List<List<Rune>> removedLines = new List<List<Rune>> () { new List<Rune> (prevRow) };
  3316. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  3317. historyText.Add (removedLines, new Point (currentColumn, prowIdx),
  3318. HistoryText.LineStatus.Removed);
  3319. var prevCount = prevRow.Count;
  3320. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  3321. model.RemoveLine (currentRow);
  3322. if (wordWrap) {
  3323. wrapNeeded = true;
  3324. }
  3325. currentRow--;
  3326. historyText.Add (new List<List<Rune>> () { GetCurrentLine () }, new Point (currentColumn, prowIdx),
  3327. HistoryText.LineStatus.Replaced);
  3328. currentColumn = prevCount;
  3329. SetNeedsDisplay ();
  3330. }
  3331. UpdateWrapModel ();
  3332. return false;
  3333. }
  3334. bool copyWithoutSelection;
  3335. /// <summary>
  3336. /// Copy the selected text to the clipboard contents.
  3337. /// </summary>
  3338. public void Copy ()
  3339. {
  3340. SetWrapModel ();
  3341. if (selecting) {
  3342. SetClipboard (GetRegion ());
  3343. copyWithoutSelection = false;
  3344. } else {
  3345. var currentLine = GetCurrentLine ();
  3346. SetClipboard (ustring.Make (currentLine));
  3347. copyWithoutSelection = true;
  3348. }
  3349. UpdateWrapModel ();
  3350. DoNeededAction ();
  3351. }
  3352. /// <summary>
  3353. /// Cut the selected text to the clipboard contents.
  3354. /// </summary>
  3355. public void Cut ()
  3356. {
  3357. SetWrapModel ();
  3358. SetClipboard (GetRegion ());
  3359. if (!isReadOnly) {
  3360. ClearRegion ();
  3361. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3362. HistoryText.LineStatus.Replaced);
  3363. }
  3364. UpdateWrapModel ();
  3365. selecting = false;
  3366. DoNeededAction ();
  3367. OnContentsChanged ();
  3368. }
  3369. /// <summary>
  3370. /// Paste the clipboard contents into the current selected position.
  3371. /// </summary>
  3372. public void Paste ()
  3373. {
  3374. if (isReadOnly) {
  3375. return;
  3376. }
  3377. SetWrapModel ();
  3378. var contents = Clipboard.Contents;
  3379. if (copyWithoutSelection && contents.FirstOrDefault (x => x == '\n' || x == '\r') == 0) {
  3380. var runeList = contents == null ? new List<Rune> () : contents.ToRuneList ();
  3381. var currentLine = GetCurrentLine ();
  3382. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3383. var addedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  3384. addedLine.Add (runeList);
  3385. historyText.Add (new List<List<Rune>> (addedLine), CursorPosition, HistoryText.LineStatus.Added);
  3386. model.AddLine (currentRow, runeList);
  3387. currentRow++;
  3388. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3389. HistoryText.LineStatus.Replaced);
  3390. OnContentsChanged ();
  3391. } else {
  3392. if (selecting) {
  3393. ClearRegion ();
  3394. }
  3395. copyWithoutSelection = false;
  3396. InsertText (contents);
  3397. if (selecting) {
  3398. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3399. HistoryText.LineStatus.Original);
  3400. }
  3401. }
  3402. UpdateWrapModel ();
  3403. selecting = false;
  3404. DoNeededAction ();
  3405. }
  3406. void StartSelecting ()
  3407. {
  3408. if (shiftSelecting && selecting) {
  3409. return;
  3410. }
  3411. shiftSelecting = true;
  3412. selecting = true;
  3413. selectionStartColumn = currentColumn;
  3414. selectionStartRow = currentRow;
  3415. }
  3416. void StopSelecting ()
  3417. {
  3418. shiftSelecting = false;
  3419. selecting = false;
  3420. isButtonShift = false;
  3421. }
  3422. void ClearSelectedRegion ()
  3423. {
  3424. SetWrapModel ();
  3425. if (!isReadOnly) {
  3426. ClearRegion ();
  3427. }
  3428. UpdateWrapModel ();
  3429. selecting = false;
  3430. DoNeededAction ();
  3431. }
  3432. void MoveUp ()
  3433. {
  3434. if (currentRow > 0) {
  3435. if (columnTrack == -1) {
  3436. columnTrack = currentColumn;
  3437. }
  3438. currentRow--;
  3439. if (currentRow < topRow) {
  3440. topRow--;
  3441. SetNeedsDisplay ();
  3442. }
  3443. TrackColumn ();
  3444. PositionCursor ();
  3445. }
  3446. DoNeededAction ();
  3447. }
  3448. void MoveDown ()
  3449. {
  3450. if (currentRow + 1 < model.Count) {
  3451. if (columnTrack == -1) {
  3452. columnTrack = currentColumn;
  3453. }
  3454. currentRow++;
  3455. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  3456. topRow++;
  3457. SetNeedsDisplay ();
  3458. }
  3459. TrackColumn ();
  3460. PositionCursor ();
  3461. } else if (currentRow > Frame.Height) {
  3462. Adjust ();
  3463. }
  3464. DoNeededAction ();
  3465. }
  3466. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  3467. {
  3468. if (col < 0 || row < 0)
  3469. yield break;
  3470. if (row >= model.Count)
  3471. yield break;
  3472. var line = GetCurrentLine ();
  3473. if (col >= line.Count)
  3474. yield break;
  3475. while (row < model.Count) {
  3476. for (int c = col; c < line.Count; c++) {
  3477. yield return (c, row, line [c]);
  3478. }
  3479. col = 0;
  3480. row++;
  3481. line = GetCurrentLine ();
  3482. }
  3483. }
  3484. Rune RuneAt (int col, int row)
  3485. {
  3486. var line = model.GetLine (row);
  3487. if (line.Count > 0) {
  3488. return line [col > line.Count - 1 ? line.Count - 1 : col];
  3489. } else {
  3490. return 0;
  3491. }
  3492. }
  3493. /// <summary>
  3494. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  3495. /// </summary>
  3496. public void MoveEnd ()
  3497. {
  3498. currentRow = model.Count - 1;
  3499. var line = GetCurrentLine ();
  3500. currentColumn = line.Count;
  3501. TrackColumn ();
  3502. PositionCursor ();
  3503. }
  3504. /// <summary>
  3505. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  3506. /// </summary>
  3507. public void MoveHome ()
  3508. {
  3509. currentRow = 0;
  3510. topRow = 0;
  3511. currentColumn = 0;
  3512. leftColumn = 0;
  3513. TrackColumn ();
  3514. PositionCursor ();
  3515. }
  3516. bool MoveNext (ref int col, ref int row, out Rune rune)
  3517. {
  3518. var line = model.GetLine (row);
  3519. if (col + 1 < line.Count) {
  3520. col++;
  3521. rune = line [col];
  3522. if (col + 1 == line.Count && !Rune.IsLetterOrDigit (rune)
  3523. && !Rune.IsWhiteSpace (line [col - 1])) {
  3524. col++;
  3525. }
  3526. return true;
  3527. } else if (col + 1 == line.Count) {
  3528. col++;
  3529. }
  3530. while (row + 1 < model.Count) {
  3531. col = 0;
  3532. row++;
  3533. line = model.GetLine (row);
  3534. if (line.Count > 0) {
  3535. rune = line [0];
  3536. return true;
  3537. }
  3538. }
  3539. rune = 0;
  3540. return false;
  3541. }
  3542. bool MovePrev (ref int col, ref int row, out Rune rune)
  3543. {
  3544. var line = model.GetLine (row);
  3545. if (col > 0) {
  3546. col--;
  3547. rune = line [col];
  3548. return true;
  3549. }
  3550. if (row == 0) {
  3551. rune = 0;
  3552. return false;
  3553. }
  3554. while (row > 0) {
  3555. row--;
  3556. line = model.GetLine (row);
  3557. col = line.Count - 1;
  3558. if (col >= 0) {
  3559. rune = line [col];
  3560. return true;
  3561. }
  3562. }
  3563. rune = 0;
  3564. return false;
  3565. }
  3566. (int col, int row)? WordForward (int fromCol, int fromRow)
  3567. {
  3568. var col = fromCol;
  3569. var row = fromRow;
  3570. try {
  3571. var rune = RuneAt (col, row);
  3572. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  3573. {
  3574. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3575. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3576. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))
  3577. return;
  3578. }
  3579. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3580. return;
  3581. }
  3582. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3583. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3584. break;
  3585. }
  3586. } else {
  3587. if (!MoveNext (ref nCol, ref nRow, out nRune)) {
  3588. return;
  3589. }
  3590. var line = model.GetLine (fromRow);
  3591. if ((nRow != fromRow && fromCol < line.Count)
  3592. || (nRow == fromRow && nCol == line.Count - 1)) {
  3593. nCol = line.Count;
  3594. nRow = fromRow;
  3595. return;
  3596. } else if (nRow != fromRow && fromCol == line.Count) {
  3597. line = model.GetLine (nRow);
  3598. if (Rune.IsLetterOrDigit (line [nCol]) || Rune.IsPunctuation (line [nCol])) {
  3599. return;
  3600. }
  3601. }
  3602. ProcMoveNext (ref nCol, ref nRow, nRune);
  3603. }
  3604. }
  3605. ProcMoveNext (ref col, ref row, rune);
  3606. if (fromCol != col || fromRow != row)
  3607. return (col, row);
  3608. return null;
  3609. } catch (Exception) {
  3610. return null;
  3611. }
  3612. }
  3613. (int col, int row)? WordBackward (int fromCol, int fromRow)
  3614. {
  3615. if (fromRow == 0 && fromCol == 0)
  3616. return null;
  3617. var col = Math.Max (fromCol - 1, 0);
  3618. var row = fromRow;
  3619. try {
  3620. var rune = RuneAt (col, row);
  3621. int lastValidCol = Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) ? col : -1;
  3622. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  3623. {
  3624. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3625. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3626. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune)) {
  3627. lastValidCol = nCol;
  3628. break;
  3629. }
  3630. }
  3631. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3632. if (lastValidCol > -1) {
  3633. nCol = lastValidCol;
  3634. }
  3635. return;
  3636. }
  3637. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3638. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3639. break;
  3640. if (nRow != fromRow) {
  3641. break;
  3642. }
  3643. lastValidCol = nCol;
  3644. }
  3645. if (lastValidCol > -1) {
  3646. nCol = lastValidCol;
  3647. nRow = fromRow;
  3648. }
  3649. } else {
  3650. if (!MovePrev (ref nCol, ref nRow, out nRune)) {
  3651. return;
  3652. }
  3653. var line = model.GetLine (nRow);
  3654. if (nCol == 0 && nRow == fromRow && (Rune.IsLetterOrDigit (line [0]) || Rune.IsPunctuation (line [0]))) {
  3655. return;
  3656. }
  3657. lastValidCol = Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) ? nCol : lastValidCol;
  3658. if (lastValidCol > -1 && (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune))) {
  3659. nCol = lastValidCol;
  3660. return;
  3661. }
  3662. if (fromRow != nRow) {
  3663. nCol = line.Count;
  3664. return;
  3665. }
  3666. ProcMovePrev (ref nCol, ref nRow, nRune);
  3667. }
  3668. }
  3669. ProcMovePrev (ref col, ref row, rune);
  3670. if (fromCol != col || fromRow != row)
  3671. return (col, row);
  3672. return null;
  3673. } catch (Exception) {
  3674. return null;
  3675. }
  3676. }
  3677. bool isButtonShift;
  3678. bool clickWithSelecting;
  3679. ///<inheritdoc/>
  3680. public override bool MouseEvent (MouseEvent ev)
  3681. {
  3682. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  3683. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  3684. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  3685. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  3686. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  3687. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  3688. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)
  3689. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  3690. && !ev.Flags.HasFlag (ContextMenu.MouseFlags)) {
  3691. return false;
  3692. }
  3693. if (!CanFocus) {
  3694. return true;
  3695. }
  3696. if (!HasFocus) {
  3697. SetFocus ();
  3698. }
  3699. continuousFind = false;
  3700. // Give autocomplete first opportunity to respond to mouse clicks
  3701. if (SelectedLength == 0 && Autocomplete.MouseEvent (ev, true)) {
  3702. return true;
  3703. }
  3704. if (ev.Flags == MouseFlags.Button1Clicked) {
  3705. if (shiftSelecting && !isButtonShift) {
  3706. StopSelecting ();
  3707. }
  3708. ProcessMouseClick (ev, out _);
  3709. PositionCursor ();
  3710. lastWasKill = false;
  3711. columnTrack = currentColumn;
  3712. } else if (ev.Flags == MouseFlags.WheeledDown) {
  3713. lastWasKill = false;
  3714. columnTrack = currentColumn;
  3715. ScrollTo (topRow + 1);
  3716. } else if (ev.Flags == MouseFlags.WheeledUp) {
  3717. lastWasKill = false;
  3718. columnTrack = currentColumn;
  3719. ScrollTo (topRow - 1);
  3720. } else if (ev.Flags == MouseFlags.WheeledRight) {
  3721. lastWasKill = false;
  3722. columnTrack = currentColumn;
  3723. ScrollTo (leftColumn + 1, false);
  3724. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  3725. lastWasKill = false;
  3726. columnTrack = currentColumn;
  3727. ScrollTo (leftColumn - 1, false);
  3728. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  3729. ProcessMouseClick (ev, out List<Rune> line);
  3730. PositionCursor ();
  3731. if (model.Count > 0 && shiftSelecting && selecting) {
  3732. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  3733. && model.Count + BottomOffset > topRow + currentRow) {
  3734. ScrollTo (topRow + Frame.Height);
  3735. } else if (topRow > 0 && currentRow <= topRow) {
  3736. ScrollTo (topRow - Frame.Height);
  3737. } else if (ev.Y >= Frame.Height) {
  3738. ScrollTo (model.Count + BottomOffset);
  3739. } else if (ev.Y < 0 && topRow > 0) {
  3740. ScrollTo (0);
  3741. }
  3742. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  3743. && line.Count + RightOffset > leftColumn + currentColumn) {
  3744. ScrollTo (leftColumn + Frame.Width, false);
  3745. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  3746. ScrollTo (leftColumn - Frame.Width, false);
  3747. } else if (ev.X >= Frame.Width) {
  3748. ScrollTo (line.Count + RightOffset, false);
  3749. } else if (ev.X < 0 && leftColumn > 0) {
  3750. ScrollTo (0, false);
  3751. }
  3752. }
  3753. lastWasKill = false;
  3754. columnTrack = currentColumn;
  3755. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  3756. if (!shiftSelecting) {
  3757. isButtonShift = true;
  3758. StartSelecting ();
  3759. }
  3760. ProcessMouseClick (ev, out _);
  3761. PositionCursor ();
  3762. lastWasKill = false;
  3763. columnTrack = currentColumn;
  3764. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  3765. if (shiftSelecting) {
  3766. clickWithSelecting = true;
  3767. StopSelecting ();
  3768. }
  3769. ProcessMouseClick (ev, out _);
  3770. PositionCursor ();
  3771. if (!selecting) {
  3772. StartSelecting ();
  3773. }
  3774. lastWasKill = false;
  3775. columnTrack = currentColumn;
  3776. if (Application.MouseGrabView == null) {
  3777. Application.GrabMouse (this);
  3778. }
  3779. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  3780. Application.UngrabMouse ();
  3781. } else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)) {
  3782. if (ev.Flags.HasFlag (MouseFlags.ButtonShift)) {
  3783. if (!selecting) {
  3784. StartSelecting ();
  3785. }
  3786. } else if (selecting) {
  3787. StopSelecting ();
  3788. }
  3789. ProcessMouseClick (ev, out List<Rune> line);
  3790. (int col, int row)? newPos;
  3791. if (currentColumn == line.Count || (currentColumn > 0 && (line [currentColumn - 1] != ' '
  3792. || line [currentColumn] == ' '))) {
  3793. newPos = WordBackward (currentColumn, currentRow);
  3794. if (newPos.HasValue) {
  3795. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : 0;
  3796. }
  3797. }
  3798. if (!selecting) {
  3799. StartSelecting ();
  3800. }
  3801. newPos = WordForward (currentColumn, currentRow);
  3802. if (newPos != null && newPos.HasValue) {
  3803. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : line.Count;
  3804. }
  3805. PositionCursor ();
  3806. lastWasKill = false;
  3807. columnTrack = currentColumn;
  3808. } else if (ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  3809. if (selecting) {
  3810. StopSelecting ();
  3811. }
  3812. ProcessMouseClick (ev, out List<Rune> line);
  3813. currentColumn = 0;
  3814. if (!selecting) {
  3815. StartSelecting ();
  3816. }
  3817. currentColumn = line.Count;
  3818. PositionCursor ();
  3819. lastWasKill = false;
  3820. columnTrack = currentColumn;
  3821. } else if (ev.Flags == ContextMenu.MouseFlags) {
  3822. ContextMenu.Position = new Point (ev.X + 2, ev.Y + 2);
  3823. ShowContextMenu ();
  3824. }
  3825. return true;
  3826. }
  3827. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  3828. {
  3829. List<Rune> r = null;
  3830. if (model.Count > 0) {
  3831. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  3832. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  3833. currentRow = maxCursorPositionableLine + topRow;
  3834. } else {
  3835. currentRow = Math.Max (ev.Y + topRow, 0);
  3836. }
  3837. r = GetCurrentLine ();
  3838. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0), TabWidth);
  3839. if (idx - leftColumn >= r.Count + RightOffset) {
  3840. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  3841. } else {
  3842. currentColumn = idx + leftColumn;
  3843. }
  3844. }
  3845. line = r;
  3846. }
  3847. /// <summary>
  3848. /// Allows clearing the <see cref="HistoryText.HistoryTextItem"/> items updating the original text.
  3849. /// </summary>
  3850. public void ClearHistoryChanges ()
  3851. {
  3852. historyText?.Clear (Text);
  3853. }
  3854. }
  3855. /// <summary>
  3856. /// Renders an overlay on another view at a given point that allows selecting
  3857. /// from a range of 'autocomplete' options.
  3858. /// An implementation on a TextView.
  3859. /// </summary>
  3860. public class TextViewAutocomplete : Autocomplete {
  3861. ///<inheritdoc/>
  3862. protected override string GetCurrentWord (int columnOffset = 0)
  3863. {
  3864. var host = (TextView)HostControl;
  3865. var currentLine = host.GetCurrentLine ();
  3866. var cursorPosition = Math.Min (host.CurrentColumn + columnOffset, currentLine.Count);
  3867. return IdxToWord (currentLine, cursorPosition, columnOffset);
  3868. }
  3869. /// <inheritdoc/>
  3870. protected override void DeleteTextBackwards ()
  3871. {
  3872. ((TextView)HostControl).DeleteCharLeft ();
  3873. }
  3874. /// <inheritdoc/>
  3875. protected override void InsertText (string accepted)
  3876. {
  3877. ((TextView)HostControl).InsertText (accepted);
  3878. }
  3879. }
  3880. }