2
0

TextView.cs 117 KB

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