TextView.cs 30 KB

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