TextView.cs 126 KB

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