TextView.cs 97 KB

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