TextView.cs 126 KB

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