TextView.cs 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. //
  2. // TextView.cs: multi-line text editing
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. //
  8. // TODO:
  9. // In ReadOnly mode backspace/space behave like pageup/pagedown
  10. // Attributed text on spans
  11. // Replace insertion with Insert method
  12. // String accumulation (Control-k, control-k is not preserving the last new line, see StringToRunes
  13. // Alt-D, Alt-Backspace
  14. // API to set the cursor position
  15. // API to scroll to a particular place
  16. // keybindings to go to top/bottom
  17. // public API to insert, remove ranges
  18. // Add word forward/word backwards commands
  19. // Save buffer API
  20. // Mouse
  21. //
  22. // Desirable:
  23. // Move all the text manipulation into the TextModel
  24. using System;
  25. using System.Collections.Generic;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Text;
  29. using NStack;
  30. using Rune = System.Rune;
  31. namespace Terminal.Gui {
  32. class TextModel {
  33. List<List<Rune>> lines = new List<List<Rune>> ();
  34. public bool LoadFile (string file)
  35. {
  36. if (file == null)
  37. throw new ArgumentNullException (nameof (file));
  38. try {
  39. FilePath = file;
  40. var stream = File.OpenRead (file);
  41. } catch {
  42. return false;
  43. }
  44. LoadStream (File.OpenRead (file));
  45. return true;
  46. }
  47. public bool CloseFile ()
  48. {
  49. if (FilePath == null)
  50. throw new ArgumentNullException (nameof (FilePath));
  51. try {
  52. FilePath = null;
  53. lines = new List<List<Rune>> ();
  54. } catch {
  55. return false;
  56. }
  57. return true;
  58. }
  59. // Turns the ustring into runes, this does not split the
  60. // contents on a newline if it is present.
  61. internal static List<Rune> ToRunes (ustring str)
  62. {
  63. List<Rune> runes = new List<Rune> ();
  64. foreach (var x in str.ToRunes ()) {
  65. runes.Add (x);
  66. }
  67. return runes;
  68. }
  69. // Splits a string into a List that contains a List<Rune> for each line
  70. public static List<List<Rune>> StringToRunes (ustring content)
  71. {
  72. var lines = new List<List<Rune>> ();
  73. int start = 0, i = 0;
  74. // BUGBUG: I think this is buggy w.r.t Unicode. content.Length is bytes, and content[i] is bytes
  75. // and content[i] == 10 may be the middle of a Rune.
  76. for (; i < content.Length; i++) {
  77. if (content [i] == 10) {
  78. if (i - start > 0)
  79. lines.Add (ToRunes (content [start, i]));
  80. else
  81. lines.Add (ToRunes (ustring.Empty));
  82. start = i + 1;
  83. }
  84. }
  85. if (i - start >= 0)
  86. lines.Add (ToRunes (content [start, null]));
  87. return lines;
  88. }
  89. void Append (List<byte> line)
  90. {
  91. var str = ustring.Make (line.ToArray ());
  92. lines.Add (ToRunes (str));
  93. }
  94. public void LoadStream (Stream input)
  95. {
  96. if (input == null)
  97. throw new ArgumentNullException (nameof (input));
  98. lines = new List<List<Rune>> ();
  99. var buff = new BufferedStream (input);
  100. int v;
  101. var line = new List<byte> ();
  102. while ((v = buff.ReadByte ()) != -1) {
  103. if (v == 10) {
  104. Append (line);
  105. line.Clear ();
  106. continue;
  107. }
  108. line.Add ((byte)v);
  109. }
  110. if (line.Count > 0)
  111. Append (line);
  112. }
  113. public void LoadString (ustring content)
  114. {
  115. lines = StringToRunes (content);
  116. }
  117. public override string ToString ()
  118. {
  119. var sb = new StringBuilder ();
  120. for (int i = 0; i < lines.Count; i++) {
  121. sb.Append (ustring.Make (lines[i]));
  122. if ((i + 1) < lines.Count) {
  123. sb.AppendLine ();
  124. }
  125. }
  126. return sb.ToString ();
  127. }
  128. public string FilePath { get; set; }
  129. /// <summary>
  130. /// The number of text lines in the model
  131. /// </summary>
  132. public int Count => lines.Count;
  133. /// <summary>
  134. /// Returns the specified line as a List of Rune
  135. /// </summary>
  136. /// <returns>The line.</returns>
  137. /// <param name="line">Line number to retrieve.</param>
  138. public List<Rune> GetLine (int line) => line < Count ? lines [line] : lines [Count - 1];
  139. /// <summary>
  140. /// Adds a line to the model at the specified position.
  141. /// </summary>
  142. /// <param name="pos">Line number where the line will be inserted.</param>
  143. /// <param name="runes">The line of text, as a List of Rune.</param>
  144. public void AddLine (int pos, List<Rune> runes)
  145. {
  146. lines.Insert (pos, runes);
  147. }
  148. /// <summary>
  149. /// Removes the line at the specified position
  150. /// </summary>
  151. /// <param name="pos">Position.</param>
  152. public void RemoveLine (int pos)
  153. {
  154. lines.RemoveAt (pos);
  155. }
  156. }
  157. /// <summary>
  158. /// Multi-line text editing <see cref="View"/>
  159. /// </summary>
  160. /// <remarks>
  161. /// <para>
  162. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  163. /// with it with the standard Emacs commands for movement or the arrow
  164. /// keys.
  165. /// </para>
  166. /// <list type="table">
  167. /// <listheader>
  168. /// <term>Shortcut</term>
  169. /// <description>Action performed</description>
  170. /// </listheader>
  171. /// <item>
  172. /// <term>Left cursor, Control-b</term>
  173. /// <description>
  174. /// Moves the editing point left.
  175. /// </description>
  176. /// </item>
  177. /// <item>
  178. /// <term>Right cursor, Control-f</term>
  179. /// <description>
  180. /// Moves the editing point right.
  181. /// </description>
  182. /// </item>
  183. /// <item>
  184. /// <term>Alt-b</term>
  185. /// <description>
  186. /// Moves one word back.
  187. /// </description>
  188. /// </item>
  189. /// <item>
  190. /// <term>Alt-f</term>
  191. /// <description>
  192. /// Moves one word forward.
  193. /// </description>
  194. /// </item>
  195. /// <item>
  196. /// <term>Up cursor, Control-p</term>
  197. /// <description>
  198. /// Moves the editing point one line up.
  199. /// </description>
  200. /// </item>
  201. /// <item>
  202. /// <term>Down cursor, Control-n</term>
  203. /// <description>
  204. /// Moves the editing point one line down
  205. /// </description>
  206. /// </item>
  207. /// <item>
  208. /// <term>Home key, Control-a</term>
  209. /// <description>
  210. /// Moves the cursor to the beginning of the line.
  211. /// </description>
  212. /// </item>
  213. /// <item>
  214. /// <term>End key, Control-e</term>
  215. /// <description>
  216. /// Moves the cursor to the end of the line.
  217. /// </description>
  218. /// </item>
  219. /// <item>
  220. /// <term>Control-Home</term>
  221. /// <description>
  222. /// Scrolls to the first line and moves the cursor there.
  223. /// </description>
  224. /// </item>
  225. /// <item>
  226. /// <term>Control-End</term>
  227. /// <description>
  228. /// Scrolls to the last line and moves the cursor there.
  229. /// </description>
  230. /// </item>
  231. /// <item>
  232. /// <term>Delete, Control-d</term>
  233. /// <description>
  234. /// Deletes the character in front of the cursor.
  235. /// </description>
  236. /// </item>
  237. /// <item>
  238. /// <term>Backspace</term>
  239. /// <description>
  240. /// Deletes the character behind the cursor.
  241. /// </description>
  242. /// </item>
  243. /// <item>
  244. /// <term>Control-k</term>
  245. /// <description>
  246. /// Deletes the text until the end of the line and replaces the kill buffer
  247. /// with the deleted text. You can paste this text in a different place by
  248. /// using Control-y.
  249. /// </description>
  250. /// </item>
  251. /// <item>
  252. /// <term>Control-y</term>
  253. /// <description>
  254. /// Pastes the content of the kill ring into the current position.
  255. /// </description>
  256. /// </item>
  257. /// <item>
  258. /// <term>Alt-d</term>
  259. /// <description>
  260. /// Deletes the word above the cursor and adds it to the kill ring. You
  261. /// can paste the contents of the kill ring with Control-y.
  262. /// </description>
  263. /// </item>
  264. /// <item>
  265. /// <term>Control-q</term>
  266. /// <description>
  267. /// Quotes the next input character, to prevent the normal processing of
  268. /// key handling to take place.
  269. /// </description>
  270. /// </item>
  271. /// </list>
  272. /// </remarks>
  273. public class TextView : View {
  274. TextModel model = new TextModel ();
  275. int topRow;
  276. int leftColumn;
  277. int currentRow;
  278. int currentColumn;
  279. int selectionStartColumn, selectionStartRow;
  280. bool selecting;
  281. //bool used;
  282. /// <summary>
  283. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  284. /// </summary>
  285. public event Action TextChanged;
  286. #if false
  287. /// <summary>
  288. /// Changed event, raised when the text has clicked.
  289. /// </summary>
  290. /// <remarks>
  291. /// Client code can hook up to this event, it is
  292. /// raised when the text in the entry changes.
  293. /// </remarks>
  294. public Action Changed;
  295. #endif
  296. /// <summary>
  297. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  298. /// </summary>
  299. /// <remarks>
  300. /// </remarks>
  301. public TextView (Rect frame) : base (frame)
  302. {
  303. CanFocus = true;
  304. }
  305. /// <summary>
  306. /// Initializes a <see cref="TextView"/> on the specified area,
  307. /// with dimensions controlled with the X, Y, Width and Height properties.
  308. /// </summary>
  309. public TextView () : base ()
  310. {
  311. CanFocus = true;
  312. }
  313. void ResetPosition ()
  314. {
  315. topRow = leftColumn = currentRow = currentColumn = 0;
  316. }
  317. /// <summary>
  318. /// Sets or gets the text in the <see cref="TextView"/>.
  319. /// </summary>
  320. /// <remarks>
  321. /// </remarks>
  322. public override ustring Text {
  323. get {
  324. return model.ToString ();
  325. }
  326. set {
  327. ResetPosition ();
  328. model.LoadString (value);
  329. TextChanged?.Invoke ();
  330. SetNeedsDisplay ();
  331. }
  332. }
  333. /// <summary>
  334. /// Loads the contents of the file into the <see cref="TextView"/>.
  335. /// </summary>
  336. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  337. /// <param name="path">Path to the file to load.</param>
  338. public bool LoadFile (string path)
  339. {
  340. if (path == null)
  341. throw new ArgumentNullException (nameof (path));
  342. ResetPosition ();
  343. var res = model.LoadFile (path);
  344. SetNeedsDisplay ();
  345. return res;
  346. }
  347. /// <summary>
  348. /// Loads the contents of the stream into the <see cref="TextView"/>.
  349. /// </summary>
  350. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  351. /// <param name="stream">Stream to load the contents from.</param>
  352. public void LoadStream (Stream stream)
  353. {
  354. if (stream == null)
  355. throw new ArgumentNullException (nameof (stream));
  356. ResetPosition ();
  357. model.LoadStream (stream);
  358. SetNeedsDisplay ();
  359. }
  360. /// <summary>
  361. /// Closes the contents of the stream into the <see cref="TextView"/>.
  362. /// </summary>
  363. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  364. public bool CloseFile ()
  365. {
  366. ResetPosition ();
  367. var res = model.CloseFile ();
  368. SetNeedsDisplay ();
  369. return res;
  370. }
  371. /// <summary>
  372. /// Gets the current cursor row.
  373. /// </summary>
  374. public int CurrentRow => currentRow;
  375. /// <summary>
  376. /// Gets the cursor column.
  377. /// </summary>
  378. /// <value>The cursor column.</value>
  379. public int CurrentColumn => currentColumn;
  380. /// <summary>
  381. /// Positions the cursor on the current row and column
  382. /// </summary>
  383. public override void PositionCursor ()
  384. {
  385. if (selecting) {
  386. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  387. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  388. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  389. }
  390. var line = model.GetLine (currentRow);
  391. var retreat = 0;
  392. if (line.Count > 0) {
  393. retreat = Math.Max ((SpecialRune (line [Math.Max (CurrentColumn - leftColumn - 1, 0)])
  394. ? 1 : 0), 0);
  395. }
  396. Move (CurrentColumn - leftColumn - retreat, CurrentRow - topRow);
  397. }
  398. void ClearRegion (int left, int top, int right, int bottom)
  399. {
  400. for (int row = top; row < bottom; row++) {
  401. Move (left, row);
  402. for (int col = left; col < right; col++)
  403. AddRune (col, row, ' ');
  404. }
  405. }
  406. void ColorNormal ()
  407. {
  408. Driver.SetAttribute (ColorScheme.Normal);
  409. }
  410. void ColorSelection ()
  411. {
  412. if (HasFocus)
  413. Driver.SetAttribute (ColorScheme.Focus);
  414. else
  415. Driver.SetAttribute (ColorScheme.Normal);
  416. }
  417. bool isReadOnly = false;
  418. /// <summary>
  419. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  420. /// </summary>
  421. /// <value>Boolean value(Default false)</value>
  422. public bool ReadOnly {
  423. get => isReadOnly;
  424. set {
  425. isReadOnly = value;
  426. }
  427. }
  428. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  429. void GetEncodedRegionBounds (out long start, out long end)
  430. {
  431. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  432. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  433. if (selection > point) {
  434. start = point;
  435. end = selection;
  436. } else {
  437. start = selection;
  438. end = point;
  439. }
  440. }
  441. bool PointInSelection (int col, int row)
  442. {
  443. long start, end;
  444. GetEncodedRegionBounds (out start, out end);
  445. var q = ((long)(uint)row << 32) | (uint)col;
  446. return q >= start && q <= end;
  447. }
  448. //
  449. // Returns a ustring with the text in the selected
  450. // region.
  451. //
  452. ustring GetRegion ()
  453. {
  454. long start, end;
  455. GetEncodedRegionBounds (out start, out end);
  456. int startRow = (int)(start >> 32);
  457. var maxrow = ((int)(end >> 32));
  458. int startCol = (int)(start & 0xffffffff);
  459. var endCol = (int)(end & 0xffffffff);
  460. var line = model.GetLine (startRow);
  461. if (startRow == maxrow)
  462. return StringFromRunes (line.GetRange (startCol, endCol));
  463. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  464. for (int row = startRow + 1; row < maxrow; row++) {
  465. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  466. }
  467. line = model.GetLine (maxrow);
  468. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  469. return res;
  470. }
  471. //
  472. // Clears the contents of the selected region
  473. //
  474. void ClearRegion ()
  475. {
  476. long start, end;
  477. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  478. GetEncodedRegionBounds (out start, out end);
  479. int startRow = (int)(start >> 32);
  480. var maxrow = ((int)(end >> 32));
  481. int startCol = (int)(start & 0xffffffff);
  482. var endCol = (int)(end & 0xffffffff);
  483. var line = model.GetLine (startRow);
  484. if (startRow == maxrow) {
  485. line.RemoveRange (startCol, endCol - startCol);
  486. currentColumn = startCol;
  487. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  488. return;
  489. }
  490. line.RemoveRange (startCol, line.Count - startCol);
  491. var line2 = model.GetLine (maxrow);
  492. line.AddRange (line2.Skip (endCol));
  493. for (int row = startRow + 1; row <= maxrow; row++) {
  494. model.RemoveLine (startRow + 1);
  495. }
  496. if (currentEncoded == end) {
  497. currentRow -= maxrow - (startRow);
  498. }
  499. currentColumn = startCol;
  500. SetNeedsDisplay ();
  501. }
  502. ///<inheritdoc/>
  503. public override void Redraw (Rect bounds)
  504. {
  505. ColorNormal ();
  506. int bottom = bounds.Bottom;
  507. int right = bounds.Right;
  508. for (int row = bounds.Top; row < bottom; row++) {
  509. int textLine = topRow + row;
  510. if (textLine >= model.Count) {
  511. ColorNormal ();
  512. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  513. continue;
  514. }
  515. var line = model.GetLine (textLine);
  516. int lineRuneCount = line.Count;
  517. if (line.Count < bounds.Left) {
  518. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  519. continue;
  520. }
  521. Move (bounds.Left, row);
  522. for (int col = bounds.Left; col < right; col++) {
  523. var lineCol = leftColumn + col;
  524. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  525. if (selecting && PointInSelection (col, row)) {
  526. ColorSelection ();
  527. } else {
  528. ColorNormal ();
  529. }
  530. if (!SpecialRune (rune)) {
  531. AddRune (col, row, rune);
  532. }
  533. }
  534. }
  535. PositionCursor ();
  536. }
  537. bool SpecialRune (Rune rune)
  538. {
  539. switch (rune) {
  540. case (uint)Key.Enter:
  541. case 0xd:
  542. return true;
  543. default:
  544. return false; }
  545. }
  546. ///<inheritdoc/>
  547. public override bool CanFocus {
  548. get => base.CanFocus;
  549. set { base.CanFocus = value; }
  550. }
  551. void SetClipboard (ustring text)
  552. {
  553. Clipboard.Contents = text;
  554. }
  555. void AppendClipboard (ustring text)
  556. {
  557. Clipboard.Contents = Clipboard.Contents + text;
  558. }
  559. void Insert (Rune rune)
  560. {
  561. var line = GetCurrentLine ();
  562. line.Insert (currentColumn, rune);
  563. var prow = currentRow - topRow;
  564. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  565. }
  566. ustring StringFromRunes (List<Rune> runes)
  567. {
  568. if (runes == null)
  569. throw new ArgumentNullException (nameof (runes));
  570. int size = 0;
  571. foreach (var rune in runes) {
  572. size += Utf8.RuneLen (rune);
  573. }
  574. var encoded = new byte [size];
  575. int offset = 0;
  576. foreach (var rune in runes) {
  577. offset += Utf8.EncodeRune (rune, encoded, offset);
  578. }
  579. return ustring.Make (encoded);
  580. }
  581. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  582. void InsertText (ustring text)
  583. {
  584. var lines = TextModel.StringToRunes (text);
  585. if (lines.Count == 0)
  586. return;
  587. var line = GetCurrentLine ();
  588. // Optmize single line
  589. if (lines.Count == 1) {
  590. line.InsertRange (currentColumn, lines [0]);
  591. currentColumn += lines [0].Count;
  592. if (currentColumn - leftColumn > Frame.Width)
  593. leftColumn = currentColumn - Frame.Width + 1;
  594. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  595. return;
  596. }
  597. // Keep a copy of the rest of the line
  598. var restCount = line.Count - currentColumn;
  599. var rest = line.GetRange (currentColumn, restCount);
  600. line.RemoveRange (currentColumn, restCount);
  601. // First line is inserted at the current location, the rest is appended
  602. line.InsertRange (currentColumn, lines [0]);
  603. for (int i = 1; i < lines.Count; i++)
  604. model.AddLine (currentRow + i, lines [i]);
  605. var last = model.GetLine (currentRow + lines.Count - 1);
  606. var lastp = last.Count;
  607. last.InsertRange (last.Count, rest);
  608. // Now adjjust column and row positions
  609. currentRow += lines.Count - 1;
  610. currentColumn = lastp;
  611. if (currentRow - topRow > Frame.Height) {
  612. topRow = currentRow - Frame.Height + 1;
  613. if (topRow < 0)
  614. topRow = 0;
  615. }
  616. if (currentColumn < leftColumn)
  617. leftColumn = currentColumn;
  618. if (currentColumn - leftColumn >= Frame.Width)
  619. leftColumn = currentColumn - Frame.Width + 1;
  620. SetNeedsDisplay ();
  621. }
  622. // The column we are tracking, or -1 if we are not tracking any column
  623. int columnTrack = -1;
  624. // Tries to snap the cursor to the tracking column
  625. void TrackColumn ()
  626. {
  627. // Now track the column
  628. var line = GetCurrentLine ();
  629. if (line.Count < columnTrack)
  630. currentColumn = line.Count;
  631. else if (columnTrack != -1)
  632. currentColumn = columnTrack;
  633. else if (currentColumn > line.Count)
  634. currentColumn = line.Count;
  635. Adjust ();
  636. }
  637. void Adjust ()
  638. {
  639. bool need = false;
  640. if (currentColumn < leftColumn) {
  641. currentColumn = leftColumn;
  642. need = true;
  643. }
  644. if (currentColumn - leftColumn > Frame.Width) {
  645. leftColumn = currentColumn - Frame.Width + 1;
  646. need = true;
  647. }
  648. if (currentRow < topRow) {
  649. topRow = currentRow;
  650. need = true;
  651. }
  652. if (currentRow - topRow > Frame.Height) {
  653. topRow = currentRow - Frame.Height + 1;
  654. need = true;
  655. }
  656. if (need)
  657. SetNeedsDisplay ();
  658. else
  659. PositionCursor ();
  660. }
  661. /// <summary>
  662. /// Will scroll the <see cref="TextView"/> to display the specified row at the top
  663. /// </summary>
  664. /// <param name="row">Row that should be displayed at the top, if the value is negative it will be reset to zero</param>
  665. public void ScrollTo (int row)
  666. {
  667. if (row < 0)
  668. row = 0;
  669. topRow = row > model.Count ? model.Count - 1 : row;
  670. SetNeedsDisplay ();
  671. }
  672. bool lastWasKill;
  673. ///<inheritdoc/>
  674. public override bool ProcessKey (KeyEvent kb)
  675. {
  676. int restCount;
  677. List<Rune> rest;
  678. // Handle some state here - whether the last command was a kill
  679. // operation and the column tracking (up/down)
  680. switch (kb.Key) {
  681. case Key.N | Key.CtrlMask:
  682. case Key.CursorDown:
  683. case Key.P | Key.CtrlMask:
  684. case Key.CursorUp:
  685. lastWasKill = false;
  686. break;
  687. case Key.K | Key.CtrlMask:
  688. break;
  689. default:
  690. lastWasKill = false;
  691. columnTrack = -1;
  692. break;
  693. }
  694. // Dispatch the command.
  695. switch (kb.Key) {
  696. case Key.PageDown:
  697. case Key.V | Key.CtrlMask:
  698. int nPageDnShift = Frame.Height - 1;
  699. if (currentRow < model.Count) {
  700. if (columnTrack == -1)
  701. columnTrack = currentColumn;
  702. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  703. if (topRow < currentRow - nPageDnShift) {
  704. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  705. SetNeedsDisplay ();
  706. }
  707. TrackColumn ();
  708. PositionCursor ();
  709. }
  710. break;
  711. case Key.PageUp:
  712. case ((int)'v' + Key.AltMask):
  713. int nPageUpShift = Frame.Height - 1;
  714. if (currentRow > 0) {
  715. if (columnTrack == -1)
  716. columnTrack = currentColumn;
  717. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  718. if (currentRow < topRow) {
  719. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  720. SetNeedsDisplay ();
  721. }
  722. TrackColumn ();
  723. PositionCursor ();
  724. }
  725. break;
  726. case Key.N | Key.CtrlMask:
  727. case Key.CursorDown:
  728. MoveDown ();
  729. break;
  730. case Key.P | Key.CtrlMask:
  731. case Key.CursorUp:
  732. MoveUp ();
  733. break;
  734. case Key.F | Key.CtrlMask:
  735. case Key.CursorRight:
  736. var currentLine = GetCurrentLine ();
  737. if (currentColumn < currentLine.Count) {
  738. currentColumn++;
  739. if (currentColumn >= leftColumn + Frame.Width) {
  740. leftColumn++;
  741. SetNeedsDisplay ();
  742. }
  743. PositionCursor ();
  744. } else {
  745. if (currentRow + 1 < model.Count) {
  746. currentRow++;
  747. currentColumn = 0;
  748. leftColumn = 0;
  749. if (currentRow >= topRow + Frame.Height) {
  750. topRow++;
  751. }
  752. SetNeedsDisplay ();
  753. PositionCursor ();
  754. }
  755. break;
  756. }
  757. break;
  758. case Key.B | Key.CtrlMask:
  759. case Key.CursorLeft:
  760. if (currentColumn > 0) {
  761. currentColumn--;
  762. if (currentColumn < leftColumn) {
  763. leftColumn--;
  764. SetNeedsDisplay ();
  765. }
  766. PositionCursor ();
  767. } else {
  768. if (currentRow > 0) {
  769. currentRow--;
  770. if (currentRow < topRow) {
  771. topRow--;
  772. SetNeedsDisplay ();
  773. }
  774. currentLine = GetCurrentLine ();
  775. currentColumn = currentLine.Count;
  776. int prev = leftColumn;
  777. leftColumn = currentColumn - Frame.Width + 1;
  778. if (leftColumn < 0)
  779. leftColumn = 0;
  780. if (prev != leftColumn)
  781. SetNeedsDisplay ();
  782. PositionCursor ();
  783. }
  784. }
  785. break;
  786. case Key.Delete:
  787. case Key.Backspace:
  788. if (isReadOnly)
  789. break;
  790. if (currentColumn > 0) {
  791. // Delete backwards
  792. currentLine = GetCurrentLine ();
  793. currentLine.RemoveAt (currentColumn - 1);
  794. currentColumn--;
  795. if (currentColumn < leftColumn) {
  796. leftColumn--;
  797. SetNeedsDisplay ();
  798. } else
  799. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  800. } else {
  801. // Merges the current line with the previous one.
  802. if (currentRow == 0)
  803. return true;
  804. var prowIdx = currentRow - 1;
  805. var prevRow = model.GetLine (prowIdx);
  806. var prevCount = prevRow.Count;
  807. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  808. model.RemoveLine (currentRow);
  809. currentRow--;
  810. currentColumn = prevCount;
  811. leftColumn = currentColumn - Frame.Width + 1;
  812. if (leftColumn < 0)
  813. leftColumn = 0;
  814. SetNeedsDisplay ();
  815. }
  816. break;
  817. // Home, C-A
  818. case Key.Home:
  819. case Key.A | Key.CtrlMask:
  820. currentColumn = 0;
  821. if (currentColumn < leftColumn) {
  822. leftColumn = 0;
  823. SetNeedsDisplay ();
  824. } else
  825. PositionCursor ();
  826. break;
  827. case Key.DeleteChar:
  828. case Key.D | Key.CtrlMask: // Delete
  829. if (isReadOnly)
  830. break;
  831. currentLine = GetCurrentLine ();
  832. if (currentColumn == currentLine.Count) {
  833. if (currentRow + 1 == model.Count)
  834. break;
  835. var nextLine = model.GetLine (currentRow + 1);
  836. currentLine.AddRange (nextLine);
  837. model.RemoveLine (currentRow + 1);
  838. var sr = currentRow - topRow;
  839. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  840. } else {
  841. currentLine.RemoveAt (currentColumn);
  842. var r = currentRow - topRow;
  843. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  844. }
  845. break;
  846. case Key.End:
  847. case Key.E | Key.CtrlMask: // End
  848. currentLine = GetCurrentLine ();
  849. currentColumn = currentLine.Count;
  850. int pcol = leftColumn;
  851. leftColumn = currentColumn - Frame.Width + 1;
  852. if (leftColumn < 0)
  853. leftColumn = 0;
  854. if (pcol != leftColumn)
  855. SetNeedsDisplay ();
  856. PositionCursor ();
  857. break;
  858. case Key.K | Key.CtrlMask: // kill-to-end
  859. if (isReadOnly)
  860. break;
  861. currentLine = GetCurrentLine ();
  862. if (currentLine.Count == 0) {
  863. model.RemoveLine (currentRow);
  864. var val = ustring.Make ((Rune)'\n');
  865. if (lastWasKill)
  866. AppendClipboard (val);
  867. else
  868. SetClipboard (val);
  869. } else {
  870. restCount = currentLine.Count - currentColumn;
  871. rest = currentLine.GetRange (currentColumn, restCount);
  872. var val = StringFromRunes (rest);
  873. if (lastWasKill)
  874. AppendClipboard (val);
  875. else
  876. SetClipboard (val);
  877. currentLine.RemoveRange (currentColumn, restCount);
  878. }
  879. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  880. lastWasKill = true;
  881. break;
  882. case Key.Y | Key.CtrlMask: // Control-y, yank
  883. if (isReadOnly)
  884. break;
  885. InsertText (Clipboard.Contents);
  886. selecting = false;
  887. break;
  888. case Key.Space | Key.CtrlMask:
  889. selecting = true;
  890. selectionStartColumn = currentColumn;
  891. selectionStartRow = currentRow;
  892. break;
  893. case ((int)'w' + Key.AltMask):
  894. SetClipboard (GetRegion ());
  895. selecting = false;
  896. break;
  897. case Key.W | Key.CtrlMask:
  898. SetClipboard (GetRegion ());
  899. if (!isReadOnly)
  900. ClearRegion ();
  901. selecting = false;
  902. break;
  903. case (Key)((int)'b' + Key.AltMask):
  904. var newPos = WordBackward (currentColumn, currentRow);
  905. if (newPos.HasValue) {
  906. currentColumn = newPos.Value.col;
  907. currentRow = newPos.Value.row;
  908. }
  909. Adjust ();
  910. break;
  911. case (Key)((int)'f' + Key.AltMask):
  912. newPos = WordForward (currentColumn, currentRow);
  913. if (newPos.HasValue) {
  914. currentColumn = newPos.Value.col;
  915. currentRow = newPos.Value.row;
  916. }
  917. Adjust ();
  918. break;
  919. case Key.Enter:
  920. if (isReadOnly)
  921. break;
  922. var orow = currentRow;
  923. currentLine = GetCurrentLine ();
  924. restCount = currentLine.Count - currentColumn;
  925. rest = currentLine.GetRange (currentColumn, restCount);
  926. currentLine.RemoveRange (currentColumn, restCount);
  927. model.AddLine (currentRow + 1, rest);
  928. currentRow++;
  929. bool fullNeedsDisplay = false;
  930. if (currentRow >= topRow + Frame.Height) {
  931. topRow++;
  932. fullNeedsDisplay = true;
  933. }
  934. currentColumn = 0;
  935. if (currentColumn < leftColumn) {
  936. fullNeedsDisplay = true;
  937. leftColumn = 0;
  938. }
  939. if (fullNeedsDisplay)
  940. SetNeedsDisplay ();
  941. else
  942. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  943. break;
  944. case Key.CtrlMask | Key.End:
  945. MoveEnd ();
  946. break;
  947. case Key.CtrlMask | Key.Home:
  948. MoveHome ();
  949. break;
  950. default:
  951. // Ignore control characters and other special keys
  952. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  953. return false;
  954. //So that special keys like tab can be processed
  955. if (isReadOnly)
  956. return true;
  957. Insert ((uint)kb.Key);
  958. currentColumn++;
  959. if (currentColumn >= leftColumn + Frame.Width) {
  960. leftColumn++;
  961. SetNeedsDisplay ();
  962. }
  963. PositionCursor ();
  964. return true;
  965. }
  966. return true;
  967. }
  968. private void MoveUp ()
  969. {
  970. if (currentRow > 0) {
  971. if (columnTrack == -1)
  972. columnTrack = currentColumn;
  973. currentRow--;
  974. if (currentRow < topRow) {
  975. topRow--;
  976. SetNeedsDisplay ();
  977. }
  978. TrackColumn ();
  979. PositionCursor ();
  980. }
  981. }
  982. private void MoveDown ()
  983. {
  984. if (currentRow + 1 < model.Count) {
  985. if (columnTrack == -1)
  986. columnTrack = currentColumn;
  987. currentRow++;
  988. if (currentRow >= topRow + Frame.Height) {
  989. topRow++;
  990. SetNeedsDisplay ();
  991. }
  992. TrackColumn ();
  993. PositionCursor ();
  994. }
  995. }
  996. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  997. {
  998. if (col < 0 || row < 0)
  999. yield break;
  1000. if (row >= model.Count)
  1001. yield break;
  1002. var line = GetCurrentLine ();
  1003. if (col >= line.Count)
  1004. yield break;
  1005. while (row < model.Count) {
  1006. for (int c = col; c < line.Count; c++) {
  1007. yield return (c, row, line [c]);
  1008. }
  1009. col = 0;
  1010. row++;
  1011. line = GetCurrentLine ();
  1012. }
  1013. }
  1014. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  1015. /// <summary>
  1016. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  1017. /// </summary>
  1018. public void MoveEnd ()
  1019. {
  1020. currentRow = model.Count - 1;
  1021. TrackColumn ();
  1022. PositionCursor ();
  1023. }
  1024. /// <summary>
  1025. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  1026. /// </summary>
  1027. public void MoveHome ()
  1028. {
  1029. currentRow = 0;
  1030. TrackColumn ();
  1031. PositionCursor ();
  1032. }
  1033. bool MoveNext (ref int col, ref int row, out Rune rune)
  1034. {
  1035. var line = model.GetLine (row);
  1036. if (col + 1 < line.Count) {
  1037. col++;
  1038. rune = line [col];
  1039. return true;
  1040. }
  1041. while (row + 1 < model.Count) {
  1042. col = 0;
  1043. row++;
  1044. line = model.GetLine (row);
  1045. if (line.Count > 0) {
  1046. rune = line [0];
  1047. return true;
  1048. }
  1049. }
  1050. rune = 0;
  1051. return false;
  1052. }
  1053. bool MovePrev (ref int col, ref int row, out Rune rune)
  1054. {
  1055. var line = model.GetLine (row);
  1056. if (col > 0) {
  1057. col--;
  1058. rune = line [col];
  1059. return true;
  1060. }
  1061. if (row == 0) {
  1062. rune = 0;
  1063. return false;
  1064. }
  1065. while (row > 0) {
  1066. row--;
  1067. line = model.GetLine (row);
  1068. col = line.Count - 1;
  1069. if (col >= 0) {
  1070. rune = line [col];
  1071. return true;
  1072. }
  1073. }
  1074. rune = 0;
  1075. return false;
  1076. }
  1077. (int col, int row)? WordForward (int fromCol, int fromRow)
  1078. {
  1079. var col = fromCol;
  1080. var row = fromRow;
  1081. var line = GetCurrentLine ();
  1082. var rune = RuneAt (col, row);
  1083. var srow = row;
  1084. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  1085. while (MoveNext (ref col, ref row, out rune)) {
  1086. if (Rune.IsLetterOrDigit (rune))
  1087. break;
  1088. }
  1089. while (MoveNext (ref col, ref row, out rune)) {
  1090. if (!Rune.IsLetterOrDigit (rune))
  1091. break;
  1092. }
  1093. } else {
  1094. while (MoveNext (ref col, ref row, out rune)) {
  1095. if (!Rune.IsLetterOrDigit (rune))
  1096. break;
  1097. }
  1098. }
  1099. if (fromCol != col || fromRow != row)
  1100. return (col, row);
  1101. return null;
  1102. }
  1103. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1104. {
  1105. if (fromRow == 0 && fromCol == 0)
  1106. return null;
  1107. var col = fromCol;
  1108. var row = fromRow;
  1109. var line = GetCurrentLine ();
  1110. var rune = RuneAt (col, row);
  1111. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1112. while (MovePrev (ref col, ref row, out rune)) {
  1113. if (Rune.IsLetterOrDigit (rune))
  1114. break;
  1115. }
  1116. while (MovePrev (ref col, ref row, out rune)) {
  1117. if (!Rune.IsLetterOrDigit (rune))
  1118. break;
  1119. }
  1120. } else {
  1121. while (MovePrev (ref col, ref row, out rune)) {
  1122. if (!Rune.IsLetterOrDigit (rune))
  1123. break;
  1124. }
  1125. }
  1126. if (fromCol != col || fromRow != row)
  1127. return (col, row);
  1128. return null;
  1129. }
  1130. ///<inheritdoc/>
  1131. public override bool MouseEvent (MouseEvent ev)
  1132. {
  1133. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  1134. !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)) {
  1135. return false;
  1136. }
  1137. if (!CanFocus) {
  1138. return true;
  1139. }
  1140. if (!HasFocus) {
  1141. SetFocus ();
  1142. }
  1143. if (ev.Flags == MouseFlags.Button1Clicked) {
  1144. if (model.Count > 0) {
  1145. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1146. if (ev.Y > maxCursorPositionableLine) {
  1147. currentRow = maxCursorPositionableLine;
  1148. } else {
  1149. currentRow = ev.Y + topRow;
  1150. }
  1151. var r = GetCurrentLine ();
  1152. if (ev.X - leftColumn >= r.Count)
  1153. currentColumn = r.Count - leftColumn;
  1154. else
  1155. currentColumn = ev.X - leftColumn;
  1156. }
  1157. PositionCursor ();
  1158. } else if (ev.Flags == MouseFlags.WheeledDown) {
  1159. lastWasKill = false;
  1160. MoveDown ();
  1161. } else if (ev.Flags == MouseFlags.WheeledUp) {
  1162. lastWasKill = false;
  1163. MoveUp ();
  1164. }
  1165. return true;
  1166. }
  1167. }
  1168. }