TextView.cs 121 KB

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