TextView.cs 124 KB

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