TextView.cs 84 KB

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