TextView.cs 120 KB

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