TextView.cs 124 KB

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