TextView.cs 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129
  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. /// <summary>
  1207. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to <see cref="ColorScheme.Normal"/>.
  1208. /// </summary>
  1209. protected virtual void ColorNormal ()
  1210. {
  1211. Driver.SetAttribute (ColorScheme.Normal);
  1212. }
  1213. /// <summary>
  1214. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1215. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1216. /// Defaults to <see cref="ColorScheme.Normal"/>.
  1217. /// </summary>
  1218. /// <param name="line"></param>
  1219. /// <param name="idx"></param>
  1220. protected virtual void ColorNormal (List<Rune> line, int idx)
  1221. {
  1222. Driver.SetAttribute (ColorScheme.Normal);
  1223. }
  1224. /// <summary>
  1225. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1226. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1227. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1228. /// </summary>
  1229. /// <param name="line"></param>
  1230. /// <param name="idx"></param>
  1231. protected virtual void ColorSelection (List<Rune> line, int idx)
  1232. {
  1233. Driver.SetAttribute (ColorScheme.Focus);
  1234. }
  1235. /// <summary>
  1236. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1237. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1238. /// Defaults to <see cref="ColorScheme.HotFocus"/>.
  1239. /// </summary>
  1240. /// <param name="line"></param>
  1241. /// <param name="idx"></param>
  1242. protected virtual void ColorUsed (List<Rune> line, int idx)
  1243. {
  1244. Driver.SetAttribute (ColorScheme.HotFocus);
  1245. }
  1246. bool isReadOnly = false;
  1247. /// <summary>
  1248. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1249. /// </summary>
  1250. /// <value>Boolean value(Default false)</value>
  1251. public bool ReadOnly {
  1252. get => isReadOnly;
  1253. set {
  1254. isReadOnly = value;
  1255. }
  1256. }
  1257. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1258. /// <summary>
  1259. /// Get / Set the wished cursor when the field is focused
  1260. /// </summary>
  1261. public CursorVisibility DesiredCursorVisibility {
  1262. get => desiredCursorVisibility;
  1263. set {
  1264. if (desiredCursorVisibility != value && HasFocus) {
  1265. Application.Driver.SetCursorVisibility (value);
  1266. }
  1267. desiredCursorVisibility = value;
  1268. }
  1269. }
  1270. ///<inheritdoc/>
  1271. public override bool OnEnter (View view)
  1272. {
  1273. //TODO: Improve it by handling read only mode of the text field
  1274. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1275. return base.OnEnter (view);
  1276. }
  1277. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1278. void GetEncodedRegionBounds (out long start, out long end)
  1279. {
  1280. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1281. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1282. if (selection > point) {
  1283. start = point;
  1284. end = selection;
  1285. } else {
  1286. start = selection;
  1287. end = point;
  1288. }
  1289. }
  1290. bool PointInSelection (int col, int row)
  1291. {
  1292. long start, end;
  1293. GetEncodedRegionBounds (out start, out end);
  1294. var q = ((long)(uint)row << 32) | (uint)col;
  1295. return q >= start && q <= end - 1;
  1296. }
  1297. //
  1298. // Returns a ustring with the text in the selected
  1299. // region.
  1300. //
  1301. ustring GetRegion ()
  1302. {
  1303. long start, end;
  1304. GetEncodedRegionBounds (out start, out end);
  1305. if (start == end) {
  1306. return ustring.Empty;
  1307. }
  1308. int startRow = (int)(start >> 32);
  1309. var maxrow = ((int)(end >> 32));
  1310. int startCol = (int)(start & 0xffffffff);
  1311. var endCol = (int)(end & 0xffffffff);
  1312. var line = model.GetLine (startRow);
  1313. if (startRow == maxrow)
  1314. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1315. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1316. for (int row = startRow + 1; row < maxrow; row++) {
  1317. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  1318. }
  1319. line = model.GetLine (maxrow);
  1320. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  1321. return res;
  1322. }
  1323. //
  1324. // Clears the contents of the selected region
  1325. //
  1326. void ClearRegion ()
  1327. {
  1328. long start, end;
  1329. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1330. GetEncodedRegionBounds (out start, out end);
  1331. int startRow = (int)(start >> 32);
  1332. var maxrow = ((int)(end >> 32));
  1333. int startCol = (int)(start & 0xffffffff);
  1334. var endCol = (int)(end & 0xffffffff);
  1335. var line = model.GetLine (startRow);
  1336. if (startRow == maxrow) {
  1337. line.RemoveRange (startCol, endCol - startCol);
  1338. currentColumn = startCol;
  1339. if (wordWrap) {
  1340. SetNeedsDisplay ();
  1341. } else {
  1342. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1343. }
  1344. return;
  1345. }
  1346. line.RemoveRange (startCol, line.Count - startCol);
  1347. var line2 = model.GetLine (maxrow);
  1348. line.AddRange (line2.Skip (endCol));
  1349. for (int row = startRow + 1; row <= maxrow; row++) {
  1350. model.RemoveLine (startRow + 1);
  1351. }
  1352. if (currentEncoded == end) {
  1353. currentRow -= maxrow - (startRow);
  1354. }
  1355. currentColumn = startCol;
  1356. SetNeedsDisplay ();
  1357. }
  1358. /// <summary>
  1359. /// Select all text.
  1360. /// </summary>
  1361. public void SelectAll ()
  1362. {
  1363. if (model.Count == 0) {
  1364. return;
  1365. }
  1366. StartSelecting ();
  1367. selectionStartColumn = 0;
  1368. selectionStartRow = 0;
  1369. currentColumn = model.GetLine (model.Count - 1).Count;
  1370. currentRow = model.Count - 1;
  1371. SetNeedsDisplay ();
  1372. }
  1373. /// <summary>
  1374. /// Find the next text based on the match case with the option to replace it.
  1375. /// </summary>
  1376. /// <param name="textToFind">The text to find.</param>
  1377. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1378. /// <param name="matchCase">The match case setting.</param>
  1379. /// <param name="matchWholeWord">The match whole word setting.</param>
  1380. /// <param name="textToReplace">The text to replace.</param>
  1381. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1382. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1383. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1384. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1385. {
  1386. if (model.Count == 0) {
  1387. gaveFullTurn = false;
  1388. return false;
  1389. }
  1390. SetWrapModel ();
  1391. ResetContinuousFind ();
  1392. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1393. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1394. }
  1395. /// <summary>
  1396. /// Find the previous text based on the match case with the option to replace it.
  1397. /// </summary>
  1398. /// <param name="textToFind">The text to find.</param>
  1399. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</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. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1404. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1405. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1406. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1407. {
  1408. if (model.Count == 0) {
  1409. gaveFullTurn = false;
  1410. return false;
  1411. }
  1412. SetWrapModel ();
  1413. ResetContinuousFind ();
  1414. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1415. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1416. }
  1417. /// <summary>
  1418. /// Reset the flag to stop continuous find.
  1419. /// </summary>
  1420. public void FindTextChanged ()
  1421. {
  1422. continuousFind = false;
  1423. }
  1424. /// <summary>
  1425. /// Replaces all the text based on the match case.
  1426. /// </summary>
  1427. /// <param name="textToFind">The text to find.</param>
  1428. /// <param name="matchCase">The match case setting.</param>
  1429. /// <param name="matchWholeWord">The match whole word setting.</param>
  1430. /// <param name="textToReplace">The text to replace.</param>
  1431. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1432. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1433. ustring textToReplace = null)
  1434. {
  1435. if (isReadOnly || model.Count == 0) {
  1436. return false;
  1437. }
  1438. SetWrapModel ();
  1439. ResetContinuousFind ();
  1440. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1441. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1442. }
  1443. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1444. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1445. {
  1446. if (foundPos.found) {
  1447. StartSelecting ();
  1448. selectionStartColumn = foundPos.current.X;
  1449. selectionStartRow = foundPos.current.Y;
  1450. if (!replaceAll) {
  1451. currentColumn = selectionStartColumn + text.RuneCount;
  1452. } else {
  1453. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1454. }
  1455. currentRow = foundPos.current.Y;
  1456. if (!isReadOnly && replace) {
  1457. Adjust ();
  1458. ClearSelectedRegion ();
  1459. InsertText (textToReplace);
  1460. StartSelecting ();
  1461. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1462. } else {
  1463. UpdateWrapModel ();
  1464. SetNeedsDisplay ();
  1465. Adjust ();
  1466. }
  1467. continuousFind = true;
  1468. return foundPos.found;
  1469. }
  1470. UpdateWrapModel ();
  1471. continuousFind = false;
  1472. return foundPos.found;
  1473. }
  1474. void ResetContinuousFind ()
  1475. {
  1476. if (!continuousFind) {
  1477. var col = selecting ? selectionStartColumn : currentColumn;
  1478. var row = selecting ? selectionStartRow : currentRow;
  1479. model.ResetContinuousFind (new Point (col, row));
  1480. }
  1481. }
  1482. /// <summary>
  1483. /// Restore from original model.
  1484. /// </summary>
  1485. void SetWrapModel ()
  1486. {
  1487. if (wordWrap) {
  1488. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  1489. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  1490. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  1491. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  1492. model = wrapManager.Model;
  1493. }
  1494. }
  1495. /// <summary>
  1496. /// Update the original model.
  1497. /// </summary>
  1498. void UpdateWrapModel ()
  1499. {
  1500. if (wordWrap) {
  1501. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  1502. out int nStartRow, out int nStartCol,
  1503. currentRow, currentColumn,
  1504. selectionStartRow, selectionStartColumn);
  1505. currentRow = nRow;
  1506. currentColumn = nCol;
  1507. selectionStartRow = nStartRow;
  1508. selectionStartColumn = nStartCol;
  1509. wrapNeeded = true;
  1510. }
  1511. }
  1512. ///<inheritdoc/>
  1513. public override void Redraw (Rect bounds)
  1514. {
  1515. ColorNormal ();
  1516. var offB = OffSetBackground ();
  1517. int right = Frame.Width + offB.width + RightOffset;
  1518. int bottom = Frame.Height + offB.height + BottomOffset;
  1519. var row = 0;
  1520. for (int idxRow = topRow; idxRow < model.Count; idxRow++) {
  1521. var line = model.GetLine (idxRow);
  1522. int lineRuneCount = line.Count;
  1523. var col = 0;
  1524. Move (0, row);
  1525. for (int idxCol = leftColumn; idxCol < lineRuneCount; idxCol++) {
  1526. var rune = idxCol >= lineRuneCount ? ' ' : line [idxCol];
  1527. var cols = Rune.ColumnWidth (rune);
  1528. if (idxCol < line.Count && selecting && PointInSelection (idxCol, idxRow)) {
  1529. ColorSelection (line, idxCol);
  1530. } else if (idxCol == currentColumn && idxRow == currentRow && !selecting && !Used
  1531. && HasFocus && idxCol < lineRuneCount) {
  1532. ColorUsed (line, idxCol);
  1533. } else {
  1534. ColorNormal (line,idxCol);
  1535. }
  1536. if (rune == '\t' && TabWidth > 0) {
  1537. cols += TabWidth + 1;
  1538. if (col + cols > right) {
  1539. cols = right - col;
  1540. }
  1541. for (int i = 0; i < cols; i++) {
  1542. if (col + i < right) {
  1543. AddRune (col + i, row, ' ');
  1544. }
  1545. }
  1546. } else if (!SpecialRune (rune)) {
  1547. AddRune (col, row, rune);
  1548. } else {
  1549. col++;
  1550. }
  1551. if (!TextModel.SetCol (ref col, bounds.Right, cols)) {
  1552. break;
  1553. }
  1554. if (idxCol + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idxCol + 1]) > right) {
  1555. break;
  1556. }
  1557. }
  1558. if (col < right) {
  1559. ColorNormal ();
  1560. ClearRegion (col, row, right, row + 1);
  1561. }
  1562. row++;
  1563. }
  1564. if (row < bottom) {
  1565. ColorNormal ();
  1566. ClearRegion (bounds.Left, row, right, bottom);
  1567. }
  1568. PositionCursor ();
  1569. }
  1570. bool SpecialRune (Rune rune)
  1571. {
  1572. switch (rune) {
  1573. case (uint)Key.Enter:
  1574. case 0xd:
  1575. return true;
  1576. default:
  1577. return false;
  1578. }
  1579. }
  1580. ///<inheritdoc/>
  1581. public override bool CanFocus {
  1582. get => base.CanFocus;
  1583. set { base.CanFocus = value; }
  1584. }
  1585. void SetClipboard (ustring text)
  1586. {
  1587. if (text != null) {
  1588. Clipboard.Contents = text;
  1589. }
  1590. }
  1591. void AppendClipboard (ustring text)
  1592. {
  1593. Clipboard.Contents += text;
  1594. }
  1595. void Insert (Rune rune)
  1596. {
  1597. var line = GetCurrentLine ();
  1598. if (Used) {
  1599. line.Insert (Math.Min (currentColumn, line.Count), rune);
  1600. } else {
  1601. if (currentColumn < line.Count) {
  1602. line.RemoveAt (currentColumn);
  1603. }
  1604. line.Insert (Math.Min (currentColumn, line.Count), rune);
  1605. }
  1606. if (wordWrap) {
  1607. if (Used) {
  1608. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  1609. } else {
  1610. wrapNeeded = wrapManager.RemoveAt (currentRow, currentColumn);
  1611. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  1612. }
  1613. if (wrapNeeded) {
  1614. SetNeedsDisplay ();
  1615. }
  1616. }
  1617. var prow = currentRow - topRow;
  1618. if (!wrapNeeded) {
  1619. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  1620. }
  1621. }
  1622. ustring StringFromRunes (List<Rune> runes)
  1623. {
  1624. if (runes == null)
  1625. throw new ArgumentNullException (nameof (runes));
  1626. int size = 0;
  1627. foreach (var rune in runes) {
  1628. size += Utf8.RuneLen (rune);
  1629. }
  1630. var encoded = new byte [size];
  1631. int offset = 0;
  1632. foreach (var rune in runes) {
  1633. offset += Utf8.EncodeRune (rune, encoded, offset);
  1634. }
  1635. return ustring.Make (encoded);
  1636. }
  1637. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  1638. void InsertText (ustring text)
  1639. {
  1640. if (ustring.IsNullOrEmpty (text)) {
  1641. return;
  1642. }
  1643. var lines = TextModel.StringToRunes (text);
  1644. if (lines.Count == 0) {
  1645. return;
  1646. }
  1647. var line = GetCurrentLine ();
  1648. // Optimize single line
  1649. if (lines.Count == 1) {
  1650. line.InsertRange (currentColumn, lines [0]);
  1651. currentColumn += lines [0].Count;
  1652. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  1653. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  1654. }
  1655. if (wordWrap) {
  1656. SetNeedsDisplay ();
  1657. } else {
  1658. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Math.Max (currentRow - topRow + 1, 0)));
  1659. }
  1660. return;
  1661. }
  1662. List<Rune> rest = null;
  1663. int lastp = 0;
  1664. if (model.Count > 0 && currentColumn > 0) {
  1665. // Keep a copy of the rest of the line
  1666. var restCount = line.Count - currentColumn;
  1667. rest = line.GetRange (currentColumn, restCount);
  1668. line.RemoveRange (currentColumn, restCount);
  1669. }
  1670. // First line is inserted at the current location, the rest is appended
  1671. line.InsertRange (currentColumn, lines [0]);
  1672. //model.AddLine (currentRow, lines [0]);
  1673. for (int i = 1; i < lines.Count; i++) {
  1674. model.AddLine (currentRow + i, lines [i]);
  1675. }
  1676. if (rest != null) {
  1677. var last = model.GetLine (currentRow + lines.Count - 1);
  1678. lastp = last.Count;
  1679. last.InsertRange (last.Count, rest);
  1680. }
  1681. // Now adjust column and row positions
  1682. currentRow += lines.Count - 1;
  1683. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  1684. Adjust ();
  1685. }
  1686. // The column we are tracking, or -1 if we are not tracking any column
  1687. int columnTrack = -1;
  1688. // Tries to snap the cursor to the tracking column
  1689. void TrackColumn ()
  1690. {
  1691. // Now track the column
  1692. var line = GetCurrentLine ();
  1693. if (line.Count < columnTrack)
  1694. currentColumn = line.Count;
  1695. else if (columnTrack != -1)
  1696. currentColumn = columnTrack;
  1697. else if (currentColumn > line.Count)
  1698. currentColumn = line.Count;
  1699. Adjust ();
  1700. }
  1701. void Adjust ()
  1702. {
  1703. var offB = OffSetBackground ();
  1704. var line = GetCurrentLine ();
  1705. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  1706. var tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  1707. var dSize = TextModel.DisplaySize (line, leftColumn, currentColumn, true, TabWidth);
  1708. if (!wordWrap && currentColumn < leftColumn) {
  1709. leftColumn = currentColumn;
  1710. need = true;
  1711. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width
  1712. || dSize.size + RightOffset >= Frame.Width + offB.width)) {
  1713. leftColumn = TextModel.CalculateLeftColumn (line, leftColumn, currentColumn,
  1714. Frame.Width + offB.width - RightOffset, TabWidth);
  1715. need = true;
  1716. } else if (dSize.size + RightOffset < Frame.Width + offB.width
  1717. && tSize.size + RightOffset < Frame.Width + offB.width) {
  1718. leftColumn = 0;
  1719. }
  1720. if (currentRow < topRow) {
  1721. topRow = currentRow;
  1722. need = true;
  1723. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  1724. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  1725. need = true;
  1726. }
  1727. if (need) {
  1728. if (wrapNeeded) {
  1729. WrapTextModel ();
  1730. wrapNeeded = false;
  1731. }
  1732. SetNeedsDisplay ();
  1733. } else {
  1734. PositionCursor ();
  1735. }
  1736. }
  1737. (int width, int height) OffSetBackground ()
  1738. {
  1739. int w = 0;
  1740. int h = 0;
  1741. if (SuperView?.Frame.Right - Frame.Right < 0) {
  1742. w = SuperView.Frame.Right - Frame.Right - 1;
  1743. }
  1744. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  1745. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  1746. }
  1747. return (w, h);
  1748. }
  1749. /// <summary>
  1750. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  1751. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  1752. /// </summary>
  1753. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  1754. /// if the value is negative it will be reset to zero</param>
  1755. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  1756. public void ScrollTo (int idx, bool isRow = true)
  1757. {
  1758. if (idx < 0) {
  1759. idx = 0;
  1760. }
  1761. if (isRow) {
  1762. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  1763. } else if (!wordWrap) {
  1764. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset, TabWidth);
  1765. leftColumn = Math.Max (idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  1766. }
  1767. SetNeedsDisplay ();
  1768. }
  1769. bool lastWasKill;
  1770. bool wrapNeeded;
  1771. bool shiftSelecting;
  1772. ///<inheritdoc/>
  1773. public override bool ProcessKey (KeyEvent kb)
  1774. {
  1775. int restCount;
  1776. List<Rune> rest;
  1777. // if the user presses Left (without any control keys) and they are at the start of the text
  1778. if(kb.Key == Key.CursorLeft && currentColumn == 0 && currentRow == 0) {
  1779. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  1780. return false;
  1781. }
  1782. // if the user presses Right (without any control keys)
  1783. if (kb.Key == Key.CursorRight) {
  1784. // determine where the last cursor position in the text is
  1785. var lastRow = model.Count - 1;
  1786. var lastCol = model.GetLine (lastRow).Count;
  1787. // 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)
  1788. if (currentColumn == lastCol && currentRow == lastRow) {
  1789. return false;
  1790. }
  1791. }
  1792. // Handle some state here - whether the last command was a kill
  1793. // operation and the column tracking (up/down)
  1794. switch (kb.Key) {
  1795. case Key.N | Key.CtrlMask:
  1796. case Key.CursorDown:
  1797. case Key.P | Key.CtrlMask:
  1798. case Key.CursorUp:
  1799. lastWasKill = false;
  1800. continuousFind = false;
  1801. break;
  1802. case Key.K | Key.CtrlMask:
  1803. break;
  1804. case Key.F | Key.CtrlMask:
  1805. case Key.B | Key.CtrlMask:
  1806. case (Key)((int)'B' + Key.AltMask):
  1807. case Key.A | Key.CtrlMask:
  1808. case Key.E | Key.CtrlMask:
  1809. case Key.CursorRight:
  1810. case Key.CursorLeft:
  1811. case Key.CursorRight | Key.CtrlMask:
  1812. case Key.CursorLeft | Key.CtrlMask:
  1813. case Key.CursorRight | Key.ShiftMask:
  1814. case Key.CursorLeft | Key.ShiftMask:
  1815. case Key.CursorRight | Key.CtrlMask | Key.ShiftMask:
  1816. case Key.CursorLeft | Key.CtrlMask | Key.ShiftMask:
  1817. case Key.Home:
  1818. case Key.Home | Key.CtrlMask:
  1819. case Key.Home | Key.ShiftMask:
  1820. case Key.Home | Key.CtrlMask | Key.ShiftMask:
  1821. case Key.End:
  1822. case Key.End | Key.CtrlMask:
  1823. case Key.End | Key.ShiftMask:
  1824. case Key.End | Key.CtrlMask | Key.ShiftMask:
  1825. lastWasKill = false;
  1826. columnTrack = -1;
  1827. continuousFind = false;
  1828. break;
  1829. default:
  1830. lastWasKill = false;
  1831. columnTrack = -1;
  1832. break;
  1833. }
  1834. // Dispatch the command.
  1835. switch (kb.Key) {
  1836. case Key.PageDown:
  1837. case Key.V | Key.CtrlMask:
  1838. case Key.PageDown | Key.ShiftMask:
  1839. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1840. StartSelecting ();
  1841. } else if (shiftSelecting && selecting) {
  1842. StopSelecting ();
  1843. }
  1844. int nPageDnShift = Frame.Height - 1;
  1845. if (currentRow >= 0 && currentRow < model.Count) {
  1846. if (columnTrack == -1)
  1847. columnTrack = currentColumn;
  1848. currentRow = (currentRow + nPageDnShift) > model.Count
  1849. ? model.Count > 0 ? model.Count - 1 : 0
  1850. : currentRow + nPageDnShift;
  1851. if (topRow < currentRow - nPageDnShift) {
  1852. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  1853. SetNeedsDisplay ();
  1854. }
  1855. TrackColumn ();
  1856. PositionCursor ();
  1857. }
  1858. break;
  1859. case Key.PageUp:
  1860. case ((int)'V' + Key.AltMask):
  1861. case Key.PageUp | Key.ShiftMask:
  1862. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1863. StartSelecting ();
  1864. } else if (shiftSelecting && selecting) {
  1865. StopSelecting ();
  1866. }
  1867. int nPageUpShift = Frame.Height - 1;
  1868. if (currentRow > 0) {
  1869. if (columnTrack == -1)
  1870. columnTrack = currentColumn;
  1871. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  1872. if (currentRow < topRow) {
  1873. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  1874. SetNeedsDisplay ();
  1875. }
  1876. TrackColumn ();
  1877. PositionCursor ();
  1878. }
  1879. break;
  1880. case Key.N | Key.CtrlMask:
  1881. case Key.CursorDown:
  1882. case Key.CursorDown | Key.ShiftMask:
  1883. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1884. StartSelecting ();
  1885. } else if (shiftSelecting && selecting) {
  1886. StopSelecting ();
  1887. }
  1888. MoveDown ();
  1889. break;
  1890. case Key.P | Key.CtrlMask:
  1891. case Key.CursorUp:
  1892. case Key.CursorUp | Key.ShiftMask:
  1893. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1894. StartSelecting ();
  1895. } else if (shiftSelecting && selecting) {
  1896. StopSelecting ();
  1897. }
  1898. MoveUp ();
  1899. break;
  1900. case Key.F | Key.CtrlMask:
  1901. case Key.CursorRight:
  1902. case Key.CursorRight | Key.ShiftMask:
  1903. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1904. StartSelecting ();
  1905. } else if (shiftSelecting && selecting) {
  1906. StopSelecting ();
  1907. }
  1908. var currentLine = GetCurrentLine ();
  1909. if (currentColumn < currentLine.Count) {
  1910. currentColumn++;
  1911. } else {
  1912. if (currentRow + 1 < model.Count) {
  1913. currentRow++;
  1914. currentColumn = 0;
  1915. if (currentRow >= topRow + Frame.Height) {
  1916. topRow++;
  1917. SetNeedsDisplay ();
  1918. }
  1919. }
  1920. }
  1921. Adjust ();
  1922. return true;
  1923. case Key.B | Key.CtrlMask:
  1924. case Key.CursorLeft:
  1925. case Key.CursorLeft | Key.ShiftMask:
  1926. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1927. StartSelecting ();
  1928. } else if (shiftSelecting && selecting) {
  1929. StopSelecting ();
  1930. }
  1931. if (currentColumn > 0) {
  1932. currentColumn--;
  1933. } else {
  1934. if (currentRow > 0) {
  1935. currentRow--;
  1936. if (currentRow < topRow) {
  1937. topRow--;
  1938. SetNeedsDisplay ();
  1939. }
  1940. currentLine = GetCurrentLine ();
  1941. currentColumn = currentLine.Count;
  1942. }
  1943. }
  1944. Adjust ();
  1945. break;
  1946. case Key.Delete:
  1947. case Key.Backspace:
  1948. if (isReadOnly)
  1949. break;
  1950. if (selecting) {
  1951. ClearSelectedRegion ();
  1952. return true;
  1953. }
  1954. if (DeleteTextBackwards ()) {
  1955. return true;
  1956. }
  1957. break;
  1958. // Home, C-A
  1959. case Key.Home:
  1960. case Key.Home | Key.ShiftMask:
  1961. case Key.A | Key.CtrlMask:
  1962. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1963. StartSelecting ();
  1964. } else if (shiftSelecting && selecting) {
  1965. StopSelecting ();
  1966. }
  1967. currentColumn = 0;
  1968. leftColumn = 0;
  1969. Adjust ();
  1970. break;
  1971. case Key.DeleteChar:
  1972. case Key.D | Key.CtrlMask: // Delete
  1973. if (isReadOnly)
  1974. break;
  1975. if (selecting) {
  1976. ClearSelectedRegion ();
  1977. return true;
  1978. }
  1979. if (DeleteTextForwards ()) {
  1980. return true;
  1981. }
  1982. break;
  1983. case Key.End:
  1984. case Key.End | Key.ShiftMask:
  1985. case Key.E | Key.CtrlMask: // End
  1986. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1987. StartSelecting ();
  1988. } else if (shiftSelecting && selecting) {
  1989. StopSelecting ();
  1990. }
  1991. currentLine = GetCurrentLine ();
  1992. currentColumn = currentLine.Count;
  1993. Adjust ();
  1994. return true;
  1995. case Key.K | Key.CtrlMask: // kill-to-end
  1996. case Key.DeleteChar | Key.CtrlMask | Key.ShiftMask:
  1997. if (isReadOnly)
  1998. break;
  1999. currentLine = GetCurrentLine ();
  2000. var setLastWasKill = true;
  2001. if (currentLine.Count > 0 && currentColumn == currentLine.Count) {
  2002. DeleteTextForwards ();
  2003. return true;
  2004. }
  2005. if (currentLine.Count == 0) {
  2006. if (currentRow < model.Count - 1) {
  2007. model.RemoveLine (currentRow);
  2008. }
  2009. if (model.Count > 0 || lastWasKill) {
  2010. var val = ustring.Make ((Rune)'\n');
  2011. if (lastWasKill) {
  2012. AppendClipboard (val);
  2013. } else {
  2014. SetClipboard (val);
  2015. }
  2016. }
  2017. if (model.Count == 0) {
  2018. // Prevents from adding line feeds if there is no more lines.
  2019. setLastWasKill = false;
  2020. }
  2021. } else {
  2022. restCount = currentLine.Count - currentColumn;
  2023. rest = currentLine.GetRange (currentColumn, restCount);
  2024. var val = ustring.Empty;
  2025. if (currentColumn == 0 && lastWasKill && currentLine.Count > 0) {
  2026. val = ustring.Make ((Rune)'\n');
  2027. }
  2028. val += StringFromRunes (rest);
  2029. if (lastWasKill) {
  2030. AppendClipboard (val);
  2031. } else {
  2032. SetClipboard (val);
  2033. }
  2034. currentLine.RemoveRange (currentColumn, restCount);
  2035. }
  2036. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2037. lastWasKill = setLastWasKill;
  2038. break;
  2039. case Key.Backspace | Key.CtrlMask | Key.ShiftMask: // kill-to-start
  2040. if (isReadOnly)
  2041. break;
  2042. currentLine = GetCurrentLine ();
  2043. setLastWasKill = true;
  2044. if (currentLine.Count > 0 && currentColumn == 0) {
  2045. DeleteTextBackwards ();
  2046. return true;
  2047. }
  2048. if (currentLine.Count == 0) {
  2049. if (currentRow > 0) {
  2050. model.RemoveLine (currentRow);
  2051. currentRow--;
  2052. currentLine = model.GetLine (currentRow);
  2053. currentColumn = currentLine.Count;
  2054. }
  2055. } else {
  2056. restCount = currentColumn;
  2057. rest = currentLine.GetRange (0, restCount);
  2058. var val = ustring.Empty;
  2059. if (currentColumn == 0 && lastWasKill && currentLine.Count > 0) {
  2060. val = ustring.Make ((Rune)'\n');
  2061. }
  2062. val += StringFromRunes (rest);
  2063. if (lastWasKill) {
  2064. AppendClipboard (val);
  2065. } else {
  2066. SetClipboard (val);
  2067. }
  2068. currentLine.RemoveRange (0, restCount);
  2069. currentColumn = 0;
  2070. }
  2071. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2072. lastWasKill = setLastWasKill;
  2073. break;
  2074. case Key.Y | Key.CtrlMask: // Control-y, yank
  2075. if (isReadOnly)
  2076. break;
  2077. Paste ();
  2078. return true;
  2079. case Key.Space | Key.CtrlMask:
  2080. selecting = !selecting;
  2081. selectionStartColumn = currentColumn;
  2082. selectionStartRow = currentRow;
  2083. break;
  2084. case ((int)'C' + Key.AltMask):
  2085. case Key.C | Key.CtrlMask:
  2086. Copy ();
  2087. return true;
  2088. case ((int)'W' + Key.AltMask):
  2089. case Key.W | Key.CtrlMask:
  2090. case Key.X | Key.CtrlMask:
  2091. Cut ();
  2092. return true;
  2093. case Key.CtrlMask | Key.CursorLeft:
  2094. case Key.CtrlMask | Key.CursorLeft | Key.ShiftMask:
  2095. case (Key)((int)'B' + Key.AltMask):
  2096. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2097. StartSelecting ();
  2098. } else if (shiftSelecting && selecting) {
  2099. StopSelecting ();
  2100. }
  2101. var newPos = WordBackward (currentColumn, currentRow);
  2102. if (newPos.HasValue) {
  2103. currentColumn = newPos.Value.col;
  2104. currentRow = newPos.Value.row;
  2105. }
  2106. Adjust ();
  2107. break;
  2108. case Key.CtrlMask | Key.CursorRight:
  2109. case Key.CtrlMask | Key.CursorRight | Key.ShiftMask:
  2110. case (Key)((int)'F' + Key.AltMask):
  2111. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2112. StartSelecting ();
  2113. } else if (shiftSelecting && selecting) {
  2114. StopSelecting ();
  2115. }
  2116. newPos = WordForward (currentColumn, currentRow);
  2117. if (newPos.HasValue) {
  2118. currentColumn = newPos.Value.col;
  2119. currentRow = newPos.Value.row;
  2120. }
  2121. Adjust ();
  2122. break;
  2123. case Key.DeleteChar | Key.CtrlMask: // kill-word-forwards
  2124. if (isReadOnly)
  2125. break;
  2126. currentLine = GetCurrentLine ();
  2127. if (currentLine.Count == 0 || currentColumn == currentLine.Count) {
  2128. DeleteTextForwards ();
  2129. return true;
  2130. }
  2131. newPos = WordForward (currentColumn, currentRow);
  2132. restCount = 0;
  2133. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2134. restCount = newPos.Value.col - currentColumn;
  2135. currentLine.RemoveRange (currentColumn, restCount);
  2136. } else if (newPos.HasValue) {
  2137. restCount = currentLine.Count - currentColumn;
  2138. currentLine.RemoveRange (currentColumn, restCount);
  2139. }
  2140. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2141. wrapNeeded = true;
  2142. }
  2143. if (wrapNeeded) {
  2144. SetNeedsDisplay ();
  2145. } else {
  2146. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2147. }
  2148. break;
  2149. case Key.Backspace | Key.CtrlMask: // kill-word-backwards
  2150. if (isReadOnly)
  2151. break;
  2152. currentLine = GetCurrentLine ();
  2153. if (currentColumn == 0) {
  2154. DeleteTextBackwards ();
  2155. return true;
  2156. }
  2157. newPos = WordBackward (currentColumn, currentRow);
  2158. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2159. restCount = currentColumn - newPos.Value.col;
  2160. currentLine.RemoveRange (newPos.Value.col, restCount);
  2161. if (wordWrap && wrapManager.RemoveRange (currentRow, newPos.Value.col, restCount)) {
  2162. wrapNeeded = true;
  2163. }
  2164. currentColumn = newPos.Value.col;
  2165. } else if (newPos.HasValue) {
  2166. restCount = currentLine.Count - currentColumn;
  2167. currentLine.RemoveRange (currentColumn, restCount);
  2168. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2169. wrapNeeded = true;
  2170. }
  2171. currentColumn = newPos.Value.col;
  2172. currentRow = newPos.Value.row;
  2173. }
  2174. if (wrapNeeded) {
  2175. SetNeedsDisplay ();
  2176. } else {
  2177. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2178. }
  2179. break;
  2180. case Key.Enter:
  2181. if (!AllowsReturn) {
  2182. return false;
  2183. }
  2184. if (isReadOnly)
  2185. break;
  2186. currentLine = GetCurrentLine ();
  2187. restCount = currentLine.Count - currentColumn;
  2188. rest = currentLine.GetRange (currentColumn, restCount);
  2189. currentLine.RemoveRange (currentColumn, restCount);
  2190. model.AddLine (currentRow + 1, rest);
  2191. if (wordWrap) {
  2192. wrapManager.AddLine (currentRow, currentColumn);
  2193. wrapNeeded = true;
  2194. }
  2195. currentRow++;
  2196. bool fullNeedsDisplay = false;
  2197. if (currentRow >= topRow + Frame.Height) {
  2198. topRow++;
  2199. fullNeedsDisplay = true;
  2200. }
  2201. currentColumn = 0;
  2202. if (!wordWrap && currentColumn < leftColumn) {
  2203. fullNeedsDisplay = true;
  2204. leftColumn = 0;
  2205. }
  2206. if (fullNeedsDisplay)
  2207. SetNeedsDisplay ();
  2208. else
  2209. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  2210. break;
  2211. case Key.CtrlMask | Key.End:
  2212. case Key.CtrlMask | Key.End | Key.ShiftMask:
  2213. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2214. StartSelecting ();
  2215. } else if (shiftSelecting && selecting) {
  2216. StopSelecting ();
  2217. }
  2218. MoveEnd ();
  2219. break;
  2220. case Key.CtrlMask | Key.Home:
  2221. case Key.CtrlMask | Key.Home | Key.ShiftMask:
  2222. if (kb.Key.HasFlag (Key.ShiftMask)) {
  2223. StartSelecting ();
  2224. } else if (shiftSelecting && selecting) {
  2225. StopSelecting ();
  2226. }
  2227. MoveHome ();
  2228. break;
  2229. case Key.T | Key.CtrlMask:
  2230. SelectAll ();
  2231. break;
  2232. case Key.InsertChar:
  2233. Used = !Used;
  2234. SetNeedsDisplay ();
  2235. break;
  2236. case Key _ when ShortcutHelper.GetModifiersKey (kb) == Key.Tab:
  2237. if (!AllowsTab) {
  2238. return false;
  2239. }
  2240. InsertText (new KeyEvent ((Key)'\t', null));
  2241. break;
  2242. case Key _ when (ShortcutHelper.GetModifiersKey (kb) == (Key.BackTab | Key.ShiftMask)):
  2243. if (!AllowsTab) {
  2244. return false;
  2245. }
  2246. if (currentColumn > 0) {
  2247. currentLine = GetCurrentLine ();
  2248. if (currentLine.Count > 0 && currentLine [currentColumn - 1] == '\t') {
  2249. currentLine.RemoveAt (currentColumn - 1);
  2250. currentColumn--;
  2251. }
  2252. }
  2253. break;
  2254. default:
  2255. // Ignore control characters and other special keys
  2256. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  2257. return false;
  2258. InsertText (kb);
  2259. break;
  2260. }
  2261. DoNeededAction ();
  2262. return true;
  2263. }
  2264. bool InsertText (KeyEvent kb)
  2265. {
  2266. //So that special keys like tab can be processed
  2267. if (isReadOnly)
  2268. return true;
  2269. if (selecting) {
  2270. ClearSelectedRegion ();
  2271. }
  2272. if (Used) {
  2273. Insert ((uint)kb.Key);
  2274. currentColumn++;
  2275. if (currentColumn >= leftColumn + Frame.Width) {
  2276. leftColumn++;
  2277. SetNeedsDisplay ();
  2278. }
  2279. } else {
  2280. Insert ((uint)kb.Key);
  2281. currentColumn++;
  2282. }
  2283. return true;
  2284. }
  2285. ///<inheritdoc/>
  2286. public override bool OnKeyUp (KeyEvent kb)
  2287. {
  2288. switch (kb.Key) {
  2289. case Key.Space | Key.CtrlMask:
  2290. return true;
  2291. }
  2292. return false;
  2293. }
  2294. void DoNeededAction ()
  2295. {
  2296. if (NeedDisplay.IsEmpty) {
  2297. PositionCursor ();
  2298. } else {
  2299. Adjust ();
  2300. }
  2301. }
  2302. bool DeleteTextForwards ()
  2303. {
  2304. var currentLine = GetCurrentLine ();
  2305. if (currentColumn == currentLine.Count) {
  2306. if (currentRow + 1 == model.Count)
  2307. return true;
  2308. var nextLine = model.GetLine (currentRow + 1);
  2309. currentLine.AddRange (nextLine);
  2310. model.RemoveLine (currentRow + 1);
  2311. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out _)) {
  2312. wrapNeeded = true;
  2313. }
  2314. var sr = currentRow - topRow;
  2315. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  2316. } else {
  2317. currentLine.RemoveAt (currentColumn);
  2318. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn)) {
  2319. wrapNeeded = true;
  2320. }
  2321. var r = currentRow - topRow;
  2322. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  2323. }
  2324. return false;
  2325. }
  2326. bool DeleteTextBackwards ()
  2327. {
  2328. if (currentColumn > 0) {
  2329. // Delete backwards
  2330. var currentLine = GetCurrentLine ();
  2331. currentLine.RemoveAt (currentColumn - 1);
  2332. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn - 1)) {
  2333. wrapNeeded = true;
  2334. }
  2335. currentColumn--;
  2336. if (currentColumn < leftColumn) {
  2337. leftColumn--;
  2338. SetNeedsDisplay ();
  2339. } else
  2340. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  2341. } else {
  2342. // Merges the current line with the previous one.
  2343. if (currentRow == 0)
  2344. return true;
  2345. var prowIdx = currentRow - 1;
  2346. var prevRow = model.GetLine (prowIdx);
  2347. var prevCount = prevRow.Count;
  2348. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  2349. model.RemoveLine (currentRow);
  2350. bool lineRemoved = false;
  2351. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out lineRemoved, false)) {
  2352. wrapNeeded = true;
  2353. }
  2354. currentRow--;
  2355. if (wrapNeeded && !lineRemoved) {
  2356. currentColumn = Math.Max (prevCount - 1, 0);
  2357. } else {
  2358. currentColumn = prevCount;
  2359. }
  2360. Adjust ();
  2361. }
  2362. return false;
  2363. }
  2364. bool copyWithoutSelection;
  2365. /// <summary>
  2366. /// Copy the selected text to the clipboard contents.
  2367. /// </summary>
  2368. public void Copy ()
  2369. {
  2370. SetWrapModel ();
  2371. if (selecting) {
  2372. SetClipboard (GetRegion ());
  2373. copyWithoutSelection = false;
  2374. } else {
  2375. var currentLine = GetCurrentLine ();
  2376. SetClipboard (ustring.Make (currentLine));
  2377. copyWithoutSelection = true;
  2378. }
  2379. UpdateWrapModel ();
  2380. DoNeededAction ();
  2381. }
  2382. /// <summary>
  2383. /// Cut the selected text to the clipboard contents.
  2384. /// </summary>
  2385. public void Cut ()
  2386. {
  2387. SetWrapModel ();
  2388. SetClipboard (GetRegion ());
  2389. if (!isReadOnly) {
  2390. ClearRegion ();
  2391. }
  2392. UpdateWrapModel ();
  2393. selecting = false;
  2394. DoNeededAction ();
  2395. }
  2396. /// <summary>
  2397. /// Paste the clipboard contents into the current selected position.
  2398. /// </summary>
  2399. public void Paste ()
  2400. {
  2401. if (isReadOnly) {
  2402. return;
  2403. }
  2404. SetWrapModel ();
  2405. if (copyWithoutSelection) {
  2406. var runeList = Clipboard.Contents == null ? new List<Rune> () : Clipboard.Contents.ToRuneList ();
  2407. model.AddLine (currentRow, runeList);
  2408. currentRow++;
  2409. } else {
  2410. if (selecting) {
  2411. ClearRegion ();
  2412. }
  2413. InsertText (Clipboard.Contents);
  2414. copyWithoutSelection = false;
  2415. }
  2416. UpdateWrapModel ();
  2417. selecting = false;
  2418. DoNeededAction ();
  2419. }
  2420. void StartSelecting ()
  2421. {
  2422. if (shiftSelecting && selecting) {
  2423. return;
  2424. }
  2425. shiftSelecting = true;
  2426. selecting = true;
  2427. selectionStartColumn = currentColumn;
  2428. selectionStartRow = currentRow;
  2429. }
  2430. void StopSelecting ()
  2431. {
  2432. shiftSelecting = false;
  2433. selecting = false;
  2434. }
  2435. void ClearSelectedRegion ()
  2436. {
  2437. SetWrapModel ();
  2438. if (!isReadOnly) {
  2439. ClearRegion ();
  2440. }
  2441. UpdateWrapModel ();
  2442. selecting = false;
  2443. DoNeededAction ();
  2444. }
  2445. void MoveUp ()
  2446. {
  2447. if (currentRow > 0) {
  2448. if (columnTrack == -1) {
  2449. columnTrack = currentColumn;
  2450. }
  2451. currentRow--;
  2452. if (currentRow < topRow) {
  2453. topRow--;
  2454. SetNeedsDisplay ();
  2455. }
  2456. TrackColumn ();
  2457. PositionCursor ();
  2458. }
  2459. }
  2460. void MoveDown ()
  2461. {
  2462. if (currentRow + 1 < model.Count) {
  2463. if (columnTrack == -1) {
  2464. columnTrack = currentColumn;
  2465. }
  2466. currentRow++;
  2467. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  2468. topRow++;
  2469. SetNeedsDisplay ();
  2470. }
  2471. TrackColumn ();
  2472. PositionCursor ();
  2473. } else if (currentRow > Frame.Height) {
  2474. Adjust ();
  2475. }
  2476. }
  2477. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  2478. {
  2479. if (col < 0 || row < 0)
  2480. yield break;
  2481. if (row >= model.Count)
  2482. yield break;
  2483. var line = GetCurrentLine ();
  2484. if (col >= line.Count)
  2485. yield break;
  2486. while (row < model.Count) {
  2487. for (int c = col; c < line.Count; c++) {
  2488. yield return (c, row, line [c]);
  2489. }
  2490. col = 0;
  2491. row++;
  2492. line = GetCurrentLine ();
  2493. }
  2494. }
  2495. Rune RuneAt (int col, int row)
  2496. {
  2497. var line = model.GetLine (row);
  2498. if (line.Count > 0) {
  2499. return line [col > line.Count - 1 ? line.Count - 1 : col];
  2500. } else {
  2501. return 0;
  2502. }
  2503. }
  2504. /// <summary>
  2505. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  2506. /// </summary>
  2507. public void MoveEnd ()
  2508. {
  2509. currentRow = model.Count - 1;
  2510. var line = GetCurrentLine ();
  2511. currentColumn = line.Count;
  2512. TrackColumn ();
  2513. PositionCursor ();
  2514. }
  2515. /// <summary>
  2516. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  2517. /// </summary>
  2518. public void MoveHome ()
  2519. {
  2520. currentRow = 0;
  2521. topRow = 0;
  2522. currentColumn = 0;
  2523. leftColumn = 0;
  2524. TrackColumn ();
  2525. PositionCursor ();
  2526. }
  2527. bool MoveNext (ref int col, ref int row, out Rune rune)
  2528. {
  2529. var line = model.GetLine (row);
  2530. if (col + 1 < line.Count) {
  2531. col++;
  2532. rune = line [col];
  2533. if (col + 1 == line.Count) {
  2534. col++;
  2535. }
  2536. return true;
  2537. }
  2538. while (row + 1 < model.Count) {
  2539. col = 0;
  2540. row++;
  2541. line = model.GetLine (row);
  2542. if (line.Count > 0) {
  2543. rune = line [0];
  2544. return true;
  2545. }
  2546. }
  2547. rune = 0;
  2548. return false;
  2549. }
  2550. bool MovePrev (ref int col, ref int row, out Rune rune)
  2551. {
  2552. var line = model.GetLine (row);
  2553. if (col > 0) {
  2554. col--;
  2555. rune = line [col];
  2556. return true;
  2557. }
  2558. if (row == 0) {
  2559. rune = 0;
  2560. return false;
  2561. }
  2562. while (row > 0) {
  2563. row--;
  2564. line = model.GetLine (row);
  2565. col = line.Count - 1;
  2566. if (col >= 0) {
  2567. rune = line [col];
  2568. return true;
  2569. }
  2570. }
  2571. rune = 0;
  2572. return false;
  2573. }
  2574. (int col, int row)? WordForward (int fromCol, int fromRow)
  2575. {
  2576. var col = fromCol;
  2577. var row = fromRow;
  2578. try {
  2579. var rune = RuneAt (col, row);
  2580. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  2581. {
  2582. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  2583. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  2584. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))
  2585. return;
  2586. }
  2587. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  2588. return;
  2589. }
  2590. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  2591. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  2592. break;
  2593. }
  2594. } else {
  2595. if (!MoveNext (ref nCol, ref nRow, out nRune)) {
  2596. return;
  2597. }
  2598. var line = model.GetLine (fromRow);
  2599. if ((nRow != fromRow && fromCol < line.Count)
  2600. || (nRow == fromRow && nCol == line.Count - 1)) {
  2601. nCol = line.Count;
  2602. nRow = fromRow;
  2603. return;
  2604. } else if (nRow != fromRow && fromCol == line.Count) {
  2605. line = model.GetLine (nRow);
  2606. if (Rune.IsLetterOrDigit (line [nCol]) || Rune.IsPunctuation (line [nCol])) {
  2607. return;
  2608. }
  2609. }
  2610. ProcMoveNext (ref nCol, ref nRow, nRune);
  2611. }
  2612. }
  2613. ProcMoveNext (ref col, ref row, rune);
  2614. if (fromCol != col || fromRow != row)
  2615. return (col, row);
  2616. return null;
  2617. } catch (Exception) {
  2618. return null;
  2619. }
  2620. }
  2621. (int col, int row)? WordBackward (int fromCol, int fromRow)
  2622. {
  2623. if (fromRow == 0 && fromCol == 0)
  2624. return null;
  2625. var col = Math.Max (fromCol - 1, 0);
  2626. var row = fromRow;
  2627. try {
  2628. var rune = RuneAt (col, row);
  2629. int lastValidCol = Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) ? col : -1;
  2630. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  2631. {
  2632. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  2633. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  2634. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune)) {
  2635. lastValidCol = nCol;
  2636. break;
  2637. }
  2638. }
  2639. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  2640. if (lastValidCol > -1) {
  2641. nCol = lastValidCol;
  2642. }
  2643. return;
  2644. }
  2645. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  2646. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  2647. break;
  2648. if (nRow != fromRow) {
  2649. break;
  2650. }
  2651. lastValidCol = nCol;
  2652. }
  2653. if (lastValidCol > -1) {
  2654. nCol = lastValidCol;
  2655. nRow = fromRow;
  2656. }
  2657. } else {
  2658. if (!MovePrev (ref nCol, ref nRow, out nRune)) {
  2659. return;
  2660. }
  2661. var line = model.GetLine (nRow);
  2662. if (nCol == 0 && nRow == fromRow && (Rune.IsLetterOrDigit (line [0]) || Rune.IsPunctuation (line [0]))) {
  2663. return;
  2664. }
  2665. lastValidCol = Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) ? nCol : lastValidCol;
  2666. if (lastValidCol > -1 && (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune))) {
  2667. nCol = lastValidCol;
  2668. return;
  2669. }
  2670. if (fromRow != nRow) {
  2671. nCol = line.Count;
  2672. return;
  2673. }
  2674. ProcMovePrev (ref nCol, ref nRow, nRune);
  2675. }
  2676. }
  2677. ProcMovePrev (ref col, ref row, rune);
  2678. if (fromCol != col || fromRow != row)
  2679. return (col, row);
  2680. return null;
  2681. } catch (Exception) {
  2682. return null;
  2683. }
  2684. }
  2685. ///<inheritdoc/>
  2686. public override bool MouseEvent (MouseEvent ev)
  2687. {
  2688. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  2689. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  2690. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  2691. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  2692. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  2693. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  2694. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)) {
  2695. return false;
  2696. }
  2697. if (!CanFocus) {
  2698. return true;
  2699. }
  2700. if (!HasFocus) {
  2701. SetFocus ();
  2702. }
  2703. continuousFind = false;
  2704. if (ev.Flags == MouseFlags.Button1Clicked) {
  2705. if (shiftSelecting) {
  2706. shiftSelecting = false;
  2707. selecting = false;
  2708. }
  2709. ProcessMouseClick (ev, out _);
  2710. PositionCursor ();
  2711. lastWasKill = false;
  2712. columnTrack = currentColumn;
  2713. } else if (ev.Flags == MouseFlags.WheeledDown) {
  2714. lastWasKill = false;
  2715. columnTrack = currentColumn;
  2716. ScrollTo (topRow + 1);
  2717. } else if (ev.Flags == MouseFlags.WheeledUp) {
  2718. lastWasKill = false;
  2719. columnTrack = currentColumn;
  2720. ScrollTo (topRow - 1);
  2721. } else if (ev.Flags == MouseFlags.WheeledRight) {
  2722. lastWasKill = false;
  2723. columnTrack = currentColumn;
  2724. ScrollTo (leftColumn + 1, false);
  2725. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  2726. lastWasKill = false;
  2727. columnTrack = currentColumn;
  2728. ScrollTo (leftColumn - 1, false);
  2729. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  2730. ProcessMouseClick (ev, out List<Rune> line);
  2731. PositionCursor ();
  2732. if (model.Count > 0 && shiftSelecting && selecting) {
  2733. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  2734. && model.Count + BottomOffset > topRow + currentRow) {
  2735. ScrollTo (topRow + Frame.Height);
  2736. } else if (topRow > 0 && currentRow <= topRow) {
  2737. ScrollTo (topRow - Frame.Height);
  2738. } else if (ev.Y >= Frame.Height) {
  2739. ScrollTo (model.Count + BottomOffset);
  2740. } else if (ev.Y < 0 && topRow > 0) {
  2741. ScrollTo (0);
  2742. }
  2743. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  2744. && line.Count + RightOffset > leftColumn + currentColumn) {
  2745. ScrollTo (leftColumn + Frame.Width, false);
  2746. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  2747. ScrollTo (leftColumn - Frame.Width, false);
  2748. } else if (ev.X >= Frame.Width) {
  2749. ScrollTo (line.Count + RightOffset, false);
  2750. } else if (ev.X < 0 && leftColumn > 0) {
  2751. ScrollTo (0, false);
  2752. }
  2753. }
  2754. lastWasKill = false;
  2755. columnTrack = currentColumn;
  2756. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  2757. if (!shiftSelecting) {
  2758. StartSelecting ();
  2759. }
  2760. ProcessMouseClick (ev, out _);
  2761. PositionCursor ();
  2762. lastWasKill = false;
  2763. columnTrack = currentColumn;
  2764. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  2765. if (shiftSelecting) {
  2766. shiftSelecting = false;
  2767. selecting = false;
  2768. }
  2769. ProcessMouseClick (ev, out _);
  2770. PositionCursor ();
  2771. if (!selecting) {
  2772. StartSelecting ();
  2773. }
  2774. lastWasKill = false;
  2775. columnTrack = currentColumn;
  2776. if (Application.mouseGrabView == null) {
  2777. Application.GrabMouse (this);
  2778. }
  2779. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  2780. Application.UngrabMouse ();
  2781. } else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)) {
  2782. if (ev.Flags.HasFlag (MouseFlags.ButtonShift)) {
  2783. if (!selecting) {
  2784. StartSelecting ();
  2785. }
  2786. } else if (selecting) {
  2787. StopSelecting ();
  2788. }
  2789. ProcessMouseClick (ev, out List<Rune> line);
  2790. (int col, int row)? newPos = null;
  2791. if (currentColumn > 0 && line [currentColumn - 1] != ' ') {
  2792. newPos = WordBackward (currentColumn, currentRow);
  2793. if (newPos.HasValue) {
  2794. currentColumn = newPos.Value.col;
  2795. currentRow = newPos.Value.row;
  2796. }
  2797. }
  2798. if (!selecting) {
  2799. StartSelecting ();
  2800. }
  2801. if (currentRow < selectionStartRow || currentRow == selectionStartRow && currentColumn < selectionStartColumn) {
  2802. if (currentColumn > 0 && line [currentColumn - 1] != ' ') {
  2803. newPos = WordBackward (currentColumn, currentRow);
  2804. }
  2805. } else {
  2806. newPos = WordForward (currentColumn, currentRow);
  2807. }
  2808. if (newPos != null && newPos.HasValue) {
  2809. currentColumn = newPos.Value.col;
  2810. currentRow = newPos.Value.row;
  2811. }
  2812. PositionCursor ();
  2813. lastWasKill = false;
  2814. columnTrack = currentColumn;
  2815. }
  2816. return true;
  2817. }
  2818. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  2819. {
  2820. List<Rune> r = null;
  2821. if (model.Count > 0) {
  2822. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  2823. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  2824. currentRow = maxCursorPositionableLine + topRow;
  2825. } else {
  2826. currentRow = Math.Max (ev.Y + topRow, 0);
  2827. }
  2828. r = GetCurrentLine ();
  2829. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0), TabWidth);
  2830. if (idx - leftColumn >= r.Count + RightOffset) {
  2831. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  2832. } else {
  2833. currentColumn = idx + leftColumn;
  2834. }
  2835. }
  2836. line = r;
  2837. }
  2838. ///<inheritdoc/>
  2839. public override bool OnLeave (View view)
  2840. {
  2841. if (Application.mouseGrabView != null && Application.mouseGrabView == this) {
  2842. Application.UngrabMouse ();
  2843. }
  2844. return base.OnLeave (view);
  2845. }
  2846. }
  2847. }