TextView.cs 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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. var col = 0;
  393. if (line.Count > 0) {
  394. retreat = Math.Max ((SpecialRune (line [Math.Max (CurrentColumn - leftColumn - 1, 0)])
  395. ? 1 : 0), 0);
  396. for (int idx = leftColumn < 0 ? 0 : leftColumn; idx < line.Count; idx++) {
  397. if (idx == CurrentColumn)
  398. break;
  399. var cols = Rune.ColumnWidth (line [idx]);
  400. col += cols - 1;
  401. }
  402. }
  403. Move (CurrentColumn - leftColumn - retreat + col, CurrentRow - topRow);
  404. }
  405. void ClearRegion (int left, int top, int right, int bottom)
  406. {
  407. for (int row = top; row < bottom; row++) {
  408. Move (left, row);
  409. for (int col = left; col < right; col++)
  410. AddRune (col, row, ' ');
  411. }
  412. }
  413. void ColorNormal ()
  414. {
  415. Driver.SetAttribute (ColorScheme.Normal);
  416. }
  417. void ColorSelection ()
  418. {
  419. if (HasFocus)
  420. Driver.SetAttribute (ColorScheme.Focus);
  421. else
  422. Driver.SetAttribute (ColorScheme.Normal);
  423. }
  424. bool isReadOnly = false;
  425. /// <summary>
  426. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  427. /// </summary>
  428. /// <value>Boolean value(Default false)</value>
  429. public bool ReadOnly {
  430. get => isReadOnly;
  431. set {
  432. isReadOnly = value;
  433. }
  434. }
  435. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  436. void GetEncodedRegionBounds (out long start, out long end)
  437. {
  438. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  439. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  440. if (selection > point) {
  441. start = point;
  442. end = selection;
  443. } else {
  444. start = selection;
  445. end = point;
  446. }
  447. }
  448. bool PointInSelection (int col, int row)
  449. {
  450. long start, end;
  451. GetEncodedRegionBounds (out start, out end);
  452. var q = ((long)(uint)row << 32) | (uint)col;
  453. return q >= start && q <= end;
  454. }
  455. //
  456. // Returns a ustring with the text in the selected
  457. // region.
  458. //
  459. ustring GetRegion ()
  460. {
  461. long start, end;
  462. GetEncodedRegionBounds (out start, out end);
  463. int startRow = (int)(start >> 32);
  464. var maxrow = ((int)(end >> 32));
  465. int startCol = (int)(start & 0xffffffff);
  466. var endCol = (int)(end & 0xffffffff);
  467. var line = model.GetLine (startRow);
  468. if (startRow == maxrow)
  469. return StringFromRunes (line.GetRange (startCol, endCol));
  470. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  471. for (int row = startRow + 1; row < maxrow; row++) {
  472. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  473. }
  474. line = model.GetLine (maxrow);
  475. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  476. return res;
  477. }
  478. //
  479. // Clears the contents of the selected region
  480. //
  481. void ClearRegion ()
  482. {
  483. long start, end;
  484. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  485. GetEncodedRegionBounds (out start, out end);
  486. int startRow = (int)(start >> 32);
  487. var maxrow = ((int)(end >> 32));
  488. int startCol = (int)(start & 0xffffffff);
  489. var endCol = (int)(end & 0xffffffff);
  490. var line = model.GetLine (startRow);
  491. if (startRow == maxrow) {
  492. line.RemoveRange (startCol, endCol - startCol);
  493. currentColumn = startCol;
  494. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  495. return;
  496. }
  497. line.RemoveRange (startCol, line.Count - startCol);
  498. var line2 = model.GetLine (maxrow);
  499. line.AddRange (line2.Skip (endCol));
  500. for (int row = startRow + 1; row <= maxrow; row++) {
  501. model.RemoveLine (startRow + 1);
  502. }
  503. if (currentEncoded == end) {
  504. currentRow -= maxrow - (startRow);
  505. }
  506. currentColumn = startCol;
  507. SetNeedsDisplay ();
  508. }
  509. ///<inheritdoc/>
  510. public override void Redraw (Rect bounds)
  511. {
  512. ColorNormal ();
  513. int bottom = bounds.Bottom;
  514. int right = bounds.Right;
  515. for (int row = bounds.Top; row < bottom; row++) {
  516. int textLine = topRow + row;
  517. if (textLine >= model.Count) {
  518. ColorNormal ();
  519. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  520. continue;
  521. }
  522. var line = model.GetLine (textLine);
  523. int lineRuneCount = line.Count;
  524. if (line.Count < bounds.Left) {
  525. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  526. continue;
  527. }
  528. Move (bounds.Left, row);
  529. var col = 0;
  530. for (int idx = bounds.Left; idx < right; idx++) {
  531. var lineCol = leftColumn + idx;
  532. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  533. var cols = Rune.ColumnWidth (rune);
  534. if (selecting && PointInSelection (idx, row)) {
  535. ColorSelection ();
  536. } else {
  537. ColorNormal ();
  538. }
  539. if (!SpecialRune (rune)) {
  540. AddRune (col, row, rune);
  541. }
  542. col = TextField.SetCol (col, bounds.Right, cols);
  543. }
  544. }
  545. PositionCursor ();
  546. }
  547. bool SpecialRune (Rune rune)
  548. {
  549. switch (rune) {
  550. case (uint)Key.Enter:
  551. case 0xd:
  552. return true;
  553. default:
  554. return false; }
  555. }
  556. ///<inheritdoc/>
  557. public override bool CanFocus {
  558. get => base.CanFocus;
  559. set { base.CanFocus = value; }
  560. }
  561. void SetClipboard (ustring text)
  562. {
  563. Clipboard.Contents = text;
  564. }
  565. void AppendClipboard (ustring text)
  566. {
  567. Clipboard.Contents = Clipboard.Contents + text;
  568. }
  569. void Insert (Rune rune)
  570. {
  571. var line = GetCurrentLine ();
  572. line.Insert (currentColumn, rune);
  573. var prow = currentRow - topRow;
  574. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  575. }
  576. ustring StringFromRunes (List<Rune> runes)
  577. {
  578. if (runes == null)
  579. throw new ArgumentNullException (nameof (runes));
  580. int size = 0;
  581. foreach (var rune in runes) {
  582. size += Utf8.RuneLen (rune);
  583. }
  584. var encoded = new byte [size];
  585. int offset = 0;
  586. foreach (var rune in runes) {
  587. offset += Utf8.EncodeRune (rune, encoded, offset);
  588. }
  589. return ustring.Make (encoded);
  590. }
  591. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  592. void InsertText (ustring text)
  593. {
  594. var lines = TextModel.StringToRunes (text);
  595. if (lines.Count == 0)
  596. return;
  597. var line = GetCurrentLine ();
  598. // Optmize single line
  599. if (lines.Count == 1) {
  600. line.InsertRange (currentColumn, lines [0]);
  601. currentColumn += lines [0].Count;
  602. if (currentColumn - leftColumn > Frame.Width)
  603. leftColumn = currentColumn - Frame.Width + 1;
  604. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  605. return;
  606. }
  607. // Keep a copy of the rest of the line
  608. var restCount = line.Count - currentColumn;
  609. var rest = line.GetRange (currentColumn, restCount);
  610. line.RemoveRange (currentColumn, restCount);
  611. // First line is inserted at the current location, the rest is appended
  612. line.InsertRange (currentColumn, lines [0]);
  613. for (int i = 1; i < lines.Count; i++)
  614. model.AddLine (currentRow + i, lines [i]);
  615. var last = model.GetLine (currentRow + lines.Count - 1);
  616. var lastp = last.Count;
  617. last.InsertRange (last.Count, rest);
  618. // Now adjjust column and row positions
  619. currentRow += lines.Count - 1;
  620. currentColumn = lastp;
  621. if (currentRow - topRow > Frame.Height) {
  622. topRow = currentRow - Frame.Height + 1;
  623. if (topRow < 0)
  624. topRow = 0;
  625. }
  626. if (currentColumn < leftColumn)
  627. leftColumn = currentColumn;
  628. if (currentColumn - leftColumn >= Frame.Width)
  629. leftColumn = currentColumn - Frame.Width + 1;
  630. SetNeedsDisplay ();
  631. }
  632. // The column we are tracking, or -1 if we are not tracking any column
  633. int columnTrack = -1;
  634. // Tries to snap the cursor to the tracking column
  635. void TrackColumn ()
  636. {
  637. // Now track the column
  638. var line = GetCurrentLine ();
  639. if (line.Count < columnTrack)
  640. currentColumn = line.Count;
  641. else if (columnTrack != -1)
  642. currentColumn = columnTrack;
  643. else if (currentColumn > line.Count)
  644. currentColumn = line.Count;
  645. Adjust ();
  646. }
  647. void Adjust ()
  648. {
  649. bool need = false;
  650. if (currentColumn < leftColumn) {
  651. currentColumn = leftColumn;
  652. need = true;
  653. }
  654. if (currentColumn - leftColumn > Frame.Width) {
  655. leftColumn = currentColumn - Frame.Width + 1;
  656. need = true;
  657. }
  658. if (currentRow < topRow) {
  659. topRow = currentRow;
  660. need = true;
  661. }
  662. if (currentRow - topRow > Frame.Height) {
  663. topRow = currentRow - Frame.Height + 1;
  664. need = true;
  665. }
  666. if (need)
  667. SetNeedsDisplay ();
  668. else
  669. PositionCursor ();
  670. }
  671. /// <summary>
  672. /// Will scroll the <see cref="TextView"/> to display the specified row at the top
  673. /// </summary>
  674. /// <param name="row">Row that should be displayed at the top, if the value is negative it will be reset to zero</param>
  675. public void ScrollTo (int row)
  676. {
  677. if (row < 0)
  678. row = 0;
  679. topRow = row > model.Count ? model.Count - 1 : row;
  680. SetNeedsDisplay ();
  681. }
  682. bool lastWasKill;
  683. ///<inheritdoc/>
  684. public override bool ProcessKey (KeyEvent kb)
  685. {
  686. int restCount;
  687. List<Rune> rest;
  688. // Handle some state here - whether the last command was a kill
  689. // operation and the column tracking (up/down)
  690. switch (kb.Key) {
  691. case Key.N | Key.CtrlMask:
  692. case Key.CursorDown:
  693. case Key.P | Key.CtrlMask:
  694. case Key.CursorUp:
  695. lastWasKill = false;
  696. break;
  697. case Key.K | Key.CtrlMask:
  698. break;
  699. default:
  700. lastWasKill = false;
  701. columnTrack = -1;
  702. break;
  703. }
  704. // Dispatch the command.
  705. switch (kb.Key) {
  706. case Key.PageDown:
  707. case Key.V | Key.CtrlMask:
  708. int nPageDnShift = Frame.Height - 1;
  709. if (currentRow < model.Count) {
  710. if (columnTrack == -1)
  711. columnTrack = currentColumn;
  712. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  713. if (topRow < currentRow - nPageDnShift) {
  714. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  715. SetNeedsDisplay ();
  716. }
  717. TrackColumn ();
  718. PositionCursor ();
  719. }
  720. break;
  721. case Key.PageUp:
  722. case ((int)'v' + Key.AltMask):
  723. int nPageUpShift = Frame.Height - 1;
  724. if (currentRow > 0) {
  725. if (columnTrack == -1)
  726. columnTrack = currentColumn;
  727. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  728. if (currentRow < topRow) {
  729. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  730. SetNeedsDisplay ();
  731. }
  732. TrackColumn ();
  733. PositionCursor ();
  734. }
  735. break;
  736. case Key.N | Key.CtrlMask:
  737. case Key.CursorDown:
  738. MoveDown ();
  739. break;
  740. case Key.P | Key.CtrlMask:
  741. case Key.CursorUp:
  742. MoveUp ();
  743. break;
  744. case Key.F | Key.CtrlMask:
  745. case Key.CursorRight:
  746. var currentLine = GetCurrentLine ();
  747. if (currentColumn < currentLine.Count) {
  748. currentColumn++;
  749. if (currentColumn >= leftColumn + Frame.Width) {
  750. leftColumn++;
  751. SetNeedsDisplay ();
  752. }
  753. PositionCursor ();
  754. } else {
  755. if (currentRow + 1 < model.Count) {
  756. currentRow++;
  757. currentColumn = 0;
  758. leftColumn = 0;
  759. if (currentRow >= topRow + Frame.Height) {
  760. topRow++;
  761. }
  762. SetNeedsDisplay ();
  763. PositionCursor ();
  764. }
  765. break;
  766. }
  767. break;
  768. case Key.B | Key.CtrlMask:
  769. case Key.CursorLeft:
  770. if (currentColumn > 0) {
  771. currentColumn--;
  772. if (currentColumn < leftColumn) {
  773. leftColumn--;
  774. SetNeedsDisplay ();
  775. }
  776. PositionCursor ();
  777. } else {
  778. if (currentRow > 0) {
  779. currentRow--;
  780. if (currentRow < topRow) {
  781. topRow--;
  782. SetNeedsDisplay ();
  783. }
  784. currentLine = GetCurrentLine ();
  785. currentColumn = currentLine.Count;
  786. int prev = leftColumn;
  787. leftColumn = currentColumn - Frame.Width + 1;
  788. if (leftColumn < 0)
  789. leftColumn = 0;
  790. if (prev != leftColumn)
  791. SetNeedsDisplay ();
  792. PositionCursor ();
  793. }
  794. }
  795. break;
  796. case Key.Delete:
  797. case Key.Backspace:
  798. if (isReadOnly)
  799. break;
  800. if (currentColumn > 0) {
  801. // Delete backwards
  802. currentLine = GetCurrentLine ();
  803. currentLine.RemoveAt (currentColumn - 1);
  804. currentColumn--;
  805. if (currentColumn < leftColumn) {
  806. leftColumn--;
  807. SetNeedsDisplay ();
  808. } else
  809. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  810. } else {
  811. // Merges the current line with the previous one.
  812. if (currentRow == 0)
  813. return true;
  814. var prowIdx = currentRow - 1;
  815. var prevRow = model.GetLine (prowIdx);
  816. var prevCount = prevRow.Count;
  817. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  818. model.RemoveLine (currentRow);
  819. currentRow--;
  820. currentColumn = prevCount;
  821. leftColumn = currentColumn - Frame.Width + 1;
  822. if (leftColumn < 0)
  823. leftColumn = 0;
  824. SetNeedsDisplay ();
  825. }
  826. break;
  827. // Home, C-A
  828. case Key.Home:
  829. case Key.A | Key.CtrlMask:
  830. currentColumn = 0;
  831. if (currentColumn < leftColumn) {
  832. leftColumn = 0;
  833. SetNeedsDisplay ();
  834. } else
  835. PositionCursor ();
  836. break;
  837. case Key.DeleteChar:
  838. case Key.D | Key.CtrlMask: // Delete
  839. if (isReadOnly)
  840. break;
  841. currentLine = GetCurrentLine ();
  842. if (currentColumn == currentLine.Count) {
  843. if (currentRow + 1 == model.Count)
  844. break;
  845. var nextLine = model.GetLine (currentRow + 1);
  846. currentLine.AddRange (nextLine);
  847. model.RemoveLine (currentRow + 1);
  848. var sr = currentRow - topRow;
  849. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  850. } else {
  851. currentLine.RemoveAt (currentColumn);
  852. var r = currentRow - topRow;
  853. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  854. }
  855. break;
  856. case Key.End:
  857. case Key.E | Key.CtrlMask: // End
  858. currentLine = GetCurrentLine ();
  859. currentColumn = currentLine.Count;
  860. int pcol = leftColumn;
  861. leftColumn = currentColumn - Frame.Width + 1;
  862. if (leftColumn < 0)
  863. leftColumn = 0;
  864. if (pcol != leftColumn)
  865. SetNeedsDisplay ();
  866. PositionCursor ();
  867. break;
  868. case Key.K | Key.CtrlMask: // kill-to-end
  869. if (isReadOnly)
  870. break;
  871. currentLine = GetCurrentLine ();
  872. if (currentLine.Count == 0) {
  873. model.RemoveLine (currentRow);
  874. var val = ustring.Make ((Rune)'\n');
  875. if (lastWasKill)
  876. AppendClipboard (val);
  877. else
  878. SetClipboard (val);
  879. } else {
  880. restCount = currentLine.Count - currentColumn;
  881. rest = currentLine.GetRange (currentColumn, restCount);
  882. var val = StringFromRunes (rest);
  883. if (lastWasKill)
  884. AppendClipboard (val);
  885. else
  886. SetClipboard (val);
  887. currentLine.RemoveRange (currentColumn, restCount);
  888. }
  889. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  890. lastWasKill = true;
  891. break;
  892. case Key.Y | Key.CtrlMask: // Control-y, yank
  893. if (isReadOnly)
  894. break;
  895. InsertText (Clipboard.Contents);
  896. selecting = false;
  897. break;
  898. case Key.Space | Key.CtrlMask:
  899. selecting = true;
  900. selectionStartColumn = currentColumn;
  901. selectionStartRow = currentRow;
  902. break;
  903. case ((int)'w' + Key.AltMask):
  904. SetClipboard (GetRegion ());
  905. selecting = false;
  906. break;
  907. case Key.W | Key.CtrlMask:
  908. SetClipboard (GetRegion ());
  909. if (!isReadOnly)
  910. ClearRegion ();
  911. selecting = false;
  912. break;
  913. case (Key)((int)'b' + Key.AltMask):
  914. var newPos = WordBackward (currentColumn, currentRow);
  915. if (newPos.HasValue) {
  916. currentColumn = newPos.Value.col;
  917. currentRow = newPos.Value.row;
  918. }
  919. Adjust ();
  920. break;
  921. case (Key)((int)'f' + Key.AltMask):
  922. newPos = WordForward (currentColumn, currentRow);
  923. if (newPos.HasValue) {
  924. currentColumn = newPos.Value.col;
  925. currentRow = newPos.Value.row;
  926. }
  927. Adjust ();
  928. break;
  929. case Key.Enter:
  930. if (isReadOnly)
  931. break;
  932. var orow = currentRow;
  933. currentLine = GetCurrentLine ();
  934. restCount = currentLine.Count - currentColumn;
  935. rest = currentLine.GetRange (currentColumn, restCount);
  936. currentLine.RemoveRange (currentColumn, restCount);
  937. model.AddLine (currentRow + 1, rest);
  938. currentRow++;
  939. bool fullNeedsDisplay = false;
  940. if (currentRow >= topRow + Frame.Height) {
  941. topRow++;
  942. fullNeedsDisplay = true;
  943. }
  944. currentColumn = 0;
  945. if (currentColumn < leftColumn) {
  946. fullNeedsDisplay = true;
  947. leftColumn = 0;
  948. }
  949. if (fullNeedsDisplay)
  950. SetNeedsDisplay ();
  951. else
  952. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  953. break;
  954. case Key.CtrlMask | Key.End:
  955. MoveEnd ();
  956. break;
  957. case Key.CtrlMask | Key.Home:
  958. MoveHome ();
  959. break;
  960. default:
  961. // Ignore control characters and other special keys
  962. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  963. return false;
  964. //So that special keys like tab can be processed
  965. if (isReadOnly)
  966. return true;
  967. Insert ((uint)kb.Key);
  968. currentColumn++;
  969. if (currentColumn >= leftColumn + Frame.Width) {
  970. leftColumn++;
  971. SetNeedsDisplay ();
  972. }
  973. PositionCursor ();
  974. return true;
  975. }
  976. return true;
  977. }
  978. private void MoveUp ()
  979. {
  980. if (currentRow > 0) {
  981. if (columnTrack == -1)
  982. columnTrack = currentColumn;
  983. currentRow--;
  984. if (currentRow < topRow) {
  985. topRow--;
  986. SetNeedsDisplay ();
  987. }
  988. TrackColumn ();
  989. PositionCursor ();
  990. }
  991. }
  992. private void MoveDown ()
  993. {
  994. if (currentRow + 1 < model.Count) {
  995. if (columnTrack == -1)
  996. columnTrack = currentColumn;
  997. currentRow++;
  998. if (currentRow >= topRow + Frame.Height) {
  999. topRow++;
  1000. SetNeedsDisplay ();
  1001. }
  1002. TrackColumn ();
  1003. PositionCursor ();
  1004. }
  1005. }
  1006. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  1007. {
  1008. if (col < 0 || row < 0)
  1009. yield break;
  1010. if (row >= model.Count)
  1011. yield break;
  1012. var line = GetCurrentLine ();
  1013. if (col >= line.Count)
  1014. yield break;
  1015. while (row < model.Count) {
  1016. for (int c = col; c < line.Count; c++) {
  1017. yield return (c, row, line [c]);
  1018. }
  1019. col = 0;
  1020. row++;
  1021. line = GetCurrentLine ();
  1022. }
  1023. }
  1024. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  1025. /// <summary>
  1026. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  1027. /// </summary>
  1028. public void MoveEnd ()
  1029. {
  1030. currentRow = model.Count - 1;
  1031. TrackColumn ();
  1032. PositionCursor ();
  1033. }
  1034. /// <summary>
  1035. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  1036. /// </summary>
  1037. public void MoveHome ()
  1038. {
  1039. currentRow = 0;
  1040. TrackColumn ();
  1041. PositionCursor ();
  1042. }
  1043. bool MoveNext (ref int col, ref int row, out Rune rune)
  1044. {
  1045. var line = model.GetLine (row);
  1046. if (col + 1 < line.Count) {
  1047. col++;
  1048. rune = line [col];
  1049. return true;
  1050. }
  1051. while (row + 1 < model.Count) {
  1052. col = 0;
  1053. row++;
  1054. line = model.GetLine (row);
  1055. if (line.Count > 0) {
  1056. rune = line [0];
  1057. return true;
  1058. }
  1059. }
  1060. rune = 0;
  1061. return false;
  1062. }
  1063. bool MovePrev (ref int col, ref int row, out Rune rune)
  1064. {
  1065. var line = model.GetLine (row);
  1066. if (col > 0) {
  1067. col--;
  1068. rune = line [col];
  1069. return true;
  1070. }
  1071. if (row == 0) {
  1072. rune = 0;
  1073. return false;
  1074. }
  1075. while (row > 0) {
  1076. row--;
  1077. line = model.GetLine (row);
  1078. col = line.Count - 1;
  1079. if (col >= 0) {
  1080. rune = line [col];
  1081. return true;
  1082. }
  1083. }
  1084. rune = 0;
  1085. return false;
  1086. }
  1087. (int col, int row)? WordForward (int fromCol, int fromRow)
  1088. {
  1089. var col = fromCol;
  1090. var row = fromRow;
  1091. var line = GetCurrentLine ();
  1092. var rune = RuneAt (col, row);
  1093. var srow = row;
  1094. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  1095. while (MoveNext (ref col, ref row, out rune)) {
  1096. if (Rune.IsLetterOrDigit (rune))
  1097. break;
  1098. }
  1099. while (MoveNext (ref col, ref row, out rune)) {
  1100. if (!Rune.IsLetterOrDigit (rune))
  1101. break;
  1102. }
  1103. } else {
  1104. while (MoveNext (ref col, ref row, out rune)) {
  1105. if (!Rune.IsLetterOrDigit (rune))
  1106. break;
  1107. }
  1108. }
  1109. if (fromCol != col || fromRow != row)
  1110. return (col, row);
  1111. return null;
  1112. }
  1113. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1114. {
  1115. if (fromRow == 0 && fromCol == 0)
  1116. return null;
  1117. var col = fromCol;
  1118. var row = fromRow;
  1119. var line = GetCurrentLine ();
  1120. var rune = RuneAt (col, row);
  1121. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1122. while (MovePrev (ref col, ref row, out rune)) {
  1123. if (Rune.IsLetterOrDigit (rune))
  1124. break;
  1125. }
  1126. while (MovePrev (ref col, ref row, out rune)) {
  1127. if (!Rune.IsLetterOrDigit (rune))
  1128. break;
  1129. }
  1130. } else {
  1131. while (MovePrev (ref col, ref row, out rune)) {
  1132. if (!Rune.IsLetterOrDigit (rune))
  1133. break;
  1134. }
  1135. }
  1136. if (fromCol != col || fromRow != row)
  1137. return (col, row);
  1138. return null;
  1139. }
  1140. ///<inheritdoc/>
  1141. public override bool MouseEvent (MouseEvent ev)
  1142. {
  1143. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  1144. !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)) {
  1145. return false;
  1146. }
  1147. if (!CanFocus) {
  1148. return true;
  1149. }
  1150. if (!HasFocus) {
  1151. SetFocus ();
  1152. }
  1153. if (ev.Flags == MouseFlags.Button1Clicked) {
  1154. if (model.Count > 0) {
  1155. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1156. if (ev.Y > maxCursorPositionableLine) {
  1157. currentRow = maxCursorPositionableLine;
  1158. } else {
  1159. currentRow = ev.Y + topRow;
  1160. }
  1161. var r = GetCurrentLine ();
  1162. var idx = TextField.GetPointFromX (r, leftColumn, ev.X);
  1163. if (idx - leftColumn >= r.Count) {
  1164. currentColumn = r.Count - leftColumn;
  1165. } else {
  1166. currentColumn = idx - leftColumn;
  1167. }
  1168. }
  1169. PositionCursor ();
  1170. } else if (ev.Flags == MouseFlags.WheeledDown) {
  1171. lastWasKill = false;
  1172. MoveDown ();
  1173. } else if (ev.Flags == MouseFlags.WheeledUp) {
  1174. lastWasKill = false;
  1175. MoveUp ();
  1176. }
  1177. return true;
  1178. }
  1179. }
  1180. }