TextView.cs 122 KB

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