TextView.cs 87 KB

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