TextView.cs 88 KB

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