TextView.cs 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454
  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. /// Invoked with the unwrapped <see cref="CursorPosition"/>.
  1038. /// </summary>
  1039. public event Action<Point> UnwrappedCursorPosition;
  1040. /// <summary>
  1041. /// Provides autocomplete context menu based on suggestions at the current cursor
  1042. /// position. Populate <see cref="Autocomplete.AllSuggestions"/> to enable this feature
  1043. /// </summary>
  1044. public IAutocomplete Autocomplete { get; protected set; } = new TextViewAutocomplete ();
  1045. #if false
  1046. /// <summary>
  1047. /// Changed event, raised when the text has clicked.
  1048. /// </summary>
  1049. /// <remarks>
  1050. /// Client code can hook up to this event, it is
  1051. /// raised when the text in the entry changes.
  1052. /// </remarks>
  1053. public Action Changed;
  1054. #endif
  1055. /// <summary>
  1056. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  1057. /// </summary>
  1058. /// <remarks>
  1059. /// </remarks>
  1060. public TextView (Rect frame) : base (frame)
  1061. {
  1062. Initialize ();
  1063. }
  1064. /// <summary>
  1065. /// Initializes a <see cref="TextView"/> on the specified area,
  1066. /// with dimensions controlled with the X, Y, Width and Height properties.
  1067. /// </summary>
  1068. public TextView () : base ()
  1069. {
  1070. Initialize ();
  1071. }
  1072. void Initialize ()
  1073. {
  1074. CanFocus = true;
  1075. Used = true;
  1076. model.LinesLoaded += Model_LinesLoaded;
  1077. historyText.ChangeText += HistoryText_ChangeText;
  1078. Initialized += TextView_Initialized;
  1079. // Things this view knows how to do
  1080. AddCommand (Command.PageDown, () => { ProcessPageDown (); return true; });
  1081. AddCommand (Command.PageDownExtend, () => { ProcessPageDownExtend (); return true; });
  1082. AddCommand (Command.PageUp, () => { ProcessPageUp (); return true; });
  1083. AddCommand (Command.PageUpExtend, () => { ProcessPageUpExtend (); return true; });
  1084. AddCommand (Command.LineDown, () => { ProcessMoveDown (); return true; });
  1085. AddCommand (Command.LineDownExtend, () => { ProcessMoveDownExtend (); return true; });
  1086. AddCommand (Command.LineUp, () => { ProcessMoveUp (); return true; });
  1087. AddCommand (Command.LineUpExtend, () => { ProcessMoveUpExtend (); return true; });
  1088. AddCommand (Command.Right, () => ProcessMoveRight ());
  1089. AddCommand (Command.RightExtend, () => { ProcessMoveRightExtend (); return true; });
  1090. AddCommand (Command.Left, () => ProcessMoveLeft ());
  1091. AddCommand (Command.LeftExtend, () => { ProcessMoveLeftExtend (); return true; });
  1092. AddCommand (Command.DeleteCharLeft, () => { ProcessDeleteCharLeft (); return true; });
  1093. AddCommand (Command.StartOfLine, () => { ProcessMoveStartOfLine (); return true; });
  1094. AddCommand (Command.StartOfLineExtend, () => { ProcessMoveStartOfLineExtend (); return true; });
  1095. AddCommand (Command.DeleteCharRight, () => { ProcessDeleteCharRight (); return true; });
  1096. AddCommand (Command.EndOfLine, () => { ProcessMoveEndOfLine (); return true; });
  1097. AddCommand (Command.EndOfLineExtend, () => { ProcessMoveEndOfLineExtend (); return true; });
  1098. AddCommand (Command.CutToEndLine, () => { KillToEndOfLine (); return true; });
  1099. AddCommand (Command.CutToStartLine, () => { KillToStartOfLine (); return true; });
  1100. AddCommand (Command.Paste, () => { ProcessPaste (); return true; });
  1101. AddCommand (Command.ToggleExtend, () => { ToggleSelecting (); return true; });
  1102. AddCommand (Command.Copy, () => { ProcessCopy (); return true; });
  1103. AddCommand (Command.Cut, () => { ProcessCut (); return true; });
  1104. AddCommand (Command.WordLeft, () => { ProcessMoveWordBackward (); return true; });
  1105. AddCommand (Command.WordLeftExtend, () => { ProcessMoveWordBackwardExtend (); return true; });
  1106. AddCommand (Command.WordRight, () => { ProcessMoveWordForward (); return true; });
  1107. AddCommand (Command.WordRightExtend, () => { ProcessMoveWordForwardExtend (); return true; });
  1108. AddCommand (Command.KillWordForwards, () => { ProcessKillWordForward (); return true; });
  1109. AddCommand (Command.KillWordBackwards, () => { ProcessKillWordBackward (); return true; });
  1110. AddCommand (Command.NewLine, () => ProcessReturn ());
  1111. AddCommand (Command.BottomEnd, () => { MoveBottomEnd (); return true; });
  1112. AddCommand (Command.BottomEndExtend, () => { MoveBottomEndExtend (); return true; });
  1113. AddCommand (Command.TopHome, () => { MoveTopHome (); return true; });
  1114. AddCommand (Command.TopHomeExtend, () => { MoveTopHomeExtend (); return true; });
  1115. AddCommand (Command.SelectAll, () => { ProcessSelectAll (); return true; });
  1116. AddCommand (Command.ToggleOverwrite, () => { ProcessSetOverwrite (); return true; });
  1117. AddCommand (Command.EnableOverwrite, () => { SetOverwrite (true); return true; });
  1118. AddCommand (Command.DisableOverwrite, () => { SetOverwrite (false); return true; });
  1119. AddCommand (Command.Tab, () => ProcessTab ());
  1120. AddCommand (Command.BackTab, () => ProcessBackTab ());
  1121. AddCommand (Command.NextView, () => ProcessMoveNextView ());
  1122. AddCommand (Command.PreviousView, () => ProcessMovePreviousView ());
  1123. AddCommand (Command.Undo, () => { UndoChanges (); return true; });
  1124. AddCommand (Command.Redo, () => { RedoChanges (); return true; });
  1125. AddCommand (Command.DeleteAll, () => { DeleteAll (); return true; });
  1126. AddCommand (Command.Accept, () => {
  1127. ContextMenu.Position = new Point (CursorPosition.X - leftColumn + 2, CursorPosition.Y - topRow + 2);
  1128. ShowContextMenu ();
  1129. return true;
  1130. });
  1131. // Default keybindings for this view
  1132. AddKeyBinding (Key.PageDown, Command.PageDown);
  1133. AddKeyBinding (Key.V | Key.CtrlMask, Command.PageDown);
  1134. AddKeyBinding (Key.PageDown | Key.ShiftMask, Command.PageDownExtend);
  1135. AddKeyBinding (Key.PageUp, Command.PageUp);
  1136. AddKeyBinding (((int)'V' + Key.AltMask), Command.PageUp);
  1137. AddKeyBinding (Key.PageUp | Key.ShiftMask, Command.PageUpExtend);
  1138. AddKeyBinding (Key.N | Key.CtrlMask, Command.LineDown);
  1139. AddKeyBinding (Key.CursorDown, Command.LineDown);
  1140. AddKeyBinding (Key.CursorDown | Key.ShiftMask, Command.LineDownExtend);
  1141. AddKeyBinding (Key.P | Key.CtrlMask, Command.LineUp);
  1142. AddKeyBinding (Key.CursorUp, Command.LineUp);
  1143. AddKeyBinding (Key.CursorUp | Key.ShiftMask, Command.LineUpExtend);
  1144. AddKeyBinding (Key.F | Key.CtrlMask, Command.Right);
  1145. AddKeyBinding (Key.CursorRight, Command.Right);
  1146. AddKeyBinding (Key.CursorRight | Key.ShiftMask, Command.RightExtend);
  1147. AddKeyBinding (Key.B | Key.CtrlMask, Command.Left);
  1148. AddKeyBinding (Key.CursorLeft, Command.Left);
  1149. AddKeyBinding (Key.CursorLeft | Key.ShiftMask, Command.LeftExtend);
  1150. AddKeyBinding (Key.Delete, Command.DeleteCharLeft);
  1151. AddKeyBinding (Key.Backspace, Command.DeleteCharLeft);
  1152. AddKeyBinding (Key.Home, Command.StartOfLine);
  1153. AddKeyBinding (Key.A | Key.CtrlMask, Command.StartOfLine);
  1154. AddKeyBinding (Key.Home | Key.ShiftMask, Command.StartOfLineExtend);
  1155. AddKeyBinding (Key.DeleteChar, Command.DeleteCharRight);
  1156. AddKeyBinding (Key.D | Key.CtrlMask, Command.DeleteCharRight);
  1157. AddKeyBinding (Key.End, Command.EndOfLine);
  1158. AddKeyBinding (Key.E | Key.CtrlMask, Command.EndOfLine);
  1159. AddKeyBinding (Key.End | Key.ShiftMask, Command.EndOfLineExtend);
  1160. AddKeyBinding (Key.K | Key.CtrlMask, Command.CutToEndLine); // kill-to-end
  1161. AddKeyBinding (Key.DeleteChar | Key.CtrlMask | Key.ShiftMask, Command.CutToEndLine); // kill-to-end
  1162. AddKeyBinding (Key.K | Key.AltMask, Command.CutToStartLine); // kill-to-start
  1163. AddKeyBinding (Key.Backspace | Key.CtrlMask | Key.ShiftMask, Command.CutToStartLine); // kill-to-start
  1164. AddKeyBinding (Key.Y | Key.CtrlMask, Command.Paste); // Control-y, yank
  1165. AddKeyBinding (Key.Space | Key.CtrlMask, Command.ToggleExtend);
  1166. AddKeyBinding (((int)'C' + Key.AltMask), Command.Copy);
  1167. AddKeyBinding (Key.C | Key.CtrlMask, Command.Copy);
  1168. AddKeyBinding (((int)'W' + Key.AltMask), Command.Cut);
  1169. AddKeyBinding (Key.W | Key.CtrlMask, Command.Cut);
  1170. AddKeyBinding (Key.X | Key.CtrlMask, Command.Cut);
  1171. AddKeyBinding (Key.CursorLeft | Key.CtrlMask, Command.WordLeft);
  1172. AddKeyBinding ((Key)((int)'B' + Key.AltMask), Command.WordLeft);
  1173. AddKeyBinding (Key.CursorLeft | Key.CtrlMask | Key.ShiftMask, Command.WordLeftExtend);
  1174. AddKeyBinding (Key.CursorRight | Key.CtrlMask, Command.WordRight);
  1175. AddKeyBinding ((Key)((int)'F' + Key.AltMask), Command.WordRight);
  1176. AddKeyBinding (Key.CursorRight | Key.CtrlMask | Key.ShiftMask, Command.WordRightExtend);
  1177. AddKeyBinding (Key.DeleteChar | Key.CtrlMask, Command.KillWordForwards); // kill-word-forwards
  1178. AddKeyBinding (Key.Backspace | Key.CtrlMask, Command.KillWordBackwards); // kill-word-backwards
  1179. AddKeyBinding (Key.Enter, Command.NewLine);
  1180. AddKeyBinding (Key.End | Key.CtrlMask, Command.BottomEnd);
  1181. AddKeyBinding (Key.End | Key.CtrlMask | Key.ShiftMask, Command.BottomEndExtend);
  1182. AddKeyBinding (Key.Home | Key.CtrlMask, Command.TopHome);
  1183. AddKeyBinding (Key.Home | Key.CtrlMask | Key.ShiftMask, Command.TopHomeExtend);
  1184. AddKeyBinding (Key.T | Key.CtrlMask, Command.SelectAll);
  1185. AddKeyBinding (Key.InsertChar, Command.ToggleOverwrite);
  1186. AddKeyBinding (Key.Tab, Command.Tab);
  1187. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.BackTab);
  1188. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextView);
  1189. AddKeyBinding (Application.AlternateForwardKey, Command.NextView);
  1190. AddKeyBinding (Key.Tab | Key.CtrlMask | Key.ShiftMask, Command.PreviousView);
  1191. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousView);
  1192. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Undo);
  1193. AddKeyBinding (Key.R | Key.CtrlMask, Command.Redo);
  1194. AddKeyBinding (Key.G | Key.CtrlMask, Command.DeleteAll);
  1195. AddKeyBinding (Key.D | Key.CtrlMask | Key.ShiftMask, Command.DeleteAll);
  1196. currentCulture = Thread.CurrentThread.CurrentUICulture;
  1197. ContextMenu = new ContextMenu () { MenuItems = BuildContextMenuBarItem () };
  1198. ContextMenu.KeyChanged += ContextMenu_KeyChanged;
  1199. AddKeyBinding (ContextMenu.Key, Command.Accept);
  1200. }
  1201. private MenuBarItem BuildContextMenuBarItem ()
  1202. {
  1203. return new MenuBarItem (new MenuItem [] {
  1204. new MenuItem (Strings.ctxSelectAll, "", () => SelectAll (), null, null, GetKeyFromCommand (Command.SelectAll)),
  1205. new MenuItem (Strings.ctxDeleteAll, "", () => DeleteAll (), null, null, GetKeyFromCommand (Command.DeleteAll)),
  1206. new MenuItem (Strings.ctxCopy, "", () => Copy (), null, null, GetKeyFromCommand (Command.Copy)),
  1207. new MenuItem (Strings.ctxCut, "", () => Cut (), null, null, GetKeyFromCommand (Command.Cut)),
  1208. new MenuItem (Strings.ctxPaste, "", () => Paste (), null, null, GetKeyFromCommand (Command.Paste)),
  1209. new MenuItem (Strings.ctxUndo, "", () => UndoChanges (), null, null, GetKeyFromCommand (Command.Undo)),
  1210. new MenuItem (Strings.ctxRedo, "", () => RedoChanges (), null, null, GetKeyFromCommand (Command.Redo)),
  1211. });
  1212. }
  1213. private void ContextMenu_KeyChanged (Key obj)
  1214. {
  1215. ReplaceKeyBinding (obj, ContextMenu.Key);
  1216. }
  1217. private void Model_LinesLoaded ()
  1218. {
  1219. historyText.Clear (Text);
  1220. }
  1221. private void HistoryText_ChangeText (HistoryText.HistoryTextItem obj)
  1222. {
  1223. SetWrapModel ();
  1224. var startLine = obj.CursorPosition.Y;
  1225. if (obj.RemovedOnAdded != null) {
  1226. int offset;
  1227. if (obj.IsUndoing) {
  1228. offset = Math.Max (obj.RemovedOnAdded.Lines.Count - obj.Lines.Count, 1);
  1229. } else {
  1230. offset = obj.RemovedOnAdded.Lines.Count - 1;
  1231. }
  1232. for (int i = 0; i < offset; i++) {
  1233. if (Lines > obj.RemovedOnAdded.CursorPosition.Y) {
  1234. model.RemoveLine (obj.RemovedOnAdded.CursorPosition.Y);
  1235. } else {
  1236. break;
  1237. }
  1238. }
  1239. }
  1240. for (int i = 0; i < obj.Lines.Count; i++) {
  1241. if (i == 0) {
  1242. model.ReplaceLine (startLine, obj.Lines [i]);
  1243. } else if ((obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Removed)
  1244. || !obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Added) {
  1245. model.AddLine (startLine, obj.Lines [i]);
  1246. } else if (Lines > obj.CursorPosition.Y + 1) {
  1247. model.RemoveLine (obj.CursorPosition.Y + 1);
  1248. }
  1249. startLine++;
  1250. }
  1251. CursorPosition = obj.FinalCursorPosition;
  1252. UpdateWrapModel ();
  1253. Adjust ();
  1254. }
  1255. void TextView_Initialized (object sender, EventArgs e)
  1256. {
  1257. Autocomplete.HostControl = this;
  1258. Application.Top.AlternateForwardKeyChanged += Top_AlternateForwardKeyChanged;
  1259. Application.Top.AlternateBackwardKeyChanged += Top_AlternateBackwardKeyChanged;
  1260. }
  1261. void Top_AlternateBackwardKeyChanged (Key obj)
  1262. {
  1263. ReplaceKeyBinding (obj, Application.AlternateBackwardKey);
  1264. }
  1265. void Top_AlternateForwardKeyChanged (Key obj)
  1266. {
  1267. ReplaceKeyBinding (obj, Application.AlternateForwardKey);
  1268. }
  1269. /// <summary>
  1270. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry,
  1271. /// so new input should be appended at the cursor position, rather than clearing the entry
  1272. /// </summary>
  1273. public bool Used { get; set; }
  1274. void ResetPosition ()
  1275. {
  1276. topRow = leftColumn = currentRow = currentColumn = 0;
  1277. StopSelecting ();
  1278. ResetCursorVisibility ();
  1279. }
  1280. /// <summary>
  1281. /// Sets or gets the text in the <see cref="TextView"/>.
  1282. /// </summary>
  1283. /// <remarks>
  1284. /// </remarks>
  1285. public override ustring Text {
  1286. get {
  1287. if (wordWrap) {
  1288. return wrapManager.Model.ToString ();
  1289. } else {
  1290. return model.ToString ();
  1291. }
  1292. }
  1293. set {
  1294. ResetPosition ();
  1295. model.LoadString (value);
  1296. if (wordWrap) {
  1297. wrapManager = new WordWrapManager (model);
  1298. model = wrapManager.WrapModel (frameWidth, out _, out _, out _, out _);
  1299. }
  1300. TextChanged?.Invoke ();
  1301. SetNeedsDisplay ();
  1302. historyText.Clear (Text);
  1303. }
  1304. }
  1305. ///<inheritdoc/>
  1306. public override Rect Frame {
  1307. get => base.Frame;
  1308. set {
  1309. base.Frame = value;
  1310. WrapTextModel ();
  1311. Adjust ();
  1312. }
  1313. }
  1314. void WrapTextModel ()
  1315. {
  1316. if (wordWrap && wrapManager != null) {
  1317. model = wrapManager.WrapModel (frameWidth,
  1318. out int nRow, out int nCol,
  1319. out int nStartRow, out int nStartCol,
  1320. currentRow, currentColumn,
  1321. selectionStartRow, selectionStartColumn,
  1322. tabWidth, preserveTrailingSpaces: true);
  1323. currentRow = nRow;
  1324. currentColumn = nCol;
  1325. selectionStartRow = nStartRow;
  1326. selectionStartColumn = nStartCol;
  1327. SetNeedsDisplay ();
  1328. }
  1329. }
  1330. int frameWidth => Math.Max (Frame.Width - (RightOffset != 0 ? 2 : 1), 0);
  1331. /// <summary>
  1332. /// Gets or sets the top row.
  1333. /// </summary>
  1334. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  1335. /// <summary>
  1336. /// Gets or sets the left column.
  1337. /// </summary>
  1338. public int LeftColumn {
  1339. get => leftColumn;
  1340. set {
  1341. if (value > 0 && wordWrap)
  1342. return;
  1343. leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0);
  1344. }
  1345. }
  1346. /// <summary>
  1347. /// Gets the maximum visible length line.
  1348. /// </summary>
  1349. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height, TabWidth);
  1350. /// <summary>
  1351. /// Gets the number of lines.
  1352. /// </summary>
  1353. public int Lines => model.Count;
  1354. /// <summary>
  1355. /// Sets or gets the current cursor position.
  1356. /// </summary>
  1357. public Point CursorPosition {
  1358. get => new Point (currentColumn, currentRow);
  1359. set {
  1360. var line = model.GetLine (Math.Max (Math.Min (value.Y, model.Count - 1), 0));
  1361. currentColumn = value.X < 0 ? 0 : value.X > line.Count ? line.Count : value.X;
  1362. currentRow = value.Y < 0 ? 0 : value.Y > model.Count - 1
  1363. ? Math.Max (model.Count - 1, 0) : value.Y;
  1364. SetNeedsDisplay ();
  1365. Adjust ();
  1366. }
  1367. }
  1368. /// <summary>
  1369. /// Start column position of the selected text.
  1370. /// </summary>
  1371. public int SelectionStartColumn {
  1372. get => selectionStartColumn;
  1373. set {
  1374. var line = model.GetLine (currentRow);
  1375. selectionStartColumn = value < 0 ? 0 : value > line.Count ? line.Count : value;
  1376. selecting = true;
  1377. SetNeedsDisplay ();
  1378. Adjust ();
  1379. }
  1380. }
  1381. /// <summary>
  1382. /// Start row position of the selected text.
  1383. /// </summary>
  1384. public int SelectionStartRow {
  1385. get => selectionStartRow;
  1386. set {
  1387. selectionStartRow = value < 0 ? 0 : value > model.Count - 1
  1388. ? Math.Max (model.Count - 1, 0) : value;
  1389. selecting = true;
  1390. SetNeedsDisplay ();
  1391. Adjust ();
  1392. }
  1393. }
  1394. /// <summary>
  1395. /// The selected text.
  1396. /// </summary>
  1397. public ustring SelectedText {
  1398. get {
  1399. if (!selecting || (model.Count == 1 && model.GetLine (0).Count == 0)) {
  1400. return ustring.Empty;
  1401. }
  1402. return GetSelectedRegion ();
  1403. }
  1404. }
  1405. /// <summary>
  1406. /// Length of the selected text.
  1407. /// </summary>
  1408. public int SelectedLength => GetSelectedLength ();
  1409. /// <summary>
  1410. /// Get or sets the selecting.
  1411. /// </summary>
  1412. public bool Selecting {
  1413. get => selecting;
  1414. set => selecting = value;
  1415. }
  1416. /// <summary>
  1417. /// Allows word wrap the to fit the available container width.
  1418. /// </summary>
  1419. public bool WordWrap {
  1420. get => wordWrap;
  1421. set {
  1422. if (value == wordWrap) {
  1423. return;
  1424. }
  1425. if (value && !multiline) {
  1426. return;
  1427. }
  1428. wordWrap = value;
  1429. ResetPosition ();
  1430. if (wordWrap) {
  1431. wrapManager = new WordWrapManager (model);
  1432. model = wrapManager.WrapModel (frameWidth, out _, out _, out _, out _);
  1433. } else if (!wordWrap && wrapManager != null) {
  1434. model = wrapManager.Model;
  1435. }
  1436. SetNeedsDisplay ();
  1437. }
  1438. }
  1439. /// <summary>
  1440. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  1441. /// This is only needed with the keyboard navigation.
  1442. /// </summary>
  1443. public int BottomOffset {
  1444. get => bottomOffset;
  1445. set {
  1446. if (currentRow == Lines - 1 && bottomOffset > 0 && value == 0) {
  1447. topRow = Math.Max (topRow - bottomOffset, 0);
  1448. }
  1449. bottomOffset = value;
  1450. Adjust ();
  1451. }
  1452. }
  1453. /// <summary>
  1454. /// The right offset needed to use a vertical scrollbar or for another reason.
  1455. /// This is only needed with the keyboard navigation.
  1456. /// </summary>
  1457. public int RightOffset {
  1458. get => rightOffset;
  1459. set {
  1460. if (!wordWrap && currentColumn == GetCurrentLine ().Count && rightOffset > 0 && value == 0) {
  1461. leftColumn = Math.Max (leftColumn - rightOffset, 0);
  1462. }
  1463. rightOffset = value;
  1464. Adjust ();
  1465. }
  1466. }
  1467. /// <summary>
  1468. /// Gets or sets a value indicating whether pressing ENTER in a <see cref="TextView"/>
  1469. /// creates a new line of text in the view or activates the default button for the toplevel.
  1470. /// </summary>
  1471. public bool AllowsReturn {
  1472. get => allowsReturn;
  1473. set {
  1474. allowsReturn = value;
  1475. if (allowsReturn && !multiline) {
  1476. Multiline = true;
  1477. }
  1478. if (!allowsReturn && multiline) {
  1479. Multiline = false;
  1480. AllowsTab = false;
  1481. }
  1482. SetNeedsDisplay ();
  1483. }
  1484. }
  1485. /// <summary>
  1486. /// Gets or sets whether the <see cref="TextView"/> inserts a tab character into the text or ignores
  1487. /// tab input. If set to `false` and the user presses the tab key (or shift-tab) the focus will move to the
  1488. /// next view (or previous with shift-tab). The default is `true`; if the user presses the tab key, a tab
  1489. /// character will be inserted into the text.
  1490. /// </summary>
  1491. public bool AllowsTab {
  1492. get => allowsTab;
  1493. set {
  1494. allowsTab = value;
  1495. if (allowsTab && tabWidth == 0) {
  1496. tabWidth = 4;
  1497. }
  1498. if (allowsTab && !multiline) {
  1499. Multiline = true;
  1500. }
  1501. if (!allowsTab && tabWidth > 0) {
  1502. tabWidth = 0;
  1503. }
  1504. SetNeedsDisplay ();
  1505. }
  1506. }
  1507. /// <summary>
  1508. /// Gets or sets a value indicating the number of whitespace when pressing the TAB key.
  1509. /// </summary>
  1510. public int TabWidth {
  1511. get => tabWidth;
  1512. set {
  1513. tabWidth = Math.Max (value, 0);
  1514. if (tabWidth > 0 && !AllowsTab) {
  1515. AllowsTab = true;
  1516. }
  1517. SetNeedsDisplay ();
  1518. }
  1519. }
  1520. Dim savedHeight = null;
  1521. /// <summary>
  1522. /// Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.
  1523. /// </summary>
  1524. public bool Multiline {
  1525. get => multiline;
  1526. set {
  1527. multiline = value;
  1528. if (multiline && !allowsTab) {
  1529. AllowsTab = true;
  1530. }
  1531. if (multiline && !allowsReturn) {
  1532. AllowsReturn = true;
  1533. }
  1534. if (!multiline) {
  1535. AllowsReturn = false;
  1536. AllowsTab = false;
  1537. WordWrap = false;
  1538. currentColumn = 0;
  1539. currentRow = 0;
  1540. savedHeight = Height;
  1541. var lyout = LayoutStyle;
  1542. if (LayoutStyle == LayoutStyle.Computed) {
  1543. LayoutStyle = LayoutStyle.Absolute;
  1544. }
  1545. Height = 1;
  1546. LayoutStyle = lyout;
  1547. Autocomplete.PopupInsideContainer = false;
  1548. SetNeedsDisplay ();
  1549. } else if (multiline && savedHeight != null) {
  1550. var lyout = LayoutStyle;
  1551. if (LayoutStyle == LayoutStyle.Computed) {
  1552. LayoutStyle = LayoutStyle.Absolute;
  1553. }
  1554. Height = savedHeight;
  1555. LayoutStyle = lyout;
  1556. Autocomplete.PopupInsideContainer = true;
  1557. SetNeedsDisplay ();
  1558. }
  1559. }
  1560. }
  1561. /// <summary>
  1562. /// Indicates whatever the text was changed or not.
  1563. /// <see langword="true"/> if the text was changed <see langword="false"/> otherwise.
  1564. /// </summary>
  1565. public bool IsDirty => historyText.IsDirty (Text);
  1566. /// <summary>
  1567. /// Indicates whatever the text has history changes or not.
  1568. /// <see langword="true"/> if the text has history changes <see langword="false"/> otherwise.
  1569. /// </summary>
  1570. public bool HasHistoryChanges => historyText.HasHistoryChanges;
  1571. /// <summary>
  1572. /// Get the <see cref="ContextMenu"/> for this view.
  1573. /// </summary>
  1574. public ContextMenu ContextMenu { get; private set; }
  1575. int GetSelectedLength ()
  1576. {
  1577. return SelectedText.Length;
  1578. }
  1579. CursorVisibility savedCursorVisibility;
  1580. void SaveCursorVisibility ()
  1581. {
  1582. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  1583. if (savedCursorVisibility == 0) {
  1584. savedCursorVisibility = desiredCursorVisibility;
  1585. }
  1586. DesiredCursorVisibility = CursorVisibility.Invisible;
  1587. }
  1588. }
  1589. void ResetCursorVisibility ()
  1590. {
  1591. if (savedCursorVisibility != 0) {
  1592. DesiredCursorVisibility = savedCursorVisibility;
  1593. savedCursorVisibility = 0;
  1594. }
  1595. }
  1596. /// <summary>
  1597. /// Loads the contents of the file into the <see cref="TextView"/>.
  1598. /// </summary>
  1599. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  1600. /// <param name="path">Path to the file to load.</param>
  1601. public bool LoadFile (string path)
  1602. {
  1603. bool res;
  1604. try {
  1605. SetWrapModel ();
  1606. res = model.LoadFile (path);
  1607. ResetPosition ();
  1608. } catch (Exception) {
  1609. throw;
  1610. } finally {
  1611. UpdateWrapModel ();
  1612. SetNeedsDisplay ();
  1613. Adjust ();
  1614. }
  1615. return res;
  1616. }
  1617. /// <summary>
  1618. /// Loads the contents of the stream into the <see cref="TextView"/>.
  1619. /// </summary>
  1620. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  1621. /// <param name="stream">Stream to load the contents from.</param>
  1622. public void LoadStream (Stream stream)
  1623. {
  1624. model.LoadStream (stream);
  1625. ResetPosition ();
  1626. SetNeedsDisplay ();
  1627. }
  1628. /// <summary>
  1629. /// Closes the contents of the stream into the <see cref="TextView"/>.
  1630. /// </summary>
  1631. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  1632. public bool CloseFile ()
  1633. {
  1634. var res = model.CloseFile ();
  1635. ResetPosition ();
  1636. SetNeedsDisplay ();
  1637. return res;
  1638. }
  1639. /// <summary>
  1640. /// Gets the current cursor row.
  1641. /// </summary>
  1642. public int CurrentRow => currentRow;
  1643. /// <summary>
  1644. /// Gets the cursor column.
  1645. /// </summary>
  1646. /// <value>The cursor column.</value>
  1647. public int CurrentColumn => currentColumn;
  1648. /// <summary>
  1649. /// Positions the cursor on the current row and column
  1650. /// </summary>
  1651. public override void PositionCursor ()
  1652. {
  1653. if (!CanFocus || !Enabled) {
  1654. return;
  1655. }
  1656. if (selecting) {
  1657. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1658. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1659. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  1660. }
  1661. var line = model.GetLine (currentRow);
  1662. var col = 0;
  1663. if (line.Count > 0) {
  1664. for (int idx = leftColumn; idx < line.Count; idx++) {
  1665. if (idx >= currentColumn)
  1666. break;
  1667. var cols = Rune.ColumnWidth (line [idx]);
  1668. if (line [idx] == '\t') {
  1669. cols += TabWidth + 1;
  1670. }
  1671. if (!TextModel.SetCol (ref col, Frame.Width, cols)) {
  1672. col = currentColumn;
  1673. break;
  1674. }
  1675. }
  1676. }
  1677. var posX = currentColumn - leftColumn;
  1678. var posY = currentRow - topRow;
  1679. if (posX > -1 && col >= posX && posX < Frame.Width - RightOffset
  1680. && topRow <= currentRow && posY < Frame.Height - BottomOffset) {
  1681. ResetCursorVisibility ();
  1682. Move (col, currentRow - topRow);
  1683. } else {
  1684. SaveCursorVisibility ();
  1685. }
  1686. }
  1687. void ClearRegion (int left, int top, int right, int bottom)
  1688. {
  1689. for (int row = top; row < bottom; row++) {
  1690. Move (left, row);
  1691. for (int col = left; col < right; col++)
  1692. AddRune (col, row, ' ');
  1693. }
  1694. }
  1695. /// <summary>
  1696. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to <see cref="ColorScheme.Normal"/>.
  1697. /// </summary>
  1698. protected virtual void SetNormalColor ()
  1699. {
  1700. Driver.SetAttribute (GetNormalColor ());
  1701. }
  1702. /// <summary>
  1703. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1704. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1705. /// Defaults to <see cref="ColorScheme.Normal"/>.
  1706. /// </summary>
  1707. /// <param name="line"></param>
  1708. /// <param name="idx"></param>
  1709. protected virtual void SetNormalColor (List<Rune> line, int idx)
  1710. {
  1711. Driver.SetAttribute (GetNormalColor ());
  1712. }
  1713. /// <summary>
  1714. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1715. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1716. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1717. /// </summary>
  1718. /// <param name="line"></param>
  1719. /// <param name="idx"></param>
  1720. protected virtual void SetSelectionColor (List<Rune> line, int idx)
  1721. {
  1722. Driver.SetAttribute (new Attribute (ColorScheme.Focus.Background, ColorScheme.Focus.Foreground));
  1723. }
  1724. /// <summary>
  1725. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1726. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1727. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1728. /// </summary>
  1729. /// <param name="line"></param>
  1730. /// <param name="idx"></param>
  1731. protected virtual void SetReadOnlyColor (List<Rune> line, int idx)
  1732. {
  1733. Attribute attribute;
  1734. if (ColorScheme.Disabled.Foreground == ColorScheme.Focus.Background) {
  1735. attribute = new Attribute (ColorScheme.Focus.Foreground, ColorScheme.Focus.Background);
  1736. } else {
  1737. attribute = new Attribute (ColorScheme.Disabled.Foreground, ColorScheme.Focus.Background);
  1738. }
  1739. Driver.SetAttribute (attribute);
  1740. }
  1741. /// <summary>
  1742. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1743. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1744. /// Defaults to <see cref="ColorScheme.HotFocus"/>.
  1745. /// </summary>
  1746. /// <param name="line"></param>
  1747. /// <param name="idx"></param>
  1748. protected virtual void SetUsedColor (List<Rune> line, int idx)
  1749. {
  1750. Driver.SetAttribute (ColorScheme.HotFocus);
  1751. }
  1752. bool isReadOnly = false;
  1753. /// <summary>
  1754. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1755. /// </summary>
  1756. /// <value>Boolean value(Default false)</value>
  1757. public bool ReadOnly {
  1758. get => isReadOnly;
  1759. set {
  1760. if (value != isReadOnly) {
  1761. isReadOnly = value;
  1762. SetNeedsDisplay ();
  1763. Adjust ();
  1764. }
  1765. }
  1766. }
  1767. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1768. /// <summary>
  1769. /// Get / Set the wished cursor when the field is focused
  1770. /// </summary>
  1771. public CursorVisibility DesiredCursorVisibility {
  1772. get => desiredCursorVisibility;
  1773. set {
  1774. if (HasFocus) {
  1775. Application.Driver.SetCursorVisibility (value);
  1776. }
  1777. desiredCursorVisibility = value;
  1778. SetNeedsDisplay ();
  1779. }
  1780. }
  1781. ///<inheritdoc/>
  1782. public override bool OnEnter (View view)
  1783. {
  1784. //TODO: Improve it by handling read only mode of the text field
  1785. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1786. return base.OnEnter (view);
  1787. }
  1788. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1789. void GetEncodedRegionBounds (out long start, out long end,
  1790. int? startRow = null, int? startCol = null, int? cRow = null, int? cCol = null)
  1791. {
  1792. long selection;
  1793. long point;
  1794. if (startRow == null || startCol == null || cRow == null || cCol == null) {
  1795. selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1796. point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1797. } else {
  1798. selection = ((long)(uint)startRow << 32) | (uint)startCol;
  1799. point = ((long)(uint)cRow << 32) | (uint)cCol;
  1800. }
  1801. if (selection > point) {
  1802. start = point;
  1803. end = selection;
  1804. } else {
  1805. start = selection;
  1806. end = point;
  1807. }
  1808. }
  1809. bool PointInSelection (int col, int row)
  1810. {
  1811. long start, end;
  1812. GetEncodedRegionBounds (out start, out end);
  1813. var q = ((long)(uint)row << 32) | (uint)col;
  1814. return q >= start && q <= end - 1;
  1815. }
  1816. //
  1817. // Returns a ustring with the text in the selected
  1818. // region.
  1819. //
  1820. ustring GetRegion (int? sRow = null, int? sCol = null, int? cRow = null, int? cCol = null, TextModel model = null)
  1821. {
  1822. long start, end;
  1823. GetEncodedRegionBounds (out start, out end, sRow, sCol, cRow, cCol);
  1824. if (start == end) {
  1825. return ustring.Empty;
  1826. }
  1827. int startRow = (int)(start >> 32);
  1828. var maxrow = ((int)(end >> 32));
  1829. int startCol = (int)(start & 0xffffffff);
  1830. var endCol = (int)(end & 0xffffffff);
  1831. var line = model == null ? this.model.GetLine (startRow) : model.GetLine (startRow);
  1832. if (startRow == maxrow)
  1833. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1834. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1835. for (int row = startRow + 1; row < maxrow; row++) {
  1836. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (model == null
  1837. ? this.model.GetLine (row) : model.GetLine (row));
  1838. }
  1839. line = model == null ? this.model.GetLine (maxrow) : model.GetLine (maxrow);
  1840. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (line.GetRange (0, endCol));
  1841. return res;
  1842. }
  1843. //
  1844. // Clears the contents of the selected region
  1845. //
  1846. void ClearRegion ()
  1847. {
  1848. SetWrapModel ();
  1849. long start, end;
  1850. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1851. GetEncodedRegionBounds (out start, out end);
  1852. int startRow = (int)(start >> 32);
  1853. var maxrow = ((int)(end >> 32));
  1854. int startCol = (int)(start & 0xffffffff);
  1855. var endCol = (int)(end & 0xffffffff);
  1856. var line = model.GetLine (startRow);
  1857. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, new Point (startCol, startRow));
  1858. List<List<Rune>> removedLines = new List<List<Rune>> ();
  1859. if (startRow == maxrow) {
  1860. removedLines.Add (new List<Rune> (line));
  1861. line.RemoveRange (startCol, endCol - startCol);
  1862. currentColumn = startCol;
  1863. if (wordWrap) {
  1864. SetNeedsDisplay ();
  1865. } else {
  1866. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1867. }
  1868. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition, HistoryText.LineStatus.Removed);
  1869. UpdateWrapModel ();
  1870. return;
  1871. }
  1872. removedLines.Add (new List<Rune> (line));
  1873. line.RemoveRange (startCol, line.Count - startCol);
  1874. var line2 = model.GetLine (maxrow);
  1875. line.AddRange (line2.Skip (endCol));
  1876. for (int row = startRow + 1; row <= maxrow; row++) {
  1877. removedLines.Add (new List<Rune> (model.GetLine (startRow + 1)));
  1878. model.RemoveLine (startRow + 1);
  1879. }
  1880. if (currentEncoded == end) {
  1881. currentRow -= maxrow - (startRow);
  1882. }
  1883. currentColumn = startCol;
  1884. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  1885. HistoryText.LineStatus.Removed);
  1886. UpdateWrapModel ();
  1887. SetNeedsDisplay ();
  1888. }
  1889. /// <summary>
  1890. /// Select all text.
  1891. /// </summary>
  1892. public void SelectAll ()
  1893. {
  1894. if (model.Count == 0) {
  1895. return;
  1896. }
  1897. StartSelecting ();
  1898. selectionStartColumn = 0;
  1899. selectionStartRow = 0;
  1900. currentColumn = model.GetLine (model.Count - 1).Count;
  1901. currentRow = model.Count - 1;
  1902. SetNeedsDisplay ();
  1903. }
  1904. /// <summary>
  1905. /// Find the next text based on the match case with the option to replace it.
  1906. /// </summary>
  1907. /// <param name="textToFind">The text to find.</param>
  1908. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1909. /// <param name="matchCase">The match case setting.</param>
  1910. /// <param name="matchWholeWord">The match whole word setting.</param>
  1911. /// <param name="textToReplace">The text to replace.</param>
  1912. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1913. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1914. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1915. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1916. {
  1917. if (model.Count == 0) {
  1918. gaveFullTurn = false;
  1919. return false;
  1920. }
  1921. SetWrapModel ();
  1922. ResetContinuousFind ();
  1923. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1924. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1925. }
  1926. /// <summary>
  1927. /// Find the previous text based on the match case with the option to replace it.
  1928. /// </summary>
  1929. /// <param name="textToFind">The text to find.</param>
  1930. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  1931. /// <param name="matchCase">The match case setting.</param>
  1932. /// <param name="matchWholeWord">The match whole word setting.</param>
  1933. /// <param name="textToReplace">The text to replace.</param>
  1934. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1935. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1936. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1937. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1938. {
  1939. if (model.Count == 0) {
  1940. gaveFullTurn = false;
  1941. return false;
  1942. }
  1943. SetWrapModel ();
  1944. ResetContinuousFind ();
  1945. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1946. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1947. }
  1948. /// <summary>
  1949. /// Reset the flag to stop continuous find.
  1950. /// </summary>
  1951. public void FindTextChanged ()
  1952. {
  1953. continuousFind = false;
  1954. }
  1955. /// <summary>
  1956. /// Replaces all the text based on the match case.
  1957. /// </summary>
  1958. /// <param name="textToFind">The text to find.</param>
  1959. /// <param name="matchCase">The match case setting.</param>
  1960. /// <param name="matchWholeWord">The match whole word setting.</param>
  1961. /// <param name="textToReplace">The text to replace.</param>
  1962. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1963. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1964. ustring textToReplace = null)
  1965. {
  1966. if (isReadOnly || model.Count == 0) {
  1967. return false;
  1968. }
  1969. SetWrapModel ();
  1970. ResetContinuousFind ();
  1971. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1972. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1973. }
  1974. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1975. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1976. {
  1977. if (foundPos.found) {
  1978. StartSelecting ();
  1979. selectionStartColumn = foundPos.current.X;
  1980. selectionStartRow = foundPos.current.Y;
  1981. if (!replaceAll) {
  1982. currentColumn = selectionStartColumn + text.RuneCount;
  1983. } else {
  1984. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1985. }
  1986. currentRow = foundPos.current.Y;
  1987. if (!isReadOnly && replace) {
  1988. Adjust ();
  1989. ClearSelectedRegion ();
  1990. InsertText (textToReplace);
  1991. StartSelecting ();
  1992. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1993. } else {
  1994. UpdateWrapModel ();
  1995. SetNeedsDisplay ();
  1996. Adjust ();
  1997. }
  1998. continuousFind = true;
  1999. return foundPos.found;
  2000. }
  2001. UpdateWrapModel ();
  2002. continuousFind = false;
  2003. return foundPos.found;
  2004. }
  2005. void ResetContinuousFind ()
  2006. {
  2007. if (!continuousFind) {
  2008. var col = selecting ? selectionStartColumn : currentColumn;
  2009. var row = selecting ? selectionStartRow : currentRow;
  2010. model.ResetContinuousFind (new Point (col, row));
  2011. }
  2012. }
  2013. string currentCaller;
  2014. /// <summary>
  2015. /// Restore from original model.
  2016. /// </summary>
  2017. void SetWrapModel ([CallerMemberName] string caller = null)
  2018. {
  2019. if (currentCaller != null)
  2020. return;
  2021. if (wordWrap) {
  2022. currentCaller = caller;
  2023. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2024. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2025. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  2026. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  2027. model = wrapManager.Model;
  2028. }
  2029. }
  2030. /// <summary>
  2031. /// Update the original model.
  2032. /// </summary>
  2033. void UpdateWrapModel ([CallerMemberName] string caller = null)
  2034. {
  2035. if (currentCaller != null && currentCaller != caller)
  2036. return;
  2037. if (wordWrap) {
  2038. currentCaller = null;
  2039. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  2040. out int nStartRow, out int nStartCol,
  2041. currentRow, currentColumn,
  2042. selectionStartRow, selectionStartColumn, preserveTrailingSpaces: true);
  2043. currentRow = nRow;
  2044. currentColumn = nCol;
  2045. selectionStartRow = nStartRow;
  2046. selectionStartColumn = nStartCol;
  2047. wrapNeeded = true;
  2048. }
  2049. if (currentCaller != null)
  2050. throw new InvalidOperationException ($"WordWrap settings was changed after the {currentCaller} call.");
  2051. }
  2052. /// <summary>
  2053. /// Invoke the <see cref="UnwrappedCursorPosition"/> event with the unwrapped <see cref="CursorPosition"/>.
  2054. /// </summary>
  2055. public virtual void OnUnwrappedCursorPosition (int? cRow = null, int? cCol = null)
  2056. {
  2057. var row = cRow == null ? currentRow : cRow;
  2058. var col = cCol == null ? currentColumn : cCol;
  2059. if (cRow == null && cCol == null && wordWrap) {
  2060. row = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2061. col = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2062. }
  2063. UnwrappedCursorPosition?.Invoke (new Point ((int)col, (int)row));
  2064. }
  2065. ustring GetSelectedRegion ()
  2066. {
  2067. var cRow = currentRow;
  2068. var cCol = currentColumn;
  2069. var startRow = selectionStartRow;
  2070. var startCol = selectionStartColumn;
  2071. var model = this.model;
  2072. if (wordWrap) {
  2073. cRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2074. cCol = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2075. startRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  2076. startCol = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  2077. model = wrapManager.Model;
  2078. }
  2079. OnUnwrappedCursorPosition (cRow, cCol);
  2080. return GetRegion (startRow, startCol, cRow, cCol, model);
  2081. }
  2082. ///<inheritdoc/>
  2083. public override void Redraw (Rect bounds)
  2084. {
  2085. SetNormalColor ();
  2086. var offB = OffSetBackground ();
  2087. int right = Frame.Width + offB.width + RightOffset;
  2088. int bottom = Frame.Height + offB.height + BottomOffset;
  2089. var row = 0;
  2090. for (int idxRow = topRow; idxRow < model.Count; idxRow++) {
  2091. var line = model.GetLine (idxRow);
  2092. int lineRuneCount = line.Count;
  2093. var col = 0;
  2094. Move (0, row);
  2095. for (int idxCol = leftColumn; idxCol < lineRuneCount; idxCol++) {
  2096. var rune = idxCol >= lineRuneCount ? ' ' : line [idxCol];
  2097. var cols = Rune.ColumnWidth (rune);
  2098. if (idxCol < line.Count && selecting && PointInSelection (idxCol, idxRow)) {
  2099. SetSelectionColor (line, idxCol);
  2100. } else if (idxCol == currentColumn && idxRow == currentRow && !selecting && !Used
  2101. && HasFocus && idxCol < lineRuneCount) {
  2102. SetSelectionColor (line, idxCol);
  2103. } else if (ReadOnly) {
  2104. SetReadOnlyColor (line, idxCol);
  2105. } else {
  2106. SetNormalColor (line, idxCol);
  2107. }
  2108. if (rune == '\t') {
  2109. cols += TabWidth + 1;
  2110. if (col + cols > right) {
  2111. cols = right - col;
  2112. }
  2113. for (int i = 0; i < cols; i++) {
  2114. if (col + i < right) {
  2115. AddRune (col + i, row, ' ');
  2116. }
  2117. }
  2118. } else {
  2119. AddRune (col, row, rune);
  2120. }
  2121. if (!TextModel.SetCol (ref col, bounds.Right, cols)) {
  2122. break;
  2123. }
  2124. if (idxCol + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idxCol + 1]) > right) {
  2125. break;
  2126. }
  2127. }
  2128. if (col < right) {
  2129. SetNormalColor ();
  2130. ClearRegion (col, row, right, row + 1);
  2131. }
  2132. row++;
  2133. }
  2134. if (row < bottom) {
  2135. SetNormalColor ();
  2136. ClearRegion (bounds.Left, row, right, bottom);
  2137. }
  2138. PositionCursor ();
  2139. if (SelectedLength > 0)
  2140. return;
  2141. // draw autocomplete
  2142. Autocomplete.GenerateSuggestions ();
  2143. var renderAt = new Point (
  2144. CursorPosition.X - LeftColumn,
  2145. Autocomplete.PopupInsideContainer
  2146. ? (CursorPosition.Y + 1) - TopRow
  2147. : 0);
  2148. Autocomplete.RenderOverlay (renderAt);
  2149. }
  2150. /// <inheritdoc/>
  2151. public override Attribute GetNormalColor ()
  2152. {
  2153. return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  2154. }
  2155. ///<inheritdoc/>
  2156. public override bool CanFocus {
  2157. get => base.CanFocus;
  2158. set { base.CanFocus = value; }
  2159. }
  2160. void SetClipboard (ustring text)
  2161. {
  2162. if (text != null) {
  2163. Clipboard.Contents = text;
  2164. }
  2165. }
  2166. void AppendClipboard (ustring text)
  2167. {
  2168. Clipboard.Contents += text;
  2169. }
  2170. /// <summary>
  2171. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position
  2172. /// exactly as if the user had just typed it
  2173. /// </summary>
  2174. /// <param name="toAdd">Text to add</param>
  2175. public void InsertText (string toAdd)
  2176. {
  2177. foreach (var ch in toAdd) {
  2178. Key key;
  2179. try {
  2180. key = (Key)ch;
  2181. } catch (Exception) {
  2182. throw new ArgumentException ($"Cannot insert character '{ch}' because it does not map to a Key");
  2183. }
  2184. InsertText (new KeyEvent () { Key = key });
  2185. }
  2186. }
  2187. void Insert (Rune rune)
  2188. {
  2189. var line = GetCurrentLine ();
  2190. if (Used) {
  2191. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2192. } else {
  2193. if (currentColumn < line.Count) {
  2194. line.RemoveAt (currentColumn);
  2195. }
  2196. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2197. }
  2198. var prow = currentRow - topRow;
  2199. if (!wrapNeeded) {
  2200. SetNeedsDisplay (new Rect (0, prow, Math.Max (Frame.Width, 0), Math.Max (prow + 1, 0)));
  2201. }
  2202. }
  2203. ustring StringFromRunes (List<Rune> runes)
  2204. {
  2205. if (runes == null)
  2206. throw new ArgumentNullException (nameof (runes));
  2207. int size = 0;
  2208. foreach (var rune in runes) {
  2209. size += Utf8.RuneLen (rune);
  2210. }
  2211. var encoded = new byte [size];
  2212. int offset = 0;
  2213. foreach (var rune in runes) {
  2214. offset += Utf8.EncodeRune (rune, encoded, offset);
  2215. }
  2216. return ustring.Make (encoded);
  2217. }
  2218. /// <summary>
  2219. /// Returns the characters on the current line (where the cursor is positioned).
  2220. /// Use <see cref="CurrentColumn"/> to determine the position of the cursor within
  2221. /// that line
  2222. /// </summary>
  2223. /// <returns></returns>
  2224. public List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  2225. void InsertText (ustring text)
  2226. {
  2227. if (ustring.IsNullOrEmpty (text)) {
  2228. return;
  2229. }
  2230. var lines = TextModel.StringToRunes (text);
  2231. if (lines.Count == 0) {
  2232. return;
  2233. }
  2234. SetWrapModel ();
  2235. var line = GetCurrentLine ();
  2236. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition);
  2237. // Optimize single line
  2238. if (lines.Count == 1) {
  2239. line.InsertRange (currentColumn, lines [0]);
  2240. currentColumn += lines [0].Count;
  2241. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2242. HistoryText.LineStatus.Replaced);
  2243. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  2244. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  2245. }
  2246. if (wordWrap) {
  2247. SetNeedsDisplay ();
  2248. } else {
  2249. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Math.Max (currentRow - topRow + 1, 0)));
  2250. }
  2251. UpdateWrapModel ();
  2252. return;
  2253. }
  2254. List<Rune> rest = null;
  2255. int lastp = 0;
  2256. if (model.Count > 0 && line.Count > 0 && !copyWithoutSelection) {
  2257. // Keep a copy of the rest of the line
  2258. var restCount = line.Count - currentColumn;
  2259. rest = line.GetRange (currentColumn, restCount);
  2260. line.RemoveRange (currentColumn, restCount);
  2261. }
  2262. // First line is inserted at the current location, the rest is appended
  2263. line.InsertRange (currentColumn, lines [0]);
  2264. //model.AddLine (currentRow, lines [0]);
  2265. var addedLines = new List<List<Rune>> () { new List<Rune> (line) };
  2266. for (int i = 1; i < lines.Count; i++) {
  2267. model.AddLine (currentRow + i, lines [i]);
  2268. addedLines.Add (new List<Rune> (lines [i]));
  2269. }
  2270. if (rest != null) {
  2271. var last = model.GetLine (currentRow + lines.Count - 1);
  2272. lastp = last.Count;
  2273. last.InsertRange (last.Count, rest);
  2274. addedLines.Last ().InsertRange (addedLines.Last ().Count, rest);
  2275. }
  2276. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2277. // Now adjust column and row positions
  2278. currentRow += lines.Count - 1;
  2279. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  2280. Adjust ();
  2281. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2282. HistoryText.LineStatus.Replaced);
  2283. UpdateWrapModel ();
  2284. }
  2285. // The column we are tracking, or -1 if we are not tracking any column
  2286. int columnTrack = -1;
  2287. // Tries to snap the cursor to the tracking column
  2288. void TrackColumn ()
  2289. {
  2290. // Now track the column
  2291. var line = GetCurrentLine ();
  2292. if (line.Count < columnTrack)
  2293. currentColumn = line.Count;
  2294. else if (columnTrack != -1)
  2295. currentColumn = columnTrack;
  2296. else if (currentColumn > line.Count)
  2297. currentColumn = line.Count;
  2298. Adjust ();
  2299. }
  2300. void Adjust ()
  2301. {
  2302. var offB = OffSetBackground ();
  2303. var line = GetCurrentLine ();
  2304. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  2305. var tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  2306. var dSize = TextModel.DisplaySize (line, leftColumn, currentColumn, true, TabWidth);
  2307. if (!wordWrap && currentColumn < leftColumn) {
  2308. leftColumn = currentColumn;
  2309. need = true;
  2310. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width
  2311. || dSize.size + RightOffset >= Frame.Width + offB.width)) {
  2312. leftColumn = TextModel.CalculateLeftColumn (line, leftColumn, currentColumn,
  2313. Frame.Width + offB.width - RightOffset, TabWidth);
  2314. need = true;
  2315. } else if ((wordWrap && leftColumn > 0) || (dSize.size + RightOffset < Frame.Width + offB.width
  2316. && tSize.size + RightOffset < Frame.Width + offB.width)) {
  2317. leftColumn = 0;
  2318. need = true;
  2319. }
  2320. if (currentRow < topRow) {
  2321. topRow = currentRow;
  2322. need = true;
  2323. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  2324. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  2325. need = true;
  2326. } else if (topRow > 0 && currentRow == topRow) {
  2327. topRow = Math.Max (topRow - 1, 0);
  2328. }
  2329. if (need) {
  2330. if (wrapNeeded) {
  2331. WrapTextModel ();
  2332. wrapNeeded = false;
  2333. }
  2334. SetNeedsDisplay ();
  2335. } else {
  2336. PositionCursor ();
  2337. }
  2338. OnUnwrappedCursorPosition ();
  2339. }
  2340. (int width, int height) OffSetBackground ()
  2341. {
  2342. int w = 0;
  2343. int h = 0;
  2344. if (SuperView?.Frame.Right - Frame.Right < 0) {
  2345. w = SuperView.Frame.Right - Frame.Right - 1;
  2346. }
  2347. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  2348. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  2349. }
  2350. return (w, h);
  2351. }
  2352. /// <summary>
  2353. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  2354. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  2355. /// </summary>
  2356. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  2357. /// if the value is negative it will be reset to zero</param>
  2358. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  2359. public void ScrollTo (int idx, bool isRow = true)
  2360. {
  2361. if (idx < 0) {
  2362. idx = 0;
  2363. }
  2364. if (isRow) {
  2365. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  2366. } else if (!wordWrap) {
  2367. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset, TabWidth);
  2368. leftColumn = Math.Max (!wordWrap && idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  2369. }
  2370. SetNeedsDisplay ();
  2371. }
  2372. bool lastWasKill;
  2373. bool wrapNeeded;
  2374. bool shiftSelecting;
  2375. ///<inheritdoc/>
  2376. public override bool ProcessKey (KeyEvent kb)
  2377. {
  2378. if (!CanFocus) {
  2379. return true;
  2380. }
  2381. // Give autocomplete first opportunity to respond to key presses
  2382. if (SelectedLength == 0 && Autocomplete.ProcessKey (kb)) {
  2383. return true;
  2384. }
  2385. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (kb),
  2386. new KeyModifiers () { Alt = kb.IsAlt, Ctrl = kb.IsCtrl, Shift = kb.IsShift }));
  2387. if (result != null)
  2388. return (bool)result;
  2389. ResetColumnTrack ();
  2390. // Ignore control characters and other special keys
  2391. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  2392. return false;
  2393. InsertText (kb);
  2394. DoNeededAction ();
  2395. return true;
  2396. }
  2397. void RedoChanges ()
  2398. {
  2399. if (ReadOnly)
  2400. return;
  2401. historyText.Redo ();
  2402. }
  2403. void UndoChanges ()
  2404. {
  2405. if (ReadOnly)
  2406. return;
  2407. historyText.Undo ();
  2408. }
  2409. bool ProcessMovePreviousView ()
  2410. {
  2411. ResetColumnTrack ();
  2412. return MovePreviousView ();
  2413. }
  2414. bool ProcessMoveNextView ()
  2415. {
  2416. ResetColumnTrack ();
  2417. return MoveNextView ();
  2418. }
  2419. void ProcessSetOverwrite ()
  2420. {
  2421. ResetColumnTrack ();
  2422. SetOverwrite (!Used);
  2423. }
  2424. void ProcessSelectAll ()
  2425. {
  2426. ResetColumnTrack ();
  2427. SelectAll ();
  2428. }
  2429. void MoveTopHomeExtend ()
  2430. {
  2431. ResetColumnTrack ();
  2432. StartSelecting ();
  2433. MoveHome ();
  2434. }
  2435. void MoveTopHome ()
  2436. {
  2437. ResetAllTrack ();
  2438. if (shiftSelecting && selecting) {
  2439. StopSelecting ();
  2440. }
  2441. MoveHome ();
  2442. }
  2443. void MoveBottomEndExtend ()
  2444. {
  2445. ResetAllTrack ();
  2446. StartSelecting ();
  2447. MoveEnd ();
  2448. }
  2449. void MoveBottomEnd ()
  2450. {
  2451. ResetAllTrack ();
  2452. if (shiftSelecting && selecting) {
  2453. StopSelecting ();
  2454. }
  2455. MoveEnd ();
  2456. }
  2457. void ProcessKillWordBackward ()
  2458. {
  2459. ResetColumnTrack ();
  2460. KillWordBackward ();
  2461. }
  2462. void ProcessKillWordForward ()
  2463. {
  2464. ResetColumnTrack ();
  2465. KillWordForward ();
  2466. }
  2467. void ProcessMoveWordForwardExtend ()
  2468. {
  2469. ResetAllTrack ();
  2470. StartSelecting ();
  2471. MoveWordForward ();
  2472. }
  2473. void ProcessMoveWordForward ()
  2474. {
  2475. ResetAllTrack ();
  2476. if (shiftSelecting && selecting) {
  2477. StopSelecting ();
  2478. }
  2479. MoveWordForward ();
  2480. }
  2481. void ProcessMoveWordBackwardExtend ()
  2482. {
  2483. ResetAllTrack ();
  2484. StartSelecting ();
  2485. MoveWordBackward ();
  2486. }
  2487. void ProcessMoveWordBackward ()
  2488. {
  2489. ResetAllTrack ();
  2490. if (shiftSelecting && selecting) {
  2491. StopSelecting ();
  2492. }
  2493. MoveWordBackward ();
  2494. }
  2495. void ProcessCut ()
  2496. {
  2497. ResetColumnTrack ();
  2498. Cut ();
  2499. }
  2500. void ProcessCopy ()
  2501. {
  2502. ResetColumnTrack ();
  2503. Copy ();
  2504. }
  2505. void ToggleSelecting ()
  2506. {
  2507. ResetColumnTrack ();
  2508. selecting = !selecting;
  2509. selectionStartColumn = currentColumn;
  2510. selectionStartRow = currentRow;
  2511. }
  2512. void ProcessPaste ()
  2513. {
  2514. ResetColumnTrack ();
  2515. if (isReadOnly)
  2516. return;
  2517. Paste ();
  2518. }
  2519. void ProcessMoveEndOfLineExtend ()
  2520. {
  2521. ResetAllTrack ();
  2522. StartSelecting ();
  2523. MoveEndOfLine ();
  2524. }
  2525. void ProcessMoveEndOfLine ()
  2526. {
  2527. ResetAllTrack ();
  2528. if (shiftSelecting && selecting) {
  2529. StopSelecting ();
  2530. }
  2531. MoveEndOfLine ();
  2532. }
  2533. void ProcessDeleteCharRight ()
  2534. {
  2535. ResetColumnTrack ();
  2536. DeleteCharRight ();
  2537. }
  2538. void ProcessMoveStartOfLineExtend ()
  2539. {
  2540. ResetAllTrack ();
  2541. StartSelecting ();
  2542. MoveStartOfLine ();
  2543. }
  2544. void ProcessMoveStartOfLine ()
  2545. {
  2546. ResetAllTrack ();
  2547. if (shiftSelecting && selecting) {
  2548. StopSelecting ();
  2549. }
  2550. MoveStartOfLine ();
  2551. }
  2552. void ProcessDeleteCharLeft ()
  2553. {
  2554. ResetColumnTrack ();
  2555. DeleteCharLeft ();
  2556. }
  2557. void ProcessMoveLeftExtend ()
  2558. {
  2559. ResetAllTrack ();
  2560. StartSelecting ();
  2561. MoveLeft ();
  2562. }
  2563. bool ProcessMoveLeft ()
  2564. {
  2565. // if the user presses Left (without any control keys) and they are at the start of the text
  2566. if (currentColumn == 0 && currentRow == 0) {
  2567. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  2568. return false;
  2569. }
  2570. ResetAllTrack ();
  2571. if (shiftSelecting && selecting) {
  2572. StopSelecting ();
  2573. }
  2574. MoveLeft ();
  2575. return true;
  2576. }
  2577. void ProcessMoveRightExtend ()
  2578. {
  2579. ResetAllTrack ();
  2580. StartSelecting ();
  2581. MoveRight ();
  2582. }
  2583. bool ProcessMoveRight ()
  2584. {
  2585. // if the user presses Right (without any control keys)
  2586. // determine where the last cursor position in the text is
  2587. var lastRow = model.Count - 1;
  2588. var lastCol = model.GetLine (lastRow).Count;
  2589. // 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)
  2590. if (currentColumn == lastCol && currentRow == lastRow) {
  2591. return false;
  2592. }
  2593. ResetAllTrack ();
  2594. if (shiftSelecting && selecting) {
  2595. StopSelecting ();
  2596. }
  2597. MoveRight ();
  2598. return true;
  2599. }
  2600. void ProcessMoveUpExtend ()
  2601. {
  2602. ResetColumnTrack ();
  2603. StartSelecting ();
  2604. MoveUp ();
  2605. }
  2606. void ProcessMoveUp ()
  2607. {
  2608. ResetContinuousFindTrack ();
  2609. if (shiftSelecting && selecting) {
  2610. StopSelecting ();
  2611. }
  2612. MoveUp ();
  2613. }
  2614. void ProcessMoveDownExtend ()
  2615. {
  2616. ResetColumnTrack ();
  2617. StartSelecting ();
  2618. MoveDown ();
  2619. }
  2620. void ProcessMoveDown ()
  2621. {
  2622. ResetContinuousFindTrack ();
  2623. if (shiftSelecting && selecting) {
  2624. StopSelecting ();
  2625. }
  2626. MoveDown ();
  2627. }
  2628. void ProcessPageUpExtend ()
  2629. {
  2630. ResetColumnTrack ();
  2631. StartSelecting ();
  2632. MovePageUp ();
  2633. }
  2634. void ProcessPageUp ()
  2635. {
  2636. ResetColumnTrack ();
  2637. if (shiftSelecting && selecting) {
  2638. StopSelecting ();
  2639. }
  2640. MovePageUp ();
  2641. }
  2642. void ProcessPageDownExtend ()
  2643. {
  2644. ResetColumnTrack ();
  2645. StartSelecting ();
  2646. MovePageDown ();
  2647. }
  2648. void ProcessPageDown ()
  2649. {
  2650. ResetColumnTrack ();
  2651. if (shiftSelecting && selecting) {
  2652. StopSelecting ();
  2653. }
  2654. MovePageDown ();
  2655. }
  2656. bool MovePreviousView ()
  2657. {
  2658. if (Application.MdiTop != null) {
  2659. return SuperView?.FocusPrev () == true;
  2660. }
  2661. return false;
  2662. }
  2663. bool MoveNextView ()
  2664. {
  2665. if (Application.MdiTop != null) {
  2666. return SuperView?.FocusNext () == true;
  2667. }
  2668. return false;
  2669. }
  2670. bool ProcessBackTab ()
  2671. {
  2672. ResetColumnTrack ();
  2673. if (!AllowsTab || isReadOnly) {
  2674. return ProcessMovePreviousView ();
  2675. }
  2676. if (currentColumn > 0) {
  2677. SetWrapModel ();
  2678. var currentLine = GetCurrentLine ();
  2679. if (currentLine.Count > 0 && currentLine [currentColumn - 1] == '\t') {
  2680. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2681. currentLine.RemoveAt (currentColumn - 1);
  2682. currentColumn--;
  2683. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2684. HistoryText.LineStatus.Replaced);
  2685. }
  2686. UpdateWrapModel ();
  2687. }
  2688. DoNeededAction ();
  2689. return true;
  2690. }
  2691. bool ProcessTab ()
  2692. {
  2693. ResetColumnTrack ();
  2694. if (!AllowsTab || isReadOnly) {
  2695. return ProcessMoveNextView ();
  2696. }
  2697. InsertText (new KeyEvent ((Key)'\t', null));
  2698. DoNeededAction ();
  2699. return true;
  2700. }
  2701. void SetOverwrite (bool overwrite)
  2702. {
  2703. Used = overwrite;
  2704. SetNeedsDisplay ();
  2705. DoNeededAction ();
  2706. }
  2707. bool ProcessReturn ()
  2708. {
  2709. ResetColumnTrack ();
  2710. if (!AllowsReturn || isReadOnly) {
  2711. return false;
  2712. }
  2713. SetWrapModel ();
  2714. var currentLine = GetCurrentLine ();
  2715. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2716. if (selecting) {
  2717. ClearSelectedRegion ();
  2718. currentLine = GetCurrentLine ();
  2719. }
  2720. var restCount = currentLine.Count - currentColumn;
  2721. var rest = currentLine.GetRange (currentColumn, restCount);
  2722. currentLine.RemoveRange (currentColumn, restCount);
  2723. var addedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2724. model.AddLine (currentRow + 1, rest);
  2725. addedLines.Add (new List<Rune> (model.GetLine (currentRow + 1)));
  2726. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2727. currentRow++;
  2728. bool fullNeedsDisplay = false;
  2729. if (currentRow >= topRow + Frame.Height) {
  2730. topRow++;
  2731. fullNeedsDisplay = true;
  2732. }
  2733. currentColumn = 0;
  2734. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2735. HistoryText.LineStatus.Replaced);
  2736. if (!wordWrap && currentColumn < leftColumn) {
  2737. fullNeedsDisplay = true;
  2738. leftColumn = 0;
  2739. }
  2740. if (fullNeedsDisplay)
  2741. SetNeedsDisplay ();
  2742. else
  2743. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  2744. UpdateWrapModel ();
  2745. DoNeededAction ();
  2746. return true;
  2747. }
  2748. void KillWordBackward ()
  2749. {
  2750. if (isReadOnly)
  2751. return;
  2752. SetWrapModel ();
  2753. var currentLine = GetCurrentLine ();
  2754. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2755. if (currentColumn == 0) {
  2756. DeleteTextBackwards ();
  2757. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2758. HistoryText.LineStatus.Replaced);
  2759. UpdateWrapModel ();
  2760. return;
  2761. }
  2762. var newPos = WordBackward (currentColumn, currentRow);
  2763. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2764. var restCount = currentColumn - newPos.Value.col;
  2765. currentLine.RemoveRange (newPos.Value.col, restCount);
  2766. if (wordWrap) {
  2767. wrapNeeded = true;
  2768. }
  2769. currentColumn = newPos.Value.col;
  2770. } else if (newPos.HasValue) {
  2771. var restCount = currentLine.Count - currentColumn;
  2772. currentLine.RemoveRange (currentColumn, restCount);
  2773. if (wordWrap) {
  2774. wrapNeeded = true;
  2775. }
  2776. currentColumn = newPos.Value.col;
  2777. currentRow = newPos.Value.row;
  2778. }
  2779. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2780. HistoryText.LineStatus.Replaced);
  2781. UpdateWrapModel ();
  2782. if (wrapNeeded) {
  2783. SetNeedsDisplay ();
  2784. } else {
  2785. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2786. }
  2787. DoNeededAction ();
  2788. }
  2789. void KillWordForward ()
  2790. {
  2791. if (isReadOnly)
  2792. return;
  2793. SetWrapModel ();
  2794. var currentLine = GetCurrentLine ();
  2795. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2796. if (currentLine.Count == 0 || currentColumn == currentLine.Count) {
  2797. DeleteTextForwards ();
  2798. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2799. HistoryText.LineStatus.Replaced);
  2800. UpdateWrapModel ();
  2801. return;
  2802. }
  2803. var newPos = WordForward (currentColumn, currentRow);
  2804. var restCount = 0;
  2805. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2806. restCount = newPos.Value.col - currentColumn;
  2807. currentLine.RemoveRange (currentColumn, restCount);
  2808. } else if (newPos.HasValue) {
  2809. restCount = currentLine.Count - currentColumn;
  2810. currentLine.RemoveRange (currentColumn, restCount);
  2811. }
  2812. if (wordWrap) {
  2813. wrapNeeded = true;
  2814. }
  2815. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2816. HistoryText.LineStatus.Replaced);
  2817. UpdateWrapModel ();
  2818. if (wrapNeeded) {
  2819. SetNeedsDisplay ();
  2820. } else {
  2821. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2822. }
  2823. DoNeededAction ();
  2824. }
  2825. void MoveWordForward ()
  2826. {
  2827. var newPos = WordForward (currentColumn, currentRow);
  2828. if (newPos.HasValue) {
  2829. currentColumn = newPos.Value.col;
  2830. currentRow = newPos.Value.row;
  2831. }
  2832. Adjust ();
  2833. DoNeededAction ();
  2834. }
  2835. void MoveWordBackward ()
  2836. {
  2837. var newPos = WordBackward (currentColumn, currentRow);
  2838. if (newPos.HasValue) {
  2839. currentColumn = newPos.Value.col;
  2840. currentRow = newPos.Value.row;
  2841. }
  2842. Adjust ();
  2843. DoNeededAction ();
  2844. }
  2845. void KillToStartOfLine ()
  2846. {
  2847. if (isReadOnly)
  2848. return;
  2849. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2850. // Prevents from adding line feeds if there is no more lines.
  2851. return;
  2852. }
  2853. SetWrapModel ();
  2854. var currentLine = GetCurrentLine ();
  2855. var setLastWasKill = true;
  2856. if (currentLine.Count > 0 && currentColumn == 0) {
  2857. UpdateWrapModel ();
  2858. DeleteTextBackwards ();
  2859. return;
  2860. }
  2861. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2862. if (currentLine.Count == 0) {
  2863. if (currentRow > 0) {
  2864. model.RemoveLine (currentRow);
  2865. if (model.Count > 0 || lastWasKill) {
  2866. var val = ustring.Make (Environment.NewLine);
  2867. if (lastWasKill) {
  2868. AppendClipboard (val);
  2869. } else {
  2870. SetClipboard (val);
  2871. }
  2872. }
  2873. if (model.Count == 0) {
  2874. // Prevents from adding line feeds if there is no more lines.
  2875. setLastWasKill = false;
  2876. }
  2877. currentRow--;
  2878. currentLine = model.GetLine (currentRow);
  2879. var removedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2880. removedLine.Add (new List<Rune> ());
  2881. historyText.Add (new List<List<Rune>> (removedLine), CursorPosition, HistoryText.LineStatus.Removed);
  2882. currentColumn = currentLine.Count;
  2883. }
  2884. } else {
  2885. var restCount = currentColumn;
  2886. var rest = currentLine.GetRange (0, restCount);
  2887. var val = ustring.Empty;
  2888. val += StringFromRunes (rest);
  2889. if (lastWasKill) {
  2890. AppendClipboard (val);
  2891. } else {
  2892. SetClipboard (val);
  2893. }
  2894. currentLine.RemoveRange (0, restCount);
  2895. currentColumn = 0;
  2896. }
  2897. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2898. HistoryText.LineStatus.Replaced);
  2899. UpdateWrapModel ();
  2900. if (wrapNeeded)
  2901. SetNeedsDisplay ();
  2902. else
  2903. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2904. lastWasKill = setLastWasKill;
  2905. DoNeededAction ();
  2906. }
  2907. void KillToEndOfLine ()
  2908. {
  2909. if (isReadOnly)
  2910. return;
  2911. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2912. // Prevents from adding line feeds if there is no more lines.
  2913. return;
  2914. }
  2915. SetWrapModel ();
  2916. var currentLine = GetCurrentLine ();
  2917. var setLastWasKill = true;
  2918. if (currentLine.Count > 0 && currentColumn == currentLine.Count) {
  2919. UpdateWrapModel ();
  2920. DeleteTextForwards ();
  2921. return;
  2922. }
  2923. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2924. if (currentLine.Count == 0) {
  2925. if (currentRow < model.Count - 1) {
  2926. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2927. model.RemoveLine (currentRow);
  2928. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  2929. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  2930. HistoryText.LineStatus.Removed);
  2931. }
  2932. if (model.Count > 0 || lastWasKill) {
  2933. var val = ustring.Make (Environment.NewLine);
  2934. if (lastWasKill) {
  2935. AppendClipboard (val);
  2936. } else {
  2937. SetClipboard (val);
  2938. }
  2939. }
  2940. if (model.Count == 0) {
  2941. // Prevents from adding line feeds if there is no more lines.
  2942. setLastWasKill = false;
  2943. }
  2944. } else {
  2945. var restCount = currentLine.Count - currentColumn;
  2946. var rest = currentLine.GetRange (currentColumn, restCount);
  2947. var val = ustring.Empty;
  2948. val += StringFromRunes (rest);
  2949. if (lastWasKill) {
  2950. AppendClipboard (val);
  2951. } else {
  2952. SetClipboard (val);
  2953. }
  2954. currentLine.RemoveRange (currentColumn, restCount);
  2955. }
  2956. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2957. HistoryText.LineStatus.Replaced);
  2958. UpdateWrapModel ();
  2959. if (wrapNeeded)
  2960. SetNeedsDisplay ();
  2961. else
  2962. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2963. lastWasKill = setLastWasKill;
  2964. DoNeededAction ();
  2965. }
  2966. void MoveEndOfLine ()
  2967. {
  2968. var currentLine = GetCurrentLine ();
  2969. currentColumn = currentLine.Count;
  2970. Adjust ();
  2971. DoNeededAction ();
  2972. }
  2973. void MoveStartOfLine ()
  2974. {
  2975. currentColumn = 0;
  2976. leftColumn = 0;
  2977. Adjust ();
  2978. DoNeededAction ();
  2979. }
  2980. /// <summary>
  2981. /// Deletes all the selected or a single character at right from the position of the cursor.
  2982. /// </summary>
  2983. public void DeleteCharRight ()
  2984. {
  2985. if (isReadOnly)
  2986. return;
  2987. SetWrapModel ();
  2988. if (selecting) {
  2989. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2990. HistoryText.LineStatus.Original);
  2991. ClearSelectedRegion ();
  2992. var currentLine = GetCurrentLine ();
  2993. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  2994. HistoryText.LineStatus.Replaced);
  2995. UpdateWrapModel ();
  2996. return;
  2997. }
  2998. if (DeleteTextForwards ()) {
  2999. UpdateWrapModel ();
  3000. return;
  3001. }
  3002. UpdateWrapModel ();
  3003. DoNeededAction ();
  3004. }
  3005. /// <summary>
  3006. /// Deletes all the selected or a single character at left from the position of the cursor.
  3007. /// </summary>
  3008. public void DeleteCharLeft ()
  3009. {
  3010. if (isReadOnly)
  3011. return;
  3012. SetWrapModel ();
  3013. if (selecting) {
  3014. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3015. HistoryText.LineStatus.Original);
  3016. ClearSelectedRegion ();
  3017. var currentLine = GetCurrentLine ();
  3018. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3019. HistoryText.LineStatus.Replaced);
  3020. UpdateWrapModel ();
  3021. return;
  3022. }
  3023. if (DeleteTextBackwards ()) {
  3024. UpdateWrapModel ();
  3025. return;
  3026. }
  3027. UpdateWrapModel ();
  3028. DoNeededAction ();
  3029. }
  3030. void MoveLeft ()
  3031. {
  3032. if (currentColumn > 0) {
  3033. currentColumn--;
  3034. } else {
  3035. if (currentRow > 0) {
  3036. currentRow--;
  3037. if (currentRow < topRow) {
  3038. topRow--;
  3039. SetNeedsDisplay ();
  3040. }
  3041. var currentLine = GetCurrentLine ();
  3042. currentColumn = currentLine.Count;
  3043. }
  3044. }
  3045. Adjust ();
  3046. DoNeededAction ();
  3047. }
  3048. void MoveRight ()
  3049. {
  3050. var currentLine = GetCurrentLine ();
  3051. if (currentColumn < currentLine.Count) {
  3052. currentColumn++;
  3053. } else {
  3054. if (currentRow + 1 < model.Count) {
  3055. currentRow++;
  3056. currentColumn = 0;
  3057. if (currentRow >= topRow + Frame.Height) {
  3058. topRow++;
  3059. SetNeedsDisplay ();
  3060. }
  3061. }
  3062. }
  3063. Adjust ();
  3064. DoNeededAction ();
  3065. }
  3066. void MovePageUp ()
  3067. {
  3068. int nPageUpShift = Frame.Height - 1;
  3069. if (currentRow > 0) {
  3070. if (columnTrack == -1)
  3071. columnTrack = currentColumn;
  3072. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  3073. if (currentRow < topRow) {
  3074. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  3075. SetNeedsDisplay ();
  3076. }
  3077. TrackColumn ();
  3078. PositionCursor ();
  3079. }
  3080. DoNeededAction ();
  3081. }
  3082. void MovePageDown ()
  3083. {
  3084. int nPageDnShift = Frame.Height - 1;
  3085. if (currentRow >= 0 && currentRow < model.Count) {
  3086. if (columnTrack == -1)
  3087. columnTrack = currentColumn;
  3088. currentRow = (currentRow + nPageDnShift) > model.Count
  3089. ? model.Count > 0 ? model.Count - 1 : 0
  3090. : currentRow + nPageDnShift;
  3091. if (topRow < currentRow - nPageDnShift) {
  3092. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  3093. SetNeedsDisplay ();
  3094. }
  3095. TrackColumn ();
  3096. PositionCursor ();
  3097. }
  3098. DoNeededAction ();
  3099. }
  3100. void ResetContinuousFindTrack ()
  3101. {
  3102. // Handle some state here - whether the last command was a kill
  3103. // operation and the column tracking (up/down)
  3104. lastWasKill = false;
  3105. continuousFind = false;
  3106. }
  3107. void ResetColumnTrack ()
  3108. {
  3109. // Handle some state here - whether the last command was a kill
  3110. // operation and the column tracking (up/down)
  3111. lastWasKill = false;
  3112. columnTrack = -1;
  3113. }
  3114. void ResetAllTrack ()
  3115. {
  3116. // Handle some state here - whether the last command was a kill
  3117. // operation and the column tracking (up/down)
  3118. lastWasKill = false;
  3119. columnTrack = -1;
  3120. continuousFind = false;
  3121. }
  3122. bool InsertText (KeyEvent kb)
  3123. {
  3124. //So that special keys like tab can be processed
  3125. if (isReadOnly)
  3126. return true;
  3127. SetWrapModel ();
  3128. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  3129. if (selecting) {
  3130. ClearSelectedRegion ();
  3131. }
  3132. if (kb.Key == Key.Enter) {
  3133. model.AddLine (currentRow + 1, new List<Rune> ());
  3134. currentRow++;
  3135. currentColumn = 0;
  3136. } else if ((uint)kb.Key == 13) {
  3137. currentColumn = 0;
  3138. } else {
  3139. if (Used) {
  3140. Insert ((uint)kb.Key);
  3141. currentColumn++;
  3142. if (currentColumn >= leftColumn + Frame.Width) {
  3143. leftColumn++;
  3144. SetNeedsDisplay ();
  3145. }
  3146. } else {
  3147. Insert ((uint)kb.Key);
  3148. currentColumn++;
  3149. }
  3150. }
  3151. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3152. HistoryText.LineStatus.Replaced);
  3153. UpdateWrapModel ();
  3154. return true;
  3155. }
  3156. void ShowContextMenu ()
  3157. {
  3158. if (currentCulture != Thread.CurrentThread.CurrentUICulture) {
  3159. currentCulture = Thread.CurrentThread.CurrentUICulture;
  3160. ContextMenu.MenuItems = BuildContextMenuBarItem ();
  3161. }
  3162. ContextMenu.Show ();
  3163. }
  3164. /// <summary>
  3165. /// Deletes all text.
  3166. /// </summary>
  3167. public void DeleteAll ()
  3168. {
  3169. if (Lines == 0) {
  3170. return;
  3171. }
  3172. selectionStartColumn = 0;
  3173. selectionStartRow = 0;
  3174. MoveBottomEndExtend ();
  3175. DeleteCharLeft ();
  3176. SetNeedsDisplay ();
  3177. }
  3178. ///<inheritdoc/>
  3179. public override bool OnKeyUp (KeyEvent kb)
  3180. {
  3181. switch (kb.Key) {
  3182. case Key.Space | Key.CtrlMask:
  3183. return true;
  3184. }
  3185. return false;
  3186. }
  3187. void DoNeededAction ()
  3188. {
  3189. if (NeedDisplay.IsEmpty) {
  3190. PositionCursor ();
  3191. } else {
  3192. Adjust ();
  3193. }
  3194. }
  3195. bool DeleteTextForwards ()
  3196. {
  3197. SetWrapModel ();
  3198. var currentLine = GetCurrentLine ();
  3199. if (currentColumn == currentLine.Count) {
  3200. if (currentRow + 1 == model.Count) {
  3201. UpdateWrapModel ();
  3202. return true;
  3203. }
  3204. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3205. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  3206. var nextLine = model.GetLine (currentRow + 1);
  3207. removedLines.Add (new List<Rune> (nextLine));
  3208. historyText.Add (removedLines, CursorPosition, HistoryText.LineStatus.Removed);
  3209. currentLine.AddRange (nextLine);
  3210. model.RemoveLine (currentRow + 1);
  3211. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3212. HistoryText.LineStatus.Replaced);
  3213. if (wordWrap) {
  3214. wrapNeeded = true;
  3215. }
  3216. if (wrapNeeded) {
  3217. SetNeedsDisplay ();
  3218. } else {
  3219. var sr = currentRow - topRow;
  3220. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  3221. }
  3222. } else {
  3223. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3224. currentLine.RemoveAt (currentColumn);
  3225. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3226. HistoryText.LineStatus.Replaced);
  3227. if (wordWrap) {
  3228. wrapNeeded = true;
  3229. }
  3230. if (wrapNeeded) {
  3231. SetNeedsDisplay ();
  3232. } else {
  3233. var r = currentRow - topRow;
  3234. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  3235. }
  3236. }
  3237. UpdateWrapModel ();
  3238. return false;
  3239. }
  3240. bool DeleteTextBackwards ()
  3241. {
  3242. SetWrapModel ();
  3243. if (currentColumn > 0) {
  3244. // Delete backwards
  3245. var currentLine = GetCurrentLine ();
  3246. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3247. currentLine.RemoveAt (currentColumn - 1);
  3248. if (wordWrap) {
  3249. wrapNeeded = true;
  3250. }
  3251. currentColumn--;
  3252. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3253. HistoryText.LineStatus.Replaced);
  3254. if (currentColumn < leftColumn) {
  3255. leftColumn--;
  3256. SetNeedsDisplay ();
  3257. } else
  3258. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  3259. } else {
  3260. // Merges the current line with the previous one.
  3261. if (currentRow == 0)
  3262. return true;
  3263. var prowIdx = currentRow - 1;
  3264. var prevRow = model.GetLine (prowIdx);
  3265. historyText.Add (new List<List<Rune>> () { new List<Rune> (prevRow) }, CursorPosition);
  3266. List<List<Rune>> removedLines = new List<List<Rune>> () { new List<Rune> (prevRow) };
  3267. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  3268. historyText.Add (removedLines, new Point (currentColumn, prowIdx),
  3269. HistoryText.LineStatus.Removed);
  3270. var prevCount = prevRow.Count;
  3271. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  3272. model.RemoveLine (currentRow);
  3273. if (wordWrap) {
  3274. wrapNeeded = true;
  3275. }
  3276. currentRow--;
  3277. historyText.Add (new List<List<Rune>> () { GetCurrentLine () }, new Point (currentColumn, prowIdx),
  3278. HistoryText.LineStatus.Replaced);
  3279. currentColumn = prevCount;
  3280. SetNeedsDisplay ();
  3281. }
  3282. UpdateWrapModel ();
  3283. return false;
  3284. }
  3285. bool copyWithoutSelection;
  3286. /// <summary>
  3287. /// Copy the selected text to the clipboard contents.
  3288. /// </summary>
  3289. public void Copy ()
  3290. {
  3291. SetWrapModel ();
  3292. if (selecting) {
  3293. SetClipboard (GetRegion ());
  3294. copyWithoutSelection = false;
  3295. } else {
  3296. var currentLine = GetCurrentLine ();
  3297. SetClipboard (ustring.Make (currentLine));
  3298. copyWithoutSelection = true;
  3299. }
  3300. UpdateWrapModel ();
  3301. DoNeededAction ();
  3302. }
  3303. /// <summary>
  3304. /// Cut the selected text to the clipboard contents.
  3305. /// </summary>
  3306. public void Cut ()
  3307. {
  3308. SetWrapModel ();
  3309. SetClipboard (GetRegion ());
  3310. if (!isReadOnly) {
  3311. ClearRegion ();
  3312. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3313. HistoryText.LineStatus.Replaced);
  3314. }
  3315. UpdateWrapModel ();
  3316. selecting = false;
  3317. DoNeededAction ();
  3318. }
  3319. /// <summary>
  3320. /// Paste the clipboard contents into the current selected position.
  3321. /// </summary>
  3322. public void Paste ()
  3323. {
  3324. if (isReadOnly) {
  3325. return;
  3326. }
  3327. SetWrapModel ();
  3328. var contents = Clipboard.Contents;
  3329. if (copyWithoutSelection && contents.FirstOrDefault (x => x == '\n' || x == '\r') == 0) {
  3330. var runeList = contents == null ? new List<Rune> () : contents.ToRuneList ();
  3331. var currentLine = GetCurrentLine ();
  3332. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3333. var addedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  3334. addedLine.Add (runeList);
  3335. historyText.Add (new List<List<Rune>> (addedLine), CursorPosition, HistoryText.LineStatus.Added);
  3336. model.AddLine (currentRow, runeList);
  3337. currentRow++;
  3338. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3339. HistoryText.LineStatus.Replaced);
  3340. } else {
  3341. if (selecting) {
  3342. ClearRegion ();
  3343. }
  3344. copyWithoutSelection = false;
  3345. InsertText (contents);
  3346. if (selecting) {
  3347. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3348. HistoryText.LineStatus.Original);
  3349. }
  3350. }
  3351. UpdateWrapModel ();
  3352. selecting = false;
  3353. DoNeededAction ();
  3354. }
  3355. void StartSelecting ()
  3356. {
  3357. if (shiftSelecting && selecting) {
  3358. return;
  3359. }
  3360. shiftSelecting = true;
  3361. selecting = true;
  3362. selectionStartColumn = currentColumn;
  3363. selectionStartRow = currentRow;
  3364. }
  3365. void StopSelecting ()
  3366. {
  3367. shiftSelecting = false;
  3368. selecting = false;
  3369. isButtonShift = false;
  3370. }
  3371. void ClearSelectedRegion ()
  3372. {
  3373. SetWrapModel ();
  3374. if (!isReadOnly) {
  3375. ClearRegion ();
  3376. }
  3377. UpdateWrapModel ();
  3378. selecting = false;
  3379. DoNeededAction ();
  3380. }
  3381. void MoveUp ()
  3382. {
  3383. if (currentRow > 0) {
  3384. if (columnTrack == -1) {
  3385. columnTrack = currentColumn;
  3386. }
  3387. currentRow--;
  3388. if (currentRow < topRow) {
  3389. topRow--;
  3390. SetNeedsDisplay ();
  3391. }
  3392. TrackColumn ();
  3393. PositionCursor ();
  3394. }
  3395. DoNeededAction ();
  3396. }
  3397. void MoveDown ()
  3398. {
  3399. if (currentRow + 1 < model.Count) {
  3400. if (columnTrack == -1) {
  3401. columnTrack = currentColumn;
  3402. }
  3403. currentRow++;
  3404. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  3405. topRow++;
  3406. SetNeedsDisplay ();
  3407. }
  3408. TrackColumn ();
  3409. PositionCursor ();
  3410. } else if (currentRow > Frame.Height) {
  3411. Adjust ();
  3412. }
  3413. DoNeededAction ();
  3414. }
  3415. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  3416. {
  3417. if (col < 0 || row < 0)
  3418. yield break;
  3419. if (row >= model.Count)
  3420. yield break;
  3421. var line = GetCurrentLine ();
  3422. if (col >= line.Count)
  3423. yield break;
  3424. while (row < model.Count) {
  3425. for (int c = col; c < line.Count; c++) {
  3426. yield return (c, row, line [c]);
  3427. }
  3428. col = 0;
  3429. row++;
  3430. line = GetCurrentLine ();
  3431. }
  3432. }
  3433. Rune RuneAt (int col, int row)
  3434. {
  3435. var line = model.GetLine (row);
  3436. if (line.Count > 0) {
  3437. return line [col > line.Count - 1 ? line.Count - 1 : col];
  3438. } else {
  3439. return 0;
  3440. }
  3441. }
  3442. /// <summary>
  3443. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  3444. /// </summary>
  3445. public void MoveEnd ()
  3446. {
  3447. currentRow = model.Count - 1;
  3448. var line = GetCurrentLine ();
  3449. currentColumn = line.Count;
  3450. TrackColumn ();
  3451. PositionCursor ();
  3452. }
  3453. /// <summary>
  3454. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  3455. /// </summary>
  3456. public void MoveHome ()
  3457. {
  3458. currentRow = 0;
  3459. topRow = 0;
  3460. currentColumn = 0;
  3461. leftColumn = 0;
  3462. TrackColumn ();
  3463. PositionCursor ();
  3464. }
  3465. bool MoveNext (ref int col, ref int row, out Rune rune)
  3466. {
  3467. var line = model.GetLine (row);
  3468. if (col + 1 < line.Count) {
  3469. col++;
  3470. rune = line [col];
  3471. if (col + 1 == line.Count && !Rune.IsLetterOrDigit (rune)
  3472. && !Rune.IsWhiteSpace (line [col - 1])) {
  3473. col++;
  3474. }
  3475. return true;
  3476. } else if (col + 1 == line.Count) {
  3477. col++;
  3478. }
  3479. while (row + 1 < model.Count) {
  3480. col = 0;
  3481. row++;
  3482. line = model.GetLine (row);
  3483. if (line.Count > 0) {
  3484. rune = line [0];
  3485. return true;
  3486. }
  3487. }
  3488. rune = 0;
  3489. return false;
  3490. }
  3491. bool MovePrev (ref int col, ref int row, out Rune rune)
  3492. {
  3493. var line = model.GetLine (row);
  3494. if (col > 0) {
  3495. col--;
  3496. rune = line [col];
  3497. return true;
  3498. }
  3499. if (row == 0) {
  3500. rune = 0;
  3501. return false;
  3502. }
  3503. while (row > 0) {
  3504. row--;
  3505. line = model.GetLine (row);
  3506. col = line.Count - 1;
  3507. if (col >= 0) {
  3508. rune = line [col];
  3509. return true;
  3510. }
  3511. }
  3512. rune = 0;
  3513. return false;
  3514. }
  3515. (int col, int row)? WordForward (int fromCol, int fromRow)
  3516. {
  3517. var col = fromCol;
  3518. var row = fromRow;
  3519. try {
  3520. var rune = RuneAt (col, row);
  3521. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  3522. {
  3523. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3524. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3525. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))
  3526. return;
  3527. }
  3528. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3529. return;
  3530. }
  3531. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3532. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3533. break;
  3534. }
  3535. } else {
  3536. if (!MoveNext (ref nCol, ref nRow, out nRune)) {
  3537. return;
  3538. }
  3539. var line = model.GetLine (fromRow);
  3540. if ((nRow != fromRow && fromCol < line.Count)
  3541. || (nRow == fromRow && nCol == line.Count - 1)) {
  3542. nCol = line.Count;
  3543. nRow = fromRow;
  3544. return;
  3545. } else if (nRow != fromRow && fromCol == line.Count) {
  3546. line = model.GetLine (nRow);
  3547. if (Rune.IsLetterOrDigit (line [nCol]) || Rune.IsPunctuation (line [nCol])) {
  3548. return;
  3549. }
  3550. }
  3551. ProcMoveNext (ref nCol, ref nRow, nRune);
  3552. }
  3553. }
  3554. ProcMoveNext (ref col, ref row, rune);
  3555. if (fromCol != col || fromRow != row)
  3556. return (col, row);
  3557. return null;
  3558. } catch (Exception) {
  3559. return null;
  3560. }
  3561. }
  3562. (int col, int row)? WordBackward (int fromCol, int fromRow)
  3563. {
  3564. if (fromRow == 0 && fromCol == 0)
  3565. return null;
  3566. var col = Math.Max (fromCol - 1, 0);
  3567. var row = fromRow;
  3568. try {
  3569. var rune = RuneAt (col, row);
  3570. int lastValidCol = Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) ? col : -1;
  3571. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  3572. {
  3573. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3574. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3575. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune)) {
  3576. lastValidCol = nCol;
  3577. break;
  3578. }
  3579. }
  3580. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3581. if (lastValidCol > -1) {
  3582. nCol = lastValidCol;
  3583. }
  3584. return;
  3585. }
  3586. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3587. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3588. break;
  3589. if (nRow != fromRow) {
  3590. break;
  3591. }
  3592. lastValidCol = nCol;
  3593. }
  3594. if (lastValidCol > -1) {
  3595. nCol = lastValidCol;
  3596. nRow = fromRow;
  3597. }
  3598. } else {
  3599. if (!MovePrev (ref nCol, ref nRow, out nRune)) {
  3600. return;
  3601. }
  3602. var line = model.GetLine (nRow);
  3603. if (nCol == 0 && nRow == fromRow && (Rune.IsLetterOrDigit (line [0]) || Rune.IsPunctuation (line [0]))) {
  3604. return;
  3605. }
  3606. lastValidCol = Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) ? nCol : lastValidCol;
  3607. if (lastValidCol > -1 && (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune))) {
  3608. nCol = lastValidCol;
  3609. return;
  3610. }
  3611. if (fromRow != nRow) {
  3612. nCol = line.Count;
  3613. return;
  3614. }
  3615. ProcMovePrev (ref nCol, ref nRow, nRune);
  3616. }
  3617. }
  3618. ProcMovePrev (ref col, ref row, rune);
  3619. if (fromCol != col || fromRow != row)
  3620. return (col, row);
  3621. return null;
  3622. } catch (Exception) {
  3623. return null;
  3624. }
  3625. }
  3626. bool isButtonShift;
  3627. ///<inheritdoc/>
  3628. public override bool MouseEvent (MouseEvent ev)
  3629. {
  3630. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  3631. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  3632. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  3633. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  3634. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  3635. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  3636. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)
  3637. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  3638. && !ev.Flags.HasFlag (ContextMenu.MouseFlags)) {
  3639. return false;
  3640. }
  3641. if (!CanFocus) {
  3642. return true;
  3643. }
  3644. if (!HasFocus) {
  3645. SetFocus ();
  3646. }
  3647. continuousFind = false;
  3648. // Give autocomplete first opportunity to respond to mouse clicks
  3649. if (SelectedLength == 0 && Autocomplete.MouseEvent (ev, true)) {
  3650. return true;
  3651. }
  3652. if (ev.Flags == MouseFlags.Button1Clicked) {
  3653. if (shiftSelecting && !isButtonShift) {
  3654. StopSelecting ();
  3655. }
  3656. ProcessMouseClick (ev, out _);
  3657. PositionCursor ();
  3658. lastWasKill = false;
  3659. columnTrack = currentColumn;
  3660. } else if (ev.Flags == MouseFlags.WheeledDown) {
  3661. lastWasKill = false;
  3662. columnTrack = currentColumn;
  3663. ScrollTo (topRow + 1);
  3664. } else if (ev.Flags == MouseFlags.WheeledUp) {
  3665. lastWasKill = false;
  3666. columnTrack = currentColumn;
  3667. ScrollTo (topRow - 1);
  3668. } else if (ev.Flags == MouseFlags.WheeledRight) {
  3669. lastWasKill = false;
  3670. columnTrack = currentColumn;
  3671. ScrollTo (leftColumn + 1, false);
  3672. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  3673. lastWasKill = false;
  3674. columnTrack = currentColumn;
  3675. ScrollTo (leftColumn - 1, false);
  3676. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  3677. ProcessMouseClick (ev, out List<Rune> line);
  3678. PositionCursor ();
  3679. if (model.Count > 0 && shiftSelecting && selecting) {
  3680. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  3681. && model.Count + BottomOffset > topRow + currentRow) {
  3682. ScrollTo (topRow + Frame.Height);
  3683. } else if (topRow > 0 && currentRow <= topRow) {
  3684. ScrollTo (topRow - Frame.Height);
  3685. } else if (ev.Y >= Frame.Height) {
  3686. ScrollTo (model.Count + BottomOffset);
  3687. } else if (ev.Y < 0 && topRow > 0) {
  3688. ScrollTo (0);
  3689. }
  3690. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  3691. && line.Count + RightOffset > leftColumn + currentColumn) {
  3692. ScrollTo (leftColumn + Frame.Width, false);
  3693. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  3694. ScrollTo (leftColumn - Frame.Width, false);
  3695. } else if (ev.X >= Frame.Width) {
  3696. ScrollTo (line.Count + RightOffset, false);
  3697. } else if (ev.X < 0 && leftColumn > 0) {
  3698. ScrollTo (0, false);
  3699. }
  3700. }
  3701. lastWasKill = false;
  3702. columnTrack = currentColumn;
  3703. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  3704. if (!shiftSelecting) {
  3705. isButtonShift = true;
  3706. StartSelecting ();
  3707. }
  3708. ProcessMouseClick (ev, out _);
  3709. PositionCursor ();
  3710. lastWasKill = false;
  3711. columnTrack = currentColumn;
  3712. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  3713. if (shiftSelecting) {
  3714. StopSelecting ();
  3715. }
  3716. ProcessMouseClick (ev, out _);
  3717. PositionCursor ();
  3718. if (!selecting) {
  3719. StartSelecting ();
  3720. }
  3721. lastWasKill = false;
  3722. columnTrack = currentColumn;
  3723. if (Application.mouseGrabView == null) {
  3724. Application.GrabMouse (this);
  3725. }
  3726. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  3727. Application.UngrabMouse ();
  3728. } else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)) {
  3729. if (ev.Flags.HasFlag (MouseFlags.ButtonShift)) {
  3730. if (!selecting) {
  3731. StartSelecting ();
  3732. }
  3733. } else if (selecting) {
  3734. StopSelecting ();
  3735. }
  3736. ProcessMouseClick (ev, out List<Rune> line);
  3737. (int col, int row)? newPos;
  3738. if (currentColumn == line.Count || (currentColumn > 0 && (line [currentColumn - 1] != ' '
  3739. || line [currentColumn] == ' '))) {
  3740. newPos = WordBackward (currentColumn, currentRow);
  3741. if (newPos.HasValue) {
  3742. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : 0;
  3743. }
  3744. }
  3745. if (!selecting) {
  3746. StartSelecting ();
  3747. }
  3748. newPos = WordForward (currentColumn, currentRow);
  3749. if (newPos != null && newPos.HasValue) {
  3750. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : line.Count;
  3751. }
  3752. PositionCursor ();
  3753. lastWasKill = false;
  3754. columnTrack = currentColumn;
  3755. } else if (ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  3756. if (selecting) {
  3757. StopSelecting ();
  3758. }
  3759. ProcessMouseClick (ev, out List<Rune> line);
  3760. currentColumn = 0;
  3761. if (!selecting) {
  3762. StartSelecting ();
  3763. }
  3764. currentColumn = line.Count;
  3765. PositionCursor ();
  3766. lastWasKill = false;
  3767. columnTrack = currentColumn;
  3768. } else if (ev.Flags == ContextMenu.MouseFlags) {
  3769. ContextMenu.Position = new Point (ev.X + 2, ev.Y + 2);
  3770. ShowContextMenu ();
  3771. }
  3772. return true;
  3773. }
  3774. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  3775. {
  3776. List<Rune> r = null;
  3777. if (model.Count > 0) {
  3778. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  3779. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  3780. currentRow = maxCursorPositionableLine + topRow;
  3781. } else {
  3782. currentRow = Math.Max (ev.Y + topRow, 0);
  3783. }
  3784. r = GetCurrentLine ();
  3785. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0), TabWidth);
  3786. if (idx - leftColumn >= r.Count + RightOffset) {
  3787. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  3788. } else {
  3789. currentColumn = idx + leftColumn;
  3790. }
  3791. }
  3792. line = r;
  3793. }
  3794. ///<inheritdoc/>
  3795. public override bool OnLeave (View view)
  3796. {
  3797. if (Application.mouseGrabView != null && Application.mouseGrabView == this) {
  3798. Application.UngrabMouse ();
  3799. }
  3800. return base.OnLeave (view);
  3801. }
  3802. /// <summary>
  3803. /// Allows clearing the <see cref="HistoryText.HistoryTextItem"/> items updating the original text.
  3804. /// </summary>
  3805. public void ClearHistoryChanges ()
  3806. {
  3807. historyText?.Clear (Text);
  3808. }
  3809. }
  3810. /// <summary>
  3811. /// Renders an overlay on another view at a given point that allows selecting
  3812. /// from a range of 'autocomplete' options.
  3813. /// An implementation on a TextView.
  3814. /// </summary>
  3815. public class TextViewAutocomplete : Autocomplete {
  3816. ///<inheritdoc/>
  3817. protected override string GetCurrentWord ()
  3818. {
  3819. var host = (TextView)HostControl;
  3820. var currentLine = host.GetCurrentLine ();
  3821. var cursorPosition = Math.Min (host.CurrentColumn, currentLine.Count);
  3822. return IdxToWord (currentLine, cursorPosition);
  3823. }
  3824. /// <inheritdoc/>
  3825. protected override void DeleteTextBackwards ()
  3826. {
  3827. ((TextView)HostControl).DeleteCharLeft ();
  3828. }
  3829. /// <inheritdoc/>
  3830. protected override void InsertText (string accepted)
  3831. {
  3832. ((TextView)HostControl).InsertText (accepted);
  3833. }
  3834. }
  3835. }