TextView.cs 87 KB

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