2
0

TextView.cs 31 KB

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