2
0

TextView.cs 124 KB

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