TextView.cs 83 KB

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