TextView.cs 122 KB

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