TextView.cs 142 KB

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