TextView.cs 122 KB

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