TextView.cs 85 KB

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