TextView.cs 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234
  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.IO;
  27. using System.Linq;
  28. using System.Text;
  29. using NStack;
  30. using Rune = System.Rune;
  31. namespace Terminal.Gui {
  32. class TextModel {
  33. List<List<Rune>> lines = new List<List<Rune>> ();
  34. public bool LoadFile (string file)
  35. {
  36. FilePath = file ?? throw new ArgumentNullException (nameof (file));
  37. var stream = File.OpenRead (file);
  38. LoadStream (stream);
  39. return true;
  40. }
  41. public bool CloseFile ()
  42. {
  43. if (FilePath == null)
  44. throw new ArgumentNullException (nameof (FilePath));
  45. FilePath = null;
  46. lines = new List<List<Rune>> ();
  47. return true;
  48. }
  49. // Turns the ustring into runes, this does not split the
  50. // contents on a newline if it is present.
  51. internal static List<Rune> ToRunes (ustring str)
  52. {
  53. List<Rune> runes = new List<Rune> ();
  54. foreach (var x in str.ToRunes ()) {
  55. runes.Add (x);
  56. }
  57. return runes;
  58. }
  59. // Splits a string into a List that contains a List<Rune> for each line
  60. public static List<List<Rune>> StringToRunes (ustring content)
  61. {
  62. var lines = new List<List<Rune>> ();
  63. int start = 0, i = 0;
  64. var hasCR = false;
  65. // ASCII code 13 = Carriage Return.
  66. // ASCII code 10 = Line Feed.
  67. for (; i < content.Length; i++) {
  68. if (content [i] == 13) {
  69. hasCR = true;
  70. continue;
  71. }
  72. if (content [i] == 10) {
  73. if (i - start > 0)
  74. lines.Add (ToRunes (content [start, hasCR ? i - 1 : i]));
  75. else
  76. lines.Add (ToRunes (ustring.Empty));
  77. start = i + 1;
  78. hasCR = false;
  79. }
  80. }
  81. if (i - start >= 0)
  82. lines.Add (ToRunes (content [start, null]));
  83. return lines;
  84. }
  85. void Append (List<byte> line)
  86. {
  87. var str = ustring.Make (line.ToArray ());
  88. lines.Add (ToRunes (str));
  89. }
  90. public void LoadStream (Stream input)
  91. {
  92. if (input == null)
  93. throw new ArgumentNullException (nameof (input));
  94. lines = new List<List<Rune>> ();
  95. var buff = new BufferedStream (input);
  96. int v;
  97. var line = new List<byte> ();
  98. var wasNewLine = false;
  99. while ((v = buff.ReadByte ()) != -1) {
  100. if (v == 13) {
  101. continue;
  102. }
  103. if (v == 10) {
  104. Append (line);
  105. line.Clear ();
  106. wasNewLine = true;
  107. continue;
  108. }
  109. line.Add ((byte)v);
  110. wasNewLine = false;
  111. }
  112. if (line.Count > 0 || wasNewLine)
  113. Append (line);
  114. buff.Dispose ();
  115. }
  116. public void LoadString (ustring content)
  117. {
  118. lines = StringToRunes (content);
  119. }
  120. public override string ToString ()
  121. {
  122. var sb = new StringBuilder ();
  123. for (int i = 0; i < lines.Count; i++) {
  124. sb.Append (ustring.Make (lines [i]));
  125. if ((i + 1) < lines.Count) {
  126. sb.AppendLine ();
  127. }
  128. }
  129. return sb.ToString ();
  130. }
  131. public string FilePath { get; set; }
  132. /// <summary>
  133. /// The number of text lines in the model
  134. /// </summary>
  135. public int Count => lines.Count;
  136. /// <summary>
  137. /// Returns the specified line as a List of Rune
  138. /// </summary>
  139. /// <returns>The line.</returns>
  140. /// <param name="line">Line number to retrieve.</param>
  141. public List<Rune> GetLine (int line)
  142. {
  143. if (lines.Count > 0) {
  144. if (line < Count) {
  145. return lines [line];
  146. } else {
  147. return lines [Count - 1];
  148. }
  149. } else {
  150. lines.Add (new List<Rune> ());
  151. return lines [0];
  152. }
  153. }
  154. /// <summary>
  155. /// Adds a line to the model at the specified position.
  156. /// </summary>
  157. /// <param name="pos">Line number where the line will be inserted.</param>
  158. /// <param name="runes">The line of text, as a List of Rune.</param>
  159. public void AddLine (int pos, List<Rune> runes)
  160. {
  161. lines.Insert (pos, runes);
  162. }
  163. /// <summary>
  164. /// Removes the line at the specified position
  165. /// </summary>
  166. /// <param name="pos">Position.</param>
  167. public void RemoveLine (int pos)
  168. {
  169. if (lines.Count > 0) {
  170. if (lines.Count == 1 && lines [0].Count == 0) {
  171. return;
  172. }
  173. lines.RemoveAt (pos);
  174. }
  175. }
  176. /// <summary>
  177. /// Returns the maximum line length of the visible lines.
  178. /// </summary>
  179. /// <param name="first">The first line.</param>
  180. /// <param name="last">The last line.</param>
  181. /// <param name="tabWidth">The tab width.</param>
  182. public int GetMaxVisibleLine (int first, int last, int tabWidth)
  183. {
  184. int maxLength = 0;
  185. last = last < lines.Count ? last : lines.Count;
  186. for (int i = first; i < last; i++) {
  187. var line = GetLine (i);
  188. var tabSum = line.Sum (r => r == '\t' ? Math.Max (tabWidth - 1, 0) : 0);
  189. var l = line.Count + tabSum;
  190. if (l > maxLength) {
  191. maxLength = l;
  192. }
  193. }
  194. return maxLength;
  195. }
  196. internal static bool SetCol (ref int col, int width, int cols)
  197. {
  198. if (col + cols <= width) {
  199. col += cols;
  200. return true;
  201. }
  202. return false;
  203. }
  204. internal static int GetColFromX (List<Rune> t, int start, int x, int tabWidth = 0)
  205. {
  206. if (x < 0) {
  207. return x;
  208. }
  209. int size = start;
  210. var pX = x + start;
  211. for (int i = start; i < t.Count; i++) {
  212. var r = t [i];
  213. size += Rune.ColumnWidth (r);
  214. if (r == '\t') {
  215. size += tabWidth + 1;
  216. }
  217. if (i == pX || (size > pX)) {
  218. return i - start;
  219. }
  220. }
  221. return t.Count - start;
  222. }
  223. // Returns the size and length in a range of the string.
  224. internal static (int size, int length) DisplaySize (List<Rune> t, int start = -1, int end = -1,
  225. bool checkNextRune = true, int tabWidth = 0)
  226. {
  227. if (t == null || t.Count == 0) {
  228. return (0, 0);
  229. }
  230. int size = 0;
  231. int len = 0;
  232. int tcount = end == -1 ? t.Count : end > t.Count ? t.Count : end;
  233. int i = start == -1 ? 0 : start;
  234. for (; i < tcount; i++) {
  235. var rune = t [i];
  236. size += Rune.ColumnWidth (rune);
  237. len += Rune.RuneLen (rune);
  238. if (rune == '\t') {
  239. size += tabWidth + 1;
  240. len += tabWidth - 1;
  241. }
  242. if (checkNextRune && i == tcount - 1 && t.Count > tcount
  243. && IsWideRune (t [i + 1], tabWidth, out int s, out int l)) {
  244. size += s;
  245. len += l;
  246. }
  247. }
  248. bool IsWideRune (Rune r, int tWidth, out int s, out int l)
  249. {
  250. s = Rune.ColumnWidth (r);
  251. l = Rune.RuneLen (r);
  252. if (r == '\t') {
  253. s += tWidth + 1;
  254. l += tWidth - 1;
  255. }
  256. return s > 1;
  257. }
  258. return (size, len);
  259. }
  260. // Returns the left column in a range of the string.
  261. internal static int CalculateLeftColumn (List<Rune> t, int start, int end, int width, int tabWidth = 0)
  262. {
  263. if (t == null || t.Count == 0) {
  264. return 0;
  265. }
  266. int size = 0;
  267. int tcount = end > t.Count - 1 ? t.Count - 1 : end;
  268. int col = 0;
  269. for (int i = tcount; i >= 0; i--) {
  270. var rune = t [i];
  271. size += Rune.ColumnWidth (rune);
  272. if (rune == '\t') {
  273. size += tabWidth + 1;
  274. }
  275. if (size >= width) {
  276. break;
  277. } else if (end < t.Count && col > 0 && start < end && col == start) {
  278. break;
  279. }
  280. col = i;
  281. }
  282. return col;
  283. }
  284. (Point startPointToFind, Point currentPointToFind, bool found) toFind;
  285. internal (Point current, bool found) FindNextText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  286. {
  287. if (text == null || lines.Count == 0) {
  288. gaveFullTurn = false;
  289. return (Point.Empty, false);
  290. }
  291. if (toFind.found) {
  292. toFind.currentPointToFind.X++;
  293. }
  294. var foundPos = GetFoundNextTextPoint (text, lines.Count, matchCase, matchWholeWord, toFind.currentPointToFind);
  295. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  296. foundPos = GetFoundNextTextPoint (text, toFind.startPointToFind.Y + 1, matchCase, matchWholeWord, Point.Empty);
  297. }
  298. gaveFullTurn = ApplyToFind (foundPos);
  299. return foundPos;
  300. }
  301. internal (Point current, bool found) FindPreviousText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  302. {
  303. if (text == null || lines.Count == 0) {
  304. gaveFullTurn = false;
  305. return (Point.Empty, false);
  306. }
  307. if (toFind.found) {
  308. toFind.currentPointToFind.X++;
  309. }
  310. var linesCount = toFind.currentPointToFind.IsEmpty ? lines.Count - 1 : toFind.currentPointToFind.Y;
  311. var foundPos = GetFoundPreviousTextPoint (text, linesCount, matchCase, matchWholeWord, toFind.currentPointToFind);
  312. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  313. foundPos = GetFoundPreviousTextPoint (text, lines.Count - 1, matchCase, matchWholeWord,
  314. new Point (lines [lines.Count - 1].Count, lines.Count));
  315. }
  316. gaveFullTurn = ApplyToFind (foundPos);
  317. return foundPos;
  318. }
  319. internal (Point current, bool found) ReplaceAllText (ustring text, bool matchCase = false, bool matchWholeWord = false, ustring textToReplace = null)
  320. {
  321. bool found = false;
  322. Point pos = Point.Empty;
  323. for (int i = 0; i < lines.Count; i++) {
  324. var x = lines [i];
  325. var txt = GetText (x);
  326. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  327. var col = txt.IndexOf (matchText);
  328. while (col > -1) {
  329. if (matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  330. if (col + 1 > txt.Length) {
  331. break;
  332. }
  333. col = txt.IndexOf (matchText, col + 1);
  334. continue;
  335. }
  336. if (col > -1) {
  337. if (!found) {
  338. found = true;
  339. }
  340. lines [i] = ReplaceText (x, textToReplace, matchText, col).ToRuneList ();
  341. x = lines [i];
  342. txt = GetText (x);
  343. pos = new Point (col, i);
  344. col += (textToReplace.Length - matchText.Length);
  345. }
  346. if (col + 1 > txt.Length) {
  347. break;
  348. }
  349. col = txt.IndexOf (matchText, col + 1);
  350. }
  351. }
  352. string GetText (List<Rune> x)
  353. {
  354. var txt = ustring.Make (x).ToString ();
  355. if (!matchCase) {
  356. txt = txt.ToUpper ();
  357. }
  358. return txt;
  359. }
  360. return (pos, found);
  361. }
  362. ustring ReplaceText (List<Rune> source, ustring textToReplace, string matchText, int col)
  363. {
  364. var origTxt = ustring.Make (source);
  365. (int _, int len) = TextModel.DisplaySize (source, 0, col, false);
  366. (var _, var len2) = TextModel.DisplaySize (source, col, col + matchText.Length, false);
  367. (var _, var len3) = TextModel.DisplaySize (source, col + matchText.Length, origTxt.RuneCount, false);
  368. return origTxt [0, len] +
  369. textToReplace.ToString () +
  370. origTxt [len + len2, len + len2 + len3];
  371. }
  372. bool ApplyToFind ((Point current, bool found) foundPos)
  373. {
  374. bool gaveFullTurn = false;
  375. if (foundPos.found) {
  376. toFind.currentPointToFind = foundPos.current;
  377. if (toFind.found && toFind.currentPointToFind == toFind.startPointToFind) {
  378. gaveFullTurn = true;
  379. }
  380. if (!toFind.found) {
  381. toFind.startPointToFind = toFind.currentPointToFind = foundPos.current;
  382. toFind.found = foundPos.found;
  383. }
  384. }
  385. return gaveFullTurn;
  386. }
  387. (Point current, bool found) GetFoundNextTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  388. {
  389. for (int i = start.Y; i < linesCount; i++) {
  390. var x = lines [i];
  391. var txt = ustring.Make (x).ToString ();
  392. if (!matchCase) {
  393. txt = txt.ToUpper ();
  394. }
  395. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  396. var col = txt.IndexOf (matchText, Math.Min (start.X, txt.Length));
  397. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  398. continue;
  399. }
  400. if (col > -1 && ((i == start.Y && col >= start.X)
  401. || i > start.Y)
  402. && txt.Contains (matchText)) {
  403. return (new Point (col, i), true);
  404. } else if (col == -1 && start.X > 0) {
  405. start.X = 0;
  406. }
  407. }
  408. return (Point.Empty, false);
  409. }
  410. (Point current, bool found) GetFoundPreviousTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  411. {
  412. for (int i = linesCount; i >= 0; i--) {
  413. var x = lines [i];
  414. var txt = ustring.Make (x).ToString ();
  415. if (!matchCase) {
  416. txt = txt.ToUpper ();
  417. }
  418. if (start.Y != i) {
  419. start.X = Math.Max (x.Count - 1, 0);
  420. }
  421. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  422. var col = txt.LastIndexOf (matchText, toFind.found ? start.X - 1 : start.X);
  423. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  424. continue;
  425. }
  426. if (col > -1 && ((i <= linesCount && col <= start.X)
  427. || i < start.Y)
  428. && txt.Contains (matchText)) {
  429. return (new Point (col, i), true);
  430. }
  431. }
  432. return (Point.Empty, false);
  433. }
  434. bool MatchWholeWord (string source, string matchText, int index = 0)
  435. {
  436. if (string.IsNullOrEmpty (source) || string.IsNullOrEmpty (matchText)) {
  437. return false;
  438. }
  439. var txt = matchText.Trim ();
  440. var start = index > 0 ? index - 1 : 0;
  441. var end = index + txt.Length;
  442. if ((start == 0 || Rune.IsWhiteSpace (source [start]))
  443. && (end == source.Length || Rune.IsWhiteSpace (source [end]))) {
  444. return true;
  445. }
  446. return false;
  447. }
  448. /// <summary>
  449. /// Redefine column and line tracking.
  450. /// </summary>
  451. /// <param name="point">Contains the column and line.</param>
  452. internal void ResetContinuousFind (Point point)
  453. {
  454. toFind.startPointToFind = toFind.currentPointToFind = point;
  455. toFind.found = false;
  456. }
  457. }
  458. class WordWrapManager {
  459. class WrappedLine {
  460. public int ModelLine;
  461. public int Row;
  462. public int RowIndex;
  463. public int ColWidth;
  464. }
  465. List<WrappedLine> wrappedModelLines = new List<WrappedLine> ();
  466. int frameWidth;
  467. bool isWrapModelRefreshing;
  468. public TextModel Model { get; private set; }
  469. public WordWrapManager (TextModel model)
  470. {
  471. Model = model;
  472. }
  473. public TextModel WrapModel (int width, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  474. int row = 0, int col = 0, int startRow = 0, int startCol = 0, int tabWidth = 0)
  475. {
  476. frameWidth = width;
  477. var modelRow = isWrapModelRefreshing ? row : GetModelLineFromWrappedLines (row);
  478. var modelCol = isWrapModelRefreshing ? col : GetModelColFromWrappedLines (row, col);
  479. var modelStartRow = isWrapModelRefreshing ? startRow : GetModelLineFromWrappedLines (startRow);
  480. var modelStartCol = isWrapModelRefreshing ? startCol : GetModelColFromWrappedLines (startRow, startCol);
  481. var wrappedModel = new TextModel ();
  482. int lines = 0;
  483. nRow = 0;
  484. nCol = 0;
  485. nStartRow = 0;
  486. nStartCol = 0;
  487. bool isRowAndColSetted = row == 0 && col == 0;
  488. bool isStartRowAndColSetted = startRow == 0 && startCol == 0;
  489. List<WrappedLine> wModelLines = new List<WrappedLine> ();
  490. for (int i = 0; i < Model.Count; i++) {
  491. var line = Model.GetLine (i);
  492. var wrappedLines = ToListRune (
  493. TextFormatter.Format (ustring.Make (line), width,
  494. TextAlignment.Left, true, true, tabWidth));
  495. int sumColWidth = 0;
  496. for (int j = 0; j < wrappedLines.Count; j++) {
  497. var wrapLine = wrappedLines [j];
  498. if (!isRowAndColSetted && modelRow == i) {
  499. if (nCol + wrapLine.Count <= modelCol) {
  500. nCol += wrapLine.Count;
  501. nRow = lines;
  502. if (nCol == modelCol) {
  503. nCol = wrapLine.Count;
  504. isRowAndColSetted = true;
  505. } else if (j == wrappedLines.Count - 1) {
  506. nCol = wrapLine.Count - j + modelCol - nCol;
  507. isRowAndColSetted = true;
  508. }
  509. } else {
  510. var offset = nCol + wrapLine.Count - modelCol;
  511. nCol = wrapLine.Count - offset;
  512. nRow = lines;
  513. isRowAndColSetted = true;
  514. }
  515. }
  516. if (!isStartRowAndColSetted && modelStartRow == i) {
  517. if (nStartCol + wrapLine.Count <= modelStartCol) {
  518. nStartCol += wrapLine.Count;
  519. nStartRow = lines;
  520. if (nStartCol == modelStartCol) {
  521. nStartCol = wrapLine.Count;
  522. isStartRowAndColSetted = true;
  523. } else if (j == wrappedLines.Count - 1) {
  524. nStartCol = wrapLine.Count - j + modelStartCol - nStartCol;
  525. isStartRowAndColSetted = true;
  526. }
  527. } else {
  528. var offset = nStartCol + wrapLine.Count - modelStartCol;
  529. nStartCol = wrapLine.Count - offset;
  530. nStartRow = lines;
  531. isStartRowAndColSetted = true;
  532. }
  533. }
  534. wrappedModel.AddLine (lines, wrapLine);
  535. sumColWidth += wrapLine.Count;
  536. var wrappedLine = new WrappedLine () {
  537. ModelLine = i,
  538. Row = lines,
  539. RowIndex = j,
  540. ColWidth = wrapLine.Count,
  541. };
  542. wModelLines.Add (wrappedLine);
  543. lines++;
  544. }
  545. }
  546. wrappedModelLines = wModelLines;
  547. return wrappedModel;
  548. }
  549. public List<List<Rune>> ToListRune (List<ustring> textList)
  550. {
  551. var runesList = new List<List<Rune>> ();
  552. foreach (var text in textList) {
  553. runesList.Add (text.ToRuneList ());
  554. }
  555. return runesList;
  556. }
  557. public int GetModelLineFromWrappedLines (int line) => wrappedModelLines.Count > 0
  558. ? wrappedModelLines [Math.Min (line, wrappedModelLines.Count - 1)].ModelLine
  559. : 0;
  560. public int GetModelColFromWrappedLines (int line, int col)
  561. {
  562. if (wrappedModelLines?.Count == 0) {
  563. return 0;
  564. }
  565. var modelLine = GetModelLineFromWrappedLines (line);
  566. var firstLine = wrappedModelLines.IndexOf (r => r.ModelLine == modelLine);
  567. int modelCol = 0;
  568. for (int i = firstLine; i <= line; i++) {
  569. var wLine = wrappedModelLines [i];
  570. if (i < line) {
  571. modelCol += wLine.ColWidth;
  572. } else {
  573. modelCol += col;
  574. }
  575. }
  576. return modelCol;
  577. }
  578. List<Rune> GetCurrentLine (int row) => Model.GetLine (row);
  579. public void AddLine (int row, int col)
  580. {
  581. var modelRow = GetModelLineFromWrappedLines (row);
  582. var modelCol = GetModelColFromWrappedLines (row, col);
  583. var line = GetCurrentLine (modelRow);
  584. var restCount = line.Count - modelCol;
  585. var rest = line.GetRange (modelCol, restCount);
  586. line.RemoveRange (modelCol, restCount);
  587. Model.AddLine (modelRow + 1, rest);
  588. isWrapModelRefreshing = true;
  589. WrapModel (frameWidth, out _, out _, out _, out _, modelRow + 1, 0);
  590. isWrapModelRefreshing = false;
  591. }
  592. public bool Insert (int row, int col, Rune rune)
  593. {
  594. var line = GetCurrentLine (GetModelLineFromWrappedLines (row));
  595. line.Insert (GetModelColFromWrappedLines (row, col), rune);
  596. if (line.Count > frameWidth) {
  597. return true;
  598. } else {
  599. return false;
  600. }
  601. }
  602. public bool RemoveAt (int row, int col)
  603. {
  604. var modelRow = GetModelLineFromWrappedLines (row);
  605. var line = GetCurrentLine (modelRow);
  606. var modelCol = GetModelColFromWrappedLines (row, col);
  607. if (modelCol >= line.Count) {
  608. Model.RemoveLine (modelRow);
  609. RemoveAt (row, 0);
  610. return false;
  611. }
  612. line.RemoveAt (modelCol);
  613. if (line.Count > frameWidth || (row + 1 < wrappedModelLines.Count
  614. && wrappedModelLines [row + 1].ModelLine == modelRow)) {
  615. return true;
  616. }
  617. return false;
  618. }
  619. public bool RemoveLine (int row, int col, out bool lineRemoved, bool forward = true)
  620. {
  621. lineRemoved = false;
  622. var modelRow = GetModelLineFromWrappedLines (row);
  623. var line = GetCurrentLine (modelRow);
  624. var modelCol = GetModelColFromWrappedLines (row, col);
  625. if (modelCol == 0 && line.Count == 0) {
  626. Model.RemoveLine (modelRow);
  627. return false;
  628. } else if (modelCol < line.Count) {
  629. if (forward) {
  630. line.RemoveAt (modelCol);
  631. return true;
  632. } else if (modelCol - 1 > -1) {
  633. line.RemoveAt (modelCol - 1);
  634. return true;
  635. }
  636. }
  637. lineRemoved = true;
  638. if (forward) {
  639. if (modelRow + 1 == Model.Count) {
  640. return false;
  641. }
  642. var nextLine = Model.GetLine (modelRow + 1);
  643. line.AddRange (nextLine);
  644. Model.RemoveLine (modelRow + 1);
  645. if (line.Count > frameWidth) {
  646. return true;
  647. }
  648. } else {
  649. if (modelRow == 0) {
  650. return false;
  651. }
  652. var prevLine = Model.GetLine (modelRow - 1);
  653. prevLine.AddRange (line);
  654. Model.RemoveLine (modelRow);
  655. if (prevLine.Count > frameWidth) {
  656. return true;
  657. }
  658. }
  659. return false;
  660. }
  661. public bool RemoveRange (int row, int index, int count)
  662. {
  663. var modelRow = GetModelLineFromWrappedLines (row);
  664. var line = GetCurrentLine (modelRow);
  665. var modelCol = GetModelColFromWrappedLines (row, index);
  666. try {
  667. line.RemoveRange (modelCol, count);
  668. } catch (Exception) {
  669. return false;
  670. }
  671. return true;
  672. }
  673. public void UpdateModel (TextModel model, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  674. int row, int col, int startRow, int startCol)
  675. {
  676. isWrapModelRefreshing = true;
  677. Model = model;
  678. WrapModel (frameWidth, out nRow, out nCol, out nStartRow, out nStartCol, row, col, startRow, startCol);
  679. isWrapModelRefreshing = false;
  680. }
  681. }
  682. /// <summary>
  683. /// Multi-line text editing <see cref="View"/>
  684. /// </summary>
  685. /// <remarks>
  686. /// <para>
  687. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  688. /// with it with the standard Emacs commands for movement or the arrow
  689. /// keys.
  690. /// </para>
  691. /// <list type="table">
  692. /// <listheader>
  693. /// <term>Shortcut</term>
  694. /// <description>Action performed</description>
  695. /// </listheader>
  696. /// <item>
  697. /// <term>Left cursor, Control-b</term>
  698. /// <description>
  699. /// Moves the editing point left.
  700. /// </description>
  701. /// </item>
  702. /// <item>
  703. /// <term>Right cursor, Control-f</term>
  704. /// <description>
  705. /// Moves the editing point right.
  706. /// </description>
  707. /// </item>
  708. /// <item>
  709. /// <term>Alt-b</term>
  710. /// <description>
  711. /// Moves one word back.
  712. /// </description>
  713. /// </item>
  714. /// <item>
  715. /// <term>Alt-f</term>
  716. /// <description>
  717. /// Moves one word forward.
  718. /// </description>
  719. /// </item>
  720. /// <item>
  721. /// <term>Up cursor, Control-p</term>
  722. /// <description>
  723. /// Moves the editing point one line up.
  724. /// </description>
  725. /// </item>
  726. /// <item>
  727. /// <term>Down cursor, Control-n</term>
  728. /// <description>
  729. /// Moves the editing point one line down
  730. /// </description>
  731. /// </item>
  732. /// <item>
  733. /// <term>Home key, Control-a</term>
  734. /// <description>
  735. /// Moves the cursor to the beginning of the line.
  736. /// </description>
  737. /// </item>
  738. /// <item>
  739. /// <term>End key, Control-e</term>
  740. /// <description>
  741. /// Moves the cursor to the end of the line.
  742. /// </description>
  743. /// </item>
  744. /// <item>
  745. /// <term>Control-Home</term>
  746. /// <description>
  747. /// Scrolls to the first line and moves the cursor there.
  748. /// </description>
  749. /// </item>
  750. /// <item>
  751. /// <term>Control-End</term>
  752. /// <description>
  753. /// Scrolls to the last line and moves the cursor there.
  754. /// </description>
  755. /// </item>
  756. /// <item>
  757. /// <term>Delete, Control-d</term>
  758. /// <description>
  759. /// Deletes the character in front of the cursor.
  760. /// </description>
  761. /// </item>
  762. /// <item>
  763. /// <term>Backspace</term>
  764. /// <description>
  765. /// Deletes the character behind the cursor.
  766. /// </description>
  767. /// </item>
  768. /// <item>
  769. /// <term>Control-k</term>
  770. /// <description>
  771. /// Deletes the text until the end of the line and replaces the kill buffer
  772. /// with the deleted text. You can paste this text in a different place by
  773. /// using Control-y.
  774. /// </description>
  775. /// </item>
  776. /// <item>
  777. /// <term>Control-y</term>
  778. /// <description>
  779. /// Pastes the content of the kill ring into the current position.
  780. /// </description>
  781. /// </item>
  782. /// <item>
  783. /// <term>Alt-d</term>
  784. /// <description>
  785. /// Deletes the word above the cursor and adds it to the kill ring. You
  786. /// can paste the contents of the kill ring with Control-y.
  787. /// </description>
  788. /// </item>
  789. /// <item>
  790. /// <term>Control-q</term>
  791. /// <description>
  792. /// Quotes the next input character, to prevent the normal processing of
  793. /// key handling to take place.
  794. /// </description>
  795. /// </item>
  796. /// </list>
  797. /// </remarks>
  798. public class TextView : View {
  799. TextModel model = new TextModel ();
  800. int topRow;
  801. int leftColumn;
  802. int currentRow;
  803. int currentColumn;
  804. int selectionStartColumn, selectionStartRow;
  805. bool selecting;
  806. bool wordWrap;
  807. WordWrapManager wrapManager;
  808. bool continuousFind;
  809. int bottomOffset, rightOffset;
  810. int tabWidth = 4;
  811. bool allowsTab = true;
  812. bool allowsReturn = true;
  813. bool multiline = true;
  814. /// <summary>
  815. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  816. /// </summary>
  817. public event Action TextChanged;
  818. /// <summary>
  819. /// Provides autocomplete context menu based on suggestions at the current cursor
  820. /// position. Populate <see cref="Autocomplete.AllSuggestions"/> to enable this feature
  821. /// </summary>
  822. public Autocomplete Autocomplete { get; protected set; } = new Autocomplete ();
  823. #if false
  824. /// <summary>
  825. /// Changed event, raised when the text has clicked.
  826. /// </summary>
  827. /// <remarks>
  828. /// Client code can hook up to this event, it is
  829. /// raised when the text in the entry changes.
  830. /// </remarks>
  831. public Action Changed;
  832. #endif
  833. /// <summary>
  834. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  835. /// </summary>
  836. /// <remarks>
  837. /// </remarks>
  838. public TextView (Rect frame) : base (frame)
  839. {
  840. Initialize ();
  841. }
  842. /// <summary>
  843. /// Initializes a <see cref="TextView"/> on the specified area,
  844. /// with dimensions controlled with the X, Y, Width and Height properties.
  845. /// </summary>
  846. public TextView () : base ()
  847. {
  848. Initialize ();
  849. }
  850. void Initialize ()
  851. {
  852. CanFocus = true;
  853. Used = true;
  854. }
  855. /// <summary>
  856. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry,
  857. /// so new input should be appended at the cursor position, rather than clearing the entry
  858. /// </summary>
  859. public bool Used { get; set; }
  860. void ResetPosition ()
  861. {
  862. topRow = leftColumn = currentRow = currentColumn = 0;
  863. selecting = false;
  864. shiftSelecting = false;
  865. ResetCursorVisibility ();
  866. }
  867. /// <summary>
  868. /// Sets or gets the text in the <see cref="TextView"/>.
  869. /// </summary>
  870. /// <remarks>
  871. /// </remarks>
  872. public override ustring Text {
  873. get {
  874. if (wordWrap) {
  875. return wrapManager.Model.ToString ();
  876. } else {
  877. return model.ToString ();
  878. }
  879. }
  880. set {
  881. ResetPosition ();
  882. model.LoadString (value);
  883. if (wordWrap) {
  884. wrapManager = new WordWrapManager (model);
  885. model = wrapManager.WrapModel (Frame.Width - 2, out _, out _, out _, out _);
  886. }
  887. TextChanged?.Invoke ();
  888. SetNeedsDisplay ();
  889. }
  890. }
  891. ///<inheritdoc/>
  892. public override Rect Frame {
  893. get => base.Frame;
  894. set {
  895. base.Frame = value;
  896. WrapTextModel ();
  897. Adjust ();
  898. }
  899. }
  900. void WrapTextModel ()
  901. {
  902. if (wordWrap && wrapManager != null) {
  903. model = wrapManager.WrapModel (Frame.Width - 2,
  904. out int nRow, out int nCol,
  905. out int nStartRow, out int nStartCol,
  906. currentRow, currentColumn,
  907. selectionStartRow, selectionStartColumn,
  908. tabWidth);
  909. currentRow = nRow;
  910. currentColumn = nCol;
  911. selectionStartRow = nStartRow;
  912. selectionStartColumn = nStartCol;
  913. SetNeedsDisplay ();
  914. }
  915. }
  916. /// <summary>
  917. /// Gets or sets the top row.
  918. /// </summary>
  919. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  920. /// <summary>
  921. /// Gets or sets the left column.
  922. /// </summary>
  923. public int LeftColumn { get => leftColumn; set => leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0); }
  924. /// <summary>
  925. /// Gets the maximum visible length line.
  926. /// </summary>
  927. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height, TabWidth);
  928. /// <summary>
  929. /// Gets the number of lines.
  930. /// </summary>
  931. public int Lines => model.Count;
  932. /// <summary>
  933. /// Sets or gets the current cursor position.
  934. /// </summary>
  935. public Point CursorPosition {
  936. get => new Point (currentColumn, currentRow);
  937. set {
  938. var line = model.GetLine (Math.Max (Math.Min (value.Y, model.Count - 1), 0));
  939. currentColumn = value.X < 0 ? 0 : value.X > line.Count ? line.Count : value.X;
  940. currentRow = value.Y < 0 ? 0 : value.Y > model.Count - 1
  941. ? Math.Max (model.Count - 1, 0) : value.Y;
  942. SetNeedsDisplay ();
  943. Adjust ();
  944. }
  945. }
  946. /// <summary>
  947. /// Start column position of the selected text.
  948. /// </summary>
  949. public int SelectionStartColumn {
  950. get => selectionStartColumn;
  951. set {
  952. var line = model.GetLine (currentRow);
  953. selectionStartColumn = value < 0 ? 0 : value > line.Count ? line.Count : value;
  954. selecting = true;
  955. SetNeedsDisplay ();
  956. Adjust ();
  957. }
  958. }
  959. /// <summary>
  960. /// Start row position of the selected text.
  961. /// </summary>
  962. public int SelectionStartRow {
  963. get => selectionStartRow;
  964. set {
  965. selectionStartRow = value < 0 ? 0 : value > model.Count - 1
  966. ? Math.Max (model.Count - 1, 0) : value;
  967. selecting = true;
  968. SetNeedsDisplay ();
  969. Adjust ();
  970. }
  971. }
  972. /// <summary>
  973. /// The selected text.
  974. /// </summary>
  975. public ustring SelectedText {
  976. get {
  977. if (!selecting || (model.Count == 1 && model.GetLine (0).Count == 0)) {
  978. return ustring.Empty;
  979. }
  980. SetWrapModel ();
  981. var sel = GetRegion ();
  982. UpdateWrapModel ();
  983. Adjust ();
  984. return sel;
  985. }
  986. }
  987. /// <summary>
  988. /// Length of the selected text.
  989. /// </summary>
  990. public int SelectedLength => GetSelectedLength ();
  991. /// <summary>
  992. /// Get or sets the selecting.
  993. /// </summary>
  994. public bool Selecting {
  995. get => selecting;
  996. set => selecting = value;
  997. }
  998. /// <summary>
  999. /// Allows word wrap the to fit the available container width.
  1000. /// </summary>
  1001. public bool WordWrap {
  1002. get => wordWrap;
  1003. set {
  1004. if (value == wordWrap) {
  1005. return;
  1006. }
  1007. wordWrap = value;
  1008. ResetPosition ();
  1009. if (wordWrap) {
  1010. wrapManager = new WordWrapManager (model);
  1011. model = wrapManager.WrapModel (Math.Max (Frame.Width - 2, 0), out _, out _, out _, out _);
  1012. } else if (!wordWrap && wrapManager != null) {
  1013. model = wrapManager.Model;
  1014. }
  1015. SetNeedsDisplay ();
  1016. }
  1017. }
  1018. /// <summary>
  1019. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  1020. /// This is only needed with the keyboard navigation.
  1021. /// </summary>
  1022. public int BottomOffset {
  1023. get => bottomOffset;
  1024. set {
  1025. if (currentRow == Lines - 1 && bottomOffset > 0 && value == 0) {
  1026. topRow = Math.Max (topRow - bottomOffset, 0);
  1027. }
  1028. bottomOffset = value;
  1029. Adjust ();
  1030. }
  1031. }
  1032. /// <summary>
  1033. /// The right offset needed to use a vertical scrollbar or for another reason.
  1034. /// This is only needed with the keyboard navigation.
  1035. /// </summary>
  1036. public int RightOffset {
  1037. get => rightOffset;
  1038. set {
  1039. if (currentColumn == GetCurrentLine ().Count && rightOffset > 0 && value == 0) {
  1040. leftColumn = Math.Max (leftColumn - rightOffset, 0);
  1041. }
  1042. rightOffset = value;
  1043. Adjust ();
  1044. }
  1045. }
  1046. /// <summary>
  1047. /// Gets or sets a value indicating whether pressing ENTER in a <see cref="TextView"/>
  1048. /// creates a new line of text in the view or activates the default button for the toplevel.
  1049. /// </summary>
  1050. public bool AllowsReturn {
  1051. get => allowsReturn;
  1052. set {
  1053. allowsReturn = value;
  1054. if (allowsReturn && !multiline) {
  1055. Multiline = true;
  1056. }
  1057. if (!allowsReturn && multiline) {
  1058. Multiline = false;
  1059. AllowsTab = false;
  1060. }
  1061. SetNeedsDisplay ();
  1062. }
  1063. }
  1064. /// <summary>
  1065. /// Gets or sets a value indicating whether pressing the TAB key in a <see cref="TextView"/>
  1066. /// types a TAB character in the view instead of moving the focus to the next view in the tab order.
  1067. /// </summary>
  1068. public bool AllowsTab {
  1069. get => allowsTab;
  1070. set {
  1071. allowsTab = value;
  1072. if (allowsTab && tabWidth == 0) {
  1073. tabWidth = 4;
  1074. }
  1075. if (allowsTab && !multiline) {
  1076. Multiline = true;
  1077. }
  1078. if (!allowsTab && tabWidth > 0) {
  1079. tabWidth = 0;
  1080. }
  1081. SetNeedsDisplay ();
  1082. }
  1083. }
  1084. /// <summary>
  1085. /// Gets or sets a value indicating the number of whitespace when pressing the TAB key.
  1086. /// </summary>
  1087. public int TabWidth {
  1088. get => tabWidth;
  1089. set {
  1090. tabWidth = Math.Max (value, 0);
  1091. if (tabWidth > 0 && !AllowsTab) {
  1092. AllowsTab = true;
  1093. }
  1094. SetNeedsDisplay ();
  1095. }
  1096. }
  1097. Dim savedHeight = null;
  1098. /// <summary>
  1099. /// Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.
  1100. /// </summary>
  1101. public bool Multiline {
  1102. get => multiline;
  1103. set {
  1104. multiline = value;
  1105. if (multiline && !allowsTab) {
  1106. AllowsTab = true;
  1107. }
  1108. if (multiline && !allowsReturn) {
  1109. AllowsReturn = true;
  1110. }
  1111. if (!multiline) {
  1112. AllowsReturn = false;
  1113. AllowsTab = false;
  1114. currentColumn = 0;
  1115. currentRow = 0;
  1116. savedHeight = Height;
  1117. var lyout = LayoutStyle;
  1118. if (LayoutStyle == LayoutStyle.Computed) {
  1119. LayoutStyle = LayoutStyle.Absolute;
  1120. }
  1121. Height = 1;
  1122. LayoutStyle = lyout;
  1123. SetNeedsDisplay ();
  1124. } else if (multiline && savedHeight != null) {
  1125. var lyout = LayoutStyle;
  1126. if (LayoutStyle == LayoutStyle.Computed) {
  1127. LayoutStyle = LayoutStyle.Absolute;
  1128. }
  1129. Height = savedHeight;
  1130. LayoutStyle = lyout;
  1131. SetNeedsDisplay ();
  1132. }
  1133. }
  1134. }
  1135. int GetSelectedLength ()
  1136. {
  1137. return SelectedText.Length;
  1138. }
  1139. CursorVisibility savedCursorVisibility;
  1140. void SaveCursorVisibility ()
  1141. {
  1142. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  1143. if (savedCursorVisibility == 0) {
  1144. savedCursorVisibility = desiredCursorVisibility;
  1145. }
  1146. DesiredCursorVisibility = CursorVisibility.Invisible;
  1147. }
  1148. }
  1149. void ResetCursorVisibility ()
  1150. {
  1151. if (savedCursorVisibility != 0) {
  1152. DesiredCursorVisibility = savedCursorVisibility;
  1153. savedCursorVisibility = 0;
  1154. }
  1155. }
  1156. /// <summary>
  1157. /// Loads the contents of the file into the <see cref="TextView"/>.
  1158. /// </summary>
  1159. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  1160. /// <param name="path">Path to the file to load.</param>
  1161. public bool LoadFile (string path)
  1162. {
  1163. var res = model.LoadFile (path);
  1164. ResetPosition ();
  1165. SetNeedsDisplay ();
  1166. return res;
  1167. }
  1168. /// <summary>
  1169. /// Loads the contents of the stream into the <see cref="TextView"/>.
  1170. /// </summary>
  1171. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  1172. /// <param name="stream">Stream to load the contents from.</param>
  1173. public void LoadStream (Stream stream)
  1174. {
  1175. model.LoadStream (stream);
  1176. ResetPosition ();
  1177. SetNeedsDisplay ();
  1178. }
  1179. /// <summary>
  1180. /// Closes the contents of the stream into the <see cref="TextView"/>.
  1181. /// </summary>
  1182. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  1183. public bool CloseFile ()
  1184. {
  1185. var res = model.CloseFile ();
  1186. ResetPosition ();
  1187. SetNeedsDisplay ();
  1188. return res;
  1189. }
  1190. /// <summary>
  1191. /// Gets the current cursor row.
  1192. /// </summary>
  1193. public int CurrentRow => currentRow;
  1194. /// <summary>
  1195. /// Gets the cursor column.
  1196. /// </summary>
  1197. /// <value>The cursor column.</value>
  1198. public int CurrentColumn => currentColumn;
  1199. /// <summary>
  1200. /// Positions the cursor on the current row and column
  1201. /// </summary>
  1202. public override void PositionCursor ()
  1203. {
  1204. if (!CanFocus || !Enabled) {
  1205. return;
  1206. }
  1207. if (selecting) {
  1208. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1209. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1210. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  1211. }
  1212. var line = model.GetLine (currentRow);
  1213. var col = 0;
  1214. if (line.Count > 0) {
  1215. for (int idx = leftColumn; idx < line.Count; idx++) {
  1216. if (idx >= currentColumn)
  1217. break;
  1218. var cols = Rune.ColumnWidth (line [idx]);
  1219. if (line [idx] == '\t') {
  1220. cols += TabWidth + 1;
  1221. }
  1222. if (!TextModel.SetCol (ref col, Frame.Width, cols)) {
  1223. col = currentColumn;
  1224. break;
  1225. }
  1226. }
  1227. }
  1228. var posX = currentColumn - leftColumn;
  1229. var posY = currentRow - topRow;
  1230. if ( posX > -1 && col >= posX && posX < Frame.Width - RightOffset
  1231. && topRow <= currentRow && posY < Frame.Height - BottomOffset) {
  1232. ResetCursorVisibility ();
  1233. Move (col, currentRow - topRow);
  1234. } else {
  1235. SaveCursorVisibility ();
  1236. }
  1237. }
  1238. void ClearRegion (int left, int top, int right, int bottom)
  1239. {
  1240. for (int row = top; row < bottom; row++) {
  1241. Move (left, row);
  1242. for (int col = left; col < right; col++)
  1243. AddRune (col, row, ' ');
  1244. }
  1245. }
  1246. /// <summary>
  1247. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to <see cref="ColorScheme.Normal"/>.
  1248. /// </summary>
  1249. protected virtual void ColorNormal ()
  1250. {
  1251. Driver.SetAttribute (GetNormalColor ());
  1252. }
  1253. /// <summary>
  1254. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1255. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1256. /// Defaults to <see cref="ColorScheme.Normal"/>.
  1257. /// </summary>
  1258. /// <param name="line"></param>
  1259. /// <param name="idx"></param>
  1260. protected virtual void ColorNormal (List<Rune> line, int idx)
  1261. {
  1262. Driver.SetAttribute (GetNormalColor ());
  1263. }
  1264. /// <summary>
  1265. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1266. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1267. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1268. /// </summary>
  1269. /// <param name="line"></param>
  1270. /// <param name="idx"></param>
  1271. protected virtual void ColorSelection (List<Rune> line, int idx)
  1272. {
  1273. Driver.SetAttribute (ColorScheme.Focus);
  1274. }
  1275. /// <summary>
  1276. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1277. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1278. /// Defaults to <see cref="ColorScheme.HotFocus"/>.
  1279. /// </summary>
  1280. /// <param name="line"></param>
  1281. /// <param name="idx"></param>
  1282. protected virtual void ColorUsed (List<Rune> line, int idx)
  1283. {
  1284. Driver.SetAttribute (ColorScheme.HotFocus);
  1285. }
  1286. bool isReadOnly = false;
  1287. /// <summary>
  1288. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1289. /// </summary>
  1290. /// <value>Boolean value(Default false)</value>
  1291. public bool ReadOnly {
  1292. get => isReadOnly;
  1293. set {
  1294. isReadOnly = value;
  1295. SetNeedsDisplay ();
  1296. }
  1297. }
  1298. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1299. /// <summary>
  1300. /// Get / Set the wished cursor when the field is focused
  1301. /// </summary>
  1302. public CursorVisibility DesiredCursorVisibility {
  1303. get => desiredCursorVisibility;
  1304. set {
  1305. if (HasFocus) {
  1306. Application.Driver.SetCursorVisibility (value);
  1307. }
  1308. desiredCursorVisibility = value;
  1309. SetNeedsDisplay ();
  1310. }
  1311. }
  1312. ///<inheritdoc/>
  1313. public override bool OnEnter (View view)
  1314. {
  1315. //TODO: Improve it by handling read only mode of the text field
  1316. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1317. return base.OnEnter (view);
  1318. }
  1319. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1320. void GetEncodedRegionBounds (out long start, out long end)
  1321. {
  1322. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1323. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1324. if (selection > point) {
  1325. start = point;
  1326. end = selection;
  1327. } else {
  1328. start = selection;
  1329. end = point;
  1330. }
  1331. }
  1332. bool PointInSelection (int col, int row)
  1333. {
  1334. long start, end;
  1335. GetEncodedRegionBounds (out start, out end);
  1336. var q = ((long)(uint)row << 32) | (uint)col;
  1337. return q >= start && q <= end - 1;
  1338. }
  1339. //
  1340. // Returns a ustring with the text in the selected
  1341. // region.
  1342. //
  1343. ustring GetRegion ()
  1344. {
  1345. long start, end;
  1346. GetEncodedRegionBounds (out start, out end);
  1347. if (start == end) {
  1348. return ustring.Empty;
  1349. }
  1350. int startRow = (int)(start >> 32);
  1351. var maxrow = ((int)(end >> 32));
  1352. int startCol = (int)(start & 0xffffffff);
  1353. var endCol = (int)(end & 0xffffffff);
  1354. var line = model.GetLine (startRow);
  1355. if (startRow == maxrow)
  1356. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1357. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1358. for (int row = startRow + 1; row < maxrow; row++) {
  1359. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  1360. }
  1361. line = model.GetLine (maxrow);
  1362. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  1363. return res;
  1364. }
  1365. //
  1366. // Clears the contents of the selected region
  1367. //
  1368. void ClearRegion ()
  1369. {
  1370. long start, end;
  1371. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1372. GetEncodedRegionBounds (out start, out end);
  1373. int startRow = (int)(start >> 32);
  1374. var maxrow = ((int)(end >> 32));
  1375. int startCol = (int)(start & 0xffffffff);
  1376. var endCol = (int)(end & 0xffffffff);
  1377. var line = model.GetLine (startRow);
  1378. if (startRow == maxrow) {
  1379. line.RemoveRange (startCol, endCol - startCol);
  1380. currentColumn = startCol;
  1381. if (wordWrap) {
  1382. SetNeedsDisplay ();
  1383. } else {
  1384. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1385. }
  1386. return;
  1387. }
  1388. line.RemoveRange (startCol, line.Count - startCol);
  1389. var line2 = model.GetLine (maxrow);
  1390. line.AddRange (line2.Skip (endCol));
  1391. for (int row = startRow + 1; row <= maxrow; row++) {
  1392. model.RemoveLine (startRow + 1);
  1393. }
  1394. if (currentEncoded == end) {
  1395. currentRow -= maxrow - (startRow);
  1396. }
  1397. currentColumn = startCol;
  1398. SetNeedsDisplay ();
  1399. }
  1400. /// <summary>
  1401. /// Select all text.
  1402. /// </summary>
  1403. public void SelectAll ()
  1404. {
  1405. if (model.Count == 0) {
  1406. return;
  1407. }
  1408. StartSelecting ();
  1409. selectionStartColumn = 0;
  1410. selectionStartRow = 0;
  1411. currentColumn = model.GetLine (model.Count - 1).Count;
  1412. currentRow = model.Count - 1;
  1413. SetNeedsDisplay ();
  1414. }
  1415. /// <summary>
  1416. /// Find the next text based on the match case with the option to replace it.
  1417. /// </summary>
  1418. /// <param name="textToFind">The text to find.</param>
  1419. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1420. /// <param name="matchCase">The match case setting.</param>
  1421. /// <param name="matchWholeWord">The match whole word setting.</param>
  1422. /// <param name="textToReplace">The text to replace.</param>
  1423. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1424. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1425. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1426. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1427. {
  1428. if (model.Count == 0) {
  1429. gaveFullTurn = false;
  1430. return false;
  1431. }
  1432. SetWrapModel ();
  1433. ResetContinuousFind ();
  1434. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1435. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1436. }
  1437. /// <summary>
  1438. /// Find the previous text based on the match case with the option to replace it.
  1439. /// </summary>
  1440. /// <param name="textToFind">The text to find.</param>
  1441. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  1442. /// <param name="matchCase">The match case setting.</param>
  1443. /// <param name="matchWholeWord">The match whole word setting.</param>
  1444. /// <param name="textToReplace">The text to replace.</param>
  1445. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1446. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1447. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1448. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1449. {
  1450. if (model.Count == 0) {
  1451. gaveFullTurn = false;
  1452. return false;
  1453. }
  1454. SetWrapModel ();
  1455. ResetContinuousFind ();
  1456. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1457. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1458. }
  1459. /// <summary>
  1460. /// Reset the flag to stop continuous find.
  1461. /// </summary>
  1462. public void FindTextChanged ()
  1463. {
  1464. continuousFind = false;
  1465. }
  1466. /// <summary>
  1467. /// Replaces all the text based on the match case.
  1468. /// </summary>
  1469. /// <param name="textToFind">The text to find.</param>
  1470. /// <param name="matchCase">The match case setting.</param>
  1471. /// <param name="matchWholeWord">The match whole word setting.</param>
  1472. /// <param name="textToReplace">The text to replace.</param>
  1473. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1474. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1475. ustring textToReplace = null)
  1476. {
  1477. if (isReadOnly || model.Count == 0) {
  1478. return false;
  1479. }
  1480. SetWrapModel ();
  1481. ResetContinuousFind ();
  1482. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1483. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1484. }
  1485. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1486. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1487. {
  1488. if (foundPos.found) {
  1489. StartSelecting ();
  1490. selectionStartColumn = foundPos.current.X;
  1491. selectionStartRow = foundPos.current.Y;
  1492. if (!replaceAll) {
  1493. currentColumn = selectionStartColumn + text.RuneCount;
  1494. } else {
  1495. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1496. }
  1497. currentRow = foundPos.current.Y;
  1498. if (!isReadOnly && replace) {
  1499. Adjust ();
  1500. ClearSelectedRegion ();
  1501. InsertText (textToReplace);
  1502. StartSelecting ();
  1503. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1504. } else {
  1505. UpdateWrapModel ();
  1506. SetNeedsDisplay ();
  1507. Adjust ();
  1508. }
  1509. continuousFind = true;
  1510. return foundPos.found;
  1511. }
  1512. UpdateWrapModel ();
  1513. continuousFind = false;
  1514. return foundPos.found;
  1515. }
  1516. void ResetContinuousFind ()
  1517. {
  1518. if (!continuousFind) {
  1519. var col = selecting ? selectionStartColumn : currentColumn;
  1520. var row = selecting ? selectionStartRow : currentRow;
  1521. model.ResetContinuousFind (new Point (col, row));
  1522. }
  1523. }
  1524. /// <summary>
  1525. /// Restore from original model.
  1526. /// </summary>
  1527. void SetWrapModel ()
  1528. {
  1529. if (wordWrap) {
  1530. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  1531. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  1532. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  1533. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  1534. model = wrapManager.Model;
  1535. }
  1536. }
  1537. /// <summary>
  1538. /// Update the original model.
  1539. /// </summary>
  1540. void UpdateWrapModel ()
  1541. {
  1542. if (wordWrap) {
  1543. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  1544. out int nStartRow, out int nStartCol,
  1545. currentRow, currentColumn,
  1546. selectionStartRow, selectionStartColumn);
  1547. currentRow = nRow;
  1548. currentColumn = nCol;
  1549. selectionStartRow = nStartRow;
  1550. selectionStartColumn = nStartCol;
  1551. wrapNeeded = true;
  1552. }
  1553. }
  1554. ///<inheritdoc/>
  1555. public override void Redraw (Rect bounds)
  1556. {
  1557. ColorNormal ();
  1558. var offB = OffSetBackground ();
  1559. int right = Frame.Width + offB.width + RightOffset;
  1560. int bottom = Frame.Height + offB.height + BottomOffset;
  1561. var row = 0;
  1562. for (int idxRow = topRow; idxRow < model.Count; idxRow++) {
  1563. var line = model.GetLine (idxRow);
  1564. int lineRuneCount = line.Count;
  1565. var col = 0;
  1566. Move (0, row);
  1567. for (int idxCol = leftColumn; idxCol < lineRuneCount; idxCol++) {
  1568. var rune = idxCol >= lineRuneCount ? ' ' : line [idxCol];
  1569. var cols = Rune.ColumnWidth (rune);
  1570. if (idxCol < line.Count && selecting && PointInSelection (idxCol, idxRow)) {
  1571. ColorSelection (line, idxCol);
  1572. } else if (idxCol == currentColumn && idxRow == currentRow && !selecting && !Used
  1573. && HasFocus && idxCol < lineRuneCount) {
  1574. ColorUsed (line, idxCol);
  1575. } else {
  1576. ColorNormal (line, idxCol);
  1577. }
  1578. if (rune == '\t') {
  1579. cols += TabWidth + 1;
  1580. if (col + cols > right) {
  1581. cols = right - col;
  1582. }
  1583. for (int i = 0; i < cols; i++) {
  1584. if (col + i < right) {
  1585. AddRune (col + i, row, ' ');
  1586. }
  1587. }
  1588. } else {
  1589. AddRune (col, row, rune);
  1590. }
  1591. if (!TextModel.SetCol (ref col, bounds.Right, cols)) {
  1592. break;
  1593. }
  1594. if (idxCol + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idxCol + 1]) > right) {
  1595. break;
  1596. }
  1597. }
  1598. if (col < right) {
  1599. ColorNormal ();
  1600. ClearRegion (col, row, right, row + 1);
  1601. }
  1602. row++;
  1603. }
  1604. if (row < bottom) {
  1605. ColorNormal ();
  1606. ClearRegion (bounds.Left, row, right, bottom);
  1607. }
  1608. PositionCursor ();
  1609. // draw autocomplete
  1610. Autocomplete.GenerateSuggestions (this);
  1611. var renderAt = new Point (
  1612. CursorPosition.X - LeftColumn,
  1613. (CursorPosition.Y + 1) - TopRow);
  1614. Autocomplete.RenderOverlay (this, renderAt);
  1615. }
  1616. ///<inheritdoc/>
  1617. public override bool CanFocus {
  1618. get => base.CanFocus;
  1619. set { base.CanFocus = value; }
  1620. }
  1621. void SetClipboard (ustring text)
  1622. {
  1623. if (text != null) {
  1624. Clipboard.Contents = text;
  1625. }
  1626. }
  1627. void AppendClipboard (ustring text)
  1628. {
  1629. Clipboard.Contents += text;
  1630. }
  1631. /// <summary>
  1632. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position
  1633. /// exactly as if the user had just typed it
  1634. /// </summary>
  1635. /// <param name="toAdd">Text to add</param>
  1636. public void InsertText (string toAdd)
  1637. {
  1638. foreach (var ch in toAdd) {
  1639. Key key;
  1640. try {
  1641. key = (Key)ch;
  1642. } catch (Exception) {
  1643. throw new ArgumentException ($"Cannot insert character '{ch}' because it does not map to a Key");
  1644. }
  1645. InsertText (new KeyEvent () { Key = key });
  1646. }
  1647. }
  1648. void Insert (Rune rune)
  1649. {
  1650. var line = GetCurrentLine ();
  1651. if (Used) {
  1652. line.Insert (Math.Min (currentColumn, line.Count), rune);
  1653. } else {
  1654. if (currentColumn < line.Count) {
  1655. line.RemoveAt (currentColumn);
  1656. }
  1657. line.Insert (Math.Min (currentColumn, line.Count), rune);
  1658. }
  1659. if (wordWrap) {
  1660. if (Used) {
  1661. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  1662. } else {
  1663. wrapNeeded = wrapManager.RemoveAt (currentRow, currentColumn);
  1664. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  1665. }
  1666. if (wrapNeeded) {
  1667. SetNeedsDisplay ();
  1668. }
  1669. }
  1670. var prow = currentRow - topRow;
  1671. if (!wrapNeeded) {
  1672. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  1673. }
  1674. }
  1675. ustring StringFromRunes (List<Rune> runes)
  1676. {
  1677. if (runes == null)
  1678. throw new ArgumentNullException (nameof (runes));
  1679. int size = 0;
  1680. foreach (var rune in runes) {
  1681. size += Utf8.RuneLen (rune);
  1682. }
  1683. var encoded = new byte [size];
  1684. int offset = 0;
  1685. foreach (var rune in runes) {
  1686. offset += Utf8.EncodeRune (rune, encoded, offset);
  1687. }
  1688. return ustring.Make (encoded);
  1689. }
  1690. /// <summary>
  1691. /// Returns the characters on the current line (where the cursor is positioned).
  1692. /// Use <see cref="CurrentColumn"/> to determine the position of the cursor within
  1693. /// that line
  1694. /// </summary>
  1695. /// <returns></returns>
  1696. public List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  1697. void InsertText (ustring text)
  1698. {
  1699. if (ustring.IsNullOrEmpty (text)) {
  1700. return;
  1701. }
  1702. var lines = TextModel.StringToRunes (text);
  1703. if (lines.Count == 0) {
  1704. return;
  1705. }
  1706. var line = GetCurrentLine ();
  1707. // Optimize single line
  1708. if (lines.Count == 1) {
  1709. line.InsertRange (currentColumn, lines [0]);
  1710. currentColumn += lines [0].Count;
  1711. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  1712. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  1713. }
  1714. if (wordWrap) {
  1715. SetNeedsDisplay ();
  1716. } else {
  1717. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Math.Max (currentRow - topRow + 1, 0)));
  1718. }
  1719. return;
  1720. }
  1721. List<Rune> rest = null;
  1722. int lastp = 0;
  1723. if (model.Count > 0 && currentColumn > 0) {
  1724. // Keep a copy of the rest of the line
  1725. var restCount = line.Count - currentColumn;
  1726. rest = line.GetRange (currentColumn, restCount);
  1727. line.RemoveRange (currentColumn, restCount);
  1728. }
  1729. // First line is inserted at the current location, the rest is appended
  1730. line.InsertRange (currentColumn, lines [0]);
  1731. //model.AddLine (currentRow, lines [0]);
  1732. for (int i = 1; i < lines.Count; i++) {
  1733. model.AddLine (currentRow + i, lines [i]);
  1734. }
  1735. if (rest != null) {
  1736. var last = model.GetLine (currentRow + lines.Count - 1);
  1737. lastp = last.Count;
  1738. last.InsertRange (last.Count, rest);
  1739. }
  1740. // Now adjust column and row positions
  1741. currentRow += lines.Count - 1;
  1742. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  1743. Adjust ();
  1744. }
  1745. // The column we are tracking, or -1 if we are not tracking any column
  1746. int columnTrack = -1;
  1747. // Tries to snap the cursor to the tracking column
  1748. void TrackColumn ()
  1749. {
  1750. // Now track the column
  1751. var line = GetCurrentLine ();
  1752. if (line.Count < columnTrack)
  1753. currentColumn = line.Count;
  1754. else if (columnTrack != -1)
  1755. currentColumn = columnTrack;
  1756. else if (currentColumn > line.Count)
  1757. currentColumn = line.Count;
  1758. Adjust ();
  1759. }
  1760. void Adjust ()
  1761. {
  1762. var offB = OffSetBackground ();
  1763. var line = GetCurrentLine ();
  1764. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  1765. var tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  1766. var dSize = TextModel.DisplaySize (line, leftColumn, currentColumn, true, TabWidth);
  1767. if (!wordWrap && currentColumn < leftColumn) {
  1768. leftColumn = currentColumn;
  1769. need = true;
  1770. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width
  1771. || dSize.size + RightOffset >= Frame.Width + offB.width)) {
  1772. leftColumn = TextModel.CalculateLeftColumn (line, leftColumn, currentColumn,
  1773. Frame.Width + offB.width - RightOffset, TabWidth);
  1774. need = true;
  1775. } else if (dSize.size + RightOffset < Frame.Width + offB.width
  1776. && tSize.size + RightOffset < Frame.Width + offB.width) {
  1777. leftColumn = 0;
  1778. need = true;
  1779. }
  1780. if (currentRow < topRow) {
  1781. topRow = currentRow;
  1782. need = true;
  1783. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  1784. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  1785. need = true;
  1786. }
  1787. if (need) {
  1788. if (wrapNeeded) {
  1789. WrapTextModel ();
  1790. wrapNeeded = false;
  1791. }
  1792. SetNeedsDisplay ();
  1793. } else {
  1794. PositionCursor ();
  1795. }
  1796. }
  1797. (int width, int height) OffSetBackground ()
  1798. {
  1799. int w = 0;
  1800. int h = 0;
  1801. if (SuperView?.Frame.Right - Frame.Right < 0) {
  1802. w = SuperView.Frame.Right - Frame.Right - 1;
  1803. }
  1804. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  1805. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  1806. }
  1807. return (w, h);
  1808. }
  1809. /// <summary>
  1810. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  1811. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  1812. /// </summary>
  1813. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  1814. /// if the value is negative it will be reset to zero</param>
  1815. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  1816. public void ScrollTo (int idx, bool isRow = true)
  1817. {
  1818. if (idx < 0) {
  1819. idx = 0;
  1820. }
  1821. if (isRow) {
  1822. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  1823. } else if (!wordWrap) {
  1824. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset, TabWidth);
  1825. leftColumn = Math.Max (idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  1826. }
  1827. SetNeedsDisplay ();
  1828. }
  1829. bool lastWasKill;
  1830. bool wrapNeeded;
  1831. bool shiftSelecting;
  1832. ///<inheritdoc/>
  1833. public override bool ProcessKey (KeyEvent kb)
  1834. {
  1835. if (!CanFocus) {
  1836. return true;
  1837. }
  1838. int restCount;
  1839. List<Rune> rest;
  1840. // if the user presses Left (without any control keys) and they are at the start of the text
  1841. if (kb.Key == Key.CursorLeft && currentColumn == 0 && currentRow == 0) {
  1842. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  1843. return false;
  1844. }
  1845. // if the user presses Right (without any control keys)
  1846. if (kb.Key == Key.CursorRight) {
  1847. // determine where the last cursor position in the text is
  1848. var lastRow = model.Count - 1;
  1849. var lastCol = model.GetLine (lastRow).Count;
  1850. // 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)
  1851. if (currentColumn == lastCol && currentRow == lastRow) {
  1852. return false;
  1853. }
  1854. }
  1855. // Give autocomplete first opportunity to respond to key presses
  1856. if (Autocomplete.ProcessKey (this, kb)) {
  1857. return true;
  1858. }
  1859. // Handle some state here - whether the last command was a kill
  1860. // operation and the column tracking (up/down)
  1861. switch (kb.Key) {
  1862. case Key.N | Key.CtrlMask:
  1863. case Key.CursorDown:
  1864. case Key.P | Key.CtrlMask:
  1865. case Key.CursorUp:
  1866. lastWasKill = false;
  1867. continuousFind = false;
  1868. break;
  1869. case Key.K | Key.CtrlMask:
  1870. break;
  1871. case Key.F | Key.CtrlMask:
  1872. case Key.B | Key.CtrlMask:
  1873. case (Key)((int)'B' + Key.AltMask):
  1874. case Key.A | Key.CtrlMask:
  1875. case Key.E | Key.CtrlMask:
  1876. case Key.CursorRight:
  1877. case Key.CursorLeft:
  1878. case Key.CursorRight | Key.CtrlMask:
  1879. case Key.CursorLeft | Key.CtrlMask:
  1880. case Key.CursorRight | Key.ShiftMask:
  1881. case Key.CursorLeft | Key.ShiftMask:
  1882. case Key.CursorRight | Key.CtrlMask | Key.ShiftMask:
  1883. case Key.CursorLeft | Key.CtrlMask | Key.ShiftMask:
  1884. case Key.Home:
  1885. case Key.Home | Key.CtrlMask:
  1886. case Key.Home | Key.ShiftMask:
  1887. case Key.Home | Key.CtrlMask | Key.ShiftMask:
  1888. case Key.End:
  1889. case Key.End | Key.CtrlMask:
  1890. case Key.End | Key.ShiftMask:
  1891. case Key.End | Key.CtrlMask | Key.ShiftMask:
  1892. lastWasKill = false;
  1893. columnTrack = -1;
  1894. continuousFind = false;
  1895. break;
  1896. default:
  1897. lastWasKill = false;
  1898. columnTrack = -1;
  1899. break;
  1900. }
  1901. // Dispatch the command.
  1902. switch (kb.Key) {
  1903. case Key.PageDown:
  1904. case Key.V | Key.CtrlMask:
  1905. case Key.PageDown | Key.ShiftMask:
  1906. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1907. StartSelecting ();
  1908. } else if (shiftSelecting && selecting) {
  1909. StopSelecting ();
  1910. }
  1911. int nPageDnShift = Frame.Height - 1;
  1912. if (currentRow >= 0 && currentRow < model.Count) {
  1913. if (columnTrack == -1)
  1914. columnTrack = currentColumn;
  1915. currentRow = (currentRow + nPageDnShift) > model.Count
  1916. ? model.Count > 0 ? model.Count - 1 : 0
  1917. : currentRow + nPageDnShift;
  1918. if (topRow < currentRow - nPageDnShift) {
  1919. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  1920. SetNeedsDisplay ();
  1921. }
  1922. TrackColumn ();
  1923. PositionCursor ();
  1924. }
  1925. break;
  1926. case Key.PageUp:
  1927. case ((int)'V' + Key.AltMask):
  1928. case Key.PageUp | Key.ShiftMask:
  1929. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1930. StartSelecting ();
  1931. } else if (shiftSelecting && selecting) {
  1932. StopSelecting ();
  1933. }
  1934. int nPageUpShift = Frame.Height - 1;
  1935. if (currentRow > 0) {
  1936. if (columnTrack == -1)
  1937. columnTrack = currentColumn;
  1938. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  1939. if (currentRow < topRow) {
  1940. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  1941. SetNeedsDisplay ();
  1942. }
  1943. TrackColumn ();
  1944. PositionCursor ();
  1945. }
  1946. break;
  1947. case Key.N | Key.CtrlMask:
  1948. case Key.CursorDown:
  1949. case Key.CursorDown | Key.ShiftMask:
  1950. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1951. StartSelecting ();
  1952. } else if (shiftSelecting && selecting) {
  1953. StopSelecting ();
  1954. }
  1955. MoveDown ();
  1956. break;
  1957. case Key.P | Key.CtrlMask:
  1958. case Key.CursorUp:
  1959. case Key.CursorUp | Key.ShiftMask:
  1960. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1961. StartSelecting ();
  1962. } else if (shiftSelecting && selecting) {
  1963. StopSelecting ();
  1964. }
  1965. MoveUp ();
  1966. break;
  1967. case Key.F | Key.CtrlMask:
  1968. case Key.CursorRight:
  1969. case Key.CursorRight | Key.ShiftMask:
  1970. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1971. StartSelecting ();
  1972. } else if (shiftSelecting && selecting) {
  1973. StopSelecting ();
  1974. }
  1975. var currentLine = GetCurrentLine ();
  1976. if (currentColumn < currentLine.Count) {
  1977. currentColumn++;
  1978. } else {
  1979. if (currentRow + 1 < model.Count) {
  1980. currentRow++;
  1981. currentColumn = 0;
  1982. if (currentRow >= topRow + Frame.Height) {
  1983. topRow++;
  1984. SetNeedsDisplay ();
  1985. }
  1986. }
  1987. }
  1988. Adjust ();
  1989. return true;
  1990. case Key.B | Key.CtrlMask:
  1991. case Key.CursorLeft:
  1992. case Key.CursorLeft | Key.ShiftMask:
  1993. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1994. StartSelecting ();
  1995. } else if (shiftSelecting && selecting) {
  1996. StopSelecting ();
  1997. }
  1998. if (currentColumn > 0) {
  1999. currentColumn--;
  2000. } else {
  2001. if (currentRow > 0) {
  2002. currentRow--;
  2003. if (currentRow < topRow) {
  2004. topRow--;
  2005. SetNeedsDisplay ();
  2006. }
  2007. currentLine = GetCurrentLine ();
  2008. currentColumn = currentLine.Count;
  2009. }
  2010. }
  2011. Adjust ();
  2012. break;
  2013. case Key.Delete:
  2014. case Key.Backspace:
  2015. if (isReadOnly)
  2016. break;
  2017. if (selecting) {
  2018. ClearSelectedRegion ();
  2019. return true;
  2020. }
  2021. if (DeleteTextBackwards ()) {
  2022. return true;
  2023. }
  2024. break;
  2025. // Home, C-A
  2026. case Key.Home:
  2027. case Key.Home | Key.ShiftMask:
  2028. case Key.A | Key.CtrlMask:
  2029. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2030. StartSelecting ();
  2031. } else if (shiftSelecting && selecting) {
  2032. StopSelecting ();
  2033. }
  2034. currentColumn = 0;
  2035. leftColumn = 0;
  2036. Adjust ();
  2037. break;
  2038. case Key.DeleteChar:
  2039. case Key.D | Key.CtrlMask: // Delete
  2040. if (isReadOnly)
  2041. break;
  2042. if (selecting) {
  2043. ClearSelectedRegion ();
  2044. return true;
  2045. }
  2046. if (DeleteTextForwards ()) {
  2047. return true;
  2048. }
  2049. break;
  2050. case Key.End:
  2051. case Key.End | Key.ShiftMask:
  2052. case Key.E | Key.CtrlMask: // End
  2053. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2054. StartSelecting ();
  2055. } else if (shiftSelecting && selecting) {
  2056. StopSelecting ();
  2057. }
  2058. currentLine = GetCurrentLine ();
  2059. currentColumn = currentLine.Count;
  2060. Adjust ();
  2061. return true;
  2062. case Key.K | Key.CtrlMask: // kill-to-end
  2063. case Key.DeleteChar | Key.CtrlMask | Key.ShiftMask:
  2064. if (isReadOnly)
  2065. break;
  2066. currentLine = GetCurrentLine ();
  2067. var setLastWasKill = true;
  2068. if (currentLine.Count > 0 && currentColumn == currentLine.Count) {
  2069. DeleteTextForwards ();
  2070. return true;
  2071. }
  2072. if (currentLine.Count == 0) {
  2073. if (currentRow < model.Count - 1) {
  2074. model.RemoveLine (currentRow);
  2075. }
  2076. if (model.Count > 0 || lastWasKill) {
  2077. var val = ustring.Make ((Rune)'\n');
  2078. if (lastWasKill) {
  2079. AppendClipboard (val);
  2080. } else {
  2081. SetClipboard (val);
  2082. }
  2083. }
  2084. if (model.Count == 0) {
  2085. // Prevents from adding line feeds if there is no more lines.
  2086. setLastWasKill = false;
  2087. }
  2088. } else {
  2089. restCount = currentLine.Count - currentColumn;
  2090. rest = currentLine.GetRange (currentColumn, restCount);
  2091. var val = ustring.Empty;
  2092. if (currentColumn == 0 && lastWasKill && currentLine.Count > 0) {
  2093. val = ustring.Make ((Rune)'\n');
  2094. }
  2095. val += StringFromRunes (rest);
  2096. if (lastWasKill) {
  2097. AppendClipboard (val);
  2098. } else {
  2099. SetClipboard (val);
  2100. }
  2101. currentLine.RemoveRange (currentColumn, restCount);
  2102. }
  2103. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2104. lastWasKill = setLastWasKill;
  2105. break;
  2106. case Key.Backspace | Key.CtrlMask | Key.ShiftMask: // kill-to-start
  2107. if (isReadOnly)
  2108. break;
  2109. currentLine = GetCurrentLine ();
  2110. setLastWasKill = true;
  2111. if (currentLine.Count > 0 && currentColumn == 0) {
  2112. DeleteTextBackwards ();
  2113. return true;
  2114. }
  2115. if (currentLine.Count == 0) {
  2116. if (currentRow > 0) {
  2117. model.RemoveLine (currentRow);
  2118. currentRow--;
  2119. currentLine = model.GetLine (currentRow);
  2120. currentColumn = currentLine.Count;
  2121. }
  2122. } else {
  2123. restCount = currentColumn;
  2124. rest = currentLine.GetRange (0, restCount);
  2125. var val = ustring.Empty;
  2126. if (currentColumn == 0 && lastWasKill && currentLine.Count > 0) {
  2127. val = ustring.Make ((Rune)'\n');
  2128. }
  2129. val += StringFromRunes (rest);
  2130. if (lastWasKill) {
  2131. AppendClipboard (val);
  2132. } else {
  2133. SetClipboard (val);
  2134. }
  2135. currentLine.RemoveRange (0, restCount);
  2136. currentColumn = 0;
  2137. }
  2138. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2139. lastWasKill = setLastWasKill;
  2140. break;
  2141. case Key.Y | Key.CtrlMask: // Control-y, yank
  2142. if (isReadOnly)
  2143. break;
  2144. Paste ();
  2145. return true;
  2146. case Key.Space | Key.CtrlMask:
  2147. selecting = !selecting;
  2148. selectionStartColumn = currentColumn;
  2149. selectionStartRow = currentRow;
  2150. break;
  2151. case ((int)'C' + Key.AltMask):
  2152. case Key.C | Key.CtrlMask:
  2153. Copy ();
  2154. return true;
  2155. case ((int)'W' + Key.AltMask):
  2156. case Key.W | Key.CtrlMask:
  2157. case Key.X | Key.CtrlMask:
  2158. Cut ();
  2159. return true;
  2160. case Key.CtrlMask | Key.CursorLeft:
  2161. case Key.CtrlMask | Key.CursorLeft | Key.ShiftMask:
  2162. case (Key)((int)'B' + Key.AltMask):
  2163. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2164. StartSelecting ();
  2165. } else if (shiftSelecting && selecting) {
  2166. StopSelecting ();
  2167. }
  2168. var newPos = WordBackward (currentColumn, currentRow);
  2169. if (newPos.HasValue) {
  2170. currentColumn = newPos.Value.col;
  2171. currentRow = newPos.Value.row;
  2172. }
  2173. Adjust ();
  2174. break;
  2175. case Key.CtrlMask | Key.CursorRight:
  2176. case Key.CtrlMask | Key.CursorRight | Key.ShiftMask:
  2177. case (Key)((int)'F' + Key.AltMask):
  2178. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2179. StartSelecting ();
  2180. } else if (shiftSelecting && selecting) {
  2181. StopSelecting ();
  2182. }
  2183. newPos = WordForward (currentColumn, currentRow);
  2184. if (newPos.HasValue) {
  2185. currentColumn = newPos.Value.col;
  2186. currentRow = newPos.Value.row;
  2187. }
  2188. Adjust ();
  2189. break;
  2190. case Key.DeleteChar | Key.CtrlMask: // kill-word-forwards
  2191. if (isReadOnly)
  2192. break;
  2193. currentLine = GetCurrentLine ();
  2194. if (currentLine.Count == 0 || currentColumn == currentLine.Count) {
  2195. DeleteTextForwards ();
  2196. return true;
  2197. }
  2198. newPos = WordForward (currentColumn, currentRow);
  2199. restCount = 0;
  2200. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2201. restCount = newPos.Value.col - currentColumn;
  2202. currentLine.RemoveRange (currentColumn, restCount);
  2203. } else if (newPos.HasValue) {
  2204. restCount = currentLine.Count - currentColumn;
  2205. currentLine.RemoveRange (currentColumn, restCount);
  2206. }
  2207. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2208. wrapNeeded = true;
  2209. }
  2210. if (wrapNeeded) {
  2211. SetNeedsDisplay ();
  2212. } else {
  2213. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2214. }
  2215. break;
  2216. case Key.Backspace | Key.CtrlMask: // kill-word-backwards
  2217. if (isReadOnly)
  2218. break;
  2219. currentLine = GetCurrentLine ();
  2220. if (currentColumn == 0) {
  2221. DeleteTextBackwards ();
  2222. return true;
  2223. }
  2224. newPos = WordBackward (currentColumn, currentRow);
  2225. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2226. restCount = currentColumn - newPos.Value.col;
  2227. currentLine.RemoveRange (newPos.Value.col, restCount);
  2228. if (wordWrap && wrapManager.RemoveRange (currentRow, newPos.Value.col, restCount)) {
  2229. wrapNeeded = true;
  2230. }
  2231. currentColumn = newPos.Value.col;
  2232. } else if (newPos.HasValue) {
  2233. restCount = currentLine.Count - currentColumn;
  2234. currentLine.RemoveRange (currentColumn, restCount);
  2235. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2236. wrapNeeded = true;
  2237. }
  2238. currentColumn = newPos.Value.col;
  2239. currentRow = newPos.Value.row;
  2240. }
  2241. if (wrapNeeded) {
  2242. SetNeedsDisplay ();
  2243. } else {
  2244. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2245. }
  2246. break;
  2247. case Key.Enter:
  2248. if (!AllowsReturn) {
  2249. return false;
  2250. }
  2251. if (isReadOnly)
  2252. break;
  2253. currentLine = GetCurrentLine ();
  2254. restCount = currentLine.Count - currentColumn;
  2255. rest = currentLine.GetRange (currentColumn, restCount);
  2256. currentLine.RemoveRange (currentColumn, restCount);
  2257. model.AddLine (currentRow + 1, rest);
  2258. if (wordWrap) {
  2259. wrapManager.AddLine (currentRow, currentColumn);
  2260. wrapNeeded = true;
  2261. }
  2262. currentRow++;
  2263. bool fullNeedsDisplay = false;
  2264. if (currentRow >= topRow + Frame.Height) {
  2265. topRow++;
  2266. fullNeedsDisplay = true;
  2267. }
  2268. currentColumn = 0;
  2269. if (!wordWrap && currentColumn < leftColumn) {
  2270. fullNeedsDisplay = true;
  2271. leftColumn = 0;
  2272. }
  2273. if (fullNeedsDisplay)
  2274. SetNeedsDisplay ();
  2275. else
  2276. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  2277. break;
  2278. case Key.CtrlMask | Key.End:
  2279. case Key.CtrlMask | Key.End | Key.ShiftMask:
  2280. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2281. StartSelecting ();
  2282. } else if (shiftSelecting && selecting) {
  2283. StopSelecting ();
  2284. }
  2285. MoveEnd ();
  2286. break;
  2287. case Key.CtrlMask | Key.Home:
  2288. case Key.CtrlMask | Key.Home | Key.ShiftMask:
  2289. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2290. StartSelecting ();
  2291. } else if (shiftSelecting && selecting) {
  2292. StopSelecting ();
  2293. }
  2294. MoveHome ();
  2295. break;
  2296. case Key.T | Key.CtrlMask:
  2297. SelectAll ();
  2298. break;
  2299. case Key.InsertChar:
  2300. Used = !Used;
  2301. SetNeedsDisplay ();
  2302. break;
  2303. case Key _ when ShortcutHelper.GetModifiersKey (kb) == Key.Tab:
  2304. if (!AllowsTab) {
  2305. return false;
  2306. }
  2307. InsertText (new KeyEvent ((Key)'\t', null));
  2308. break;
  2309. case Key _ when (ShortcutHelper.GetModifiersKey (kb) == (Key.BackTab | Key.ShiftMask)):
  2310. if (!AllowsTab) {
  2311. return false;
  2312. }
  2313. if (currentColumn > 0) {
  2314. currentLine = GetCurrentLine ();
  2315. if (currentLine.Count > 0 && currentLine [currentColumn - 1] == '\t') {
  2316. currentLine.RemoveAt (currentColumn - 1);
  2317. currentColumn--;
  2318. }
  2319. }
  2320. break;
  2321. default:
  2322. // Ignore control characters and other special keys
  2323. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  2324. return false;
  2325. InsertText (kb);
  2326. break;
  2327. }
  2328. DoNeededAction ();
  2329. return true;
  2330. }
  2331. bool InsertText (KeyEvent kb)
  2332. {
  2333. //So that special keys like tab can be processed
  2334. if (isReadOnly)
  2335. return true;
  2336. if (selecting) {
  2337. ClearSelectedRegion ();
  2338. }
  2339. if (Used) {
  2340. Insert ((uint)kb.Key);
  2341. currentColumn++;
  2342. if (currentColumn >= leftColumn + Frame.Width) {
  2343. leftColumn++;
  2344. SetNeedsDisplay ();
  2345. }
  2346. } else {
  2347. Insert ((uint)kb.Key);
  2348. currentColumn++;
  2349. }
  2350. return true;
  2351. }
  2352. ///<inheritdoc/>
  2353. public override bool OnKeyUp (KeyEvent kb)
  2354. {
  2355. switch (kb.Key) {
  2356. case Key.Space | Key.CtrlMask:
  2357. return true;
  2358. }
  2359. return false;
  2360. }
  2361. void DoNeededAction ()
  2362. {
  2363. if (NeedDisplay.IsEmpty) {
  2364. PositionCursor ();
  2365. } else {
  2366. Adjust ();
  2367. }
  2368. }
  2369. bool DeleteTextForwards ()
  2370. {
  2371. var currentLine = GetCurrentLine ();
  2372. if (currentColumn == currentLine.Count) {
  2373. if (currentRow + 1 == model.Count)
  2374. return true;
  2375. var nextLine = model.GetLine (currentRow + 1);
  2376. currentLine.AddRange (nextLine);
  2377. model.RemoveLine (currentRow + 1);
  2378. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out _)) {
  2379. wrapNeeded = true;
  2380. }
  2381. var sr = currentRow - topRow;
  2382. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  2383. } else {
  2384. currentLine.RemoveAt (currentColumn);
  2385. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn)) {
  2386. wrapNeeded = true;
  2387. }
  2388. var r = currentRow - topRow;
  2389. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  2390. }
  2391. return false;
  2392. }
  2393. /// <summary>
  2394. /// Deletes a single character from the position of the cursor
  2395. /// </summary>
  2396. /// <returns></returns>
  2397. public bool DeleteTextBackwards ()
  2398. {
  2399. if (currentColumn > 0) {
  2400. // Delete backwards
  2401. var currentLine = GetCurrentLine ();
  2402. currentLine.RemoveAt (currentColumn - 1);
  2403. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn - 1)) {
  2404. wrapNeeded = true;
  2405. }
  2406. currentColumn--;
  2407. if (currentColumn < leftColumn) {
  2408. leftColumn--;
  2409. SetNeedsDisplay ();
  2410. } else
  2411. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  2412. } else {
  2413. // Merges the current line with the previous one.
  2414. if (currentRow == 0)
  2415. return true;
  2416. var prowIdx = currentRow - 1;
  2417. var prevRow = model.GetLine (prowIdx);
  2418. var prevCount = prevRow.Count;
  2419. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  2420. model.RemoveLine (currentRow);
  2421. bool lineRemoved = false;
  2422. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out lineRemoved, false)) {
  2423. wrapNeeded = true;
  2424. }
  2425. currentRow--;
  2426. if (wrapNeeded && !lineRemoved) {
  2427. currentColumn = Math.Max (prevCount - 1, 0);
  2428. } else {
  2429. currentColumn = prevCount;
  2430. }
  2431. SetNeedsDisplay ();
  2432. }
  2433. return false;
  2434. }
  2435. bool copyWithoutSelection;
  2436. /// <summary>
  2437. /// Copy the selected text to the clipboard contents.
  2438. /// </summary>
  2439. public void Copy ()
  2440. {
  2441. SetWrapModel ();
  2442. if (selecting) {
  2443. SetClipboard (GetRegion ());
  2444. copyWithoutSelection = false;
  2445. } else {
  2446. var currentLine = GetCurrentLine ();
  2447. SetClipboard (ustring.Make (currentLine));
  2448. copyWithoutSelection = true;
  2449. }
  2450. UpdateWrapModel ();
  2451. DoNeededAction ();
  2452. }
  2453. /// <summary>
  2454. /// Cut the selected text to the clipboard contents.
  2455. /// </summary>
  2456. public void Cut ()
  2457. {
  2458. SetWrapModel ();
  2459. SetClipboard (GetRegion ());
  2460. if (!isReadOnly) {
  2461. ClearRegion ();
  2462. }
  2463. UpdateWrapModel ();
  2464. selecting = false;
  2465. DoNeededAction ();
  2466. }
  2467. /// <summary>
  2468. /// Paste the clipboard contents into the current selected position.
  2469. /// </summary>
  2470. public void Paste ()
  2471. {
  2472. if (isReadOnly) {
  2473. return;
  2474. }
  2475. SetWrapModel ();
  2476. var contents = Clipboard.Contents;
  2477. if (copyWithoutSelection) {
  2478. var runeList = contents == null ? new List<Rune> () : contents.ToRuneList ();
  2479. if ((runeList?.Count > 0 && runeList [0] == '\n')
  2480. || (runeList?.Count > 1 && runeList [0] == '\r'
  2481. && runeList [1] == '\n')) {
  2482. InsertText (contents);
  2483. } else {
  2484. model.AddLine (currentRow, runeList);
  2485. currentRow++;
  2486. }
  2487. } else {
  2488. if (selecting) {
  2489. ClearRegion ();
  2490. }
  2491. InsertText (contents);
  2492. copyWithoutSelection = false;
  2493. }
  2494. UpdateWrapModel ();
  2495. selecting = false;
  2496. DoNeededAction ();
  2497. }
  2498. void StartSelecting ()
  2499. {
  2500. if (shiftSelecting && selecting) {
  2501. return;
  2502. }
  2503. shiftSelecting = true;
  2504. selecting = true;
  2505. selectionStartColumn = currentColumn;
  2506. selectionStartRow = currentRow;
  2507. }
  2508. void StopSelecting ()
  2509. {
  2510. shiftSelecting = false;
  2511. selecting = false;
  2512. }
  2513. void ClearSelectedRegion ()
  2514. {
  2515. SetWrapModel ();
  2516. if (!isReadOnly) {
  2517. ClearRegion ();
  2518. }
  2519. UpdateWrapModel ();
  2520. selecting = false;
  2521. DoNeededAction ();
  2522. }
  2523. void MoveUp ()
  2524. {
  2525. if (currentRow > 0) {
  2526. if (columnTrack == -1) {
  2527. columnTrack = currentColumn;
  2528. }
  2529. currentRow--;
  2530. if (currentRow < topRow) {
  2531. topRow--;
  2532. SetNeedsDisplay ();
  2533. }
  2534. TrackColumn ();
  2535. PositionCursor ();
  2536. }
  2537. }
  2538. void MoveDown ()
  2539. {
  2540. if (currentRow + 1 < model.Count) {
  2541. if (columnTrack == -1) {
  2542. columnTrack = currentColumn;
  2543. }
  2544. currentRow++;
  2545. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  2546. topRow++;
  2547. SetNeedsDisplay ();
  2548. }
  2549. TrackColumn ();
  2550. PositionCursor ();
  2551. } else if (currentRow > Frame.Height) {
  2552. Adjust ();
  2553. }
  2554. }
  2555. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  2556. {
  2557. if (col < 0 || row < 0)
  2558. yield break;
  2559. if (row >= model.Count)
  2560. yield break;
  2561. var line = GetCurrentLine ();
  2562. if (col >= line.Count)
  2563. yield break;
  2564. while (row < model.Count) {
  2565. for (int c = col; c < line.Count; c++) {
  2566. yield return (c, row, line [c]);
  2567. }
  2568. col = 0;
  2569. row++;
  2570. line = GetCurrentLine ();
  2571. }
  2572. }
  2573. Rune RuneAt (int col, int row)
  2574. {
  2575. var line = model.GetLine (row);
  2576. if (line.Count > 0) {
  2577. return line [col > line.Count - 1 ? line.Count - 1 : col];
  2578. } else {
  2579. return 0;
  2580. }
  2581. }
  2582. /// <summary>
  2583. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  2584. /// </summary>
  2585. public void MoveEnd ()
  2586. {
  2587. currentRow = model.Count - 1;
  2588. var line = GetCurrentLine ();
  2589. currentColumn = line.Count;
  2590. TrackColumn ();
  2591. PositionCursor ();
  2592. }
  2593. /// <summary>
  2594. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  2595. /// </summary>
  2596. public void MoveHome ()
  2597. {
  2598. currentRow = 0;
  2599. topRow = 0;
  2600. currentColumn = 0;
  2601. leftColumn = 0;
  2602. TrackColumn ();
  2603. PositionCursor ();
  2604. }
  2605. bool MoveNext (ref int col, ref int row, out Rune rune)
  2606. {
  2607. var line = model.GetLine (row);
  2608. if (col + 1 < line.Count) {
  2609. col++;
  2610. rune = line [col];
  2611. if (col + 1 == line.Count && !Rune.IsLetterOrDigit (rune)
  2612. && !Rune.IsWhiteSpace (line [col - 1])) {
  2613. col++;
  2614. }
  2615. return true;
  2616. } else if (col + 1 == line.Count) {
  2617. col++;
  2618. }
  2619. while (row + 1 < model.Count) {
  2620. col = 0;
  2621. row++;
  2622. line = model.GetLine (row);
  2623. if (line.Count > 0) {
  2624. rune = line [0];
  2625. return true;
  2626. }
  2627. }
  2628. rune = 0;
  2629. return false;
  2630. }
  2631. bool MovePrev (ref int col, ref int row, out Rune rune)
  2632. {
  2633. var line = model.GetLine (row);
  2634. if (col > 0) {
  2635. col--;
  2636. rune = line [col];
  2637. return true;
  2638. }
  2639. if (row == 0) {
  2640. rune = 0;
  2641. return false;
  2642. }
  2643. while (row > 0) {
  2644. row--;
  2645. line = model.GetLine (row);
  2646. col = line.Count - 1;
  2647. if (col >= 0) {
  2648. rune = line [col];
  2649. return true;
  2650. }
  2651. }
  2652. rune = 0;
  2653. return false;
  2654. }
  2655. (int col, int row)? WordForward (int fromCol, int fromRow)
  2656. {
  2657. var col = fromCol;
  2658. var row = fromRow;
  2659. try {
  2660. var rune = RuneAt (col, row);
  2661. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  2662. {
  2663. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  2664. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  2665. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))
  2666. return;
  2667. }
  2668. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  2669. return;
  2670. }
  2671. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  2672. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  2673. break;
  2674. }
  2675. } else {
  2676. if (!MoveNext (ref nCol, ref nRow, out nRune)) {
  2677. return;
  2678. }
  2679. var line = model.GetLine (fromRow);
  2680. if ((nRow != fromRow && fromCol < line.Count)
  2681. || (nRow == fromRow && nCol == line.Count - 1)) {
  2682. nCol = line.Count;
  2683. nRow = fromRow;
  2684. return;
  2685. } else if (nRow != fromRow && fromCol == line.Count) {
  2686. line = model.GetLine (nRow);
  2687. if (Rune.IsLetterOrDigit (line [nCol]) || Rune.IsPunctuation (line [nCol])) {
  2688. return;
  2689. }
  2690. }
  2691. ProcMoveNext (ref nCol, ref nRow, nRune);
  2692. }
  2693. }
  2694. ProcMoveNext (ref col, ref row, rune);
  2695. if (fromCol != col || fromRow != row)
  2696. return (col, row);
  2697. return null;
  2698. } catch (Exception) {
  2699. return null;
  2700. }
  2701. }
  2702. (int col, int row)? WordBackward (int fromCol, int fromRow)
  2703. {
  2704. if (fromRow == 0 && fromCol == 0)
  2705. return null;
  2706. var col = Math.Max (fromCol - 1, 0);
  2707. var row = fromRow;
  2708. try {
  2709. var rune = RuneAt (col, row);
  2710. int lastValidCol = Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) ? col : -1;
  2711. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  2712. {
  2713. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  2714. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  2715. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune)) {
  2716. lastValidCol = nCol;
  2717. break;
  2718. }
  2719. }
  2720. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  2721. if (lastValidCol > -1) {
  2722. nCol = lastValidCol;
  2723. }
  2724. return;
  2725. }
  2726. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  2727. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  2728. break;
  2729. if (nRow != fromRow) {
  2730. break;
  2731. }
  2732. lastValidCol = nCol;
  2733. }
  2734. if (lastValidCol > -1) {
  2735. nCol = lastValidCol;
  2736. nRow = fromRow;
  2737. }
  2738. } else {
  2739. if (!MovePrev (ref nCol, ref nRow, out nRune)) {
  2740. return;
  2741. }
  2742. var line = model.GetLine (nRow);
  2743. if (nCol == 0 && nRow == fromRow && (Rune.IsLetterOrDigit (line [0]) || Rune.IsPunctuation (line [0]))) {
  2744. return;
  2745. }
  2746. lastValidCol = Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) ? nCol : lastValidCol;
  2747. if (lastValidCol > -1 && (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune))) {
  2748. nCol = lastValidCol;
  2749. return;
  2750. }
  2751. if (fromRow != nRow) {
  2752. nCol = line.Count;
  2753. return;
  2754. }
  2755. ProcMovePrev (ref nCol, ref nRow, nRune);
  2756. }
  2757. }
  2758. ProcMovePrev (ref col, ref row, rune);
  2759. if (fromCol != col || fromRow != row)
  2760. return (col, row);
  2761. return null;
  2762. } catch (Exception) {
  2763. return null;
  2764. }
  2765. }
  2766. ///<inheritdoc/>
  2767. public override bool MouseEvent (MouseEvent ev)
  2768. {
  2769. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  2770. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  2771. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  2772. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  2773. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  2774. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  2775. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)
  2776. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  2777. return false;
  2778. }
  2779. if (!CanFocus) {
  2780. return true;
  2781. }
  2782. if (!HasFocus) {
  2783. SetFocus ();
  2784. }
  2785. continuousFind = false;
  2786. if (ev.Flags == MouseFlags.Button1Clicked) {
  2787. if (shiftSelecting) {
  2788. shiftSelecting = false;
  2789. selecting = false;
  2790. }
  2791. ProcessMouseClick (ev, out _);
  2792. PositionCursor ();
  2793. lastWasKill = false;
  2794. columnTrack = currentColumn;
  2795. } else if (ev.Flags == MouseFlags.WheeledDown) {
  2796. lastWasKill = false;
  2797. columnTrack = currentColumn;
  2798. ScrollTo (topRow + 1);
  2799. } else if (ev.Flags == MouseFlags.WheeledUp) {
  2800. lastWasKill = false;
  2801. columnTrack = currentColumn;
  2802. ScrollTo (topRow - 1);
  2803. } else if (ev.Flags == MouseFlags.WheeledRight) {
  2804. lastWasKill = false;
  2805. columnTrack = currentColumn;
  2806. ScrollTo (leftColumn + 1, false);
  2807. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  2808. lastWasKill = false;
  2809. columnTrack = currentColumn;
  2810. ScrollTo (leftColumn - 1, false);
  2811. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  2812. ProcessMouseClick (ev, out List<Rune> line);
  2813. PositionCursor ();
  2814. if (model.Count > 0 && shiftSelecting && selecting) {
  2815. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  2816. && model.Count + BottomOffset > topRow + currentRow) {
  2817. ScrollTo (topRow + Frame.Height);
  2818. } else if (topRow > 0 && currentRow <= topRow) {
  2819. ScrollTo (topRow - Frame.Height);
  2820. } else if (ev.Y >= Frame.Height) {
  2821. ScrollTo (model.Count + BottomOffset);
  2822. } else if (ev.Y < 0 && topRow > 0) {
  2823. ScrollTo (0);
  2824. }
  2825. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  2826. && line.Count + RightOffset > leftColumn + currentColumn) {
  2827. ScrollTo (leftColumn + Frame.Width, false);
  2828. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  2829. ScrollTo (leftColumn - Frame.Width, false);
  2830. } else if (ev.X >= Frame.Width) {
  2831. ScrollTo (line.Count + RightOffset, false);
  2832. } else if (ev.X < 0 && leftColumn > 0) {
  2833. ScrollTo (0, false);
  2834. }
  2835. }
  2836. lastWasKill = false;
  2837. columnTrack = currentColumn;
  2838. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  2839. if (!shiftSelecting) {
  2840. StartSelecting ();
  2841. }
  2842. ProcessMouseClick (ev, out _);
  2843. PositionCursor ();
  2844. lastWasKill = false;
  2845. columnTrack = currentColumn;
  2846. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  2847. if (shiftSelecting) {
  2848. shiftSelecting = false;
  2849. selecting = false;
  2850. }
  2851. ProcessMouseClick (ev, out _);
  2852. PositionCursor ();
  2853. if (!selecting) {
  2854. StartSelecting ();
  2855. }
  2856. lastWasKill = false;
  2857. columnTrack = currentColumn;
  2858. if (Application.mouseGrabView == null) {
  2859. Application.GrabMouse (this);
  2860. }
  2861. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  2862. Application.UngrabMouse ();
  2863. } else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)) {
  2864. if (ev.Flags.HasFlag (MouseFlags.ButtonShift)) {
  2865. if (!selecting) {
  2866. StartSelecting ();
  2867. }
  2868. } else if (selecting) {
  2869. StopSelecting ();
  2870. }
  2871. ProcessMouseClick (ev, out List<Rune> line);
  2872. (int col, int row)? newPos;
  2873. if (currentColumn == line.Count || (currentColumn > 0 && (line [currentColumn - 1] != ' '
  2874. || line [currentColumn] == ' '))) {
  2875. newPos = WordBackward (currentColumn, currentRow);
  2876. if (newPos.HasValue) {
  2877. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : 0;
  2878. }
  2879. }
  2880. if (!selecting) {
  2881. StartSelecting ();
  2882. }
  2883. newPos = WordForward (currentColumn, currentRow);
  2884. if (newPos != null && newPos.HasValue) {
  2885. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : line.Count;
  2886. }
  2887. PositionCursor ();
  2888. lastWasKill = false;
  2889. columnTrack = currentColumn;
  2890. } else if (ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  2891. if (selecting) {
  2892. StopSelecting ();
  2893. }
  2894. ProcessMouseClick (ev, out List<Rune> line);
  2895. currentColumn = 0;
  2896. if (!selecting) {
  2897. StartSelecting ();
  2898. }
  2899. currentColumn = line.Count;
  2900. PositionCursor ();
  2901. lastWasKill = false;
  2902. columnTrack = currentColumn;
  2903. }
  2904. return true;
  2905. }
  2906. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  2907. {
  2908. List<Rune> r = null;
  2909. if (model.Count > 0) {
  2910. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  2911. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  2912. currentRow = maxCursorPositionableLine + topRow;
  2913. } else {
  2914. currentRow = Math.Max (ev.Y + topRow, 0);
  2915. }
  2916. r = GetCurrentLine ();
  2917. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0), TabWidth);
  2918. if (idx - leftColumn >= r.Count + RightOffset) {
  2919. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  2920. } else {
  2921. currentColumn = idx + leftColumn;
  2922. }
  2923. }
  2924. line = r;
  2925. }
  2926. ///<inheritdoc/>
  2927. public override bool OnLeave (View view)
  2928. {
  2929. if (Application.mouseGrabView != null && Application.mouseGrabView == this) {
  2930. Application.UngrabMouse ();
  2931. }
  2932. return base.OnLeave (view);
  2933. }
  2934. }
  2935. }