TextView.cs 82 KB

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