TextView.cs 84 KB

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