|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455 |
- (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId]) {
- /******/ return installedModules[moduleId].exports;
- /******/ }
- /******/ // Create a new module (and put it into the cache)
- /******/ var module = installedModules[moduleId] = {
- /******/ i: moduleId,
- /******/ l: false,
- /******/ exports: {}
- /******/ };
- /******/
- /******/ // Execute the module function
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
- /******/
- /******/ // Flag the module as loaded
- /******/ module.l = true;
- /******/
- /******/ // Return the exports of the module
- /******/ return module.exports;
- /******/ }
- /******/
- /******/
- /******/ // expose the modules object (__webpack_modules__)
- /******/ __webpack_require__.m = modules;
- /******/
- /******/ // expose the module cache
- /******/ __webpack_require__.c = installedModules;
- /******/
- /******/ // define getter function for harmony exports
- /******/ __webpack_require__.d = function(exports, name, getter) {
- /******/ if(!__webpack_require__.o(exports, name)) {
- /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
- /******/ }
- /******/ };
- /******/
- /******/ // define __esModule on exports
- /******/ __webpack_require__.r = function(exports) {
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
- /******/ }
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
- /******/ };
- /******/
- /******/ // create a fake namespace object
- /******/ // mode & 1: value is a module id, require it
- /******/ // mode & 2: merge all properties of value into the ns
- /******/ // mode & 4: return value when already ns object
- /******/ // mode & 8|1: behave like require
- /******/ __webpack_require__.t = function(value, mode) {
- /******/ if(mode & 1) value = __webpack_require__(value);
- /******/ if(mode & 8) return value;
- /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
- /******/ var ns = Object.create(null);
- /******/ __webpack_require__.r(ns);
- /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
- /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
- /******/ return ns;
- /******/ };
- /******/
- /******/ // getDefaultExport function for compatibility with non-harmony modules
- /******/ __webpack_require__.n = function(module) {
- /******/ var getter = module && module.__esModule ?
- /******/ function getDefault() { return module['default']; } :
- /******/ function getModuleExports() { return module; };
- /******/ __webpack_require__.d(getter, 'a', getter);
- /******/ return getter;
- /******/ };
- /******/
- /******/ // Object.prototype.hasOwnProperty.call
- /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
- /******/
- /******/ // __webpack_public_path__
- /******/ __webpack_require__.p = "";
- /******/
- /******/
- /******/ // Load entry module and return exports
- /******/ return __webpack_require__(__webpack_require__.s = 0);
- /******/ })
- /************************************************************************/
- /******/ ([
- /* 0 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- const coc_nvim_1 = __webpack_require__(1);
- const os_1 = __importDefault(__webpack_require__(2));
- const fs_1 = __importDefault(__webpack_require__(3));
- const path_1 = __importDefault(__webpack_require__(4));
- const util_1 = __importDefault(__webpack_require__(5));
- const vscode_languageserver_types_1 = __webpack_require__(6);
- const snippet_1 = __importDefault(__webpack_require__(7));
- const provider_1 = __webpack_require__(35);
- const snipmateProvider_1 = __webpack_require__(39);
- const textmateProvider_1 = __webpack_require__(43);
- const ultisnipsProvider_1 = __webpack_require__(49);
- const debounce_1 = __importDefault(__webpack_require__(52));
- const languages_1 = __importDefault(__webpack_require__(53));
- const documentation = `# A valid snippet should starts with:
- #
- # snippet trigger_word [ "description" [ options ] ]
- #
- # and end with:
- #
- # endsnippet
- #
- # Snippet options:
- #
- # b - Beginning of line.
- # i - In-word expansion.
- # w - Word boundary.
- # r - Regular expression
- # e - Custom context snippet
- # A - Snippet will be triggered automatically, when condition matches.
- #
- # Basic example:
- #
- # snippet emitter "emitter properties" b
- # private readonly $\{1} = new Emitter<$2>()
- # public readonly $\{1/^_(.*)/$1/}: Event<$2> = this.$1.event
- # endsnippet
- #
- # Online reference: https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt
- `;
- async function activate(context) {
- let { subscriptions } = context;
- const { nvim } = coc_nvim_1.workspace;
- const configuration = coc_nvim_1.workspace.getConfiguration('snippets');
- const filetypeExtends = configuration.get('extends', {});
- const manager = new provider_1.ProviderManager();
- const trace = configuration.get('trace', 'error');
- let mru = coc_nvim_1.workspace.createMru('snippets-mru');
- const channel = coc_nvim_1.workspace.createOutputChannel('snippets');
- let snippetsDir = configuration.get('userSnippetsDirectory');
- if (snippetsDir) {
- snippetsDir = snippetsDir.replace(/^~/, os_1.default.homedir());
- if (snippetsDir.indexOf('$') !== -1) {
- snippetsDir = snippetsDir.replace(/\$(\w+)/g, (match, p1) => {
- var _a;
- return (_a = process.env[p1]) !== null && _a !== void 0 ? _a : match;
- });
- }
- if (!path_1.default.isAbsolute(snippetsDir)) {
- coc_nvim_1.workspace.showMessage(`snippets.userSnippetsDirectory => ${snippetsDir} should be absolute path`, 'warning');
- snippetsDir = null;
- }
- }
- if (!snippetsDir)
- snippetsDir = path_1.default.join(path_1.default.dirname(coc_nvim_1.workspace.env.extensionRoot), 'ultisnips');
- if (!fs_1.default.existsSync(snippetsDir)) {
- await util_1.default.promisify(fs_1.default.mkdir)(snippetsDir);
- }
- coc_nvim_1.events.on('CompleteDone', async (item) => {
- if (item.user_data && item.user_data.indexOf('snippets') !== -1) {
- await mru.add(item.word);
- }
- }, null, subscriptions);
- coc_nvim_1.workspace.onDidOpenTextDocument(async (document) => {
- if (document.uri.endsWith('.snippets')) {
- let doc = coc_nvim_1.workspace.getDocument(document.uri);
- if (!doc)
- return;
- let { buffer } = doc;
- await buffer.setOption('filetype', 'snippets');
- }
- }, null, subscriptions);
- if (configuration.get('ultisnips.enable', true)) {
- let config = configuration.get('ultisnips', {});
- let c = Object.assign({}, config, {
- extends: Object.assign({}, filetypeExtends)
- });
- c.directories = c.directories ? c.directories.slice() : [];
- if (c.directories.indexOf(snippetsDir) == -1) {
- c.directories.push(snippetsDir);
- }
- let provider = new ultisnipsProvider_1.UltiSnippetsProvider(channel, trace, c, context);
- manager.regist(provider, 'ultisnips');
- subscriptions.push(provider);
- // add rtp if ultisnips not found
- nvim.getOption('runtimepath').then(async (rtp) => {
- let paths = rtp.split(',');
- let idx = paths.findIndex(s => /^ultisnips$/i.test(path_1.default.basename(s)));
- if (idx !== -1)
- return;
- let directory = path_1.default.resolve(__dirname, '..');
- nvim.command('autocmd BufNewFile,BufRead *.snippets setf snippets', true);
- nvim.command(`execute 'noa set rtp+='.fnameescape('${directory.replace(/'/g, "''")}')`, true);
- coc_nvim_1.workspace.documents.forEach(doc => {
- if (doc.uri.endsWith('.snippets')) {
- doc.buffer.setOption('filetype', 'snippets', true);
- }
- });
- }, _e => {
- // noop
- });
- }
- let config = {
- loadFromExtensions: configuration.get('loadFromExtensions', true),
- snippetsRoots: configuration.get('textmateSnippetsRoots', []),
- extends: Object.assign({}, filetypeExtends)
- };
- let provider = new textmateProvider_1.TextmateProvider(channel, trace, config);
- manager.regist(provider, 'snippets');
- if (configuration.get('snipmate.enable', true)) {
- let config = {
- author: configuration.get('snipmate.author', ''),
- extends: Object.assign({}, filetypeExtends)
- };
- let provider = new snipmateProvider_1.SnipmateProvider(channel, trace, config);
- manager.regist(provider, 'snipmate');
- }
- if (configuration.get('autoTrigger', true)) {
- let insertTs;
- coc_nvim_1.events.on('InsertCharPre', () => {
- insertTs = Date.now();
- }, null, subscriptions);
- coc_nvim_1.events.on(['TextChanged', 'TextChangedP', 'TextChangedI'], debounce_1.default(async () => {
- if (!coc_nvim_1.workspace.insertMode)
- return;
- if (!insertTs || Date.now() - insertTs > 200)
- return;
- let curr = insertTs;
- let edits = await manager.getTriggerSnippets(true);
- if (insertTs != curr || edits.length == 0)
- return;
- if (edits.length > 1) {
- channel.appendLine(`Multiple snippet found for auto trigger: ${edits.map(s => s.prefix).join(', ')}`);
- coc_nvim_1.workspace.showMessage('Multiple snippet found for auto trigger, check output by :CocCommand workspace.showOutput', 'warning');
- }
- await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[0]);
- await mru.add(edits[0].prefix);
- }, 100), null, subscriptions);
- }
- let statusItem;
- if (configuration.get('enableStatusItem', true)) {
- statusItem = coc_nvim_1.workspace.createStatusBarItem(90, { progress: true });
- statusItem.text = 'loading snippets';
- statusItem.show();
- }
- manager.init().then(() => {
- statusItem === null || statusItem === void 0 ? void 0 : statusItem.hide();
- }, e => {
- statusItem === null || statusItem === void 0 ? void 0 : statusItem.hide();
- coc_nvim_1.workspace.showMessage(`Error on load snippets: ${e.message}`, 'error');
- });
- if (manager.hasProvider) {
- let disposable = coc_nvim_1.languages.registerCompletionItemProvider('snippets', 'S', null, manager, configuration.get('triggerCharacters', []), configuration.get('priority', 90));
- subscriptions.push(disposable);
- }
- async function fallback() {
- await nvim.call('coc#start', [{ source: 'snippets' }]);
- }
- async function doExpand() {
- let edits = await manager.getTriggerSnippets();
- if (edits.length == 0)
- return false;
- if (edits.length == 1) {
- await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[0]);
- await mru.add(edits[0].prefix);
- }
- else {
- let idx = await coc_nvim_1.workspace.showQuickpick(edits.map(e => e.description || e.prefix), 'choose snippet:');
- if (idx == -1)
- return;
- await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[idx]);
- await mru.add(edits[idx].prefix);
- }
- return true;
- }
- if (configuration.get("convertToSnippetsAction")) {
- subscriptions.push(coc_nvim_1.languages.registerCodeActionProvider([{ scheme: 'file' }, { scheme: 'untitled' }], {
- provideCodeActions: async (document, range, context) => {
- if (context.only && !context.only.includes(vscode_languageserver_types_1.CodeActionKind.Source))
- return;
- let text = document.getText(range);
- if (text.endsWith('\n'))
- text = text.replace(/\n$/, '');
- let action = vscode_languageserver_types_1.CodeAction.create('Convert to snippet', {
- command: 'snippets.editSnippets',
- title: 'Convert to snippet',
- arguments: [text]
- });
- return [action];
- }
- }, 'snippets', [vscode_languageserver_types_1.CodeActionKind.Source]));
- }
- subscriptions.push(coc_nvim_1.commands.registerCommand('snippets.editSnippets', async (text) => {
- let buf = await nvim.buffer;
- let doc = coc_nvim_1.workspace.getDocument(buf.id);
- if (!doc) {
- coc_nvim_1.workspace.showMessage('Document not found', 'error');
- return;
- }
- let file = path_1.default.join(snippetsDir, `${doc.filetype}.snippets`);
- if (!fs_1.default.existsSync(file)) {
- await util_1.default.promisify(fs_1.default.writeFile)(file, documentation, 'utf8');
- }
- let uri = coc_nvim_1.Uri.file(file).toString();
- await coc_nvim_1.workspace.jumpTo(uri, null, configuration.get('editSnippetsCommand'));
- if (text) {
- await nvim.command('normal! G');
- await nvim.command('normal! 2o');
- let position = await coc_nvim_1.workspace.getCursorPosition();
- let indent = text.match(/^\s*/)[0];
- text = text.split(/\r?\n/).map(s => s.startsWith(indent) ? s.slice(indent.length) : s).join('\n');
- let escaped = text.replace(/([$}\]])/g, '\\$1');
- // tslint:disable-next-line: no-invalid-template-strings
- let snippet = 'snippet ${1:Tab_trigger} "${2:Description}" ${3:b}\n' + escaped + '\nendsnippet';
- let edit = vscode_languageserver_types_1.TextEdit.insert(position, snippet);
- await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edit);
- }
- }));
- subscriptions.push(coc_nvim_1.commands.registerCommand('snippets.openSnippetFiles', async () => {
- let buf = await nvim.buffer;
- let doc = coc_nvim_1.workspace.getDocument(buf.id);
- if (!doc) {
- coc_nvim_1.workspace.showMessage('Document not found', 'error');
- return;
- }
- let files = await manager.getSnippetFiles(doc.filetype);
- if (!files.length) {
- coc_nvim_1.workspace.showMessage('No related snippet file found', 'warning');
- return;
- }
- let idx = await coc_nvim_1.workspace.showQuickpick(files, 'choose snippet file:');
- if (idx == -1)
- return;
- let uri = coc_nvim_1.Uri.file(files[idx]).toString();
- await coc_nvim_1.workspace.jumpTo(uri, null, configuration.get('editSnippetsCommand'));
- }));
- subscriptions.push(coc_nvim_1.workspace.registerKeymap(['i'], 'snippets-expand', async () => {
- let expanded = await doExpand();
- if (!expanded)
- await fallback();
- }, { silent: true, sync: true, cancel: true }));
- subscriptions.push(coc_nvim_1.workspace.registerKeymap(['i'], 'snippets-expand-jump', async () => {
- let expanded = await doExpand();
- if (!expanded) {
- let bufnr = await nvim.call('bufnr', '%');
- let session = coc_nvim_1.snippetManager.getSession(bufnr);
- if (session && session.isActive) {
- await nvim.call('coc#_cancel', []);
- await coc_nvim_1.snippetManager.nextPlaceholder();
- return;
- }
- await fallback();
- }
- }, { silent: true, sync: true, cancel: true }));
- subscriptions.push(coc_nvim_1.workspace.registerKeymap(['v'], 'snippets-select', async () => {
- let doc = await coc_nvim_1.workspace.document;
- if (!doc)
- return;
- let mode = await nvim.call('visualmode');
- if (['v', 'V'].indexOf(mode) == -1) {
- coc_nvim_1.workspace.showMessage(`visual mode ${mode} not supported`, 'warning');
- return;
- }
- await nvim.command('normal! `<');
- let start = await coc_nvim_1.workspace.getCursorPosition();
- await nvim.command('normal! `>');
- let end = await coc_nvim_1.workspace.getCursorPosition();
- end = vscode_languageserver_types_1.Position.create(end.line, end.character + 1);
- let range = vscode_languageserver_types_1.Range.create(start, end);
- let text = doc.textDocument.getText(range);
- await nvim.call('feedkeys', ['i', 'in']);
- if (mode == 'v') {
- await doc.applyEdits(coc_nvim_1.workspace.nvim, [{ range, newText: '' }]);
- }
- else {
- // keep indent
- let currline = doc.getline(start.line);
- let indent = currline.match(/^\s*/)[0];
- let lines = text.split(/\r?\n/);
- lines = lines.map(s => s.startsWith(indent) ? s.slice(indent.length) : s);
- text = lines.join('\n');
- range = vscode_languageserver_types_1.Range.create(vscode_languageserver_types_1.Position.create(start.line, indent.length), end);
- await doc.applyEdits(coc_nvim_1.workspace.nvim, [{ range, newText: '' }]);
- }
- await nvim.setVar('coc_selected_text', text);
- await coc_nvim_1.workspace.moveTo(range.start);
- }, { silent: true, sync: false, cancel: true }));
- let languageProvider = new languages_1.default(channel, trace);
- subscriptions.push(coc_nvim_1.languages.registerCompletionItemProvider('snippets-source', 'S', ['snippets'], languageProvider, ['$'], configuration.get('priority', 90)));
- subscriptions.push(statusItem);
- subscriptions.push(channel);
- subscriptions.push(coc_nvim_1.listManager.registerList(new snippet_1.default(coc_nvim_1.workspace.nvim, manager, mru)));
- return {
- expandable: async () => {
- let edits;
- try {
- edits = await manager.getTriggerSnippets();
- }
- catch (e) {
- channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Error on getTriggerSnippets: ${e}`);
- }
- return edits && edits.length > 0;
- }
- };
- }
- exports.activate = activate;
-
-
- /***/ }),
- /* 1 */
- /***/ (function(module, exports) {
-
- module.exports = require("coc.nvim");
-
- /***/ }),
- /* 2 */
- /***/ (function(module, exports) {
-
- module.exports = require("os");
-
- /***/ }),
- /* 3 */
- /***/ (function(module, exports) {
-
- module.exports = require("fs");
-
- /***/ }),
- /* 4 */
- /***/ (function(module, exports) {
-
- module.exports = require("path");
-
- /***/ }),
- /* 5 */
- /***/ (function(module, exports) {
-
- module.exports = require("util");
-
- /***/ }),
- /* 6 */
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
-
- "use strict";
- __webpack_require__.r(__webpack_exports__);
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- /**
- * The Position namespace provides helper functions to work with
- * [Position](#Position) literals.
- */
- var Position;
- (function (Position) {
- /**
- * Creates a new Position literal from the given line and character.
- * @param line The position's line.
- * @param character The position's character.
- */
- function create(line, character) {
- return { line: line, character: character };
- }
- Position.create = create;
- /**
- * Checks whether the given liternal conforms to the [Position](#Position) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
- }
- Position.is = is;
- })(Position || (Position = {}));
- /**
- * The Range namespace provides helper functions to work with
- * [Range](#Range) literals.
- */
- var Range;
- (function (Range) {
- function create(one, two, three, four) {
- if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
- return { start: Position.create(one, two), end: Position.create(three, four) };
- }
- else if (Position.is(one) && Position.is(two)) {
- return { start: one, end: two };
- }
- else {
- throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
- }
- }
- Range.create = create;
- /**
- * Checks whether the given literal conforms to the [Range](#Range) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
- }
- Range.is = is;
- })(Range || (Range = {}));
- /**
- * The Location namespace provides helper functions to work with
- * [Location](#Location) literals.
- */
- var Location;
- (function (Location) {
- /**
- * Creates a Location literal.
- * @param uri The location's uri.
- * @param range The location's range.
- */
- function create(uri, range) {
- return { uri: uri, range: range };
- }
- Location.create = create;
- /**
- * Checks whether the given literal conforms to the [Location](#Location) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
- }
- Location.is = is;
- })(Location || (Location = {}));
- /**
- * The LocationLink namespace provides helper functions to work with
- * [LocationLink](#LocationLink) literals.
- */
- var LocationLink;
- (function (LocationLink) {
- /**
- * Creates a LocationLink literal.
- * @param targetUri The definition's uri.
- * @param targetRange The full range of the definition.
- * @param targetSelectionRange The span of the symbol definition at the target.
- * @param originSelectionRange The span of the symbol being defined in the originating source file.
- */
- function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
- return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
- }
- LocationLink.create = create;
- /**
- * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
- && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
- && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
- }
- LocationLink.is = is;
- })(LocationLink || (LocationLink = {}));
- /**
- * The Color namespace provides helper functions to work with
- * [Color](#Color) literals.
- */
- var Color;
- (function (Color) {
- /**
- * Creates a new Color literal.
- */
- function create(red, green, blue, alpha) {
- return {
- red: red,
- green: green,
- blue: blue,
- alpha: alpha,
- };
- }
- Color.create = create;
- /**
- * Checks whether the given literal conforms to the [Color](#Color) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.number(candidate.red)
- && Is.number(candidate.green)
- && Is.number(candidate.blue)
- && Is.number(candidate.alpha);
- }
- Color.is = is;
- })(Color || (Color = {}));
- /**
- * The ColorInformation namespace provides helper functions to work with
- * [ColorInformation](#ColorInformation) literals.
- */
- var ColorInformation;
- (function (ColorInformation) {
- /**
- * Creates a new ColorInformation literal.
- */
- function create(range, color) {
- return {
- range: range,
- color: color,
- };
- }
- ColorInformation.create = create;
- /**
- * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
- */
- function is(value) {
- var candidate = value;
- return Range.is(candidate.range) && Color.is(candidate.color);
- }
- ColorInformation.is = is;
- })(ColorInformation || (ColorInformation = {}));
- /**
- * The Color namespace provides helper functions to work with
- * [ColorPresentation](#ColorPresentation) literals.
- */
- var ColorPresentation;
- (function (ColorPresentation) {
- /**
- * Creates a new ColorInformation literal.
- */
- function create(label, textEdit, additionalTextEdits) {
- return {
- label: label,
- textEdit: textEdit,
- additionalTextEdits: additionalTextEdits,
- };
- }
- ColorPresentation.create = create;
- /**
- * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.string(candidate.label)
- && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
- && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
- }
- ColorPresentation.is = is;
- })(ColorPresentation || (ColorPresentation = {}));
- /**
- * Enum of known range kinds
- */
- var FoldingRangeKind;
- (function (FoldingRangeKind) {
- /**
- * Folding range for a comment
- */
- FoldingRangeKind["Comment"] = "comment";
- /**
- * Folding range for a imports or includes
- */
- FoldingRangeKind["Imports"] = "imports";
- /**
- * Folding range for a region (e.g. `#region`)
- */
- FoldingRangeKind["Region"] = "region";
- })(FoldingRangeKind || (FoldingRangeKind = {}));
- /**
- * The folding range namespace provides helper functions to work with
- * [FoldingRange](#FoldingRange) literals.
- */
- var FoldingRange;
- (function (FoldingRange) {
- /**
- * Creates a new FoldingRange literal.
- */
- function create(startLine, endLine, startCharacter, endCharacter, kind) {
- var result = {
- startLine: startLine,
- endLine: endLine
- };
- if (Is.defined(startCharacter)) {
- result.startCharacter = startCharacter;
- }
- if (Is.defined(endCharacter)) {
- result.endCharacter = endCharacter;
- }
- if (Is.defined(kind)) {
- result.kind = kind;
- }
- return result;
- }
- FoldingRange.create = create;
- /**
- * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.number(candidate.startLine) && Is.number(candidate.startLine)
- && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
- && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
- && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
- }
- FoldingRange.is = is;
- })(FoldingRange || (FoldingRange = {}));
- /**
- * The DiagnosticRelatedInformation namespace provides helper functions to work with
- * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
- */
- var DiagnosticRelatedInformation;
- (function (DiagnosticRelatedInformation) {
- /**
- * Creates a new DiagnosticRelatedInformation literal.
- */
- function create(location, message) {
- return {
- location: location,
- message: message
- };
- }
- DiagnosticRelatedInformation.create = create;
- /**
- * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
- }
- DiagnosticRelatedInformation.is = is;
- })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
- /**
- * The diagnostic's severity.
- */
- var DiagnosticSeverity;
- (function (DiagnosticSeverity) {
- /**
- * Reports an error.
- */
- DiagnosticSeverity.Error = 1;
- /**
- * Reports a warning.
- */
- DiagnosticSeverity.Warning = 2;
- /**
- * Reports an information.
- */
- DiagnosticSeverity.Information = 3;
- /**
- * Reports a hint.
- */
- DiagnosticSeverity.Hint = 4;
- })(DiagnosticSeverity || (DiagnosticSeverity = {}));
- /**
- * The diagnostic tags.
- *
- * @since 3.15.0
- */
- var DiagnosticTag;
- (function (DiagnosticTag) {
- /**
- * Unused or unnecessary code.
- *
- * Clients are allowed to render diagnostics with this tag faded out instead of having
- * an error squiggle.
- */
- DiagnosticTag.Unnecessary = 1;
- /**
- * Deprecated or obsolete code.
- *
- * Clients are allowed to rendered diagnostics with this tag strike through.
- */
- DiagnosticTag.Deprecated = 2;
- })(DiagnosticTag || (DiagnosticTag = {}));
- /**
- * The Diagnostic namespace provides helper functions to work with
- * [Diagnostic](#Diagnostic) literals.
- */
- var Diagnostic;
- (function (Diagnostic) {
- /**
- * Creates a new Diagnostic literal.
- */
- function create(range, message, severity, code, source, relatedInformation) {
- var result = { range: range, message: message };
- if (Is.defined(severity)) {
- result.severity = severity;
- }
- if (Is.defined(code)) {
- result.code = code;
- }
- if (Is.defined(source)) {
- result.source = source;
- }
- if (Is.defined(relatedInformation)) {
- result.relatedInformation = relatedInformation;
- }
- return result;
- }
- Diagnostic.create = create;
- /**
- * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate)
- && Range.is(candidate.range)
- && Is.string(candidate.message)
- && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
- && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
- && (Is.string(candidate.source) || Is.undefined(candidate.source))
- && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
- }
- Diagnostic.is = is;
- })(Diagnostic || (Diagnostic = {}));
- /**
- * The Command namespace provides helper functions to work with
- * [Command](#Command) literals.
- */
- var Command;
- (function (Command) {
- /**
- * Creates a new Command literal.
- */
- function create(title, command) {
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
- }
- var result = { title: title, command: command };
- if (Is.defined(args) && args.length > 0) {
- result.arguments = args;
- }
- return result;
- }
- Command.create = create;
- /**
- * Checks whether the given literal conforms to the [Command](#Command) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
- }
- Command.is = is;
- })(Command || (Command = {}));
- /**
- * The TextEdit namespace provides helper function to create replace,
- * insert and delete edits more easily.
- */
- var TextEdit;
- (function (TextEdit) {
- /**
- * Creates a replace text edit.
- * @param range The range of text to be replaced.
- * @param newText The new text.
- */
- function replace(range, newText) {
- return { range: range, newText: newText };
- }
- TextEdit.replace = replace;
- /**
- * Creates a insert text edit.
- * @param position The position to insert the text at.
- * @param newText The text to be inserted.
- */
- function insert(position, newText) {
- return { range: { start: position, end: position }, newText: newText };
- }
- TextEdit.insert = insert;
- /**
- * Creates a delete text edit.
- * @param range The range of text to be deleted.
- */
- function del(range) {
- return { range: range, newText: '' };
- }
- TextEdit.del = del;
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(candidate)
- && Is.string(candidate.newText)
- && Range.is(candidate.range);
- }
- TextEdit.is = is;
- })(TextEdit || (TextEdit = {}));
- /**
- * The TextDocumentEdit namespace provides helper function to create
- * an edit that manipulates a text document.
- */
- var TextDocumentEdit;
- (function (TextDocumentEdit) {
- /**
- * Creates a new `TextDocumentEdit`
- */
- function create(textDocument, edits) {
- return { textDocument: textDocument, edits: edits };
- }
- TextDocumentEdit.create = create;
- function is(value) {
- var candidate = value;
- return Is.defined(candidate)
- && VersionedTextDocumentIdentifier.is(candidate.textDocument)
- && Array.isArray(candidate.edits);
- }
- TextDocumentEdit.is = is;
- })(TextDocumentEdit || (TextDocumentEdit = {}));
- var CreateFile;
- (function (CreateFile) {
- function create(uri, options) {
- var result = {
- kind: 'create',
- uri: uri
- };
- if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
- result.options = options;
- }
- return result;
- }
- CreateFile.create = create;
- function is(value) {
- var candidate = value;
- return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
- (candidate.options === void 0 ||
- ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
- }
- CreateFile.is = is;
- })(CreateFile || (CreateFile = {}));
- var RenameFile;
- (function (RenameFile) {
- function create(oldUri, newUri, options) {
- var result = {
- kind: 'rename',
- oldUri: oldUri,
- newUri: newUri
- };
- if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
- result.options = options;
- }
- return result;
- }
- RenameFile.create = create;
- function is(value) {
- var candidate = value;
- return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
- (candidate.options === void 0 ||
- ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
- }
- RenameFile.is = is;
- })(RenameFile || (RenameFile = {}));
- var DeleteFile;
- (function (DeleteFile) {
- function create(uri, options) {
- var result = {
- kind: 'delete',
- uri: uri
- };
- if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
- result.options = options;
- }
- return result;
- }
- DeleteFile.create = create;
- function is(value) {
- var candidate = value;
- return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
- (candidate.options === void 0 ||
- ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
- }
- DeleteFile.is = is;
- })(DeleteFile || (DeleteFile = {}));
- var WorkspaceEdit;
- (function (WorkspaceEdit) {
- function is(value) {
- var candidate = value;
- return candidate &&
- (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
- (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
- if (Is.string(change.kind)) {
- return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
- }
- else {
- return TextDocumentEdit.is(change);
- }
- }));
- }
- WorkspaceEdit.is = is;
- })(WorkspaceEdit || (WorkspaceEdit = {}));
- var TextEditChangeImpl = /** @class */ (function () {
- function TextEditChangeImpl(edits) {
- this.edits = edits;
- }
- TextEditChangeImpl.prototype.insert = function (position, newText) {
- this.edits.push(TextEdit.insert(position, newText));
- };
- TextEditChangeImpl.prototype.replace = function (range, newText) {
- this.edits.push(TextEdit.replace(range, newText));
- };
- TextEditChangeImpl.prototype.delete = function (range) {
- this.edits.push(TextEdit.del(range));
- };
- TextEditChangeImpl.prototype.add = function (edit) {
- this.edits.push(edit);
- };
- TextEditChangeImpl.prototype.all = function () {
- return this.edits;
- };
- TextEditChangeImpl.prototype.clear = function () {
- this.edits.splice(0, this.edits.length);
- };
- return TextEditChangeImpl;
- }());
- /**
- * A workspace change helps constructing changes to a workspace.
- */
- var WorkspaceChange = /** @class */ (function () {
- function WorkspaceChange(workspaceEdit) {
- var _this = this;
- this._textEditChanges = Object.create(null);
- if (workspaceEdit) {
- this._workspaceEdit = workspaceEdit;
- if (workspaceEdit.documentChanges) {
- workspaceEdit.documentChanges.forEach(function (change) {
- if (TextDocumentEdit.is(change)) {
- var textEditChange = new TextEditChangeImpl(change.edits);
- _this._textEditChanges[change.textDocument.uri] = textEditChange;
- }
- });
- }
- else if (workspaceEdit.changes) {
- Object.keys(workspaceEdit.changes).forEach(function (key) {
- var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
- _this._textEditChanges[key] = textEditChange;
- });
- }
- }
- }
- Object.defineProperty(WorkspaceChange.prototype, "edit", {
- /**
- * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
- * use to be returned from a workspace edit operation like rename.
- */
- get: function () {
- return this._workspaceEdit;
- },
- enumerable: true,
- configurable: true
- });
- WorkspaceChange.prototype.getTextEditChange = function (key) {
- if (VersionedTextDocumentIdentifier.is(key)) {
- if (!this._workspaceEdit) {
- this._workspaceEdit = {
- documentChanges: []
- };
- }
- if (!this._workspaceEdit.documentChanges) {
- throw new Error('Workspace edit is not configured for document changes.');
- }
- var textDocument = key;
- var result = this._textEditChanges[textDocument.uri];
- if (!result) {
- var edits = [];
- var textDocumentEdit = {
- textDocument: textDocument,
- edits: edits
- };
- this._workspaceEdit.documentChanges.push(textDocumentEdit);
- result = new TextEditChangeImpl(edits);
- this._textEditChanges[textDocument.uri] = result;
- }
- return result;
- }
- else {
- if (!this._workspaceEdit) {
- this._workspaceEdit = {
- changes: Object.create(null)
- };
- }
- if (!this._workspaceEdit.changes) {
- throw new Error('Workspace edit is not configured for normal text edit changes.');
- }
- var result = this._textEditChanges[key];
- if (!result) {
- var edits = [];
- this._workspaceEdit.changes[key] = edits;
- result = new TextEditChangeImpl(edits);
- this._textEditChanges[key] = result;
- }
- return result;
- }
- };
- WorkspaceChange.prototype.createFile = function (uri, options) {
- this.checkDocumentChanges();
- this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
- };
- WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
- this.checkDocumentChanges();
- this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
- };
- WorkspaceChange.prototype.deleteFile = function (uri, options) {
- this.checkDocumentChanges();
- this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
- };
- WorkspaceChange.prototype.checkDocumentChanges = function () {
- if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
- throw new Error('Workspace edit is not configured for document changes.');
- }
- };
- return WorkspaceChange;
- }());
-
- /**
- * The TextDocumentIdentifier namespace provides helper functions to work with
- * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
- */
- var TextDocumentIdentifier;
- (function (TextDocumentIdentifier) {
- /**
- * Creates a new TextDocumentIdentifier literal.
- * @param uri The document's uri.
- */
- function create(uri) {
- return { uri: uri };
- }
- TextDocumentIdentifier.create = create;
- /**
- * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri);
- }
- TextDocumentIdentifier.is = is;
- })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
- /**
- * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
- * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
- */
- var VersionedTextDocumentIdentifier;
- (function (VersionedTextDocumentIdentifier) {
- /**
- * Creates a new VersionedTextDocumentIdentifier literal.
- * @param uri The document's uri.
- * @param uri The document's text.
- */
- function create(uri, version) {
- return { uri: uri, version: version };
- }
- VersionedTextDocumentIdentifier.create = create;
- /**
- * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
- }
- VersionedTextDocumentIdentifier.is = is;
- })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
- /**
- * The TextDocumentItem namespace provides helper functions to work with
- * [TextDocumentItem](#TextDocumentItem) literals.
- */
- var TextDocumentItem;
- (function (TextDocumentItem) {
- /**
- * Creates a new TextDocumentItem literal.
- * @param uri The document's uri.
- * @param languageId The document's language identifier.
- * @param version The document's version number.
- * @param text The document's text.
- */
- function create(uri, languageId, version, text) {
- return { uri: uri, languageId: languageId, version: version, text: text };
- }
- TextDocumentItem.create = create;
- /**
- * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
- }
- TextDocumentItem.is = is;
- })(TextDocumentItem || (TextDocumentItem = {}));
- /**
- * Describes the content type that a client supports in various
- * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
- *
- * Please note that `MarkupKinds` must not start with a `$`. This kinds
- * are reserved for internal usage.
- */
- var MarkupKind;
- (function (MarkupKind) {
- /**
- * Plain text is supported as a content format
- */
- MarkupKind.PlainText = 'plaintext';
- /**
- * Markdown is supported as a content format
- */
- MarkupKind.Markdown = 'markdown';
- })(MarkupKind || (MarkupKind = {}));
- (function (MarkupKind) {
- /**
- * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
- */
- function is(value) {
- var candidate = value;
- return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
- }
- MarkupKind.is = is;
- })(MarkupKind || (MarkupKind = {}));
- var MarkupContent;
- (function (MarkupContent) {
- /**
- * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
- }
- MarkupContent.is = is;
- })(MarkupContent || (MarkupContent = {}));
- /**
- * The kind of a completion entry.
- */
- var CompletionItemKind;
- (function (CompletionItemKind) {
- CompletionItemKind.Text = 1;
- CompletionItemKind.Method = 2;
- CompletionItemKind.Function = 3;
- CompletionItemKind.Constructor = 4;
- CompletionItemKind.Field = 5;
- CompletionItemKind.Variable = 6;
- CompletionItemKind.Class = 7;
- CompletionItemKind.Interface = 8;
- CompletionItemKind.Module = 9;
- CompletionItemKind.Property = 10;
- CompletionItemKind.Unit = 11;
- CompletionItemKind.Value = 12;
- CompletionItemKind.Enum = 13;
- CompletionItemKind.Keyword = 14;
- CompletionItemKind.Snippet = 15;
- CompletionItemKind.Color = 16;
- CompletionItemKind.File = 17;
- CompletionItemKind.Reference = 18;
- CompletionItemKind.Folder = 19;
- CompletionItemKind.EnumMember = 20;
- CompletionItemKind.Constant = 21;
- CompletionItemKind.Struct = 22;
- CompletionItemKind.Event = 23;
- CompletionItemKind.Operator = 24;
- CompletionItemKind.TypeParameter = 25;
- })(CompletionItemKind || (CompletionItemKind = {}));
- /**
- * Defines whether the insert text in a completion item should be interpreted as
- * plain text or a snippet.
- */
- var InsertTextFormat;
- (function (InsertTextFormat) {
- /**
- * The primary text to be inserted is treated as a plain string.
- */
- InsertTextFormat.PlainText = 1;
- /**
- * The primary text to be inserted is treated as a snippet.
- *
- * A snippet can define tab stops and placeholders with `$1`, `$2`
- * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
- * the end of the snippet. Placeholders with equal identifiers are linked,
- * that is typing in one will update others too.
- *
- * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
- */
- InsertTextFormat.Snippet = 2;
- })(InsertTextFormat || (InsertTextFormat = {}));
- /**
- * Completion item tags are extra annotations that tweak the rendering of a completion
- * item.
- *
- * @since 3.15.0
- */
- var CompletionItemTag;
- (function (CompletionItemTag) {
- /**
- * Render a completion as obsolete, usually using a strike-out.
- */
- CompletionItemTag.Deprecated = 1;
- })(CompletionItemTag || (CompletionItemTag = {}));
- /**
- * The CompletionItem namespace provides functions to deal with
- * completion items.
- */
- var CompletionItem;
- (function (CompletionItem) {
- /**
- * Create a completion item and seed it with a label.
- * @param label The completion item's label
- */
- function create(label) {
- return { label: label };
- }
- CompletionItem.create = create;
- })(CompletionItem || (CompletionItem = {}));
- /**
- * The CompletionList namespace provides functions to deal with
- * completion lists.
- */
- var CompletionList;
- (function (CompletionList) {
- /**
- * Creates a new completion list.
- *
- * @param items The completion items.
- * @param isIncomplete The list is not complete.
- */
- function create(items, isIncomplete) {
- return { items: items ? items : [], isIncomplete: !!isIncomplete };
- }
- CompletionList.create = create;
- })(CompletionList || (CompletionList = {}));
- var MarkedString;
- (function (MarkedString) {
- /**
- * Creates a marked string from plain text.
- *
- * @param plainText The plain text.
- */
- function fromPlainText(plainText) {
- return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
- }
- MarkedString.fromPlainText = fromPlainText;
- /**
- * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
- */
- function is(value) {
- var candidate = value;
- return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
- }
- MarkedString.is = is;
- })(MarkedString || (MarkedString = {}));
- var Hover;
- (function (Hover) {
- /**
- * Checks whether the given value conforms to the [Hover](#Hover) interface.
- */
- function is(value) {
- var candidate = value;
- return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
- MarkedString.is(candidate.contents) ||
- Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
- }
- Hover.is = is;
- })(Hover || (Hover = {}));
- /**
- * The ParameterInformation namespace provides helper functions to work with
- * [ParameterInformation](#ParameterInformation) literals.
- */
- var ParameterInformation;
- (function (ParameterInformation) {
- /**
- * Creates a new parameter information literal.
- *
- * @param label A label string.
- * @param documentation A doc string.
- */
- function create(label, documentation) {
- return documentation ? { label: label, documentation: documentation } : { label: label };
- }
- ParameterInformation.create = create;
- })(ParameterInformation || (ParameterInformation = {}));
- /**
- * The SignatureInformation namespace provides helper functions to work with
- * [SignatureInformation](#SignatureInformation) literals.
- */
- var SignatureInformation;
- (function (SignatureInformation) {
- function create(label, documentation) {
- var parameters = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- parameters[_i - 2] = arguments[_i];
- }
- var result = { label: label };
- if (Is.defined(documentation)) {
- result.documentation = documentation;
- }
- if (Is.defined(parameters)) {
- result.parameters = parameters;
- }
- else {
- result.parameters = [];
- }
- return result;
- }
- SignatureInformation.create = create;
- })(SignatureInformation || (SignatureInformation = {}));
- /**
- * A document highlight kind.
- */
- var DocumentHighlightKind;
- (function (DocumentHighlightKind) {
- /**
- * A textual occurrence.
- */
- DocumentHighlightKind.Text = 1;
- /**
- * Read-access of a symbol, like reading a variable.
- */
- DocumentHighlightKind.Read = 2;
- /**
- * Write-access of a symbol, like writing to a variable.
- */
- DocumentHighlightKind.Write = 3;
- })(DocumentHighlightKind || (DocumentHighlightKind = {}));
- /**
- * DocumentHighlight namespace to provide helper functions to work with
- * [DocumentHighlight](#DocumentHighlight) literals.
- */
- var DocumentHighlight;
- (function (DocumentHighlight) {
- /**
- * Create a DocumentHighlight object.
- * @param range The range the highlight applies to.
- */
- function create(range, kind) {
- var result = { range: range };
- if (Is.number(kind)) {
- result.kind = kind;
- }
- return result;
- }
- DocumentHighlight.create = create;
- })(DocumentHighlight || (DocumentHighlight = {}));
- /**
- * A symbol kind.
- */
- var SymbolKind;
- (function (SymbolKind) {
- SymbolKind.File = 1;
- SymbolKind.Module = 2;
- SymbolKind.Namespace = 3;
- SymbolKind.Package = 4;
- SymbolKind.Class = 5;
- SymbolKind.Method = 6;
- SymbolKind.Property = 7;
- SymbolKind.Field = 8;
- SymbolKind.Constructor = 9;
- SymbolKind.Enum = 10;
- SymbolKind.Interface = 11;
- SymbolKind.Function = 12;
- SymbolKind.Variable = 13;
- SymbolKind.Constant = 14;
- SymbolKind.String = 15;
- SymbolKind.Number = 16;
- SymbolKind.Boolean = 17;
- SymbolKind.Array = 18;
- SymbolKind.Object = 19;
- SymbolKind.Key = 20;
- SymbolKind.Null = 21;
- SymbolKind.EnumMember = 22;
- SymbolKind.Struct = 23;
- SymbolKind.Event = 24;
- SymbolKind.Operator = 25;
- SymbolKind.TypeParameter = 26;
- })(SymbolKind || (SymbolKind = {}));
- /**
- * Symbol tags are extra annotations that tweak the rendering of a symbol.
- * @since 3.15
- */
- var SymbolTag;
- (function (SymbolTag) {
- /**
- * Render a symbol as obsolete, usually using a strike-out.
- */
- SymbolTag.Deprecated = 1;
- })(SymbolTag || (SymbolTag = {}));
- var SymbolInformation;
- (function (SymbolInformation) {
- /**
- * Creates a new symbol information literal.
- *
- * @param name The name of the symbol.
- * @param kind The kind of the symbol.
- * @param range The range of the location of the symbol.
- * @param uri The resource of the location of symbol, defaults to the current document.
- * @param containerName The name of the symbol containing the symbol.
- */
- function create(name, kind, range, uri, containerName) {
- var result = {
- name: name,
- kind: kind,
- location: { uri: uri, range: range }
- };
- if (containerName) {
- result.containerName = containerName;
- }
- return result;
- }
- SymbolInformation.create = create;
- })(SymbolInformation || (SymbolInformation = {}));
- var DocumentSymbol;
- (function (DocumentSymbol) {
- /**
- * Creates a new symbol information literal.
- *
- * @param name The name of the symbol.
- * @param detail The detail of the symbol.
- * @param kind The kind of the symbol.
- * @param range The range of the symbol.
- * @param selectionRange The selectionRange of the symbol.
- * @param children Children of the symbol.
- */
- function create(name, detail, kind, range, selectionRange, children) {
- var result = {
- name: name,
- detail: detail,
- kind: kind,
- range: range,
- selectionRange: selectionRange
- };
- if (children !== void 0) {
- result.children = children;
- }
- return result;
- }
- DocumentSymbol.create = create;
- /**
- * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
- */
- function is(value) {
- var candidate = value;
- return candidate &&
- Is.string(candidate.name) && Is.number(candidate.kind) &&
- Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
- (candidate.detail === void 0 || Is.string(candidate.detail)) &&
- (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
- (candidate.children === void 0 || Array.isArray(candidate.children));
- }
- DocumentSymbol.is = is;
- })(DocumentSymbol || (DocumentSymbol = {}));
- /**
- * A set of predefined code action kinds
- */
- var CodeActionKind;
- (function (CodeActionKind) {
- /**
- * Empty kind.
- */
- CodeActionKind.Empty = '';
- /**
- * Base kind for quickfix actions: 'quickfix'
- */
- CodeActionKind.QuickFix = 'quickfix';
- /**
- * Base kind for refactoring actions: 'refactor'
- */
- CodeActionKind.Refactor = 'refactor';
- /**
- * Base kind for refactoring extraction actions: 'refactor.extract'
- *
- * Example extract actions:
- *
- * - Extract method
- * - Extract function
- * - Extract variable
- * - Extract interface from class
- * - ...
- */
- CodeActionKind.RefactorExtract = 'refactor.extract';
- /**
- * Base kind for refactoring inline actions: 'refactor.inline'
- *
- * Example inline actions:
- *
- * - Inline function
- * - Inline variable
- * - Inline constant
- * - ...
- */
- CodeActionKind.RefactorInline = 'refactor.inline';
- /**
- * Base kind for refactoring rewrite actions: 'refactor.rewrite'
- *
- * Example rewrite actions:
- *
- * - Convert JavaScript function to class
- * - Add or remove parameter
- * - Encapsulate field
- * - Make method static
- * - Move method to base class
- * - ...
- */
- CodeActionKind.RefactorRewrite = 'refactor.rewrite';
- /**
- * Base kind for source actions: `source`
- *
- * Source code actions apply to the entire file.
- */
- CodeActionKind.Source = 'source';
- /**
- * Base kind for an organize imports source action: `source.organizeImports`
- */
- CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
- /**
- * Base kind for auto-fix source actions: `source.fixAll`.
- *
- * Fix all actions automatically fix errors that have a clear fix that do not require user input.
- * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
- *
- * @since 3.15.0
- */
- CodeActionKind.SourceFixAll = 'source.fixAll';
- })(CodeActionKind || (CodeActionKind = {}));
- /**
- * The CodeActionContext namespace provides helper functions to work with
- * [CodeActionContext](#CodeActionContext) literals.
- */
- var CodeActionContext;
- (function (CodeActionContext) {
- /**
- * Creates a new CodeActionContext literal.
- */
- function create(diagnostics, only) {
- var result = { diagnostics: diagnostics };
- if (only !== void 0 && only !== null) {
- result.only = only;
- }
- return result;
- }
- CodeActionContext.create = create;
- /**
- * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
- }
- CodeActionContext.is = is;
- })(CodeActionContext || (CodeActionContext = {}));
- var CodeAction;
- (function (CodeAction) {
- function create(title, commandOrEdit, kind) {
- var result = { title: title };
- if (Command.is(commandOrEdit)) {
- result.command = commandOrEdit;
- }
- else {
- result.edit = commandOrEdit;
- }
- if (kind !== void 0) {
- result.kind = kind;
- }
- return result;
- }
- CodeAction.create = create;
- function is(value) {
- var candidate = value;
- return candidate && Is.string(candidate.title) &&
- (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
- (candidate.kind === void 0 || Is.string(candidate.kind)) &&
- (candidate.edit !== void 0 || candidate.command !== void 0) &&
- (candidate.command === void 0 || Command.is(candidate.command)) &&
- (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
- (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
- }
- CodeAction.is = is;
- })(CodeAction || (CodeAction = {}));
- /**
- * The CodeLens namespace provides helper functions to work with
- * [CodeLens](#CodeLens) literals.
- */
- var CodeLens;
- (function (CodeLens) {
- /**
- * Creates a new CodeLens literal.
- */
- function create(range, data) {
- var result = { range: range };
- if (Is.defined(data)) {
- result.data = data;
- }
- return result;
- }
- CodeLens.create = create;
- /**
- * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
- }
- CodeLens.is = is;
- })(CodeLens || (CodeLens = {}));
- /**
- * The FormattingOptions namespace provides helper functions to work with
- * [FormattingOptions](#FormattingOptions) literals.
- */
- var FormattingOptions;
- (function (FormattingOptions) {
- /**
- * Creates a new FormattingOptions literal.
- */
- function create(tabSize, insertSpaces) {
- return { tabSize: tabSize, insertSpaces: insertSpaces };
- }
- FormattingOptions.create = create;
- /**
- * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
- }
- FormattingOptions.is = is;
- })(FormattingOptions || (FormattingOptions = {}));
- /**
- * The DocumentLink namespace provides helper functions to work with
- * [DocumentLink](#DocumentLink) literals.
- */
- var DocumentLink;
- (function (DocumentLink) {
- /**
- * Creates a new DocumentLink literal.
- */
- function create(range, target, data) {
- return { range: range, target: target, data: data };
- }
- DocumentLink.create = create;
- /**
- * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
- }
- DocumentLink.is = is;
- })(DocumentLink || (DocumentLink = {}));
- /**
- * The SelectionRange namespace provides helper function to work with
- * SelectionRange literals.
- */
- var SelectionRange;
- (function (SelectionRange) {
- /**
- * Creates a new SelectionRange
- * @param range the range.
- * @param parent an optional parent.
- */
- function create(range, parent) {
- return { range: range, parent: parent };
- }
- SelectionRange.create = create;
- function is(value) {
- var candidate = value;
- return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
- }
- SelectionRange.is = is;
- })(SelectionRange || (SelectionRange = {}));
- var EOL = ['\n', '\r\n', '\r'];
- /**
- * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
- */
- var TextDocument;
- (function (TextDocument) {
- /**
- * Creates a new ITextDocument literal from the given uri and content.
- * @param uri The document's uri.
- * @param languageId The document's language Id.
- * @param content The document's content.
- */
- function create(uri, languageId, version, content) {
- return new FullTextDocument(uri, languageId, version, content);
- }
- TextDocument.create = create;
- /**
- * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
- && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
- }
- TextDocument.is = is;
- function applyEdits(document, edits) {
- var text = document.getText();
- var sortedEdits = mergeSort(edits, function (a, b) {
- var diff = a.range.start.line - b.range.start.line;
- if (diff === 0) {
- return a.range.start.character - b.range.start.character;
- }
- return diff;
- });
- var lastModifiedOffset = text.length;
- for (var i = sortedEdits.length - 1; i >= 0; i--) {
- var e = sortedEdits[i];
- var startOffset = document.offsetAt(e.range.start);
- var endOffset = document.offsetAt(e.range.end);
- if (endOffset <= lastModifiedOffset) {
- text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
- }
- else {
- throw new Error('Overlapping edit');
- }
- lastModifiedOffset = startOffset;
- }
- return text;
- }
- TextDocument.applyEdits = applyEdits;
- function mergeSort(data, compare) {
- if (data.length <= 1) {
- // sorted
- return data;
- }
- var p = (data.length / 2) | 0;
- var left = data.slice(0, p);
- var right = data.slice(p);
- mergeSort(left, compare);
- mergeSort(right, compare);
- var leftIdx = 0;
- var rightIdx = 0;
- var i = 0;
- while (leftIdx < left.length && rightIdx < right.length) {
- var ret = compare(left[leftIdx], right[rightIdx]);
- if (ret <= 0) {
- // smaller_equal -> take left to preserve order
- data[i++] = left[leftIdx++];
- }
- else {
- // greater -> take right
- data[i++] = right[rightIdx++];
- }
- }
- while (leftIdx < left.length) {
- data[i++] = left[leftIdx++];
- }
- while (rightIdx < right.length) {
- data[i++] = right[rightIdx++];
- }
- return data;
- }
- })(TextDocument || (TextDocument = {}));
- var FullTextDocument = /** @class */ (function () {
- function FullTextDocument(uri, languageId, version, content) {
- this._uri = uri;
- this._languageId = languageId;
- this._version = version;
- this._content = content;
- this._lineOffsets = undefined;
- }
- Object.defineProperty(FullTextDocument.prototype, "uri", {
- get: function () {
- return this._uri;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FullTextDocument.prototype, "languageId", {
- get: function () {
- return this._languageId;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FullTextDocument.prototype, "version", {
- get: function () {
- return this._version;
- },
- enumerable: true,
- configurable: true
- });
- FullTextDocument.prototype.getText = function (range) {
- if (range) {
- var start = this.offsetAt(range.start);
- var end = this.offsetAt(range.end);
- return this._content.substring(start, end);
- }
- return this._content;
- };
- FullTextDocument.prototype.update = function (event, version) {
- this._content = event.text;
- this._version = version;
- this._lineOffsets = undefined;
- };
- FullTextDocument.prototype.getLineOffsets = function () {
- if (this._lineOffsets === undefined) {
- var lineOffsets = [];
- var text = this._content;
- var isLineStart = true;
- for (var i = 0; i < text.length; i++) {
- if (isLineStart) {
- lineOffsets.push(i);
- isLineStart = false;
- }
- var ch = text.charAt(i);
- isLineStart = (ch === '\r' || ch === '\n');
- if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
- i++;
- }
- }
- if (isLineStart && text.length > 0) {
- lineOffsets.push(text.length);
- }
- this._lineOffsets = lineOffsets;
- }
- return this._lineOffsets;
- };
- FullTextDocument.prototype.positionAt = function (offset) {
- offset = Math.max(Math.min(offset, this._content.length), 0);
- var lineOffsets = this.getLineOffsets();
- var low = 0, high = lineOffsets.length;
- if (high === 0) {
- return Position.create(0, offset);
- }
- while (low < high) {
- var mid = Math.floor((low + high) / 2);
- if (lineOffsets[mid] > offset) {
- high = mid;
- }
- else {
- low = mid + 1;
- }
- }
- // low is the least x for which the line offset is larger than the current offset
- // or array.length if no line offset is larger than the current offset
- var line = low - 1;
- return Position.create(line, offset - lineOffsets[line]);
- };
- FullTextDocument.prototype.offsetAt = function (position) {
- var lineOffsets = this.getLineOffsets();
- if (position.line >= lineOffsets.length) {
- return this._content.length;
- }
- else if (position.line < 0) {
- return 0;
- }
- var lineOffset = lineOffsets[position.line];
- var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
- return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
- };
- Object.defineProperty(FullTextDocument.prototype, "lineCount", {
- get: function () {
- return this.getLineOffsets().length;
- },
- enumerable: true,
- configurable: true
- });
- return FullTextDocument;
- }());
- var Is;
- (function (Is) {
- var toString = Object.prototype.toString;
- function defined(value) {
- return typeof value !== 'undefined';
- }
- Is.defined = defined;
- function undefined(value) {
- return typeof value === 'undefined';
- }
- Is.undefined = undefined;
- function boolean(value) {
- return value === true || value === false;
- }
- Is.boolean = boolean;
- function string(value) {
- return toString.call(value) === '[object String]';
- }
- Is.string = string;
- function number(value) {
- return toString.call(value) === '[object Number]';
- }
- Is.number = number;
- function func(value) {
- return toString.call(value) === '[object Function]';
- }
- Is.func = func;
- function objectLiteral(value) {
- // Strictly speaking class instances pass this check as well. Since the LSP
- // doesn't use classes we ignore this for now. If we do we need to add something
- // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
- return value !== null && typeof value === 'object';
- }
- Is.objectLiteral = objectLiteral;
- function typedArray(value, check) {
- return Array.isArray(value) && value.every(check);
- }
- Is.typedArray = typedArray;
- })(Is || (Is = {}));
-
-
- /***/ }),
- /* 7 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(8);
- const os_1 = __importDefault(__webpack_require__(2));
- class SnippetsList extends coc_nvim_1.BasicList {
- constructor(nvim, manager, mru) {
- super(nvim);
- this.manager = manager;
- this.mru = mru;
- this.name = 'snippets';
- this.description = 'snippets list';
- this.addLocationActions();
- }
- async loadItems(context) {
- let { window } = context;
- let valid = await window.valid;
- if (!valid)
- return;
- let buf = await window.buffer;
- let doc = coc_nvim_1.workspace.getDocument(buf.id);
- if (!doc)
- return [];
- let snippets = await this.manager.getSnippets(doc.filetype);
- let res = [];
- let recents = await this.mru.load();
- for (let snip of snippets) {
- let pos = vscode_languageserver_protocol_1.Position.create(snip.lnum, 0);
- let location = vscode_languageserver_protocol_1.Location.create(coc_nvim_1.Uri.file(snip.filepath).toString(), vscode_languageserver_protocol_1.Range.create(pos, pos));
- let prefix = snip.prefix;
- if (prefix.length < 20) {
- prefix = `${prefix}${' '.repeat(20 - prefix.length)}`;
- }
- let idx = recents.indexOf(snip.prefix);
- res.push({
- label: `${prefix}\t${snip.description}\t${snip.filepath.replace(os_1.default.homedir(), '~')}`,
- filterText: `${snip.prefix} ${snip.description}`,
- location,
- recentScore: idx == -1 ? -1 : recents.length - idx
- });
- }
- return res;
- }
- async doHighlight() {
- let { nvim } = coc_nvim_1.workspace;
- nvim.pauseNotification();
- nvim.command('syntax match CocSnippetsPrefix /\\v^\\S+/ contained containedin=CocSnippetsLine', true);
- nvim.command('syntax match CocSnippetsFile /\\v\\t\\S+$/ contained containedin=CocSnippetsLine', true);
- nvim.command('highlight default link CocSnippetsPrefix Identifier', true);
- nvim.command('highlight default link CocSnippetsFile Comment', true);
- await nvim.resumeNotification();
- }
- }
- exports.default = SnippetsList;
-
-
- /***/ }),
- /* 8 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
- exports.ResponseError = vscode_jsonrpc_1.ResponseError;
- exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
- exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
- exports.Disposable = vscode_jsonrpc_1.Disposable;
- exports.Event = vscode_jsonrpc_1.Event;
- exports.Emitter = vscode_jsonrpc_1.Emitter;
- exports.Trace = vscode_jsonrpc_1.Trace;
- exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
- exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
- exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
- exports.RequestType = vscode_jsonrpc_1.RequestType;
- exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
- exports.NotificationType = vscode_jsonrpc_1.NotificationType;
- exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
- exports.MessageReader = vscode_jsonrpc_1.MessageReader;
- exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
- exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
- exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
- exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
- exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
- exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
- exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
- exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
- exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
- exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
- exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
- exports.ProgressType = vscode_jsonrpc_1.ProgressType;
- __export(__webpack_require__(6));
- __export(__webpack_require__(21));
- const callHierarchy = __webpack_require__(33);
- const st = __webpack_require__(34);
- var Proposed;
- (function (Proposed) {
- let CallHierarchyPrepareRequest;
- (function (CallHierarchyPrepareRequest) {
- CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
- CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
- })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
- let CallHierarchyIncomingCallsRequest;
- (function (CallHierarchyIncomingCallsRequest) {
- CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
- CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
- })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
- let CallHierarchyOutgoingCallsRequest;
- (function (CallHierarchyOutgoingCallsRequest) {
- CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
- CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
- })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
- Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
- Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
- Proposed.SemanticTokens = st.SemanticTokens;
- let SemanticTokensRequest;
- (function (SemanticTokensRequest) {
- SemanticTokensRequest.method = st.SemanticTokensRequest.method;
- SemanticTokensRequest.type = st.SemanticTokensRequest.type;
- })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
- let SemanticTokensEditsRequest;
- (function (SemanticTokensEditsRequest) {
- SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
- SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
- })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
- let SemanticTokensRangeRequest;
- (function (SemanticTokensRangeRequest) {
- SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
- SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
- })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
- })(Proposed = exports.Proposed || (exports.Proposed = {}));
- function createProtocolConnection(reader, writer, logger, strategy) {
- return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
- }
- exports.createProtocolConnection = createProtocolConnection;
-
-
- /***/ }),
- /* 9 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
- /// <reference path="../typings/thenable.d.ts" />
-
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- Object.defineProperty(exports, "__esModule", { value: true });
- const Is = __webpack_require__(10);
- const messages_1 = __webpack_require__(11);
- exports.RequestType = messages_1.RequestType;
- exports.RequestType0 = messages_1.RequestType0;
- exports.RequestType1 = messages_1.RequestType1;
- exports.RequestType2 = messages_1.RequestType2;
- exports.RequestType3 = messages_1.RequestType3;
- exports.RequestType4 = messages_1.RequestType4;
- exports.RequestType5 = messages_1.RequestType5;
- exports.RequestType6 = messages_1.RequestType6;
- exports.RequestType7 = messages_1.RequestType7;
- exports.RequestType8 = messages_1.RequestType8;
- exports.RequestType9 = messages_1.RequestType9;
- exports.ResponseError = messages_1.ResponseError;
- exports.ErrorCodes = messages_1.ErrorCodes;
- exports.NotificationType = messages_1.NotificationType;
- exports.NotificationType0 = messages_1.NotificationType0;
- exports.NotificationType1 = messages_1.NotificationType1;
- exports.NotificationType2 = messages_1.NotificationType2;
- exports.NotificationType3 = messages_1.NotificationType3;
- exports.NotificationType4 = messages_1.NotificationType4;
- exports.NotificationType5 = messages_1.NotificationType5;
- exports.NotificationType6 = messages_1.NotificationType6;
- exports.NotificationType7 = messages_1.NotificationType7;
- exports.NotificationType8 = messages_1.NotificationType8;
- exports.NotificationType9 = messages_1.NotificationType9;
- const messageReader_1 = __webpack_require__(12);
- exports.MessageReader = messageReader_1.MessageReader;
- exports.StreamMessageReader = messageReader_1.StreamMessageReader;
- exports.IPCMessageReader = messageReader_1.IPCMessageReader;
- exports.SocketMessageReader = messageReader_1.SocketMessageReader;
- const messageWriter_1 = __webpack_require__(14);
- exports.MessageWriter = messageWriter_1.MessageWriter;
- exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
- exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
- exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
- const events_1 = __webpack_require__(13);
- exports.Disposable = events_1.Disposable;
- exports.Event = events_1.Event;
- exports.Emitter = events_1.Emitter;
- const cancellation_1 = __webpack_require__(15);
- exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
- exports.CancellationToken = cancellation_1.CancellationToken;
- const linkedMap_1 = __webpack_require__(16);
- __export(__webpack_require__(17));
- __export(__webpack_require__(20));
- var CancelNotification;
- (function (CancelNotification) {
- CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
- })(CancelNotification || (CancelNotification = {}));
- var ProgressNotification;
- (function (ProgressNotification) {
- ProgressNotification.type = new messages_1.NotificationType('$/progress');
- })(ProgressNotification || (ProgressNotification = {}));
- class ProgressType {
- constructor() {
- }
- }
- exports.ProgressType = ProgressType;
- exports.NullLogger = Object.freeze({
- error: () => { },
- warn: () => { },
- info: () => { },
- log: () => { }
- });
- var Trace;
- (function (Trace) {
- Trace[Trace["Off"] = 0] = "Off";
- Trace[Trace["Messages"] = 1] = "Messages";
- Trace[Trace["Verbose"] = 2] = "Verbose";
- })(Trace = exports.Trace || (exports.Trace = {}));
- (function (Trace) {
- function fromString(value) {
- if (!Is.string(value)) {
- return Trace.Off;
- }
- value = value.toLowerCase();
- switch (value) {
- case 'off':
- return Trace.Off;
- case 'messages':
- return Trace.Messages;
- case 'verbose':
- return Trace.Verbose;
- default:
- return Trace.Off;
- }
- }
- Trace.fromString = fromString;
- function toString(value) {
- switch (value) {
- case Trace.Off:
- return 'off';
- case Trace.Messages:
- return 'messages';
- case Trace.Verbose:
- return 'verbose';
- default:
- return 'off';
- }
- }
- Trace.toString = toString;
- })(Trace = exports.Trace || (exports.Trace = {}));
- var TraceFormat;
- (function (TraceFormat) {
- TraceFormat["Text"] = "text";
- TraceFormat["JSON"] = "json";
- })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
- (function (TraceFormat) {
- function fromString(value) {
- value = value.toLowerCase();
- if (value === 'json') {
- return TraceFormat.JSON;
- }
- else {
- return TraceFormat.Text;
- }
- }
- TraceFormat.fromString = fromString;
- })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
- var SetTraceNotification;
- (function (SetTraceNotification) {
- SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
- })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
- var LogTraceNotification;
- (function (LogTraceNotification) {
- LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
- })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
- var ConnectionErrors;
- (function (ConnectionErrors) {
- /**
- * The connection is closed.
- */
- ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
- /**
- * The connection got disposed.
- */
- ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
- /**
- * The connection is already in listening mode.
- */
- ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
- })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
- class ConnectionError extends Error {
- constructor(code, message) {
- super(message);
- this.code = code;
- Object.setPrototypeOf(this, ConnectionError.prototype);
- }
- }
- exports.ConnectionError = ConnectionError;
- var ConnectionStrategy;
- (function (ConnectionStrategy) {
- function is(value) {
- let candidate = value;
- return candidate && Is.func(candidate.cancelUndispatched);
- }
- ConnectionStrategy.is = is;
- })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
- var ConnectionState;
- (function (ConnectionState) {
- ConnectionState[ConnectionState["New"] = 1] = "New";
- ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
- ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
- ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
- })(ConnectionState || (ConnectionState = {}));
- function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
- let sequenceNumber = 0;
- let notificationSquenceNumber = 0;
- let unknownResponseSquenceNumber = 0;
- const version = '2.0';
- let starRequestHandler = undefined;
- let requestHandlers = Object.create(null);
- let starNotificationHandler = undefined;
- let notificationHandlers = Object.create(null);
- let progressHandlers = new Map();
- let timer;
- let messageQueue = new linkedMap_1.LinkedMap();
- let responsePromises = Object.create(null);
- let requestTokens = Object.create(null);
- let trace = Trace.Off;
- let traceFormat = TraceFormat.Text;
- let tracer;
- let state = ConnectionState.New;
- let errorEmitter = new events_1.Emitter();
- let closeEmitter = new events_1.Emitter();
- let unhandledNotificationEmitter = new events_1.Emitter();
- let unhandledProgressEmitter = new events_1.Emitter();
- let disposeEmitter = new events_1.Emitter();
- function createRequestQueueKey(id) {
- return 'req-' + id.toString();
- }
- function createResponseQueueKey(id) {
- if (id === null) {
- return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
- }
- else {
- return 'res-' + id.toString();
- }
- }
- function createNotificationQueueKey() {
- return 'not-' + (++notificationSquenceNumber).toString();
- }
- function addMessageToQueue(queue, message) {
- if (messages_1.isRequestMessage(message)) {
- queue.set(createRequestQueueKey(message.id), message);
- }
- else if (messages_1.isResponseMessage(message)) {
- queue.set(createResponseQueueKey(message.id), message);
- }
- else {
- queue.set(createNotificationQueueKey(), message);
- }
- }
- function cancelUndispatched(_message) {
- return undefined;
- }
- function isListening() {
- return state === ConnectionState.Listening;
- }
- function isClosed() {
- return state === ConnectionState.Closed;
- }
- function isDisposed() {
- return state === ConnectionState.Disposed;
- }
- function closeHandler() {
- if (state === ConnectionState.New || state === ConnectionState.Listening) {
- state = ConnectionState.Closed;
- closeEmitter.fire(undefined);
- }
- // If the connection is disposed don't sent close events.
- }
- function readErrorHandler(error) {
- errorEmitter.fire([error, undefined, undefined]);
- }
- function writeErrorHandler(data) {
- errorEmitter.fire(data);
- }
- messageReader.onClose(closeHandler);
- messageReader.onError(readErrorHandler);
- messageWriter.onClose(closeHandler);
- messageWriter.onError(writeErrorHandler);
- function triggerMessageQueue() {
- if (timer || messageQueue.size === 0) {
- return;
- }
- timer = setImmediate(() => {
- timer = undefined;
- processMessageQueue();
- });
- }
- function processMessageQueue() {
- if (messageQueue.size === 0) {
- return;
- }
- let message = messageQueue.shift();
- try {
- if (messages_1.isRequestMessage(message)) {
- handleRequest(message);
- }
- else if (messages_1.isNotificationMessage(message)) {
- handleNotification(message);
- }
- else if (messages_1.isResponseMessage(message)) {
- handleResponse(message);
- }
- else {
- handleInvalidMessage(message);
- }
- }
- finally {
- triggerMessageQueue();
- }
- }
- let callback = (message) => {
- try {
- // We have received a cancellation message. Check if the message is still in the queue
- // and cancel it if allowed to do so.
- if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
- let key = createRequestQueueKey(message.params.id);
- let toCancel = messageQueue.get(key);
- if (messages_1.isRequestMessage(toCancel)) {
- let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
- if (response && (response.error !== void 0 || response.result !== void 0)) {
- messageQueue.delete(key);
- response.id = toCancel.id;
- traceSendingResponse(response, message.method, Date.now());
- messageWriter.write(response);
- return;
- }
- }
- }
- addMessageToQueue(messageQueue, message);
- }
- finally {
- triggerMessageQueue();
- }
- };
- function handleRequest(requestMessage) {
- if (isDisposed()) {
- // we return here silently since we fired an event when the
- // connection got disposed.
- return;
- }
- function reply(resultOrError, method, startTime) {
- let message = {
- jsonrpc: version,
- id: requestMessage.id
- };
- if (resultOrError instanceof messages_1.ResponseError) {
- message.error = resultOrError.toJson();
- }
- else {
- message.result = resultOrError === void 0 ? null : resultOrError;
- }
- traceSendingResponse(message, method, startTime);
- messageWriter.write(message);
- }
- function replyError(error, method, startTime) {
- let message = {
- jsonrpc: version,
- id: requestMessage.id,
- error: error.toJson()
- };
- traceSendingResponse(message, method, startTime);
- messageWriter.write(message);
- }
- function replySuccess(result, method, startTime) {
- // The JSON RPC defines that a response must either have a result or an error
- // So we can't treat undefined as a valid response result.
- if (result === void 0) {
- result = null;
- }
- let message = {
- jsonrpc: version,
- id: requestMessage.id,
- result: result
- };
- traceSendingResponse(message, method, startTime);
- messageWriter.write(message);
- }
- traceReceivedRequest(requestMessage);
- let element = requestHandlers[requestMessage.method];
- let type;
- let requestHandler;
- if (element) {
- type = element.type;
- requestHandler = element.handler;
- }
- let startTime = Date.now();
- if (requestHandler || starRequestHandler) {
- let cancellationSource = new cancellation_1.CancellationTokenSource();
- let tokenKey = String(requestMessage.id);
- requestTokens[tokenKey] = cancellationSource;
- try {
- let handlerResult;
- if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
- handlerResult = requestHandler
- ? requestHandler(cancellationSource.token)
- : starRequestHandler(requestMessage.method, cancellationSource.token);
- }
- else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
- handlerResult = requestHandler
- ? requestHandler(...requestMessage.params, cancellationSource.token)
- : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
- }
- else {
- handlerResult = requestHandler
- ? requestHandler(requestMessage.params, cancellationSource.token)
- : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
- }
- let promise = handlerResult;
- if (!handlerResult) {
- delete requestTokens[tokenKey];
- replySuccess(handlerResult, requestMessage.method, startTime);
- }
- else if (promise.then) {
- promise.then((resultOrError) => {
- delete requestTokens[tokenKey];
- reply(resultOrError, requestMessage.method, startTime);
- }, error => {
- delete requestTokens[tokenKey];
- if (error instanceof messages_1.ResponseError) {
- replyError(error, requestMessage.method, startTime);
- }
- else if (error && Is.string(error.message)) {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
- }
- else {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
- }
- });
- }
- else {
- delete requestTokens[tokenKey];
- reply(handlerResult, requestMessage.method, startTime);
- }
- }
- catch (error) {
- delete requestTokens[tokenKey];
- if (error instanceof messages_1.ResponseError) {
- reply(error, requestMessage.method, startTime);
- }
- else if (error && Is.string(error.message)) {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
- }
- else {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
- }
- }
- }
- else {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
- }
- }
- function handleResponse(responseMessage) {
- if (isDisposed()) {
- // See handle request.
- return;
- }
- if (responseMessage.id === null) {
- if (responseMessage.error) {
- logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
- }
- else {
- logger.error(`Received response message without id. No further error information provided.`);
- }
- }
- else {
- let key = String(responseMessage.id);
- let responsePromise = responsePromises[key];
- traceReceivedResponse(responseMessage, responsePromise);
- if (responsePromise) {
- delete responsePromises[key];
- try {
- if (responseMessage.error) {
- let error = responseMessage.error;
- responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
- }
- else if (responseMessage.result !== void 0) {
- responsePromise.resolve(responseMessage.result);
- }
- else {
- throw new Error('Should never happen.');
- }
- }
- catch (error) {
- if (error.message) {
- logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
- }
- else {
- logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
- }
- }
- }
- }
- }
- function handleNotification(message) {
- if (isDisposed()) {
- // See handle request.
- return;
- }
- let type = undefined;
- let notificationHandler;
- if (message.method === CancelNotification.type.method) {
- notificationHandler = (params) => {
- let id = params.id;
- let source = requestTokens[String(id)];
- if (source) {
- source.cancel();
- }
- };
- }
- else {
- let element = notificationHandlers[message.method];
- if (element) {
- notificationHandler = element.handler;
- type = element.type;
- }
- }
- if (notificationHandler || starNotificationHandler) {
- try {
- traceReceivedNotification(message);
- if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
- notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
- }
- else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
- notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
- }
- else {
- notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
- }
- }
- catch (error) {
- if (error.message) {
- logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
- }
- else {
- logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
- }
- }
- }
- else {
- unhandledNotificationEmitter.fire(message);
- }
- }
- function handleInvalidMessage(message) {
- if (!message) {
- logger.error('Received empty message.');
- return;
- }
- logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
- // Test whether we find an id to reject the promise
- let responseMessage = message;
- if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
- let key = String(responseMessage.id);
- let responseHandler = responsePromises[key];
- if (responseHandler) {
- responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
- }
- }
- }
- function traceSendingRequest(message) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose && message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
- }
- else {
- logLSPMessage('send-request', message);
- }
- }
- function traceSendingNotification(message) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- else {
- data = 'No parameters provided.\n\n';
- }
- }
- tracer.log(`Sending notification '${message.method}'.`, data);
- }
- else {
- logLSPMessage('send-notification', message);
- }
- }
- function traceSendingResponse(message, method, startTime) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.error && message.error.data) {
- data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
- }
- else {
- if (message.result) {
- data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
- }
- else if (message.error === void 0) {
- data = 'No result returned.\n\n';
- }
- }
- }
- tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
- }
- else {
- logLSPMessage('send-response', message);
- }
- }
- function traceReceivedRequest(message) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose && message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
- }
- else {
- logLSPMessage('receive-request', message);
- }
- }
- function traceReceivedNotification(message) {
- if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- else {
- data = 'No parameters provided.\n\n';
- }
- }
- tracer.log(`Received notification '${message.method}'.`, data);
- }
- else {
- logLSPMessage('receive-notification', message);
- }
- }
- function traceReceivedResponse(message, responsePromise) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.error && message.error.data) {
- data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
- }
- else {
- if (message.result) {
- data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
- }
- else if (message.error === void 0) {
- data = 'No result returned.\n\n';
- }
- }
- }
- if (responsePromise) {
- let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
- tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
- }
- else {
- tracer.log(`Received response ${message.id} without active response promise.`, data);
- }
- }
- else {
- logLSPMessage('receive-response', message);
- }
- }
- function logLSPMessage(type, message) {
- if (!tracer || trace === Trace.Off) {
- return;
- }
- const lspMessage = {
- isLSPMessage: true,
- type,
- message,
- timestamp: Date.now()
- };
- tracer.log(lspMessage);
- }
- function throwIfClosedOrDisposed() {
- if (isClosed()) {
- throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
- }
- if (isDisposed()) {
- throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
- }
- }
- function throwIfListening() {
- if (isListening()) {
- throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
- }
- }
- function throwIfNotListening() {
- if (!isListening()) {
- throw new Error('Call listen() first.');
- }
- }
- function undefinedToNull(param) {
- if (param === void 0) {
- return null;
- }
- else {
- return param;
- }
- }
- function computeMessageParams(type, params) {
- let result;
- let numberOfParams = type.numberOfParams;
- switch (numberOfParams) {
- case 0:
- result = null;
- break;
- case 1:
- result = undefinedToNull(params[0]);
- break;
- default:
- result = [];
- for (let i = 0; i < params.length && i < numberOfParams; i++) {
- result.push(undefinedToNull(params[i]));
- }
- if (params.length < numberOfParams) {
- for (let i = params.length; i < numberOfParams; i++) {
- result.push(null);
- }
- }
- break;
- }
- return result;
- }
- let connection = {
- sendNotification: (type, ...params) => {
- throwIfClosedOrDisposed();
- let method;
- let messageParams;
- if (Is.string(type)) {
- method = type;
- switch (params.length) {
- case 0:
- messageParams = null;
- break;
- case 1:
- messageParams = params[0];
- break;
- default:
- messageParams = params;
- break;
- }
- }
- else {
- method = type.method;
- messageParams = computeMessageParams(type, params);
- }
- let notificationMessage = {
- jsonrpc: version,
- method: method,
- params: messageParams
- };
- traceSendingNotification(notificationMessage);
- messageWriter.write(notificationMessage);
- },
- onNotification: (type, handler) => {
- throwIfClosedOrDisposed();
- if (Is.func(type)) {
- starNotificationHandler = type;
- }
- else if (handler) {
- if (Is.string(type)) {
- notificationHandlers[type] = { type: undefined, handler };
- }
- else {
- notificationHandlers[type.method] = { type, handler };
- }
- }
- },
- onProgress: (_type, token, handler) => {
- if (progressHandlers.has(token)) {
- throw new Error(`Progress handler for token ${token} already registered`);
- }
- progressHandlers.set(token, handler);
- return {
- dispose: () => {
- progressHandlers.delete(token);
- }
- };
- },
- sendProgress: (_type, token, value) => {
- connection.sendNotification(ProgressNotification.type, { token, value });
- },
- onUnhandledProgress: unhandledProgressEmitter.event,
- sendRequest: (type, ...params) => {
- throwIfClosedOrDisposed();
- throwIfNotListening();
- let method;
- let messageParams;
- let token = undefined;
- if (Is.string(type)) {
- method = type;
- switch (params.length) {
- case 0:
- messageParams = null;
- break;
- case 1:
- // The cancellation token is optional so it can also be undefined.
- if (cancellation_1.CancellationToken.is(params[0])) {
- messageParams = null;
- token = params[0];
- }
- else {
- messageParams = undefinedToNull(params[0]);
- }
- break;
- default:
- const last = params.length - 1;
- if (cancellation_1.CancellationToken.is(params[last])) {
- token = params[last];
- if (params.length === 2) {
- messageParams = undefinedToNull(params[0]);
- }
- else {
- messageParams = params.slice(0, last).map(value => undefinedToNull(value));
- }
- }
- else {
- messageParams = params.map(value => undefinedToNull(value));
- }
- break;
- }
- }
- else {
- method = type.method;
- messageParams = computeMessageParams(type, params);
- let numberOfParams = type.numberOfParams;
- token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
- }
- let id = sequenceNumber++;
- let result = new Promise((resolve, reject) => {
- let requestMessage = {
- jsonrpc: version,
- id: id,
- method: method,
- params: messageParams
- };
- let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
- traceSendingRequest(requestMessage);
- try {
- messageWriter.write(requestMessage);
- }
- catch (e) {
- // Writing the message failed. So we need to reject the promise.
- responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
- responsePromise = null;
- }
- if (responsePromise) {
- responsePromises[String(id)] = responsePromise;
- }
- });
- if (token) {
- token.onCancellationRequested(() => {
- connection.sendNotification(CancelNotification.type, { id });
- });
- }
- return result;
- },
- onRequest: (type, handler) => {
- throwIfClosedOrDisposed();
- if (Is.func(type)) {
- starRequestHandler = type;
- }
- else if (handler) {
- if (Is.string(type)) {
- requestHandlers[type] = { type: undefined, handler };
- }
- else {
- requestHandlers[type.method] = { type, handler };
- }
- }
- },
- trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
- let _sendNotification = false;
- let _traceFormat = TraceFormat.Text;
- if (sendNotificationOrTraceOptions !== void 0) {
- if (Is.boolean(sendNotificationOrTraceOptions)) {
- _sendNotification = sendNotificationOrTraceOptions;
- }
- else {
- _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
- _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
- }
- }
- trace = _value;
- traceFormat = _traceFormat;
- if (trace === Trace.Off) {
- tracer = undefined;
- }
- else {
- tracer = _tracer;
- }
- if (_sendNotification && !isClosed() && !isDisposed()) {
- connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
- }
- },
- onError: errorEmitter.event,
- onClose: closeEmitter.event,
- onUnhandledNotification: unhandledNotificationEmitter.event,
- onDispose: disposeEmitter.event,
- dispose: () => {
- if (isDisposed()) {
- return;
- }
- state = ConnectionState.Disposed;
- disposeEmitter.fire(undefined);
- let error = new Error('Connection got disposed.');
- Object.keys(responsePromises).forEach((key) => {
- responsePromises[key].reject(error);
- });
- responsePromises = Object.create(null);
- requestTokens = Object.create(null);
- messageQueue = new linkedMap_1.LinkedMap();
- // Test for backwards compatibility
- if (Is.func(messageWriter.dispose)) {
- messageWriter.dispose();
- }
- if (Is.func(messageReader.dispose)) {
- messageReader.dispose();
- }
- },
- listen: () => {
- throwIfClosedOrDisposed();
- throwIfListening();
- state = ConnectionState.Listening;
- messageReader.listen(callback);
- },
- inspect: () => {
- // eslint-disable-next-line no-console
- console.log('inspect');
- }
- };
- connection.onNotification(LogTraceNotification.type, (params) => {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
- });
- connection.onNotification(ProgressNotification.type, (params) => {
- const handler = progressHandlers.get(params.token);
- if (handler) {
- handler(params.value);
- }
- else {
- unhandledProgressEmitter.fire(params);
- }
- });
- return connection;
- }
- function isMessageReader(value) {
- return value.listen !== void 0 && value.read === void 0;
- }
- function isMessageWriter(value) {
- return value.write !== void 0 && value.end === void 0;
- }
- function createMessageConnection(input, output, logger, strategy) {
- if (!logger) {
- logger = exports.NullLogger;
- }
- let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
- let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
- return _createMessageConnection(reader, writer, logger, strategy);
- }
- exports.createMessageConnection = createMessageConnection;
-
-
- /***/ }),
- /* 10 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- function boolean(value) {
- return value === true || value === false;
- }
- exports.boolean = boolean;
- function string(value) {
- return typeof value === 'string' || value instanceof String;
- }
- exports.string = string;
- function number(value) {
- return typeof value === 'number' || value instanceof Number;
- }
- exports.number = number;
- function error(value) {
- return value instanceof Error;
- }
- exports.error = error;
- function func(value) {
- return typeof value === 'function';
- }
- exports.func = func;
- function array(value) {
- return Array.isArray(value);
- }
- exports.array = array;
- function stringArray(value) {
- return array(value) && value.every(elem => string(elem));
- }
- exports.stringArray = stringArray;
-
-
- /***/ }),
- /* 11 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const is = __webpack_require__(10);
- /**
- * Predefined error codes.
- */
- var ErrorCodes;
- (function (ErrorCodes) {
- // Defined by JSON RPC
- ErrorCodes.ParseError = -32700;
- ErrorCodes.InvalidRequest = -32600;
- ErrorCodes.MethodNotFound = -32601;
- ErrorCodes.InvalidParams = -32602;
- ErrorCodes.InternalError = -32603;
- ErrorCodes.serverErrorStart = -32099;
- ErrorCodes.serverErrorEnd = -32000;
- ErrorCodes.ServerNotInitialized = -32002;
- ErrorCodes.UnknownErrorCode = -32001;
- // Defined by the protocol.
- ErrorCodes.RequestCancelled = -32800;
- ErrorCodes.ContentModified = -32801;
- // Defined by VSCode library.
- ErrorCodes.MessageWriteError = 1;
- ErrorCodes.MessageReadError = 2;
- })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
- /**
- * An error object return in a response in case a request
- * has failed.
- */
- class ResponseError extends Error {
- constructor(code, message, data) {
- super(message);
- this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
- this.data = data;
- Object.setPrototypeOf(this, ResponseError.prototype);
- }
- toJson() {
- return {
- code: this.code,
- message: this.message,
- data: this.data,
- };
- }
- }
- exports.ResponseError = ResponseError;
- /**
- * An abstract implementation of a MessageType.
- */
- class AbstractMessageType {
- constructor(_method, _numberOfParams) {
- this._method = _method;
- this._numberOfParams = _numberOfParams;
- }
- get method() {
- return this._method;
- }
- get numberOfParams() {
- return this._numberOfParams;
- }
- }
- exports.AbstractMessageType = AbstractMessageType;
- /**
- * Classes to type request response pairs
- *
- * The type parameter RO will be removed in the next major version
- * of the JSON RPC library since it is a LSP concept and doesn't
- * belong here. For now it is tagged as default never.
- */
- class RequestType0 extends AbstractMessageType {
- constructor(method) {
- super(method, 0);
- }
- }
- exports.RequestType0 = RequestType0;
- class RequestType extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- }
- }
- exports.RequestType = RequestType;
- class RequestType1 extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- }
- }
- exports.RequestType1 = RequestType1;
- class RequestType2 extends AbstractMessageType {
- constructor(method) {
- super(method, 2);
- }
- }
- exports.RequestType2 = RequestType2;
- class RequestType3 extends AbstractMessageType {
- constructor(method) {
- super(method, 3);
- }
- }
- exports.RequestType3 = RequestType3;
- class RequestType4 extends AbstractMessageType {
- constructor(method) {
- super(method, 4);
- }
- }
- exports.RequestType4 = RequestType4;
- class RequestType5 extends AbstractMessageType {
- constructor(method) {
- super(method, 5);
- }
- }
- exports.RequestType5 = RequestType5;
- class RequestType6 extends AbstractMessageType {
- constructor(method) {
- super(method, 6);
- }
- }
- exports.RequestType6 = RequestType6;
- class RequestType7 extends AbstractMessageType {
- constructor(method) {
- super(method, 7);
- }
- }
- exports.RequestType7 = RequestType7;
- class RequestType8 extends AbstractMessageType {
- constructor(method) {
- super(method, 8);
- }
- }
- exports.RequestType8 = RequestType8;
- class RequestType9 extends AbstractMessageType {
- constructor(method) {
- super(method, 9);
- }
- }
- exports.RequestType9 = RequestType9;
- /**
- * The type parameter RO will be removed in the next major version
- * of the JSON RPC library since it is a LSP concept and doesn't
- * belong here. For now it is tagged as default never.
- */
- class NotificationType extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- this._ = undefined;
- }
- }
- exports.NotificationType = NotificationType;
- class NotificationType0 extends AbstractMessageType {
- constructor(method) {
- super(method, 0);
- }
- }
- exports.NotificationType0 = NotificationType0;
- class NotificationType1 extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- }
- }
- exports.NotificationType1 = NotificationType1;
- class NotificationType2 extends AbstractMessageType {
- constructor(method) {
- super(method, 2);
- }
- }
- exports.NotificationType2 = NotificationType2;
- class NotificationType3 extends AbstractMessageType {
- constructor(method) {
- super(method, 3);
- }
- }
- exports.NotificationType3 = NotificationType3;
- class NotificationType4 extends AbstractMessageType {
- constructor(method) {
- super(method, 4);
- }
- }
- exports.NotificationType4 = NotificationType4;
- class NotificationType5 extends AbstractMessageType {
- constructor(method) {
- super(method, 5);
- }
- }
- exports.NotificationType5 = NotificationType5;
- class NotificationType6 extends AbstractMessageType {
- constructor(method) {
- super(method, 6);
- }
- }
- exports.NotificationType6 = NotificationType6;
- class NotificationType7 extends AbstractMessageType {
- constructor(method) {
- super(method, 7);
- }
- }
- exports.NotificationType7 = NotificationType7;
- class NotificationType8 extends AbstractMessageType {
- constructor(method) {
- super(method, 8);
- }
- }
- exports.NotificationType8 = NotificationType8;
- class NotificationType9 extends AbstractMessageType {
- constructor(method) {
- super(method, 9);
- }
- }
- exports.NotificationType9 = NotificationType9;
- /**
- * Tests if the given message is a request message
- */
- function isRequestMessage(message) {
- let candidate = message;
- return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
- }
- exports.isRequestMessage = isRequestMessage;
- /**
- * Tests if the given message is a notification message
- */
- function isNotificationMessage(message) {
- let candidate = message;
- return candidate && is.string(candidate.method) && message.id === void 0;
- }
- exports.isNotificationMessage = isNotificationMessage;
- /**
- * Tests if the given message is a response message
- */
- function isResponseMessage(message) {
- let candidate = message;
- return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
- }
- exports.isResponseMessage = isResponseMessage;
-
-
- /***/ }),
- /* 12 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const events_1 = __webpack_require__(13);
- const Is = __webpack_require__(10);
- let DefaultSize = 8192;
- let CR = Buffer.from('\r', 'ascii')[0];
- let LF = Buffer.from('\n', 'ascii')[0];
- let CRLF = '\r\n';
- class MessageBuffer {
- constructor(encoding = 'utf8') {
- this.encoding = encoding;
- this.index = 0;
- this.buffer = Buffer.allocUnsafe(DefaultSize);
- }
- append(chunk) {
- var toAppend = chunk;
- if (typeof (chunk) === 'string') {
- var str = chunk;
- var bufferLen = Buffer.byteLength(str, this.encoding);
- toAppend = Buffer.allocUnsafe(bufferLen);
- toAppend.write(str, 0, bufferLen, this.encoding);
- }
- if (this.buffer.length - this.index >= toAppend.length) {
- toAppend.copy(this.buffer, this.index, 0, toAppend.length);
- }
- else {
- var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
- if (this.index === 0) {
- this.buffer = Buffer.allocUnsafe(newSize);
- toAppend.copy(this.buffer, 0, 0, toAppend.length);
- }
- else {
- this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
- }
- }
- this.index += toAppend.length;
- }
- tryReadHeaders() {
- let result = undefined;
- let current = 0;
- while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
- current++;
- }
- // No header / body separator found (e.g CRLFCRLF)
- if (current + 3 >= this.index) {
- return result;
- }
- result = Object.create(null);
- let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
- headers.forEach((header) => {
- let index = header.indexOf(':');
- if (index === -1) {
- throw new Error('Message header must separate key and value using :');
- }
- let key = header.substr(0, index);
- let value = header.substr(index + 1).trim();
- result[key] = value;
- });
- let nextStart = current + 4;
- this.buffer = this.buffer.slice(nextStart);
- this.index = this.index - nextStart;
- return result;
- }
- tryReadContent(length) {
- if (this.index < length) {
- return null;
- }
- let result = this.buffer.toString(this.encoding, 0, length);
- let nextStart = length;
- this.buffer.copy(this.buffer, 0, nextStart);
- this.index = this.index - nextStart;
- return result;
- }
- get numberOfBytes() {
- return this.index;
- }
- }
- var MessageReader;
- (function (MessageReader) {
- function is(value) {
- let candidate = value;
- return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
- Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
- }
- MessageReader.is = is;
- })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
- class AbstractMessageReader {
- constructor() {
- this.errorEmitter = new events_1.Emitter();
- this.closeEmitter = new events_1.Emitter();
- this.partialMessageEmitter = new events_1.Emitter();
- }
- dispose() {
- this.errorEmitter.dispose();
- this.closeEmitter.dispose();
- }
- get onError() {
- return this.errorEmitter.event;
- }
- fireError(error) {
- this.errorEmitter.fire(this.asError(error));
- }
- get onClose() {
- return this.closeEmitter.event;
- }
- fireClose() {
- this.closeEmitter.fire(undefined);
- }
- get onPartialMessage() {
- return this.partialMessageEmitter.event;
- }
- firePartialMessage(info) {
- this.partialMessageEmitter.fire(info);
- }
- asError(error) {
- if (error instanceof Error) {
- return error;
- }
- else {
- return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
- }
- }
- }
- exports.AbstractMessageReader = AbstractMessageReader;
- class StreamMessageReader extends AbstractMessageReader {
- constructor(readable, encoding = 'utf8') {
- super();
- this.readable = readable;
- this.buffer = new MessageBuffer(encoding);
- this._partialMessageTimeout = 10000;
- }
- set partialMessageTimeout(timeout) {
- this._partialMessageTimeout = timeout;
- }
- get partialMessageTimeout() {
- return this._partialMessageTimeout;
- }
- listen(callback) {
- this.nextMessageLength = -1;
- this.messageToken = 0;
- this.partialMessageTimer = undefined;
- this.callback = callback;
- this.readable.on('data', (data) => {
- this.onData(data);
- });
- this.readable.on('error', (error) => this.fireError(error));
- this.readable.on('close', () => this.fireClose());
- }
- onData(data) {
- this.buffer.append(data);
- while (true) {
- if (this.nextMessageLength === -1) {
- let headers = this.buffer.tryReadHeaders();
- if (!headers) {
- return;
- }
- let contentLength = headers['Content-Length'];
- if (!contentLength) {
- throw new Error('Header must provide a Content-Length property.');
- }
- let length = parseInt(contentLength);
- if (isNaN(length)) {
- throw new Error('Content-Length value must be a number.');
- }
- this.nextMessageLength = length;
- // Take the encoding form the header. For compatibility
- // treat both utf-8 and utf8 as node utf8
- }
- var msg = this.buffer.tryReadContent(this.nextMessageLength);
- if (msg === null) {
- /** We haven't received the full message yet. */
- this.setPartialMessageTimer();
- return;
- }
- this.clearPartialMessageTimer();
- this.nextMessageLength = -1;
- this.messageToken++;
- var json = JSON.parse(msg);
- this.callback(json);
- }
- }
- clearPartialMessageTimer() {
- if (this.partialMessageTimer) {
- clearTimeout(this.partialMessageTimer);
- this.partialMessageTimer = undefined;
- }
- }
- setPartialMessageTimer() {
- this.clearPartialMessageTimer();
- if (this._partialMessageTimeout <= 0) {
- return;
- }
- this.partialMessageTimer = setTimeout((token, timeout) => {
- this.partialMessageTimer = undefined;
- if (token === this.messageToken) {
- this.firePartialMessage({ messageToken: token, waitingTime: timeout });
- this.setPartialMessageTimer();
- }
- }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
- }
- }
- exports.StreamMessageReader = StreamMessageReader;
- class IPCMessageReader extends AbstractMessageReader {
- constructor(process) {
- super();
- this.process = process;
- let eventEmitter = this.process;
- eventEmitter.on('error', (error) => this.fireError(error));
- eventEmitter.on('close', () => this.fireClose());
- }
- listen(callback) {
- this.process.on('message', callback);
- }
- }
- exports.IPCMessageReader = IPCMessageReader;
- class SocketMessageReader extends StreamMessageReader {
- constructor(socket, encoding = 'utf-8') {
- super(socket, encoding);
- }
- }
- exports.SocketMessageReader = SocketMessageReader;
-
-
- /***/ }),
- /* 13 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- var Disposable;
- (function (Disposable) {
- function create(func) {
- return {
- dispose: func
- };
- }
- Disposable.create = create;
- })(Disposable = exports.Disposable || (exports.Disposable = {}));
- var Event;
- (function (Event) {
- const _disposable = { dispose() { } };
- Event.None = function () { return _disposable; };
- })(Event = exports.Event || (exports.Event = {}));
- class CallbackList {
- add(callback, context = null, bucket) {
- if (!this._callbacks) {
- this._callbacks = [];
- this._contexts = [];
- }
- this._callbacks.push(callback);
- this._contexts.push(context);
- if (Array.isArray(bucket)) {
- bucket.push({ dispose: () => this.remove(callback, context) });
- }
- }
- remove(callback, context = null) {
- if (!this._callbacks) {
- return;
- }
- var foundCallbackWithDifferentContext = false;
- for (var i = 0, len = this._callbacks.length; i < len; i++) {
- if (this._callbacks[i] === callback) {
- if (this._contexts[i] === context) {
- // callback & context match => remove it
- this._callbacks.splice(i, 1);
- this._contexts.splice(i, 1);
- return;
- }
- else {
- foundCallbackWithDifferentContext = true;
- }
- }
- }
- if (foundCallbackWithDifferentContext) {
- throw new Error('When adding a listener with a context, you should remove it with the same context');
- }
- }
- invoke(...args) {
- if (!this._callbacks) {
- return [];
- }
- var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
- for (var i = 0, len = callbacks.length; i < len; i++) {
- try {
- ret.push(callbacks[i].apply(contexts[i], args));
- }
- catch (e) {
- // eslint-disable-next-line no-console
- console.error(e);
- }
- }
- return ret;
- }
- isEmpty() {
- return !this._callbacks || this._callbacks.length === 0;
- }
- dispose() {
- this._callbacks = undefined;
- this._contexts = undefined;
- }
- }
- class Emitter {
- constructor(_options) {
- this._options = _options;
- }
- /**
- * For the public to allow to subscribe
- * to events from this Emitter
- */
- get event() {
- if (!this._event) {
- this._event = (listener, thisArgs, disposables) => {
- if (!this._callbacks) {
- this._callbacks = new CallbackList();
- }
- if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
- this._options.onFirstListenerAdd(this);
- }
- this._callbacks.add(listener, thisArgs);
- let result;
- result = {
- dispose: () => {
- this._callbacks.remove(listener, thisArgs);
- result.dispose = Emitter._noop;
- if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
- this._options.onLastListenerRemove(this);
- }
- }
- };
- if (Array.isArray(disposables)) {
- disposables.push(result);
- }
- return result;
- };
- }
- return this._event;
- }
- /**
- * To be kept private to fire an event to
- * subscribers
- */
- fire(event) {
- if (this._callbacks) {
- this._callbacks.invoke.call(this._callbacks, event);
- }
- }
- dispose() {
- if (this._callbacks) {
- this._callbacks.dispose();
- this._callbacks = undefined;
- }
- }
- }
- exports.Emitter = Emitter;
- Emitter._noop = function () { };
-
-
- /***/ }),
- /* 14 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const events_1 = __webpack_require__(13);
- const Is = __webpack_require__(10);
- let ContentLength = 'Content-Length: ';
- let CRLF = '\r\n';
- var MessageWriter;
- (function (MessageWriter) {
- function is(value) {
- let candidate = value;
- return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
- Is.func(candidate.onError) && Is.func(candidate.write);
- }
- MessageWriter.is = is;
- })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
- class AbstractMessageWriter {
- constructor() {
- this.errorEmitter = new events_1.Emitter();
- this.closeEmitter = new events_1.Emitter();
- }
- dispose() {
- this.errorEmitter.dispose();
- this.closeEmitter.dispose();
- }
- get onError() {
- return this.errorEmitter.event;
- }
- fireError(error, message, count) {
- this.errorEmitter.fire([this.asError(error), message, count]);
- }
- get onClose() {
- return this.closeEmitter.event;
- }
- fireClose() {
- this.closeEmitter.fire(undefined);
- }
- asError(error) {
- if (error instanceof Error) {
- return error;
- }
- else {
- return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
- }
- }
- }
- exports.AbstractMessageWriter = AbstractMessageWriter;
- class StreamMessageWriter extends AbstractMessageWriter {
- constructor(writable, encoding = 'utf8') {
- super();
- this.writable = writable;
- this.encoding = encoding;
- this.errorCount = 0;
- this.writable.on('error', (error) => this.fireError(error));
- this.writable.on('close', () => this.fireClose());
- }
- write(msg) {
- let json = JSON.stringify(msg);
- let contentLength = Buffer.byteLength(json, this.encoding);
- let headers = [
- ContentLength, contentLength.toString(), CRLF,
- CRLF
- ];
- try {
- // Header must be written in ASCII encoding
- this.writable.write(headers.join(''), 'ascii');
- // Now write the content. This can be written in any encoding
- this.writable.write(json, this.encoding);
- this.errorCount = 0;
- }
- catch (error) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- }
- }
- exports.StreamMessageWriter = StreamMessageWriter;
- class IPCMessageWriter extends AbstractMessageWriter {
- constructor(process) {
- super();
- this.process = process;
- this.errorCount = 0;
- this.queue = [];
- this.sending = false;
- let eventEmitter = this.process;
- eventEmitter.on('error', (error) => this.fireError(error));
- eventEmitter.on('close', () => this.fireClose);
- }
- write(msg) {
- if (!this.sending && this.queue.length === 0) {
- // See https://github.com/nodejs/node/issues/7657
- this.doWriteMessage(msg);
- }
- else {
- this.queue.push(msg);
- }
- }
- doWriteMessage(msg) {
- try {
- if (this.process.send) {
- this.sending = true;
- this.process.send(msg, undefined, undefined, (error) => {
- this.sending = false;
- if (error) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- else {
- this.errorCount = 0;
- }
- if (this.queue.length > 0) {
- this.doWriteMessage(this.queue.shift());
- }
- });
- }
- }
- catch (error) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- }
- }
- exports.IPCMessageWriter = IPCMessageWriter;
- class SocketMessageWriter extends AbstractMessageWriter {
- constructor(socket, encoding = 'utf8') {
- super();
- this.socket = socket;
- this.queue = [];
- this.sending = false;
- this.encoding = encoding;
- this.errorCount = 0;
- this.socket.on('error', (error) => this.fireError(error));
- this.socket.on('close', () => this.fireClose());
- }
- dispose() {
- super.dispose();
- this.socket.destroy();
- }
- write(msg) {
- if (!this.sending && this.queue.length === 0) {
- // See https://github.com/nodejs/node/issues/7657
- this.doWriteMessage(msg);
- }
- else {
- this.queue.push(msg);
- }
- }
- doWriteMessage(msg) {
- let json = JSON.stringify(msg);
- let contentLength = Buffer.byteLength(json, this.encoding);
- let headers = [
- ContentLength, contentLength.toString(), CRLF,
- CRLF
- ];
- try {
- // Header must be written in ASCII encoding
- this.sending = true;
- this.socket.write(headers.join(''), 'ascii', (error) => {
- if (error) {
- this.handleError(error, msg);
- }
- try {
- // Now write the content. This can be written in any encoding
- this.socket.write(json, this.encoding, (error) => {
- this.sending = false;
- if (error) {
- this.handleError(error, msg);
- }
- else {
- this.errorCount = 0;
- }
- if (this.queue.length > 0) {
- this.doWriteMessage(this.queue.shift());
- }
- });
- }
- catch (error) {
- this.handleError(error, msg);
- }
- });
- }
- catch (error) {
- this.handleError(error, msg);
- }
- }
- handleError(error, msg) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- }
- exports.SocketMessageWriter = SocketMessageWriter;
-
-
- /***/ }),
- /* 15 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const events_1 = __webpack_require__(13);
- const Is = __webpack_require__(10);
- var CancellationToken;
- (function (CancellationToken) {
- CancellationToken.None = Object.freeze({
- isCancellationRequested: false,
- onCancellationRequested: events_1.Event.None
- });
- CancellationToken.Cancelled = Object.freeze({
- isCancellationRequested: true,
- onCancellationRequested: events_1.Event.None
- });
- function is(value) {
- let candidate = value;
- return candidate && (candidate === CancellationToken.None
- || candidate === CancellationToken.Cancelled
- || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
- }
- CancellationToken.is = is;
- })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
- const shortcutEvent = Object.freeze(function (callback, context) {
- let handle = setTimeout(callback.bind(context), 0);
- return { dispose() { clearTimeout(handle); } };
- });
- class MutableToken {
- constructor() {
- this._isCancelled = false;
- }
- cancel() {
- if (!this._isCancelled) {
- this._isCancelled = true;
- if (this._emitter) {
- this._emitter.fire(undefined);
- this.dispose();
- }
- }
- }
- get isCancellationRequested() {
- return this._isCancelled;
- }
- get onCancellationRequested() {
- if (this._isCancelled) {
- return shortcutEvent;
- }
- if (!this._emitter) {
- this._emitter = new events_1.Emitter();
- }
- return this._emitter.event;
- }
- dispose() {
- if (this._emitter) {
- this._emitter.dispose();
- this._emitter = undefined;
- }
- }
- }
- class CancellationTokenSource {
- get token() {
- if (!this._token) {
- // be lazy and create the token only when
- // actually needed
- this._token = new MutableToken();
- }
- return this._token;
- }
- cancel() {
- if (!this._token) {
- // save an object by returning the default
- // cancelled token when cancellation happens
- // before someone asks for the token
- this._token = CancellationToken.Cancelled;
- }
- else {
- this._token.cancel();
- }
- }
- dispose() {
- if (!this._token) {
- // ensure to initialize with an empty token if we had none
- this._token = CancellationToken.None;
- }
- else if (this._token instanceof MutableToken) {
- // actually dispose
- this._token.dispose();
- }
- }
- }
- exports.CancellationTokenSource = CancellationTokenSource;
-
-
- /***/ }),
- /* 16 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- var Touch;
- (function (Touch) {
- Touch.None = 0;
- Touch.First = 1;
- Touch.Last = 2;
- })(Touch = exports.Touch || (exports.Touch = {}));
- class LinkedMap {
- constructor() {
- this._map = new Map();
- this._head = undefined;
- this._tail = undefined;
- this._size = 0;
- }
- clear() {
- this._map.clear();
- this._head = undefined;
- this._tail = undefined;
- this._size = 0;
- }
- isEmpty() {
- return !this._head && !this._tail;
- }
- get size() {
- return this._size;
- }
- has(key) {
- return this._map.has(key);
- }
- get(key) {
- const item = this._map.get(key);
- if (!item) {
- return undefined;
- }
- return item.value;
- }
- set(key, value, touch = Touch.None) {
- let item = this._map.get(key);
- if (item) {
- item.value = value;
- if (touch !== Touch.None) {
- this.touch(item, touch);
- }
- }
- else {
- item = { key, value, next: undefined, previous: undefined };
- switch (touch) {
- case Touch.None:
- this.addItemLast(item);
- break;
- case Touch.First:
- this.addItemFirst(item);
- break;
- case Touch.Last:
- this.addItemLast(item);
- break;
- default:
- this.addItemLast(item);
- break;
- }
- this._map.set(key, item);
- this._size++;
- }
- }
- delete(key) {
- const item = this._map.get(key);
- if (!item) {
- return false;
- }
- this._map.delete(key);
- this.removeItem(item);
- this._size--;
- return true;
- }
- shift() {
- if (!this._head && !this._tail) {
- return undefined;
- }
- if (!this._head || !this._tail) {
- throw new Error('Invalid list');
- }
- const item = this._head;
- this._map.delete(item.key);
- this.removeItem(item);
- this._size--;
- return item.value;
- }
- forEach(callbackfn, thisArg) {
- let current = this._head;
- while (current) {
- if (thisArg) {
- callbackfn.bind(thisArg)(current.value, current.key, this);
- }
- else {
- callbackfn(current.value, current.key, this);
- }
- current = current.next;
- }
- }
- forEachReverse(callbackfn, thisArg) {
- let current = this._tail;
- while (current) {
- if (thisArg) {
- callbackfn.bind(thisArg)(current.value, current.key, this);
- }
- else {
- callbackfn(current.value, current.key, this);
- }
- current = current.previous;
- }
- }
- values() {
- let result = [];
- let current = this._head;
- while (current) {
- result.push(current.value);
- current = current.next;
- }
- return result;
- }
- keys() {
- let result = [];
- let current = this._head;
- while (current) {
- result.push(current.key);
- current = current.next;
- }
- return result;
- }
- /* JSON RPC run on es5 which has no Symbol.iterator
- public keys(): IterableIterator<K> {
- let current = this._head;
- let iterator: IterableIterator<K> = {
- [Symbol.iterator]() {
- return iterator;
- },
- next():IteratorResult<K> {
- if (current) {
- let result = { value: current.key, done: false };
- current = current.next;
- return result;
- } else {
- return { value: undefined, done: true };
- }
- }
- };
- return iterator;
- }
-
- public values(): IterableIterator<V> {
- let current = this._head;
- let iterator: IterableIterator<V> = {
- [Symbol.iterator]() {
- return iterator;
- },
- next():IteratorResult<V> {
- if (current) {
- let result = { value: current.value, done: false };
- current = current.next;
- return result;
- } else {
- return { value: undefined, done: true };
- }
- }
- };
- return iterator;
- }
- */
- addItemFirst(item) {
- // First time Insert
- if (!this._head && !this._tail) {
- this._tail = item;
- }
- else if (!this._head) {
- throw new Error('Invalid list');
- }
- else {
- item.next = this._head;
- this._head.previous = item;
- }
- this._head = item;
- }
- addItemLast(item) {
- // First time Insert
- if (!this._head && !this._tail) {
- this._head = item;
- }
- else if (!this._tail) {
- throw new Error('Invalid list');
- }
- else {
- item.previous = this._tail;
- this._tail.next = item;
- }
- this._tail = item;
- }
- removeItem(item) {
- if (item === this._head && item === this._tail) {
- this._head = undefined;
- this._tail = undefined;
- }
- else if (item === this._head) {
- this._head = item.next;
- }
- else if (item === this._tail) {
- this._tail = item.previous;
- }
- else {
- const next = item.next;
- const previous = item.previous;
- if (!next || !previous) {
- throw new Error('Invalid list');
- }
- next.previous = previous;
- previous.next = next;
- }
- }
- touch(item, touch) {
- if (!this._head || !this._tail) {
- throw new Error('Invalid list');
- }
- if ((touch !== Touch.First && touch !== Touch.Last)) {
- return;
- }
- if (touch === Touch.First) {
- if (item === this._head) {
- return;
- }
- const next = item.next;
- const previous = item.previous;
- // Unlink the item
- if (item === this._tail) {
- // previous must be defined since item was not head but is tail
- // So there are more than on item in the map
- previous.next = undefined;
- this._tail = previous;
- }
- else {
- // Both next and previous are not undefined since item was neither head nor tail.
- next.previous = previous;
- previous.next = next;
- }
- // Insert the node at head
- item.previous = undefined;
- item.next = this._head;
- this._head.previous = item;
- this._head = item;
- }
- else if (touch === Touch.Last) {
- if (item === this._tail) {
- return;
- }
- const next = item.next;
- const previous = item.previous;
- // Unlink the item.
- if (item === this._head) {
- // next must be defined since item was not tail but is head
- // So there are more than on item in the map
- next.previous = undefined;
- this._head = next;
- }
- else {
- // Both next and previous are not undefined since item was neither head nor tail.
- next.previous = previous;
- previous.next = next;
- }
- item.next = undefined;
- item.previous = this._tail;
- this._tail.next = item;
- this._tail = item;
- }
- }
- }
- exports.LinkedMap = LinkedMap;
-
-
- /***/ }),
- /* 17 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const path_1 = __webpack_require__(4);
- const os_1 = __webpack_require__(2);
- const crypto_1 = __webpack_require__(18);
- const net_1 = __webpack_require__(19);
- const messageReader_1 = __webpack_require__(12);
- const messageWriter_1 = __webpack_require__(14);
- function generateRandomPipeName() {
- const randomSuffix = crypto_1.randomBytes(21).toString('hex');
- if (process.platform === 'win32') {
- return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
- }
- else {
- // Mac/Unix: use socket file
- return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
- }
- }
- exports.generateRandomPipeName = generateRandomPipeName;
- function createClientPipeTransport(pipeName, encoding = 'utf-8') {
- let connectResolve;
- let connected = new Promise((resolve, _reject) => {
- connectResolve = resolve;
- });
- return new Promise((resolve, reject) => {
- let server = net_1.createServer((socket) => {
- server.close();
- connectResolve([
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ]);
- });
- server.on('error', reject);
- server.listen(pipeName, () => {
- server.removeListener('error', reject);
- resolve({
- onConnected: () => { return connected; }
- });
- });
- });
- }
- exports.createClientPipeTransport = createClientPipeTransport;
- function createServerPipeTransport(pipeName, encoding = 'utf-8') {
- const socket = net_1.createConnection(pipeName);
- return [
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ];
- }
- exports.createServerPipeTransport = createServerPipeTransport;
-
-
- /***/ }),
- /* 18 */
- /***/ (function(module, exports) {
-
- module.exports = require("crypto");
-
- /***/ }),
- /* 19 */
- /***/ (function(module, exports) {
-
- module.exports = require("net");
-
- /***/ }),
- /* 20 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const net_1 = __webpack_require__(19);
- const messageReader_1 = __webpack_require__(12);
- const messageWriter_1 = __webpack_require__(14);
- function createClientSocketTransport(port, encoding = 'utf-8') {
- let connectResolve;
- let connected = new Promise((resolve, _reject) => {
- connectResolve = resolve;
- });
- return new Promise((resolve, reject) => {
- let server = net_1.createServer((socket) => {
- server.close();
- connectResolve([
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ]);
- });
- server.on('error', reject);
- server.listen(port, '127.0.0.1', () => {
- server.removeListener('error', reject);
- resolve({
- onConnected: () => { return connected; }
- });
- });
- });
- }
- exports.createClientSocketTransport = createClientSocketTransport;
- function createServerSocketTransport(port, encoding = 'utf-8') {
- const socket = net_1.createConnection(port, '127.0.0.1');
- return [
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ];
- }
- exports.createServerSocketTransport = createServerSocketTransport;
-
-
- /***/ }),
- /* 21 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const Is = __webpack_require__(22);
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- const protocol_implementation_1 = __webpack_require__(24);
- exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
- const protocol_typeDefinition_1 = __webpack_require__(25);
- exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
- const protocol_workspaceFolders_1 = __webpack_require__(26);
- exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
- exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
- const protocol_configuration_1 = __webpack_require__(27);
- exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
- const protocol_colorProvider_1 = __webpack_require__(28);
- exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
- exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
- const protocol_foldingRange_1 = __webpack_require__(29);
- exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
- const protocol_declaration_1 = __webpack_require__(30);
- exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
- const protocol_selectionRange_1 = __webpack_require__(31);
- exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
- const protocol_progress_1 = __webpack_require__(32);
- exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
- exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
- exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * The DocumentFilter namespace provides helper functions to work with
- * [DocumentFilter](#DocumentFilter) literals.
- */
- var DocumentFilter;
- (function (DocumentFilter) {
- function is(value) {
- const candidate = value;
- return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
- }
- DocumentFilter.is = is;
- })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
- /**
- * The DocumentSelector namespace provides helper functions to work with
- * [DocumentSelector](#DocumentSelector)s.
- */
- var DocumentSelector;
- (function (DocumentSelector) {
- function is(value) {
- if (!Array.isArray(value)) {
- return false;
- }
- for (let elem of value) {
- if (!Is.string(elem) && !DocumentFilter.is(elem)) {
- return false;
- }
- }
- return true;
- }
- DocumentSelector.is = is;
- })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
- /**
- * The `client/registerCapability` request is sent from the server to the client to register a new capability
- * handler on the client side.
- */
- var RegistrationRequest;
- (function (RegistrationRequest) {
- RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
- })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
- /**
- * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
- * handler on the client side.
- */
- var UnregistrationRequest;
- (function (UnregistrationRequest) {
- UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
- })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
- var ResourceOperationKind;
- (function (ResourceOperationKind) {
- /**
- * Supports creating new files and folders.
- */
- ResourceOperationKind.Create = 'create';
- /**
- * Supports renaming existing files and folders.
- */
- ResourceOperationKind.Rename = 'rename';
- /**
- * Supports deleting existing files and folders.
- */
- ResourceOperationKind.Delete = 'delete';
- })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
- var FailureHandlingKind;
- (function (FailureHandlingKind) {
- /**
- * Applying the workspace change is simply aborted if one of the changes provided
- * fails. All operations executed before the failing operation stay executed.
- */
- FailureHandlingKind.Abort = 'abort';
- /**
- * All operations are executed transactional. That means they either all
- * succeed or no changes at all are applied to the workspace.
- */
- FailureHandlingKind.Transactional = 'transactional';
- /**
- * If the workspace edit contains only textual file changes they are executed transactional.
- * If resource changes (create, rename or delete file) are part of the change the failure
- * handling startegy is abort.
- */
- FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
- /**
- * The client tries to undo the operations already executed. But there is no
- * guarantee that this is succeeding.
- */
- FailureHandlingKind.Undo = 'undo';
- })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
- /**
- * The StaticRegistrationOptions namespace provides helper functions to work with
- * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
- */
- var StaticRegistrationOptions;
- (function (StaticRegistrationOptions) {
- function hasId(value) {
- const candidate = value;
- return candidate && Is.string(candidate.id) && candidate.id.length > 0;
- }
- StaticRegistrationOptions.hasId = hasId;
- })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
- /**
- * The TextDocumentRegistrationOptions namespace provides helper functions to work with
- * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
- */
- var TextDocumentRegistrationOptions;
- (function (TextDocumentRegistrationOptions) {
- function is(value) {
- const candidate = value;
- return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
- }
- TextDocumentRegistrationOptions.is = is;
- })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
- /**
- * The WorkDoneProgressOptions namespace provides helper functions to work with
- * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
- */
- var WorkDoneProgressOptions;
- (function (WorkDoneProgressOptions) {
- function is(value) {
- const candidate = value;
- return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
- }
- WorkDoneProgressOptions.is = is;
- function hasWorkDoneProgress(value) {
- const candidate = value;
- return candidate && Is.boolean(candidate.workDoneProgress);
- }
- WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
- })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
- /**
- * The initialize request is sent from the client to the server.
- * It is sent once as the request after starting up the server.
- * The requests parameter is of type [InitializeParams](#InitializeParams)
- * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
- * resolves to such.
- */
- var InitializeRequest;
- (function (InitializeRequest) {
- InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
- })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
- /**
- * Known error codes for an `InitializeError`;
- */
- var InitializeError;
- (function (InitializeError) {
- /**
- * If the protocol version provided by the client can't be handled by the server.
- * @deprecated This initialize error got replaced by client capabilities. There is
- * no version handshake in version 3.0x
- */
- InitializeError.unknownProtocolVersion = 1;
- })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
- /**
- * The intialized notification is sent from the client to the
- * server after the client is fully initialized and the server
- * is allowed to send requests from the server to the client.
- */
- var InitializedNotification;
- (function (InitializedNotification) {
- InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
- })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
- //---- Shutdown Method ----
- /**
- * A shutdown request is sent from the client to the server.
- * It is sent once when the client decides to shutdown the
- * server. The only notification that is sent after a shutdown request
- * is the exit event.
- */
- var ShutdownRequest;
- (function (ShutdownRequest) {
- ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
- })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
- //---- Exit Notification ----
- /**
- * The exit event is sent from the client to the server to
- * ask the server to exit its process.
- */
- var ExitNotification;
- (function (ExitNotification) {
- ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
- })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
- /**
- * The configuration change notification is sent from the client to the server
- * when the client's configuration has changed. The notification contains
- * the changed configuration as defined by the language client.
- */
- var DidChangeConfigurationNotification;
- (function (DidChangeConfigurationNotification) {
- DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
- })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
- //---- Message show and log notifications ----
- /**
- * The message type
- */
- var MessageType;
- (function (MessageType) {
- /**
- * An error message.
- */
- MessageType.Error = 1;
- /**
- * A warning message.
- */
- MessageType.Warning = 2;
- /**
- * An information message.
- */
- MessageType.Info = 3;
- /**
- * A log message.
- */
- MessageType.Log = 4;
- })(MessageType = exports.MessageType || (exports.MessageType = {}));
- /**
- * The show message notification is sent from a server to a client to ask
- * the client to display a particular message in the user interface.
- */
- var ShowMessageNotification;
- (function (ShowMessageNotification) {
- ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
- })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
- /**
- * The show message request is sent from the server to the client to show a message
- * and a set of options actions to the user.
- */
- var ShowMessageRequest;
- (function (ShowMessageRequest) {
- ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
- })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
- /**
- * The log message notification is sent from the server to the client to ask
- * the client to log a particular message.
- */
- var LogMessageNotification;
- (function (LogMessageNotification) {
- LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
- })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
- //---- Telemetry notification
- /**
- * The telemetry event notification is sent from the server to the client to ask
- * the client to log telemetry data.
- */
- var TelemetryEventNotification;
- (function (TelemetryEventNotification) {
- TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
- })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
- /**
- * Defines how the host (editor) should sync
- * document changes to the language server.
- */
- var TextDocumentSyncKind;
- (function (TextDocumentSyncKind) {
- /**
- * Documents should not be synced at all.
- */
- TextDocumentSyncKind.None = 0;
- /**
- * Documents are synced by always sending the full content
- * of the document.
- */
- TextDocumentSyncKind.Full = 1;
- /**
- * Documents are synced by sending the full content on open.
- * After that only incremental updates to the document are
- * send.
- */
- TextDocumentSyncKind.Incremental = 2;
- })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
- /**
- * The document open notification is sent from the client to the server to signal
- * newly opened text documents. The document's truth is now managed by the client
- * and the server must not try to read the document's truth using the document's
- * uri. Open in this sense means it is managed by the client. It doesn't necessarily
- * mean that its content is presented in an editor. An open notification must not
- * be sent more than once without a corresponding close notification send before.
- * This means open and close notification must be balanced and the max open count
- * is one.
- */
- var DidOpenTextDocumentNotification;
- (function (DidOpenTextDocumentNotification) {
- DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
- DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
- })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
- /**
- * The document change notification is sent from the client to the server to signal
- * changes to a text document.
- */
- var DidChangeTextDocumentNotification;
- (function (DidChangeTextDocumentNotification) {
- DidChangeTextDocumentNotification.method = 'textDocument/didChange';
- DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
- })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
- /**
- * The document close notification is sent from the client to the server when
- * the document got closed in the client. The document's truth now exists where
- * the document's uri points to (e.g. if the document's uri is a file uri the
- * truth now exists on disk). As with the open notification the close notification
- * is about managing the document's content. Receiving a close notification
- * doesn't mean that the document was open in an editor before. A close
- * notification requires a previous open notification to be sent.
- */
- var DidCloseTextDocumentNotification;
- (function (DidCloseTextDocumentNotification) {
- DidCloseTextDocumentNotification.method = 'textDocument/didClose';
- DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
- })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
- /**
- * The document save notification is sent from the client to the server when
- * the document got saved in the client.
- */
- var DidSaveTextDocumentNotification;
- (function (DidSaveTextDocumentNotification) {
- DidSaveTextDocumentNotification.method = 'textDocument/didSave';
- DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
- })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
- /**
- * Represents reasons why a text document is saved.
- */
- var TextDocumentSaveReason;
- (function (TextDocumentSaveReason) {
- /**
- * Manually triggered, e.g. by the user pressing save, by starting debugging,
- * or by an API call.
- */
- TextDocumentSaveReason.Manual = 1;
- /**
- * Automatic after a delay.
- */
- TextDocumentSaveReason.AfterDelay = 2;
- /**
- * When the editor lost focus.
- */
- TextDocumentSaveReason.FocusOut = 3;
- })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
- /**
- * A document will save notification is sent from the client to the server before
- * the document is actually saved.
- */
- var WillSaveTextDocumentNotification;
- (function (WillSaveTextDocumentNotification) {
- WillSaveTextDocumentNotification.method = 'textDocument/willSave';
- WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
- })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
- /**
- * A document will save request is sent from the client to the server before
- * the document is actually saved. The request can return an array of TextEdits
- * which will be applied to the text document before it is saved. Please note that
- * clients might drop results if computing the text edits took too long or if a
- * server constantly fails on this request. This is done to keep the save fast and
- * reliable.
- */
- var WillSaveTextDocumentWaitUntilRequest;
- (function (WillSaveTextDocumentWaitUntilRequest) {
- WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
- WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
- })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
- /**
- * The watched files notification is sent from the client to the server when
- * the client detects changes to file watched by the language client.
- */
- var DidChangeWatchedFilesNotification;
- (function (DidChangeWatchedFilesNotification) {
- DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
- })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
- /**
- * The file event type
- */
- var FileChangeType;
- (function (FileChangeType) {
- /**
- * The file got created.
- */
- FileChangeType.Created = 1;
- /**
- * The file got changed.
- */
- FileChangeType.Changed = 2;
- /**
- * The file got deleted.
- */
- FileChangeType.Deleted = 3;
- })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
- var WatchKind;
- (function (WatchKind) {
- /**
- * Interested in create events.
- */
- WatchKind.Create = 1;
- /**
- * Interested in change events
- */
- WatchKind.Change = 2;
- /**
- * Interested in delete events
- */
- WatchKind.Delete = 4;
- })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
- /**
- * Diagnostics notification are sent from the server to the client to signal
- * results of validation runs.
- */
- var PublishDiagnosticsNotification;
- (function (PublishDiagnosticsNotification) {
- PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
- })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
- /**
- * How a completion was triggered
- */
- var CompletionTriggerKind;
- (function (CompletionTriggerKind) {
- /**
- * Completion was triggered by typing an identifier (24x7 code
- * complete), manual invocation (e.g Ctrl+Space) or via API.
- */
- CompletionTriggerKind.Invoked = 1;
- /**
- * Completion was triggered by a trigger character specified by
- * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
- */
- CompletionTriggerKind.TriggerCharacter = 2;
- /**
- * Completion was re-triggered as current completion list is incomplete
- */
- CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
- })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
- /**
- * Request to request completion at a given text document position. The request's
- * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
- * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
- * or a Thenable that resolves to such.
- *
- * The request can delay the computation of the [`detail`](#CompletionItem.detail)
- * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
- * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
- * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
- */
- var CompletionRequest;
- (function (CompletionRequest) {
- CompletionRequest.method = 'textDocument/completion';
- CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
- /** @deprecated Use CompletionRequest.type */
- CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
- /**
- * Request to resolve additional information for a given completion item.The request's
- * parameter is of type [CompletionItem](#CompletionItem) the response
- * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
- */
- var CompletionResolveRequest;
- (function (CompletionResolveRequest) {
- CompletionResolveRequest.method = 'completionItem/resolve';
- CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
- })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
- /**
- * Request to request hover information at a given text document position. The request's
- * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
- * type [Hover](#Hover) or a Thenable that resolves to such.
- */
- var HoverRequest;
- (function (HoverRequest) {
- HoverRequest.method = 'textDocument/hover';
- HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
- })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
- /**
- * How a signature help was triggered.
- *
- * @since 3.15.0
- */
- var SignatureHelpTriggerKind;
- (function (SignatureHelpTriggerKind) {
- /**
- * Signature help was invoked manually by the user or by a command.
- */
- SignatureHelpTriggerKind.Invoked = 1;
- /**
- * Signature help was triggered by a trigger character.
- */
- SignatureHelpTriggerKind.TriggerCharacter = 2;
- /**
- * Signature help was triggered by the cursor moving or by the document content changing.
- */
- SignatureHelpTriggerKind.ContentChange = 3;
- })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
- var SignatureHelpRequest;
- (function (SignatureHelpRequest) {
- SignatureHelpRequest.method = 'textDocument/signatureHelp';
- SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
- })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
- /**
- * A request to resolve the definition location of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPosition]
- * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
- * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
- * to such.
- */
- var DefinitionRequest;
- (function (DefinitionRequest) {
- DefinitionRequest.method = 'textDocument/definition';
- DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
- /** @deprecated Use DefinitionRequest.type */
- DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
- /**
- * A request to resolve project-wide references for the symbol denoted
- * by the given text document position. The request's parameter is of
- * type [ReferenceParams](#ReferenceParams) the response is of type
- * [Location[]](#Location) or a Thenable that resolves to such.
- */
- var ReferencesRequest;
- (function (ReferencesRequest) {
- ReferencesRequest.method = 'textDocument/references';
- ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
- /** @deprecated Use ReferencesRequest.type */
- ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
- /**
- * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
- * text document position. The request's parameter is of type [TextDocumentPosition]
- * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
- * (#DocumentHighlight) or a Thenable that resolves to such.
- */
- var DocumentHighlightRequest;
- (function (DocumentHighlightRequest) {
- DocumentHighlightRequest.method = 'textDocument/documentHighlight';
- DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
- /** @deprecated Use DocumentHighlightRequest.type */
- DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
- /**
- * A request to list all symbols found in a given text document. The request's
- * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
- * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
- * that resolves to such.
- */
- var DocumentSymbolRequest;
- (function (DocumentSymbolRequest) {
- DocumentSymbolRequest.method = 'textDocument/documentSymbol';
- DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
- /** @deprecated Use DocumentSymbolRequest.type */
- DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
- /**
- * A request to provide commands for the given text document and range.
- */
- var CodeActionRequest;
- (function (CodeActionRequest) {
- CodeActionRequest.method = 'textDocument/codeAction';
- CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
- /** @deprecated Use CodeActionRequest.type */
- CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
- /**
- * A request to list project-wide symbols matching the query string given
- * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
- * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
- * resolves to such.
- */
- var WorkspaceSymbolRequest;
- (function (WorkspaceSymbolRequest) {
- WorkspaceSymbolRequest.method = 'workspace/symbol';
- WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
- /** @deprecated Use WorkspaceSymbolRequest.type */
- WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
- /**
- * A request to provide code lens for the given text document.
- */
- var CodeLensRequest;
- (function (CodeLensRequest) {
- CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
- /** @deprecated Use CodeLensRequest.type */
- CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
- /**
- * A request to resolve a command for a given code lens.
- */
- var CodeLensResolveRequest;
- (function (CodeLensResolveRequest) {
- CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
- })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
- /**
- * A request to provide document links
- */
- var DocumentLinkRequest;
- (function (DocumentLinkRequest) {
- DocumentLinkRequest.method = 'textDocument/documentLink';
- DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
- /** @deprecated Use DocumentLinkRequest.type */
- DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
- /**
- * Request to resolve additional information for a given document link. The request's
- * parameter is of type [DocumentLink](#DocumentLink) the response
- * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
- */
- var DocumentLinkResolveRequest;
- (function (DocumentLinkResolveRequest) {
- DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
- })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
- /**
- * A request to to format a whole document.
- */
- var DocumentFormattingRequest;
- (function (DocumentFormattingRequest) {
- DocumentFormattingRequest.method = 'textDocument/formatting';
- DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
- })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
- /**
- * A request to to format a range in a document.
- */
- var DocumentRangeFormattingRequest;
- (function (DocumentRangeFormattingRequest) {
- DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
- DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
- })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
- /**
- * A request to format a document on type.
- */
- var DocumentOnTypeFormattingRequest;
- (function (DocumentOnTypeFormattingRequest) {
- DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
- DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
- })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
- /**
- * A request to rename a symbol.
- */
- var RenameRequest;
- (function (RenameRequest) {
- RenameRequest.method = 'textDocument/rename';
- RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
- })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
- /**
- * A request to test and perform the setup necessary for a rename.
- */
- var PrepareRenameRequest;
- (function (PrepareRenameRequest) {
- PrepareRenameRequest.method = 'textDocument/prepareRename';
- PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
- })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
- /**
- * A request send from the client to the server to execute a command. The request might return
- * a workspace edit which the client will apply to the workspace.
- */
- var ExecuteCommandRequest;
- (function (ExecuteCommandRequest) {
- ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
- })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
- /**
- * A request sent from the server to the client to modified certain resources.
- */
- var ApplyWorkspaceEditRequest;
- (function (ApplyWorkspaceEditRequest) {
- ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
- })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
-
-
- /***/ }),
- /* 22 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- function boolean(value) {
- return value === true || value === false;
- }
- exports.boolean = boolean;
- function string(value) {
- return typeof value === 'string' || value instanceof String;
- }
- exports.string = string;
- function number(value) {
- return typeof value === 'number' || value instanceof Number;
- }
- exports.number = number;
- function error(value) {
- return value instanceof Error;
- }
- exports.error = error;
- function func(value) {
- return typeof value === 'function';
- }
- exports.func = func;
- function array(value) {
- return Array.isArray(value);
- }
- exports.array = array;
- function stringArray(value) {
- return array(value) && value.every(elem => string(elem));
- }
- exports.stringArray = stringArray;
- function typedArray(value, check) {
- return Array.isArray(value) && value.every(check);
- }
- exports.typedArray = typedArray;
- function objectLiteral(value) {
- // Strictly speaking class instances pass this check as well. Since the LSP
- // doesn't use classes we ignore this for now. If we do we need to add something
- // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
- return value !== null && typeof value === 'object';
- }
- exports.objectLiteral = objectLiteral;
-
-
- /***/ }),
- /* 23 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolRequestType0 = ProtocolRequestType0;
- class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolRequestType = ProtocolRequestType;
- class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolNotificationType = ProtocolNotificationType;
- class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolNotificationType0 = ProtocolNotificationType0;
-
-
- /***/ }),
- /* 24 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * A request to resolve the implementation locations of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPositioParams]
- * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
- * Thenable that resolves to such.
- */
- var ImplementationRequest;
- (function (ImplementationRequest) {
- ImplementationRequest.method = 'textDocument/implementation';
- ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
- /** @deprecated Use ImplementationRequest.type */
- ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
-
-
- /***/ }),
- /* 25 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * A request to resolve the type definition locations of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPositioParams]
- * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
- * Thenable that resolves to such.
- */
- var TypeDefinitionRequest;
- (function (TypeDefinitionRequest) {
- TypeDefinitionRequest.method = 'textDocument/typeDefinition';
- TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
- /** @deprecated Use TypeDefinitionRequest.type */
- TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
-
-
- /***/ }),
- /* 26 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(23);
- /**
- * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
- */
- var WorkspaceFoldersRequest;
- (function (WorkspaceFoldersRequest) {
- WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
- })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
- /**
- * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
- * folder configuration changes.
- */
- var DidChangeWorkspaceFoldersNotification;
- (function (DidChangeWorkspaceFoldersNotification) {
- DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
- })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
-
-
- /***/ }),
- /* 27 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(23);
- /**
- * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
- * configuration setting.
- *
- * This pull model replaces the old push model were the client signaled configuration change via an
- * event. If the server still needs to react to configuration changes (since the server caches the
- * result of `workspace/configuration` requests) the server should register for an empty configuration
- * change event and empty the cache if such an event is received.
- */
- var ConfigurationRequest;
- (function (ConfigurationRequest) {
- ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
- })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
-
-
- /***/ }),
- /* 28 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- /**
- * A request to list all color symbols found in a given text document. The request's
- * parameter is of type [DocumentColorParams](#DocumentColorParams) the
- * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
- * that resolves to such.
- */
- var DocumentColorRequest;
- (function (DocumentColorRequest) {
- DocumentColorRequest.method = 'textDocument/documentColor';
- DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
- /** @deprecated Use DocumentColorRequest.type */
- DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
- /**
- * A request to list all presentation for a color. The request's
- * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
- * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
- * that resolves to such.
- */
- var ColorPresentationRequest;
- (function (ColorPresentationRequest) {
- ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
- })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
-
-
- /***/ }),
- /* 29 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- /**
- * Enum of known range kinds
- */
- var FoldingRangeKind;
- (function (FoldingRangeKind) {
- /**
- * Folding range for a comment
- */
- FoldingRangeKind["Comment"] = "comment";
- /**
- * Folding range for a imports or includes
- */
- FoldingRangeKind["Imports"] = "imports";
- /**
- * Folding range for a region (e.g. `#region`)
- */
- FoldingRangeKind["Region"] = "region";
- })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
- /**
- * A request to provide folding ranges in a document. The request's
- * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
- * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
- * that resolves to such.
- */
- var FoldingRangeRequest;
- (function (FoldingRangeRequest) {
- FoldingRangeRequest.method = 'textDocument/foldingRange';
- FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
- /** @deprecated Use FoldingRangeRequest.type */
- FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
-
-
- /***/ }),
- /* 30 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * A request to resolve the type definition locations of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPositioParams]
- * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
- * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
- * to such.
- */
- var DeclarationRequest;
- (function (DeclarationRequest) {
- DeclarationRequest.method = 'textDocument/declaration';
- DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
- /** @deprecated Use DeclarationRequest.type */
- DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
-
-
- /***/ }),
- /* 31 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- /**
- * A request to provide selection ranges in a document. The request's
- * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
- * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
- * that resolves to such.
- */
- var SelectionRangeRequest;
- (function (SelectionRangeRequest) {
- SelectionRangeRequest.method = 'textDocument/selectionRange';
- SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
- /** @deprecated Use SelectionRangeRequest.type */
- SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
-
-
- /***/ }),
- /* 32 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(9);
- const messages_1 = __webpack_require__(23);
- var WorkDoneProgress;
- (function (WorkDoneProgress) {
- WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
- })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
- /**
- * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
- * reporting from the server.
- */
- var WorkDoneProgressCreateRequest;
- (function (WorkDoneProgressCreateRequest) {
- WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
- })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
- /**
- * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
- * initiated on the server side.
- */
- var WorkDoneProgressCancelNotification;
- (function (WorkDoneProgressCancelNotification) {
- WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
- })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
-
-
- /***/ }),
- /* 33 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) TypeFox and others. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(23);
- /**
- * A request to result a `CallHierarchyItem` in a document at a given position.
- * Can be used as an input to a incoming or outgoing call hierarchy.
- *
- * @since 3.16.0 - Proposed state
- */
- var CallHierarchyPrepareRequest;
- (function (CallHierarchyPrepareRequest) {
- CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
- CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
- })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
- /**
- * A request to resolve the incoming calls for a given `CallHierarchyItem`.
- *
- * @since 3.16.0 - Proposed state
- */
- var CallHierarchyIncomingCallsRequest;
- (function (CallHierarchyIncomingCallsRequest) {
- CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
- CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
- })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
- /**
- * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
- *
- * @since 3.16.0 - Proposed state
- */
- var CallHierarchyOutgoingCallsRequest;
- (function (CallHierarchyOutgoingCallsRequest) {
- CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
- CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
- })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
-
-
- /***/ }),
- /* 34 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(23);
- /**
- * A set of predefined token types. This set is not fixed
- * an clients can specify additional token types via the
- * corresponding client capabilities.
- *
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokenTypes;
- (function (SemanticTokenTypes) {
- SemanticTokenTypes["comment"] = "comment";
- SemanticTokenTypes["keyword"] = "keyword";
- SemanticTokenTypes["string"] = "string";
- SemanticTokenTypes["number"] = "number";
- SemanticTokenTypes["regexp"] = "regexp";
- SemanticTokenTypes["operator"] = "operator";
- SemanticTokenTypes["namespace"] = "namespace";
- SemanticTokenTypes["type"] = "type";
- SemanticTokenTypes["struct"] = "struct";
- SemanticTokenTypes["class"] = "class";
- SemanticTokenTypes["interface"] = "interface";
- SemanticTokenTypes["enum"] = "enum";
- SemanticTokenTypes["typeParameter"] = "typeParameter";
- SemanticTokenTypes["function"] = "function";
- SemanticTokenTypes["member"] = "member";
- SemanticTokenTypes["property"] = "property";
- SemanticTokenTypes["macro"] = "macro";
- SemanticTokenTypes["variable"] = "variable";
- SemanticTokenTypes["parameter"] = "parameter";
- SemanticTokenTypes["label"] = "label";
- })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
- /**
- * A set of predefined token modifiers. This set is not fixed
- * an clients can specify additional token types via the
- * corresponding client capabilities.
- *
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokenModifiers;
- (function (SemanticTokenModifiers) {
- SemanticTokenModifiers["documentation"] = "documentation";
- SemanticTokenModifiers["declaration"] = "declaration";
- SemanticTokenModifiers["definition"] = "definition";
- SemanticTokenModifiers["reference"] = "reference";
- SemanticTokenModifiers["static"] = "static";
- SemanticTokenModifiers["abstract"] = "abstract";
- SemanticTokenModifiers["deprecated"] = "deprecated";
- SemanticTokenModifiers["async"] = "async";
- SemanticTokenModifiers["volatile"] = "volatile";
- SemanticTokenModifiers["readonly"] = "readonly";
- })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokens;
- (function (SemanticTokens) {
- function is(value) {
- const candidate = value;
- return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
- Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
- }
- SemanticTokens.is = is;
- })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokensRequest;
- (function (SemanticTokensRequest) {
- SemanticTokensRequest.method = 'textDocument/semanticTokens';
- SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
- })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokensEditsRequest;
- (function (SemanticTokensEditsRequest) {
- SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
- SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
- })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokensRangeRequest;
- (function (SemanticTokensRangeRequest) {
- SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
- SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
- })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
-
-
- /***/ }),
- /* 35 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- const coc_nvim_1 = __webpack_require__(1);
- const path_1 = __importDefault(__webpack_require__(4));
- const vscode_languageserver_protocol_1 = __webpack_require__(8);
- const types_1 = __webpack_require__(36);
- const util_1 = __webpack_require__(37);
- class ProviderManager {
- constructor() {
- this.providers = new Map();
- }
- regist(provider, name) {
- this.providers.set(name, provider);
- return vscode_languageserver_protocol_1.Disposable.create(() => {
- this.providers.delete(name);
- });
- }
- get hasProvider() {
- return this.providers.size > 0;
- }
- async init() {
- let providers = Array.from(this.providers.values());
- await Promise.all(providers.map(provider => {
- return provider.init();
- }));
- }
- async getSnippets(filetype) {
- let names = Array.from(this.providers.keys());
- let list = [];
- for (let name of names) {
- let provider = this.providers.get(name);
- let snippets = await provider.getSnippets(filetype);
- snippets.map(s => s.provider = name);
- list.push(...snippets);
- }
- return list;
- }
- async getSnippetFiles(filetype) {
- let files = [];
- for (let provider of this.providers.values()) {
- let res = await provider.getSnippetFiles(filetype);
- files = files.concat(res);
- }
- return files;
- }
- async getTriggerSnippets(autoTrigger = false) {
- let bufnr = await coc_nvim_1.workspace.nvim.call('bufnr', '%');
- let doc = coc_nvim_1.workspace.getDocument(bufnr);
- if (!doc)
- return [];
- await doc.patchChange();
- let position = await coc_nvim_1.workspace.getCursorPosition();
- let names = Array.from(this.providers.keys());
- let list = [];
- for (let name of names) {
- let provider = this.providers.get(name);
- let items = await provider.getTriggerSnippets(doc, position, autoTrigger);
- for (let item of items) {
- if (list.findIndex(o => o.prefix == item.prefix) == -1) {
- list.push(item);
- }
- }
- }
- list.sort((a, b) => b.priority - a.priority);
- if (list.length > 1 && list[0].priority > 0) {
- list = list.filter(o => o.priority > 0);
- }
- return list;
- }
- async provideCompletionItems(document, position, _token, context) {
- let doc = coc_nvim_1.workspace.getDocument(document.uri);
- if (!doc)
- return [];
- let snippets = await this.getSnippets(doc.filetype);
- let currline = doc.getline(position.line, true);
- let { input, col } = context.option;
- let character = characterIndex(currline, col);
- let before_content = currline.slice(0, character);
- let res = [];
- let contextPrefixes = [];
- for (let snip of snippets) {
- let contentBehind = before_content;
- if (contextPrefixes.indexOf(snip.prefix) !== -1)
- continue;
- if (snip.regex != null && snip.prefix == '')
- continue;
- if (snip.context) {
- let provider = this.providers.get(snip.provider);
- let valid = await provider.checkContext(snip.context);
- if (!valid)
- continue;
- contextPrefixes.push(snip.prefix);
- }
- let head = this.getPrefixHead(doc, snip.prefix);
- if (input.length == 0 && !before_content.endsWith(snip.prefix))
- continue;
- let item = {
- label: snip.prefix,
- kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
- filterText: snip.prefix,
- detail: snip.description,
- insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet
- };
- item.data = {
- snip,
- provider: snip.provider,
- filepath: `${path_1.default.basename(snip.filepath)}:${snip.lnum}`
- };
- if (snip.regex) {
- if (!input.length || snip.prefix && input[0] != snip.prefix[0])
- continue;
- let content = before_content + snip.prefix;
- let ms = content.match(snip.regex);
- if (!ms)
- continue;
- }
- else if (head && before_content.endsWith(head)) {
- contentBehind = before_content.slice(0, -head.length);
- let prefix = snip.prefix.slice(head.length);
- Object.assign(item, {
- textEdit: {
- range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character: character - head.length }, position),
- newText: prefix
- }
- });
- }
- else if (input.length == 0) {
- let { prefix } = snip;
- contentBehind = before_content.slice(0, -prefix.length);
- Object.assign(item, {
- preselect: true,
- textEdit: {
- range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character: character - prefix.length }, position),
- newText: prefix
- }
- });
- }
- if (snip.triggerKind == types_1.TriggerKind.LineBegin && contentBehind.trim().length)
- continue;
- if (snip.triggerKind == types_1.TriggerKind.SpaceBefore) {
- if (contentBehind.length && !/\s/.test(contentBehind[contentBehind.length - 1])) {
- continue;
- }
- }
- if (!item.textEdit) {
- item.textEdit = {
- range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character }, position),
- newText: item.label
- };
- }
- item.data.location = `${snip.filepath}:${snip.lnum}`;
- item.data.line = contentBehind + snip.prefix;
- res.push(item);
- }
- return res;
- }
- async resolveCompletionItem(item) {
- let provider = this.providers.get(item.data.provider);
- if (provider) {
- let filetype = await coc_nvim_1.workspace.nvim.eval('&filetype');
- let insertSnippet = await provider.resolveSnippetBody(item.data.snip, item.textEdit.range, item.data.line);
- item.textEdit.newText = insertSnippet;
- if (coc_nvim_1.snippetManager) {
- let snip = await Promise.resolve(coc_nvim_1.snippetManager.resolveSnippet(insertSnippet));
- item.documentation = {
- kind: 'markdown',
- value: util_1.markdownBlock(snip.toString(), filetype)
- };
- }
- }
- return item;
- }
- getPrefixHead(doc, prefix) {
- let res = 0;
- for (let idx = prefix.length - 1; idx >= 0; idx--) {
- if (!doc.isWord(prefix[idx])) {
- res = idx;
- break;
- }
- }
- return res == 0 ? '' : prefix.slice(0, res + 1);
- }
- }
- exports.ProviderManager = ProviderManager;
- function characterIndex(content, byteIndex) {
- let buf = Buffer.from(content, 'utf8');
- return buf.slice(0, byteIndex).toString('utf8').length;
- }
- exports.characterIndex = characterIndex;
-
-
- /***/ }),
- /* 36 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- var TriggerKind;
- (function (TriggerKind) {
- TriggerKind[TriggerKind["SpaceBefore"] = 0] = "SpaceBefore";
- TriggerKind[TriggerKind["LineBegin"] = 1] = "LineBegin";
- TriggerKind[TriggerKind["WordBoundary"] = 2] = "WordBoundary";
- TriggerKind[TriggerKind["InWord"] = 3] = "InWord";
- })(TriggerKind = exports.TriggerKind || (exports.TriggerKind = {}));
-
-
- /***/ }),
- /* 37 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- const pify_1 = __importDefault(__webpack_require__(38));
- const fs_1 = __importDefault(__webpack_require__(3));
- const crypto_1 = __importDefault(__webpack_require__(18));
- const BASE64 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
- function tostr(bytes) {
- let r = [];
- let i;
- for (i = 0; i < bytes.length; i++) {
- r.push(BASE64[bytes[i] % 64]);
- }
- return r.join('');
- }
- function uid() {
- return tostr(crypto_1.default.randomBytes(10));
- }
- exports.uid = uid;
- function replaceText(content, items) {
- let res = '';
- items.sort((a, b) => a.index - b.index);
- let item = items.shift();
- for (let i = 0; i < content.length; i++) {
- let idx = item ? item.index : null;
- if (idx == null || i != idx) {
- res = res + content[i];
- continue;
- }
- res = res + item.newText;
- i = i + item.length;
- }
- return res;
- }
- exports.replaceText = replaceText;
- function flatten(arr) {
- return arr.reduce((p, curr) => p.concat(curr), []);
- }
- exports.flatten = flatten;
- async function statAsync(filepath) {
- try {
- return await pify_1.default(fs_1.default.stat)(filepath);
- }
- catch (e) {
- return null;
- }
- }
- exports.statAsync = statAsync;
- async function writeFileAsync(fullpath, content) {
- await pify_1.default(fs_1.default.writeFile)(fullpath, content, 'utf8');
- }
- exports.writeFileAsync = writeFileAsync;
- async function readFileAsync(fullpath, encoding = 'utf8') {
- return await pify_1.default(fs_1.default.readFile)(fullpath, encoding);
- }
- exports.readFileAsync = readFileAsync;
- async function readdirAsync(filepath) {
- try {
- return await pify_1.default(fs_1.default.readdir)(filepath);
- }
- catch (e) {
- return null;
- }
- }
- exports.readdirAsync = readdirAsync;
- function headTail(line) {
- line = line.trim();
- let ms = line.match(/^(\S+)\s+(.*)/);
- if (!ms)
- return [line, ''];
- return [ms[1], ms[2]];
- }
- exports.headTail = headTail;
- function memorize(_target, key, descriptor) {
- let fn = descriptor.get;
- if (typeof fn !== 'function')
- return;
- let memoKey = '$' + key;
- descriptor.get = function (...args) {
- if (this.hasOwnProperty(memoKey))
- return Promise.resolve(this[memoKey]);
- return new Promise((resolve, reject) => {
- Promise.resolve(fn.apply(this, args)).then(res => {
- this[memoKey] = res;
- resolve(res);
- }, e => {
- reject(e);
- });
- });
- };
- }
- exports.memorize = memorize;
- function trimQuote(str) {
- if (str.startsWith('"') || str.startsWith("'"))
- return str.slice(1, -1);
- return str;
- }
- exports.trimQuote = trimQuote;
- function distinct(array, keyFn) {
- if (!keyFn) {
- return array.filter((element, position) => {
- return array.indexOf(element) === position;
- });
- }
- const seen = Object.create(null);
- return array.filter(elem => {
- const key = keyFn(elem);
- if (seen[key]) {
- return false;
- }
- seen[key] = true;
- return true;
- });
- }
- exports.distinct = distinct;
- const conditionRe = /\(\?\(\?:\w+\).+\|/;
- const bellRe = /\\a/;
- const commentRe = /\(\?#.*?\)/;
- const stringStartRe = /\\A/;
- const namedCaptureRe = /\(\?P<\w+>.*?\)/;
- const namedReferenceRe = /\(\?P=(\w+)\)/;
- const braceRe = /\^\]/;
- const regex = new RegExp(`${bellRe.source}|${commentRe.source}|${stringStartRe.source}|${namedCaptureRe.source}|${namedReferenceRe.source}|${braceRe}`, 'g');
- /**
- * Convert python regex to javascript regex,
- * throw error when unsupported pattern found
- *
- * @public
- * @param {string} str
- * @returns {string}
- */
- function convertRegex(str) {
- if (str.indexOf('\\z') !== -1) {
- throw new Error('pattern \\z not supported');
- }
- if (str.indexOf('(?s)') !== -1) {
- throw new Error('pattern (?s) not supported');
- }
- if (str.indexOf('(?x)') !== -1) {
- throw new Error('pattern (?x) not supported');
- }
- if (str.indexOf('\n') !== -1) {
- throw new Error('multiple line pattern not supported');
- }
- if (conditionRe.test(str)) {
- throw new Error('condition pattern not supported');
- }
- return str.replace(regex, (match, p1) => {
- if (match == '^]')
- return '^\\]';
- if (match == '\\a')
- return '';
- if (match.startsWith('(?#'))
- return '';
- if (match == '\\A')
- return '^';
- if (match.startsWith('(?P<'))
- return '(?' + match.slice(3);
- if (match.startsWith('(?P='))
- return `\\k<${p1}>`;
- return '';
- });
- }
- exports.convertRegex = convertRegex;
- function wait(ms) {
- return new Promise(resolve => {
- setTimeout(() => {
- resolve();
- }, ms);
- });
- }
- exports.wait = wait;
- function getRegexText(prefix) {
- if (prefix.startsWith('^'))
- prefix = prefix.slice(1);
- if (prefix.endsWith('$'))
- prefix = prefix.slice(0, -1);
- let content = prefix.replace(/\(.*\)\??/g, '');
- content = content.replace(/\\/g, '');
- return content;
- }
- exports.getRegexText = getRegexText;
- function markdownBlock(code, filetype) {
- filetype = filetype == 'javascriptreact' ? 'javascript' : filetype;
- filetype = filetype == 'typescriptreact' ? 'typescript' : filetype;
- return '``` ' + filetype + '\n' + code + '\n```';
- }
- exports.markdownBlock = markdownBlock;
-
-
- /***/ }),
- /* 38 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
-
- const processFn = (fn, options, proxy, unwrapped) => function (...arguments_) {
- const P = options.promiseModule;
-
- return new P((resolve, reject) => {
- if (options.multiArgs) {
- arguments_.push((...result) => {
- if (options.errorFirst) {
- if (result[0]) {
- reject(result);
- } else {
- result.shift();
- resolve(result);
- }
- } else {
- resolve(result);
- }
- });
- } else if (options.errorFirst) {
- arguments_.push((error, result) => {
- if (error) {
- reject(error);
- } else {
- resolve(result);
- }
- });
- } else {
- arguments_.push(resolve);
- }
-
- const self = this === proxy ? unwrapped : this;
- Reflect.apply(fn, self, arguments_);
- });
- };
-
- const filterCache = new WeakMap();
-
- module.exports = (input, options) => {
- options = {
- exclude: [/.+(?:Sync|Stream)$/],
- errorFirst: true,
- promiseModule: Promise,
- ...options
- };
-
- const objectType = typeof input;
- if (!(input !== null && (objectType === 'object' || objectType === 'function'))) {
- throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objectType}\``);
- }
-
- const filter = (target, key) => {
- let cached = filterCache.get(target);
-
- if (!cached) {
- cached = {};
- filterCache.set(target, cached);
- }
-
- if (key in cached) {
- return cached[key];
- }
-
- const match = pattern => (typeof pattern === 'string' || typeof key === 'symbol') ? key === pattern : pattern.test(key);
- const desc = Reflect.getOwnPropertyDescriptor(target, key);
- const writableOrConfigurableOwn = (desc === undefined || desc.writable || desc.configurable);
- const included = options.include ? options.include.some(match) : !options.exclude.some(match);
- const shouldFilter = included && writableOrConfigurableOwn;
- cached[key] = shouldFilter;
- return shouldFilter;
- };
-
- const cache = new WeakMap();
-
- const proxy = new Proxy(input, {
- apply(target, thisArg, args) {
- const cached = cache.get(target);
-
- if (cached) {
- return Reflect.apply(cached, thisArg, args);
- }
-
- const pified = options.excludeMain ? target : processFn(target, options, proxy, target);
- cache.set(target, pified);
- return Reflect.apply(pified, thisArg, args);
- },
-
- get(target, key) {
- const property = target[key];
-
- // eslint-disable-next-line no-use-extend-native/no-use-extend-native
- if (!filter(target, key) || property === Function.prototype[key]) {
- return property;
- }
-
- const cached = cache.get(property);
-
- if (cached) {
- return cached;
- }
-
- if (typeof property === 'function') {
- const pified = processFn(property, options, proxy, target);
- cache.set(property, pified);
- return pified;
- }
-
- return property;
- }
- });
-
- return proxy;
- };
-
-
- /***/ }),
- /* 39 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- const coc_nvim_1 = __webpack_require__(1);
- const fs_1 = __importDefault(__webpack_require__(3));
- const path_1 = __importDefault(__webpack_require__(4));
- const readline_1 = __importDefault(__webpack_require__(40));
- const vscode_languageserver_types_1 = __webpack_require__(6);
- const baseProvider_1 = __importDefault(__webpack_require__(41));
- const types_1 = __webpack_require__(36);
- const util_1 = __webpack_require__(37);
- const parser_1 = __importDefault(__webpack_require__(42));
- class SnipmateProvider extends baseProvider_1.default {
- constructor(channel, trace, config) {
- super(config);
- this.channel = channel;
- this.trace = trace;
- this.snippetFiles = [];
- this.disposables = [];
- coc_nvim_1.workspace.onDidSaveTextDocument(async (doc) => {
- let uri = coc_nvim_1.Uri.parse(doc.uri);
- if (uri.scheme != 'file')
- return;
- let filepath = uri.fsPath;
- if (!fs_1.default.existsSync(filepath))
- return;
- let snippetFile = this.snippetFiles.find(s => s.filepath == filepath);
- if (snippetFile)
- await this.loadSnippetsFromFile(snippetFile.filetype, snippetFile.directory, filepath);
- }, null, this.disposables);
- }
- async init() {
- let arr = await this.getAllSnippetFiles();
- let { nvim } = coc_nvim_1.workspace;
- let author = await nvim.getVar('snips_author');
- if (!author)
- await nvim.setVar('snips_author', this.config.author);
- await Promise.all(arr.map(({ filepath, directory, filetype }) => {
- return this.loadSnippetsFromFile(filetype, directory, filepath);
- }));
- }
- async loadSnippetsFromFile(filetype, directory, filepath) {
- let snippets = await this.parseSnippetsFile(filepath);
- let idx = this.snippetFiles.findIndex(o => o.filepath == filepath);
- if (idx !== -1)
- this.snippetFiles.splice(idx, 1);
- this.snippetFiles.push({
- directory,
- filepath,
- filetype,
- snippets
- });
- if (this.trace == 'verbose') {
- this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Loaded ${snippets.length} snippets from: ${filepath}`);
- }
- }
- /**
- * Resolve snippet body to inserted text.
- *
- * @public
- * @param {Snippet} snippet
- * @param {Range} _range
- * @param {string} _line
- * @returns {Promise<string>}
- */
- async resolveSnippetBody(snippet, _range, _line) {
- let parser = new parser_1.default(snippet.body);
- let resolved = '';
- let { nvim } = coc_nvim_1.workspace;
- while (!parser.eof()) {
- if (parser.curr == '`') {
- let idx = parser.nextIndex('`', true, false);
- if (idx == -1) {
- resolved = resolved + parser.eatTo(parser.len);
- break;
- }
- let code = parser.eatTo(idx + 1);
- code = code.slice(1, -1);
- if (code.startsWith('Filename')) {
- resolved = resolved + await nvim.call('expand', '%:p:t');
- }
- else {
- try {
- resolved = resolved + await nvim.eval(code);
- }
- catch (e) {
- this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Error on eval: ${code}`);
- }
- }
- continue;
- }
- parser.iterate(ch => {
- if (ch == '`') {
- return false;
- }
- else {
- resolved = resolved + ch;
- }
- return true;
- });
- }
- return resolved;
- }
- /**
- * Parse snippets from snippets file.
- *
- * @public
- * @param {string} filepath
- * @returns {Promise<Snippet[]>}
- */
- parseSnippetsFile(filepath) {
- let res = [];
- const rl = readline_1.default.createInterface({
- input: fs_1.default.createReadStream(filepath, 'utf8'),
- crlfDelay: Infinity
- });
- let lnum = 0;
- let lines = [];
- let prefix = '';
- let description = '';
- rl.on('line', line => {
- lnum += 1;
- if (line.startsWith('#'))
- return;
- if (line.startsWith('snippet')) {
- line = line.replace(/\s*$/, '');
- if (lines.length && prefix) {
- res.push({
- filepath,
- lnum: lnum - lines.length - 1,
- body: lines.join('\n').replace(/\s+$/, ''),
- prefix,
- description,
- triggerKind: types_1.TriggerKind.SpaceBefore
- });
- lines = [];
- }
- let ms = line.match(/^snippet\s+(\S+)(?:\s(.+))?$/);
- if (!ms) {
- prefix = '';
- this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Broken line on ${filepath}:${lnum}`);
- return;
- }
- prefix = ms[1];
- description = ms[2] || '';
- return;
- }
- if (prefix) {
- if (line.indexOf('VISUAL') !== -1) {
- line = line.replace(/\$(\{?)VISUAL\b(:[^\}])?(\}?)/g, '$$$1TM_SELECTED_TEXT$2$3');
- }
- if (line.startsWith('\t')) {
- lines.push(line.slice(1));
- }
- else {
- lines.push(line);
- }
- }
- });
- return new Promise(resolve => {
- rl.on('close', async () => {
- if (lines.length) {
- res.push({
- filepath,
- lnum: lnum - lines.length - 1,
- body: lines.join('\n'),
- prefix,
- description,
- triggerKind: types_1.TriggerKind.SpaceBefore
- });
- }
- resolve(res);
- });
- });
- }
- async getTriggerSnippets(document, position, autoTrigger) {
- if (autoTrigger)
- return [];
- let snippets = await this.getSnippets(document.filetype);
- let line = document.getline(position.line);
- line = line.slice(0, position.character);
- if (!line || line[line.length - 1] == ' ')
- return [];
- snippets = snippets.filter(s => {
- let { prefix } = s;
- if (!line.endsWith(prefix))
- return false;
- let pre = line.slice(0, line.length - prefix.length);
- return pre.length == 0 || /\s/.test(pre[pre.length - 1]);
- });
- let edits = [];
- for (let s of snippets) {
- let character = position.character - s.prefix.length;
- let range = vscode_languageserver_types_1.Range.create(position.line, character, position.line, position.character);
- let newText = await this.resolveSnippetBody(s, range, line);
- edits.push({
- prefix: s.prefix,
- description: s.description,
- location: s.filepath,
- range,
- newText,
- priority: -1
- });
- }
- return edits;
- }
- async getSnippetFiles(filetype) {
- let filetypes = this.getFiletypes(filetype);
- let res = [];
- for (let s of this.snippetFiles) {
- if (filetypes.indexOf(s.filetype) !== -1) {
- res.push(s.filepath);
- }
- }
- return res;
- }
- async getSnippets(filetype) {
- let filetypes = this.getFiletypes(filetype);
- filetypes.push('_');
- let snippetFiles = this.snippetFiles.filter(o => filetypes.indexOf(o.filetype) !== -1);
- let result = [];
- snippetFiles.sort((a, b) => {
- if (a.filetype == b.filetype)
- return 1;
- if (a.filetype == filetype)
- return -1;
- return 1;
- });
- for (let file of snippetFiles) {
- let { snippets } = file;
- for (let snip of snippets) {
- result.push(snip);
- }
- }
- return result;
- }
- async getAllSnippetFiles() {
- let { nvim } = coc_nvim_1.workspace;
- let opt = await nvim.eval('&rtp');
- let rtps = opt.split(',');
- let res = [];
- for (let rtp of rtps) {
- let items = await this.getSnippetFileItems(path_1.default.join(rtp, 'snippets'));
- res.push(...items);
- }
- return res;
- }
- async getSnippetFileItems(directory) {
- let res = [];
- let stat = await util_1.statAsync(directory);
- if (stat && stat.isDirectory()) {
- let files = await util_1.readdirAsync(directory);
- if (files.length) {
- for (let f of files) {
- let file = path_1.default.join(directory, f);
- if (file.endsWith('.snippets')) {
- let basename = path_1.default.basename(f, '.snippets');
- let filetype = basename.split('-', 2)[0];
- res.push({ filepath: file, directory, filetype });
- }
- else {
- let stat = await util_1.statAsync(file);
- if (stat && stat.isDirectory()) {
- let files = await util_1.readdirAsync(file);
- for (let filename of files) {
- if (filename.endsWith('.snippets')) {
- res.push({ filepath: path_1.default.join(file, filename), directory, filetype: f });
- }
- }
- }
- }
- }
- }
- }
- return res;
- }
- }
- exports.SnipmateProvider = SnipmateProvider;
-
-
- /***/ }),
- /* 40 */
- /***/ (function(module, exports) {
-
- module.exports = require("readline");
-
- /***/ }),
- /* 41 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const util_1 = __webpack_require__(37);
- class BaseProvider {
- constructor(config) {
- this.config = config;
- }
- async checkContext(_context) {
- return true;
- }
- getExtendsFiletypes(filetype, exists = new Set()) {
- if (exists.has(filetype))
- return [];
- let extend = this.config.extends ? this.config.extends[filetype] : null;
- exists.add(filetype);
- if (!extend || extend.length == 0)
- return [];
- return extend.reduce((arr, curr) => {
- return arr.concat([curr], this.getExtendsFiletypes(curr, exists));
- }, []);
- }
- getFiletypes(filetype) {
- let filetypes = [filetype];
- if (filetype.indexOf('.') !== -1) {
- filetypes.push(...filetype.split('.'));
- }
- if (filetype == 'javascript.jsx')
- filetypes.push('javascriptreact');
- if (filetype == 'typescript.jsx' || filetype == 'typescript.tsx')
- filetypes.push('typescriptreact');
- let map = coc_nvim_1.workspace.env.filetypeMap;
- if (map && map[filetype]) {
- filetypes.push(map[filetype]);
- }
- let extendFiletypes = filetypes.reduce((arr, curr) => {
- return arr.concat(this.getExtendsFiletypes(curr));
- }, []);
- filetypes.push(...extendFiletypes);
- filetypes.reverse();
- return util_1.distinct(filetypes);
- }
- }
- exports.default = BaseProvider;
-
-
- /***/ }),
- /* 42 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- Object.defineProperty(exports, "__esModule", { value: true });
- /**
- * A very basic parser
- *
- * @public
- */
- class Parser {
- constructor(_content) {
- this._content = _content;
- this._curr = 0;
- }
- eof() {
- return this._curr >= this._content.length;
- }
- skipSpaces() {
- for (let i = this._curr; i <= this._content.length; i++) {
- let ch = this._content[i];
- if (!ch || /\S/.test(ch)) {
- this._curr = i;
- break;
- }
- }
- }
- get index() {
- return this._curr;
- }
- get curr() {
- return this._content[this._curr] || '';
- }
- get len() {
- return this._content.length;
- }
- next(count = 1) {
- return this._content.slice(this._curr + 1, this._curr + 1 + count);
- }
- nextIndex(character, checkEscape = true, allowEnd = true) {
- if (this._curr >= this.len - 1)
- return allowEnd ? this.len - 1 : -1;
- let i = this._curr + 1;
- let pre = this.curr || '';
- while (i != this.len - 1) {
- let ch = this._content[i];
- if (ch == character && (!checkEscape || pre !== '\\')) {
- break;
- }
- pre = ch;
- i = i + 1;
- }
- if (!allowEnd && i == this.len - 1 && character != this._content[i]) {
- return -1;
- }
- return i;
- }
- prev() {
- return this._content[this._curr - 1] || '';
- }
- iterate(fn) {
- while (this._curr < this._content.length) {
- let fine = fn(this.curr, this._curr);
- if (fine === false) {
- break;
- }
- this._curr = this._curr + 1;
- }
- }
- eat(count) {
- let end = this._curr + count;
- end = Math.min(end, this.len);
- let str = this._content.slice(this._curr, end);
- this._curr = end;
- return str;
- }
- // make curr to index, return contnet between curr (inclusive) and index (exclusive)
- eatTo(index) {
- if (index == this._curr)
- return '';
- let str = this._content.slice(this._curr, index);
- this._curr = index;
- return str;
- }
- }
- exports.default = Parser;
-
-
- /***/ }),
- /* 43 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const fs_1 = __importDefault(__webpack_require__(3));
- const jsonc_parser_1 = __webpack_require__(44);
- const os_1 = __importDefault(__webpack_require__(2));
- const path_1 = __importDefault(__webpack_require__(4));
- const util_1 = __importDefault(__webpack_require__(5));
- const vscode_languageserver_types_1 = __webpack_require__(6);
- const baseProvider_1 = __importDefault(__webpack_require__(41));
- const types_1 = __webpack_require__(36);
- const util_2 = __webpack_require__(37);
- class TextmateProvider extends baseProvider_1.default {
- constructor(channel, trace, config) {
- super(config);
- this.channel = channel;
- this.trace = trace;
- this._snippetCache = {};
- this._userSnippets = {};
- if (config.loadFromExtensions) {
- coc_nvim_1.extensions.onDidLoadExtension(extension => {
- this.loadSnippetsFromExtension(extension).catch(e => {
- channel.appendLine(`[Error] ${e.message}`);
- });
- });
- coc_nvim_1.extensions.onDidUnloadExtension(id => {
- delete this._snippetCache[id];
- });
- }
- }
- async init() {
- if (this.config.loadFromExtensions) {
- for (let extension of coc_nvim_1.extensions.all) {
- await this.loadSnippetsFromExtension(extension);
- }
- }
- let paths = this.config.snippetsRoots;
- if (paths && paths.length) {
- for (let dir of paths) {
- await this.loadSnippetsFromRoot(dir);
- }
- }
- }
- async getSnippetFiles(filetype) {
- let filetypes = this.getFiletypes(filetype);
- let filepaths = [];
- if (this.config.loadFromExtensions) {
- for (let key of Object.keys(this._snippetCache)) {
- let cache = this._snippetCache[key];
- for (let filetype of filetypes) {
- let snippets = cache[filetype];
- if (snippets && snippets.length) {
- filepaths.push(snippets[0].filepath);
- }
- }
- }
- }
- for (let filetype of filetypes) {
- let snippets = this._userSnippets[filetype];
- if (snippets && snippets.length) {
- for (let snip of snippets) {
- let { filepath } = snip;
- if (filepaths.indexOf(filepath) == -1) {
- filepaths.push(filepath);
- }
- }
- }
- }
- return util_2.distinct(filepaths);
- }
- async getTriggerSnippets(document, position, autoTrigger) {
- if (autoTrigger)
- return [];
- let line = document.getline(position.line);
- line = line.slice(0, position.character);
- let snippets = await this.getSnippets(document.filetype);
- if (!snippets || !snippets.length)
- return [];
- let edits = [];
- for (let snip of snippets) {
- let { prefix } = snip;
- if (!line.endsWith(prefix))
- continue;
- let pre = line.slice(0, line.length - prefix.length);
- // not allowed after word
- if (pre.length && /\w/.test(pre[pre.length - 1]))
- continue;
- edits.push({
- prefix,
- range: vscode_languageserver_types_1.Range.create(position.line, position.character - prefix.length, position.line, position.character),
- newText: snip.body,
- location: snip.filepath,
- description: snip.description,
- priority: -1
- });
- }
- return edits;
- }
- async getSnippets(filetype) {
- let res = [];
- let filetypes = this.getFiletypes(filetype);
- let added = new Set();
- for (let key of Object.keys(this._snippetCache)) {
- let cache = this._snippetCache[key];
- for (let filetype of filetypes) {
- let snippets = cache[filetype];
- if (snippets) {
- for (let snip of snippets) {
- if (!added.has(snip.prefix)) {
- added.add(snip.prefix);
- res.push(snip);
- }
- }
- }
- }
- }
- for (let filetype of filetypes) {
- let snippets = this._userSnippets[filetype];
- if (snippets && snippets.length) {
- for (let snip of snippets) {
- if (!added.has(snip.prefix)) {
- added.add(snip.prefix);
- res.push(snip);
- }
- }
- }
- }
- return res;
- }
- async resolveSnippetBody(snip, _range) {
- return snip.body;
- }
- async loadSnippetsFromExtension(extension) {
- let { packageJSON } = extension;
- if (packageJSON.contributes && packageJSON.contributes.snippets) {
- let { snippets } = packageJSON.contributes;
- let def = {
- extensionId: extension.id,
- snippets: []
- };
- for (let item of snippets) {
- let p = path_1.default.join(extension.extensionPath, item.path);
- let { language } = item;
- def.snippets.push({
- languageId: language,
- filepath: p
- });
- }
- if (snippets && snippets.length) {
- await this.loadSnippetsFromDefinition(def);
- }
- }
- }
- async loadSnippetsFromRoot(root) {
- let { _userSnippets } = this;
- if (root.startsWith('~'))
- root = root.replace(/^~/, os_1.default.homedir());
- let files = await util_1.default.promisify(fs_1.default.readdir)(root, 'utf8');
- files = files.filter(f => f.endsWith('.json') || f.endsWith('.code-snippets'));
- await Promise.all(files.map(file => {
- file = path_1.default.join(root, file);
- let basename = path_1.default.basename(file, '.json');
- basename = basename.replace(/\.code-snippets$/, '');
- return this.loadSnippetsFromFile(file).then(snippets => {
- _userSnippets[basename] = snippets;
- });
- }));
- }
- async loadSnippetsFromDefinition(def) {
- let { extensionId, snippets } = def;
- let cache = this._snippetCache[extensionId] = {};
- for (let item of snippets) {
- let { languageId } = item;
- if (!fs_1.default.existsSync(item.filepath))
- continue;
- let arr = await this.loadSnippetsFromFile(item.filepath);
- let exists = cache[languageId] || [];
- cache[languageId] = [...exists, ...arr];
- }
- }
- async loadSnippetsFromFile(snippetFilePath) {
- const contents = await new Promise((resolve, reject) => {
- fs_1.default.readFile(snippetFilePath, "utf8", (err, data) => {
- if (err)
- return reject(err);
- resolve(data);
- });
- });
- const snippets = this.loadSnippetsFromText(snippetFilePath, contents);
- if (this.trace == 'verbose') {
- this.channel.appendLine(`[Info ${(new Date()).toLocaleDateString()}] Loaded ${snippets.length} snippets from ${snippetFilePath}`);
- }
- return snippets;
- }
- loadSnippetsFromText(filepath, contents) {
- let snippets = [];
- try {
- let errors = [];
- let snippetObject = jsonc_parser_1.parse(contents, errors, { allowTrailingComma: true });
- if (errors.length) {
- this.channel.appendLine(`[Error ${(new Date()).toLocaleDateString()}] parser error: ${errors[0].error}`);
- }
- if (snippetObject) {
- for (let key of Object.keys(snippetObject)) {
- snippets.push(snippetObject[key]);
- }
- }
- }
- catch (ex) {
- this.channel.appendLine(`[Error ${(new Date()).toLocaleDateString()}] ${ex.stack}`);
- snippets = [];
- }
- const normalizedSnippets = snippets.map((snip) => {
- let prefix = Array.isArray(snip.prefix) ? snip.prefix[0] : snip.prefix;
- return {
- filepath,
- lnum: 0,
- body: typeof snip.body === 'string' ? snip.body : snip.body.join('\n'),
- prefix,
- description: typeof snip.description === 'string' ? snip.description : typeof snip.description !== 'undefined' ? snip.description.join('\n') : '',
- triggerKind: types_1.TriggerKind.WordBoundary
- };
- });
- return normalizedSnippets;
- }
- }
- exports.TextmateProvider = TextmateProvider;
-
-
- /***/ }),
- /* 44 */
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
-
- "use strict";
- __webpack_require__.r(__webpack_exports__);
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printParseErrorCode", function() { return printParseErrorCode; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modify", function() { return modify; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdits", function() { return applyEdits; });
- /* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45);
- /* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47);
- /* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(46);
- /* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48);
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-
-
-
-
- /**
- * Creates a JSON scanner on the given text.
- * If ignoreTrivia is set, whitespaces or comments are ignored.
- */
- var createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_2__["createScanner"];
- /**
- * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
- */
- var getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getLocation"];
- /**
- * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
- * Therefore, always check the errors list to find out if the input was valid.
- */
- var parse = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parse"];
- /**
- * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
- */
- var parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parseTree"];
- /**
- * Finds the node at the given path in a JSON DOM.
- */
- var findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtLocation"];
- /**
- * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
- */
- var findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtOffset"];
- /**
- * Gets the JSON path of the given JSON DOM node
- */
- var getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodePath"];
- /**
- * Evaluates the JavaScript object of the given JSON DOM node
- */
- var getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"];
- /**
- * Parses the given text and invokes the visitor functions for each object, array and literal reached.
- */
- var visit = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["visit"];
- /**
- * Takes JSON with JavaScript-style comments and remove
- * them. Optionally replaces every none-newline character
- * of comments with a replaceCharacter
- */
- var stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["stripComments"];
- function printParseErrorCode(code) {
- switch (code) {
- case 1 /* InvalidSymbol */: return 'InvalidSymbol';
- case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
- case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
- case 4 /* ValueExpected */: return 'ValueExpected';
- case 5 /* ColonExpected */: return 'ColonExpected';
- case 6 /* CommaExpected */: return 'CommaExpected';
- case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
- case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
- case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
- case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
- case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
- case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
- case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
- case 14 /* InvalidUnicode */: return 'InvalidUnicode';
- case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
- case 16 /* InvalidCharacter */: return 'InvalidCharacter';
- }
- return '<unknown ParseErrorCode>';
- }
- /**
- * Computes the edits needed to format a JSON document.
- *
- * @param documentText The input text
- * @param range The range to format or `undefined` to format the full content
- * @param options The formatting options
- * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
- * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
- * text in the original document. However, multiple edits can have
- * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
- * To apply edits to an input, you can use `applyEdits`.
- */
- function format(documentText, range, options) {
- return _impl_format__WEBPACK_IMPORTED_MODULE_0__["format"](documentText, range, options);
- }
- /**
- * Computes the edits needed to modify a value in the JSON document.
- *
- * @param documentText The input text
- * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
- * If the path points to an non-existing property or item, it will be created.
- * @param value The new value for the specified property or item. If the value is undefined,
- * the property or item will be removed.
- * @param options Options
- * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
- * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
- * text in the original document. However, multiple edits can have
- * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
- * To apply edits to an input, you can use `applyEdits`.
- */
- function modify(text, path, value, options) {
- return _impl_edit__WEBPACK_IMPORTED_MODULE_1__["setProperty"](text, path, value, options.formattingOptions, options.getInsertionIndex);
- }
- /**
- * Applies edits to a input string.
- */
- function applyEdits(text, edits) {
- for (var i = edits.length - 1; i >= 0; i--) {
- text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__["applyEdit"](text, edits[i]);
- }
- return text;
- }
-
-
- /***/ }),
- /* 45 */
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
-
- "use strict";
- __webpack_require__.r(__webpack_exports__);
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEOL", function() { return isEOL; });
- /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-
- function format(documentText, range, options) {
- var initialIndentLevel;
- var formatText;
- var formatTextStart;
- var rangeStart;
- var rangeEnd;
- if (range) {
- rangeStart = range.offset;
- rangeEnd = rangeStart + range.length;
- formatTextStart = rangeStart;
- while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
- formatTextStart--;
- }
- var endOffset = rangeEnd;
- while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
- endOffset++;
- }
- formatText = documentText.substring(formatTextStart, endOffset);
- initialIndentLevel = computeIndentLevel(formatText, options);
- }
- else {
- formatText = documentText;
- initialIndentLevel = 0;
- formatTextStart = 0;
- rangeStart = 0;
- rangeEnd = documentText.length;
- }
- var eol = getEOL(options, documentText);
- var lineBreak = false;
- var indentLevel = 0;
- var indentValue;
- if (options.insertSpaces) {
- indentValue = repeat(' ', options.tabSize || 4);
- }
- else {
- indentValue = '\t';
- }
- var scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(formatText, false);
- var hasError = false;
- function newLineAndIndent() {
- return eol + repeat(indentValue, initialIndentLevel + indentLevel);
- }
- function scanNext() {
- var token = scanner.scan();
- lineBreak = false;
- while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
- lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
- token = scanner.scan();
- }
- hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
- return token;
- }
- var editOperations = [];
- function addEdit(text, startOffset, endOffset) {
- if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
- editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
- }
- }
- var firstToken = scanNext();
- if (firstToken !== 17 /* EOF */) {
- var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
- var initialIndent = repeat(indentValue, initialIndentLevel);
- addEdit(initialIndent, formatTextStart, firstTokenStart);
- }
- while (firstToken !== 17 /* EOF */) {
- var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
- var secondToken = scanNext();
- var replaceContent = '';
- while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
- // comments on the same line: keep them on the same line, but ignore them otherwise
- var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
- addEdit(' ', firstTokenEnd, commentTokenStart);
- firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
- replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : '';
- secondToken = scanNext();
- }
- if (secondToken === 2 /* CloseBraceToken */) {
- if (firstToken !== 1 /* OpenBraceToken */) {
- indentLevel--;
- replaceContent = newLineAndIndent();
- }
- }
- else if (secondToken === 4 /* CloseBracketToken */) {
- if (firstToken !== 3 /* OpenBracketToken */) {
- indentLevel--;
- replaceContent = newLineAndIndent();
- }
- }
- else {
- switch (firstToken) {
- case 3 /* OpenBracketToken */:
- case 1 /* OpenBraceToken */:
- indentLevel++;
- replaceContent = newLineAndIndent();
- break;
- case 5 /* CommaToken */:
- case 12 /* LineCommentTrivia */:
- replaceContent = newLineAndIndent();
- break;
- case 13 /* BlockCommentTrivia */:
- if (lineBreak) {
- replaceContent = newLineAndIndent();
- }
- else {
- // symbol following comment on the same line: keep on same line, separate with ' '
- replaceContent = ' ';
- }
- break;
- case 6 /* ColonToken */:
- replaceContent = ' ';
- break;
- case 10 /* StringLiteral */:
- if (secondToken === 6 /* ColonToken */) {
- replaceContent = '';
- break;
- }
- // fall through
- case 7 /* NullKeyword */:
- case 8 /* TrueKeyword */:
- case 9 /* FalseKeyword */:
- case 11 /* NumericLiteral */:
- case 2 /* CloseBraceToken */:
- case 4 /* CloseBracketToken */:
- if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
- replaceContent = ' ';
- }
- else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
- hasError = true;
- }
- break;
- case 16 /* Unknown */:
- hasError = true;
- break;
- }
- if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
- replaceContent = newLineAndIndent();
- }
- }
- var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
- addEdit(replaceContent, firstTokenEnd, secondTokenStart);
- firstToken = secondToken;
- }
- return editOperations;
- }
- function repeat(s, count) {
- var result = '';
- for (var i = 0; i < count; i++) {
- result += s;
- }
- return result;
- }
- function computeIndentLevel(content, options) {
- var i = 0;
- var nChars = 0;
- var tabSize = options.tabSize || 4;
- while (i < content.length) {
- var ch = content.charAt(i);
- if (ch === ' ') {
- nChars++;
- }
- else if (ch === '\t') {
- nChars += tabSize;
- }
- else {
- break;
- }
- i++;
- }
- return Math.floor(nChars / tabSize);
- }
- function getEOL(options, text) {
- for (var i = 0; i < text.length; i++) {
- var ch = text.charAt(i);
- if (ch === '\r') {
- if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
- return '\r\n';
- }
- return '\r';
- }
- else if (ch === '\n') {
- return '\n';
- }
- }
- return (options && options.eol) || '\n';
- }
- function isEOL(text, offset) {
- return '\r\n'.indexOf(text.charAt(offset)) !== -1;
- }
-
-
- /***/ }),
- /* 46 */
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
-
- "use strict";
- __webpack_require__.r(__webpack_exports__);
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
- /**
- * Creates a JSON scanner on the given text.
- * If ignoreTrivia is set, whitespaces or comments are ignored.
- */
- function createScanner(text, ignoreTrivia) {
- if (ignoreTrivia === void 0) { ignoreTrivia = false; }
- var len = text.length;
- var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
- function scanHexDigits(count, exact) {
- var digits = 0;
- var value = 0;
- while (digits < count || !exact) {
- var ch = text.charCodeAt(pos);
- if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
- value = value * 16 + ch - 48 /* _0 */;
- }
- else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
- value = value * 16 + ch - 65 /* A */ + 10;
- }
- else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
- value = value * 16 + ch - 97 /* a */ + 10;
- }
- else {
- break;
- }
- pos++;
- digits++;
- }
- if (digits < count) {
- value = -1;
- }
- return value;
- }
- function setPosition(newPosition) {
- pos = newPosition;
- value = '';
- tokenOffset = 0;
- token = 16 /* Unknown */;
- scanError = 0 /* None */;
- }
- function scanNumber() {
- var start = pos;
- if (text.charCodeAt(pos) === 48 /* _0 */) {
- pos++;
- }
- else {
- pos++;
- while (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- }
- }
- if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
- pos++;
- if (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- while (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- }
- }
- else {
- scanError = 3 /* UnexpectedEndOfNumber */;
- return text.substring(start, pos);
- }
- }
- var end = pos;
- if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
- pos++;
- if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
- pos++;
- }
- if (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- while (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- }
- end = pos;
- }
- else {
- scanError = 3 /* UnexpectedEndOfNumber */;
- }
- }
- return text.substring(start, end);
- }
- function scanString() {
- var result = '', start = pos;
- while (true) {
- if (pos >= len) {
- result += text.substring(start, pos);
- scanError = 2 /* UnexpectedEndOfString */;
- break;
- }
- var ch = text.charCodeAt(pos);
- if (ch === 34 /* doubleQuote */) {
- result += text.substring(start, pos);
- pos++;
- break;
- }
- if (ch === 92 /* backslash */) {
- result += text.substring(start, pos);
- pos++;
- if (pos >= len) {
- scanError = 2 /* UnexpectedEndOfString */;
- break;
- }
- var ch2 = text.charCodeAt(pos++);
- switch (ch2) {
- case 34 /* doubleQuote */:
- result += '\"';
- break;
- case 92 /* backslash */:
- result += '\\';
- break;
- case 47 /* slash */:
- result += '/';
- break;
- case 98 /* b */:
- result += '\b';
- break;
- case 102 /* f */:
- result += '\f';
- break;
- case 110 /* n */:
- result += '\n';
- break;
- case 114 /* r */:
- result += '\r';
- break;
- case 116 /* t */:
- result += '\t';
- break;
- case 117 /* u */:
- var ch3 = scanHexDigits(4, true);
- if (ch3 >= 0) {
- result += String.fromCharCode(ch3);
- }
- else {
- scanError = 4 /* InvalidUnicode */;
- }
- break;
- default:
- scanError = 5 /* InvalidEscapeCharacter */;
- }
- start = pos;
- continue;
- }
- if (ch >= 0 && ch <= 0x1f) {
- if (isLineBreak(ch)) {
- result += text.substring(start, pos);
- scanError = 2 /* UnexpectedEndOfString */;
- break;
- }
- else {
- scanError = 6 /* InvalidCharacter */;
- // mark as error but continue with string
- }
- }
- pos++;
- }
- return result;
- }
- function scanNext() {
- value = '';
- scanError = 0 /* None */;
- tokenOffset = pos;
- lineStartOffset = lineNumber;
- prevTokenLineStartOffset = tokenLineStartOffset;
- if (pos >= len) {
- // at the end
- tokenOffset = len;
- return token = 17 /* EOF */;
- }
- var code = text.charCodeAt(pos);
- // trivia: whitespace
- if (isWhiteSpace(code)) {
- do {
- pos++;
- value += String.fromCharCode(code);
- code = text.charCodeAt(pos);
- } while (isWhiteSpace(code));
- return token = 15 /* Trivia */;
- }
- // trivia: newlines
- if (isLineBreak(code)) {
- pos++;
- value += String.fromCharCode(code);
- if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
- pos++;
- value += '\n';
- }
- lineNumber++;
- tokenLineStartOffset = pos;
- return token = 14 /* LineBreakTrivia */;
- }
- switch (code) {
- // tokens: []{}:,
- case 123 /* openBrace */:
- pos++;
- return token = 1 /* OpenBraceToken */;
- case 125 /* closeBrace */:
- pos++;
- return token = 2 /* CloseBraceToken */;
- case 91 /* openBracket */:
- pos++;
- return token = 3 /* OpenBracketToken */;
- case 93 /* closeBracket */:
- pos++;
- return token = 4 /* CloseBracketToken */;
- case 58 /* colon */:
- pos++;
- return token = 6 /* ColonToken */;
- case 44 /* comma */:
- pos++;
- return token = 5 /* CommaToken */;
- // strings
- case 34 /* doubleQuote */:
- pos++;
- value = scanString();
- return token = 10 /* StringLiteral */;
- // comments
- case 47 /* slash */:
- var start = pos - 1;
- // Single-line comment
- if (text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- while (pos < len) {
- if (isLineBreak(text.charCodeAt(pos))) {
- break;
- }
- pos++;
- }
- value = text.substring(start, pos);
- return token = 12 /* LineCommentTrivia */;
- }
- // Multi-line comment
- if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
- pos += 2;
- var safeLength = len - 1; // For lookahead.
- var commentClosed = false;
- while (pos < safeLength) {
- var ch = text.charCodeAt(pos);
- if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
- pos += 2;
- commentClosed = true;
- break;
- }
- pos++;
- if (isLineBreak(ch)) {
- if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
- pos++;
- }
- lineNumber++;
- tokenLineStartOffset = pos;
- }
- }
- if (!commentClosed) {
- pos++;
- scanError = 1 /* UnexpectedEndOfComment */;
- }
- value = text.substring(start, pos);
- return token = 13 /* BlockCommentTrivia */;
- }
- // just a single slash
- value += String.fromCharCode(code);
- pos++;
- return token = 16 /* Unknown */;
- // numbers
- case 45 /* minus */:
- value += String.fromCharCode(code);
- pos++;
- if (pos === len || !isDigit(text.charCodeAt(pos))) {
- return token = 16 /* Unknown */;
- }
- // found a minus, followed by a number so
- // we fall through to proceed with scanning
- // numbers
- case 48 /* _0 */:
- case 49 /* _1 */:
- case 50 /* _2 */:
- case 51 /* _3 */:
- case 52 /* _4 */:
- case 53 /* _5 */:
- case 54 /* _6 */:
- case 55 /* _7 */:
- case 56 /* _8 */:
- case 57 /* _9 */:
- value += scanNumber();
- return token = 11 /* NumericLiteral */;
- // literals and unknown symbols
- default:
- // is a literal? Read the full word.
- while (pos < len && isUnknownContentCharacter(code)) {
- pos++;
- code = text.charCodeAt(pos);
- }
- if (tokenOffset !== pos) {
- value = text.substring(tokenOffset, pos);
- // keywords: true, false, null
- switch (value) {
- case 'true': return token = 8 /* TrueKeyword */;
- case 'false': return token = 9 /* FalseKeyword */;
- case 'null': return token = 7 /* NullKeyword */;
- }
- return token = 16 /* Unknown */;
- }
- // some
- value += String.fromCharCode(code);
- pos++;
- return token = 16 /* Unknown */;
- }
- }
- function isUnknownContentCharacter(code) {
- if (isWhiteSpace(code) || isLineBreak(code)) {
- return false;
- }
- switch (code) {
- case 125 /* closeBrace */:
- case 93 /* closeBracket */:
- case 123 /* openBrace */:
- case 91 /* openBracket */:
- case 34 /* doubleQuote */:
- case 58 /* colon */:
- case 44 /* comma */:
- case 47 /* slash */:
- return false;
- }
- return true;
- }
- function scanNextNonTrivia() {
- var result;
- do {
- result = scanNext();
- } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
- return result;
- }
- return {
- setPosition: setPosition,
- getPosition: function () { return pos; },
- scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
- getToken: function () { return token; },
- getTokenValue: function () { return value; },
- getTokenOffset: function () { return tokenOffset; },
- getTokenLength: function () { return pos - tokenOffset; },
- getTokenStartLine: function () { return lineStartOffset; },
- getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
- getTokenError: function () { return scanError; },
- };
- }
- function isWhiteSpace(ch) {
- return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
- ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
- ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
- }
- function isLineBreak(ch) {
- return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
- }
- function isDigit(ch) {
- return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
- }
-
-
- /***/ }),
- /* 47 */
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
-
- "use strict";
- __webpack_require__.r(__webpack_exports__);
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeProperty", function() { return removeProperty; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setProperty", function() { return setProperty; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdit", function() { return applyEdit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWS", function() { return isWS; });
- /* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45);
- /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48);
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-
-
- function removeProperty(text, path, formattingOptions) {
- return setProperty(text, path, void 0, formattingOptions);
- }
- function setProperty(text, originalPath, value, formattingOptions, getInsertionIndex) {
- var _a;
- var path = originalPath.slice();
- var errors = [];
- var root = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["parseTree"])(text, errors);
- var parent = void 0;
- var lastSegment = void 0;
- while (path.length > 0) {
- lastSegment = path.pop();
- parent = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(root, path);
- if (parent === void 0 && value !== void 0) {
- if (typeof lastSegment === 'string') {
- value = (_a = {}, _a[lastSegment] = value, _a);
- }
- else {
- value = [value];
- }
- }
- else {
- break;
- }
- }
- if (!parent) {
- // empty document
- if (value === void 0) { // delete
- throw new Error('Can not delete in empty document');
- }
- return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
- }
- else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
- var existing = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(parent, [lastSegment]);
- if (existing !== void 0) {
- if (value === void 0) { // delete
- if (!existing.parent) {
- throw new Error('Malformed AST');
- }
- var propertyIndex = parent.children.indexOf(existing.parent);
- var removeBegin = void 0;
- var removeEnd = existing.parent.offset + existing.parent.length;
- if (propertyIndex > 0) {
- // remove the comma of the previous node
- var previous = parent.children[propertyIndex - 1];
- removeBegin = previous.offset + previous.length;
- }
- else {
- removeBegin = parent.offset + 1;
- if (parent.children.length > 1) {
- // remove the comma of the next node
- var next = parent.children[1];
- removeEnd = next.offset;
- }
- }
- return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions);
- }
- else {
- // set value of existing property
- return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
- }
- }
- else {
- if (value === void 0) { // delete
- return []; // property does not exist, nothing to do
- }
- var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
- var index = getInsertionIndex ? getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
- var edit = void 0;
- if (index > 0) {
- var previous = parent.children[index - 1];
- edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
- }
- else if (parent.children.length === 0) {
- edit = { offset: parent.offset + 1, length: 0, content: newProperty };
- }
- else {
- edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
- }
- return withFormatting(text, edit, formattingOptions);
- }
- }
- else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
- var insertIndex = lastSegment;
- if (insertIndex === -1) {
- // Insert
- var newProperty = "" + JSON.stringify(value);
- var edit = void 0;
- if (parent.children.length === 0) {
- edit = { offset: parent.offset + 1, length: 0, content: newProperty };
- }
- else {
- var previous = parent.children[parent.children.length - 1];
- edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
- }
- return withFormatting(text, edit, formattingOptions);
- }
- else {
- if (value === void 0 && parent.children.length >= 0) {
- //Removal
- var removalIndex = lastSegment;
- var toRemove = parent.children[removalIndex];
- var edit = void 0;
- if (parent.children.length === 1) {
- // only item
- edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
- }
- else if (parent.children.length - 1 === removalIndex) {
- // last item
- var previous = parent.children[removalIndex - 1];
- var offset = previous.offset + previous.length;
- var parentEndOffset = parent.offset + parent.length;
- edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
- }
- else {
- edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
- }
- return withFormatting(text, edit, formattingOptions);
- }
- else {
- throw new Error('Array modification not supported yet');
- }
- }
- }
- else {
- throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
- }
- }
- function withFormatting(text, edit, formattingOptions) {
- // apply the edit
- var newText = applyEdit(text, edit);
- // format the new text
- var begin = edit.offset;
- var end = edit.offset + edit.content.length;
- if (edit.length === 0 || edit.content.length === 0) { // insert or remove
- while (begin > 0 && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, begin - 1)) {
- begin--;
- }
- while (end < newText.length && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, end)) {
- end++;
- }
- }
- var edits = Object(_format__WEBPACK_IMPORTED_MODULE_0__["format"])(newText, { offset: begin, length: end - begin }, formattingOptions);
- // apply the formatting edits and track the begin and end offsets of the changes
- for (var i = edits.length - 1; i >= 0; i--) {
- var edit_1 = edits[i];
- newText = applyEdit(newText, edit_1);
- begin = Math.min(begin, edit_1.offset);
- end = Math.max(end, edit_1.offset + edit_1.length);
- end += edit_1.content.length - edit_1.length;
- }
- // create a single edit with all changes
- var editLength = text.length - (newText.length - end) - begin;
- return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
- }
- function applyEdit(text, edit) {
- return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
- }
- function isWS(text, offset) {
- return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
- }
-
-
- /***/ }),
- /* 48 */
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
-
- "use strict";
- __webpack_require__.r(__webpack_exports__);
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeType", function() { return getNodeType; });
- /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-
- var ParseOptions;
- (function (ParseOptions) {
- ParseOptions.DEFAULT = {
- allowTrailingComma: false
- };
- })(ParseOptions || (ParseOptions = {}));
- /**
- * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
- */
- function getLocation(text, position) {
- var segments = []; // strings or numbers
- var earlyReturnException = new Object();
- var previousNode = undefined;
- var previousNodeInst = {
- value: {},
- offset: 0,
- length: 0,
- type: 'object',
- parent: undefined
- };
- var isAtPropertyKey = false;
- function setPreviousNode(value, offset, length, type) {
- previousNodeInst.value = value;
- previousNodeInst.offset = offset;
- previousNodeInst.length = length;
- previousNodeInst.type = type;
- previousNodeInst.colonOffset = undefined;
- previousNode = previousNodeInst;
- }
- try {
- visit(text, {
- onObjectBegin: function (offset, length) {
- if (position <= offset) {
- throw earlyReturnException;
- }
- previousNode = undefined;
- isAtPropertyKey = position > offset;
- segments.push(''); // push a placeholder (will be replaced)
- },
- onObjectProperty: function (name, offset, length) {
- if (position < offset) {
- throw earlyReturnException;
- }
- setPreviousNode(name, offset, length, 'property');
- segments[segments.length - 1] = name;
- if (position <= offset + length) {
- throw earlyReturnException;
- }
- },
- onObjectEnd: function (offset, length) {
- if (position <= offset) {
- throw earlyReturnException;
- }
- previousNode = undefined;
- segments.pop();
- },
- onArrayBegin: function (offset, length) {
- if (position <= offset) {
- throw earlyReturnException;
- }
- previousNode = undefined;
- segments.push(0);
- },
- onArrayEnd: function (offset, length) {
- if (position <= offset) {
- throw earlyReturnException;
- }
- previousNode = undefined;
- segments.pop();
- },
- onLiteralValue: function (value, offset, length) {
- if (position < offset) {
- throw earlyReturnException;
- }
- setPreviousNode(value, offset, length, getNodeType(value));
- if (position <= offset + length) {
- throw earlyReturnException;
- }
- },
- onSeparator: function (sep, offset, length) {
- if (position <= offset) {
- throw earlyReturnException;
- }
- if (sep === ':' && previousNode && previousNode.type === 'property') {
- previousNode.colonOffset = offset;
- isAtPropertyKey = false;
- previousNode = undefined;
- }
- else if (sep === ',') {
- var last = segments[segments.length - 1];
- if (typeof last === 'number') {
- segments[segments.length - 1] = last + 1;
- }
- else {
- isAtPropertyKey = true;
- segments[segments.length - 1] = '';
- }
- previousNode = undefined;
- }
- }
- });
- }
- catch (e) {
- if (e !== earlyReturnException) {
- throw e;
- }
- }
- return {
- path: segments,
- previousNode: previousNode,
- isAtPropertyKey: isAtPropertyKey,
- matches: function (pattern) {
- var k = 0;
- for (var i = 0; k < pattern.length && i < segments.length; i++) {
- if (pattern[k] === segments[i] || pattern[k] === '*') {
- k++;
- }
- else if (pattern[k] !== '**') {
- return false;
- }
- }
- return k === pattern.length;
- }
- };
- }
- /**
- * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
- * Therefore always check the errors list to find out if the input was valid.
- */
- function parse(text, errors, options) {
- if (errors === void 0) { errors = []; }
- if (options === void 0) { options = ParseOptions.DEFAULT; }
- var currentProperty = null;
- var currentParent = [];
- var previousParents = [];
- function onValue(value) {
- if (Array.isArray(currentParent)) {
- currentParent.push(value);
- }
- else if (currentProperty !== null) {
- currentParent[currentProperty] = value;
- }
- }
- var visitor = {
- onObjectBegin: function () {
- var object = {};
- onValue(object);
- previousParents.push(currentParent);
- currentParent = object;
- currentProperty = null;
- },
- onObjectProperty: function (name) {
- currentProperty = name;
- },
- onObjectEnd: function () {
- currentParent = previousParents.pop();
- },
- onArrayBegin: function () {
- var array = [];
- onValue(array);
- previousParents.push(currentParent);
- currentParent = array;
- currentProperty = null;
- },
- onArrayEnd: function () {
- currentParent = previousParents.pop();
- },
- onLiteralValue: onValue,
- onError: function (error, offset, length) {
- errors.push({ error: error, offset: offset, length: length });
- }
- };
- visit(text, visitor, options);
- return currentParent[0];
- }
- /**
- * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
- */
- function parseTree(text, errors, options) {
- if (errors === void 0) { errors = []; }
- if (options === void 0) { options = ParseOptions.DEFAULT; }
- var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
- function ensurePropertyComplete(endOffset) {
- if (currentParent.type === 'property') {
- currentParent.length = endOffset - currentParent.offset;
- currentParent = currentParent.parent;
- }
- }
- function onValue(valueNode) {
- currentParent.children.push(valueNode);
- return valueNode;
- }
- var visitor = {
- onObjectBegin: function (offset) {
- currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
- },
- onObjectProperty: function (name, offset, length) {
- currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
- currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
- },
- onObjectEnd: function (offset, length) {
- ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete
- currentParent.length = offset + length - currentParent.offset;
- currentParent = currentParent.parent;
- ensurePropertyComplete(offset + length);
- },
- onArrayBegin: function (offset, length) {
- currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
- },
- onArrayEnd: function (offset, length) {
- currentParent.length = offset + length - currentParent.offset;
- currentParent = currentParent.parent;
- ensurePropertyComplete(offset + length);
- },
- onLiteralValue: function (value, offset, length) {
- onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
- ensurePropertyComplete(offset + length);
- },
- onSeparator: function (sep, offset, length) {
- if (currentParent.type === 'property') {
- if (sep === ':') {
- currentParent.colonOffset = offset;
- }
- else if (sep === ',') {
- ensurePropertyComplete(offset);
- }
- }
- },
- onError: function (error, offset, length) {
- errors.push({ error: error, offset: offset, length: length });
- }
- };
- visit(text, visitor, options);
- var result = currentParent.children[0];
- if (result) {
- delete result.parent;
- }
- return result;
- }
- /**
- * Finds the node at the given path in a JSON DOM.
- */
- function findNodeAtLocation(root, path) {
- if (!root) {
- return undefined;
- }
- var node = root;
- for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
- var segment = path_1[_i];
- if (typeof segment === 'string') {
- if (node.type !== 'object' || !Array.isArray(node.children)) {
- return undefined;
- }
- var found = false;
- for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
- var propertyNode = _b[_a];
- if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
- node = propertyNode.children[1];
- found = true;
- break;
- }
- }
- if (!found) {
- return undefined;
- }
- }
- else {
- var index = segment;
- if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
- return undefined;
- }
- node = node.children[index];
- }
- }
- return node;
- }
- /**
- * Gets the JSON path of the given JSON DOM node
- */
- function getNodePath(node) {
- if (!node.parent || !node.parent.children) {
- return [];
- }
- var path = getNodePath(node.parent);
- if (node.parent.type === 'property') {
- var key = node.parent.children[0].value;
- path.push(key);
- }
- else if (node.parent.type === 'array') {
- var index = node.parent.children.indexOf(node);
- if (index !== -1) {
- path.push(index);
- }
- }
- return path;
- }
- /**
- * Evaluates the JavaScript object of the given JSON DOM node
- */
- function getNodeValue(node) {
- switch (node.type) {
- case 'array':
- return node.children.map(getNodeValue);
- case 'object':
- var obj = Object.create(null);
- for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
- var prop = _a[_i];
- var valueNode = prop.children[1];
- if (valueNode) {
- obj[prop.children[0].value] = getNodeValue(valueNode);
- }
- }
- return obj;
- case 'null':
- case 'string':
- case 'number':
- case 'boolean':
- return node.value;
- default:
- return undefined;
- }
- }
- function contains(node, offset, includeRightBound) {
- if (includeRightBound === void 0) { includeRightBound = false; }
- return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
- }
- /**
- * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
- */
- function findNodeAtOffset(node, offset, includeRightBound) {
- if (includeRightBound === void 0) { includeRightBound = false; }
- if (contains(node, offset, includeRightBound)) {
- var children = node.children;
- if (Array.isArray(children)) {
- for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
- var item = findNodeAtOffset(children[i], offset, includeRightBound);
- if (item) {
- return item;
- }
- }
- }
- return node;
- }
- return undefined;
- }
- /**
- * Parses the given text and invokes the visitor functions for each object, array and literal reached.
- */
- function visit(text, visitor, options) {
- if (options === void 0) { options = ParseOptions.DEFAULT; }
- var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text, false);
- function toNoArgVisit(visitFunction) {
- return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
- }
- function toOneArgVisit(visitFunction) {
- return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
- }
- var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
- var disallowComments = options && options.disallowComments;
- var allowTrailingComma = options && options.allowTrailingComma;
- function scanNext() {
- while (true) {
- var token = _scanner.scan();
- switch (_scanner.getTokenError()) {
- case 4 /* InvalidUnicode */:
- handleError(14 /* InvalidUnicode */);
- break;
- case 5 /* InvalidEscapeCharacter */:
- handleError(15 /* InvalidEscapeCharacter */);
- break;
- case 3 /* UnexpectedEndOfNumber */:
- handleError(13 /* UnexpectedEndOfNumber */);
- break;
- case 1 /* UnexpectedEndOfComment */:
- if (!disallowComments) {
- handleError(11 /* UnexpectedEndOfComment */);
- }
- break;
- case 2 /* UnexpectedEndOfString */:
- handleError(12 /* UnexpectedEndOfString */);
- break;
- case 6 /* InvalidCharacter */:
- handleError(16 /* InvalidCharacter */);
- break;
- }
- switch (token) {
- case 12 /* LineCommentTrivia */:
- case 13 /* BlockCommentTrivia */:
- if (disallowComments) {
- handleError(10 /* InvalidCommentToken */);
- }
- else {
- onComment();
- }
- break;
- case 16 /* Unknown */:
- handleError(1 /* InvalidSymbol */);
- break;
- case 15 /* Trivia */:
- case 14 /* LineBreakTrivia */:
- break;
- default:
- return token;
- }
- }
- }
- function handleError(error, skipUntilAfter, skipUntil) {
- if (skipUntilAfter === void 0) { skipUntilAfter = []; }
- if (skipUntil === void 0) { skipUntil = []; }
- onError(error);
- if (skipUntilAfter.length + skipUntil.length > 0) {
- var token = _scanner.getToken();
- while (token !== 17 /* EOF */) {
- if (skipUntilAfter.indexOf(token) !== -1) {
- scanNext();
- break;
- }
- else if (skipUntil.indexOf(token) !== -1) {
- break;
- }
- token = scanNext();
- }
- }
- }
- function parseString(isValue) {
- var value = _scanner.getTokenValue();
- if (isValue) {
- onLiteralValue(value);
- }
- else {
- onObjectProperty(value);
- }
- scanNext();
- return true;
- }
- function parseLiteral() {
- switch (_scanner.getToken()) {
- case 11 /* NumericLiteral */:
- var value = 0;
- try {
- value = JSON.parse(_scanner.getTokenValue());
- if (typeof value !== 'number') {
- handleError(2 /* InvalidNumberFormat */);
- value = 0;
- }
- }
- catch (e) {
- handleError(2 /* InvalidNumberFormat */);
- }
- onLiteralValue(value);
- break;
- case 7 /* NullKeyword */:
- onLiteralValue(null);
- break;
- case 8 /* TrueKeyword */:
- onLiteralValue(true);
- break;
- case 9 /* FalseKeyword */:
- onLiteralValue(false);
- break;
- default:
- return false;
- }
- scanNext();
- return true;
- }
- function parseProperty() {
- if (_scanner.getToken() !== 10 /* StringLiteral */) {
- handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
- return false;
- }
- parseString(false);
- if (_scanner.getToken() === 6 /* ColonToken */) {
- onSeparator(':');
- scanNext(); // consume colon
- if (!parseValue()) {
- handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
- }
- }
- else {
- handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
- }
- return true;
- }
- function parseObject() {
- onObjectBegin();
- scanNext(); // consume open brace
- var needsComma = false;
- while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
- if (_scanner.getToken() === 5 /* CommaToken */) {
- if (!needsComma) {
- handleError(4 /* ValueExpected */, [], []);
- }
- onSeparator(',');
- scanNext(); // consume comma
- if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
- break;
- }
- }
- else if (needsComma) {
- handleError(6 /* CommaExpected */, [], []);
- }
- if (!parseProperty()) {
- handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
- }
- needsComma = true;
- }
- onObjectEnd();
- if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
- handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
- }
- else {
- scanNext(); // consume close brace
- }
- return true;
- }
- function parseArray() {
- onArrayBegin();
- scanNext(); // consume open bracket
- var needsComma = false;
- while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
- if (_scanner.getToken() === 5 /* CommaToken */) {
- if (!needsComma) {
- handleError(4 /* ValueExpected */, [], []);
- }
- onSeparator(',');
- scanNext(); // consume comma
- if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
- break;
- }
- }
- else if (needsComma) {
- handleError(6 /* CommaExpected */, [], []);
- }
- if (!parseValue()) {
- handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
- }
- needsComma = true;
- }
- onArrayEnd();
- if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
- handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
- }
- else {
- scanNext(); // consume close bracket
- }
- return true;
- }
- function parseValue() {
- switch (_scanner.getToken()) {
- case 3 /* OpenBracketToken */:
- return parseArray();
- case 1 /* OpenBraceToken */:
- return parseObject();
- case 10 /* StringLiteral */:
- return parseString(true);
- default:
- return parseLiteral();
- }
- }
- scanNext();
- if (_scanner.getToken() === 17 /* EOF */) {
- if (options.allowEmptyContent) {
- return true;
- }
- handleError(4 /* ValueExpected */, [], []);
- return false;
- }
- if (!parseValue()) {
- handleError(4 /* ValueExpected */, [], []);
- return false;
- }
- if (_scanner.getToken() !== 17 /* EOF */) {
- handleError(9 /* EndOfFileExpected */, [], []);
- }
- return true;
- }
- /**
- * Takes JSON with JavaScript-style comments and remove
- * them. Optionally replaces every none-newline character
- * of comments with a replaceCharacter
- */
- function stripComments(text, replaceCh) {
- var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text), parts = [], kind, offset = 0, pos;
- do {
- pos = _scanner.getPosition();
- kind = _scanner.scan();
- switch (kind) {
- case 12 /* LineCommentTrivia */:
- case 13 /* BlockCommentTrivia */:
- case 17 /* EOF */:
- if (offset !== pos) {
- parts.push(text.substring(offset, pos));
- }
- if (replaceCh !== undefined) {
- parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
- }
- offset = _scanner.getPosition();
- break;
- }
- } while (kind !== 17 /* EOF */);
- return parts.join('');
- }
- function getNodeType(value) {
- switch (typeof value) {
- case 'boolean': return 'boolean';
- case 'number': return 'number';
- case 'string': return 'string';
- case 'object': {
- if (!value) {
- return 'null';
- }
- else if (Array.isArray(value)) {
- return 'array';
- }
- return 'object';
- }
- default: return 'null';
- }
- }
-
-
- /***/ }),
- /* 49 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- const coc_nvim_1 = __webpack_require__(1);
- const fs_1 = __importDefault(__webpack_require__(3));
- const os_1 = __importDefault(__webpack_require__(2));
- const path_1 = __importDefault(__webpack_require__(4));
- const vscode_languageserver_types_1 = __webpack_require__(6);
- const baseProvider_1 = __importDefault(__webpack_require__(41));
- const types_1 = __webpack_require__(36);
- const ultisnipsParser_1 = __importDefault(__webpack_require__(50));
- const util_1 = __webpack_require__(37);
- const pythonCodes = new Map();
- class UltiSnippetsProvider extends baseProvider_1.default {
- constructor(channel, trace, config, context) {
- super(config);
- this.channel = channel;
- this.trace = trace;
- this.config = config;
- this.context = context;
- this.snippetFiles = [];
- this.disposables = [];
- this.directories = [];
- this.runtimeDirs = [];
- this.runtimeDirs = coc_nvim_1.workspace.env.runtimepath.split(',');
- coc_nvim_1.workspace.watchOption('runtimepath', async (_, newValue) => {
- let parts = newValue.split(',');
- let subFolders = await this.getSubFolders();
- let items = [];
- for (let dir of parts) {
- if (this.runtimeDirs.indexOf(dir) == -1) {
- this.runtimeDirs.push(dir);
- let res = await this.getSnippetsFromPlugin(dir, subFolders);
- items.push(...res);
- }
- }
- if (items.length) {
- await Promise.all(items.map(({ filepath, directory, filetype }) => {
- return this.loadSnippetsFromFile(filetype, directory, filepath);
- }));
- let files = items.map(o => o.filepath);
- let pythonCode = '';
- for (let file of files) {
- let code = pythonCodes.get(file);
- if (code) {
- pythonCode += `# ${file}\n` + code + '\n';
- }
- }
- if (pythonCode) {
- pythonCodes.clear();
- await this.executePythonCode(pythonCode);
- }
- }
- }, this.disposables);
- }
- checkLoaded(filepath) {
- return this.snippetFiles.findIndex(o => o.filepath == filepath) !== -1;
- }
- async init() {
- let { nvim, env } = coc_nvim_1.workspace;
- let { runtimepath } = env;
- let { config } = this;
- for (let dir of config.directories) {
- if (dir.startsWith('~') || dir.indexOf('$') !== -1) {
- let res = await coc_nvim_1.workspace.nvim.call('expand', [dir]);
- this.directories.push(res);
- }
- else {
- this.directories.push(dir);
- }
- }
- this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Using ultisnips directories: ${this.directories.join(' ')}`);
- let hasPythonx = await nvim.call('has', ['pythonx']);
- let pythonCode = await util_1.readFileAsync(this.context.asAbsolutePath('python/ultisnips.py'), 'utf8');
- if (hasPythonx && config.usePythonx) {
- this.pyMethod = 'pyx';
- }
- else {
- this.pyMethod = config.pythonVersion == 3 ? 'py3' : 'py';
- }
- this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Using ultisnips python command: ${this.pyMethod}`);
- this.parser = new ultisnipsParser_1.default(this.pyMethod, this.channel, this.trace);
- let arr = await this.getAllSnippetFiles(runtimepath);
- let files = arr.map(o => o.filepath);
- await Promise.all(arr.map(({ filepath, directory, filetype }) => {
- return this.loadSnippetsFromFile(filetype, directory, filepath);
- }));
- for (let file of files) {
- let code = pythonCodes.get(file);
- if (code) {
- pythonCode += `\n# ${file}\n` + code + '\n';
- }
- }
- await this.executePythonCode(pythonCode);
- coc_nvim_1.workspace.onDidSaveTextDocument(async (doc) => {
- let uri = coc_nvim_1.Uri.parse(doc.uri);
- if (uri.scheme != 'file' || !doc.uri.endsWith('.snippets'))
- return;
- let filepath = uri.fsPath;
- if (!fs_1.default.existsSync(filepath))
- return;
- let snippetFile = this.snippetFiles.find(s => s.filepath == filepath);
- if (snippetFile) {
- await this.loadSnippetsFromFile(snippetFile.filetype, snippetFile.directory, filepath);
- }
- else {
- let filetype = path_1.default.basename(filepath, '.snippets');
- await this.loadSnippetsFromFile(filetype, path_1.default.dirname(filepath), filepath);
- }
- }, null, this.disposables);
- }
- async loadSnippetsFromFile(filetype, directory, filepath) {
- let { snippets, pythonCode, extendFiletypes, clearsnippets } = await this.parser.parseUltisnipsFile(filepath);
- let idx = this.snippetFiles.findIndex(o => o.filepath == filepath);
- if (idx !== -1)
- this.snippetFiles.splice(idx, 1);
- this.snippetFiles.push({
- extendFiletypes,
- clearsnippets,
- directory,
- filepath,
- filetype,
- snippets
- });
- if (extendFiletypes) {
- let filetypes = this.config.extends[filetype] || [];
- filetypes = filetypes.concat(extendFiletypes);
- this.config.extends[filetype] = util_1.distinct(filetypes);
- }
- if (this.trace == 'verbose') {
- this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Loaded ${snippets.length} snippets from: ${filepath}`);
- }
- pythonCodes.set(filepath, pythonCode);
- }
- async resolveSnippetBody(snippet, range, line) {
- let { nvim } = coc_nvim_1.workspace;
- let { body, context, originRegex } = snippet;
- let buf = await nvim.buffer;
- let filepath = await buf.name;
- let indentCount = await nvim.call('indent', '.');
- let ind = ' '.repeat(indentCount);
- if (body.indexOf('`!p') !== -1) {
- let values = new Map();
- let re = /\$\{(\d+)(?::([^}]+))?\}/g;
- let r;
- // tslint:disable-next-line: no-conditional-assignment
- while (r = re.exec(body)) {
- let idx = parseInt(r[1], 10);
- let val = r[2] || '';
- let exists = values.get(idx);
- if (exists == null || (val && exists == "''")) {
- if (/^`!\w/.test(val) && val.endsWith('`')) {
- let code = val.slice(1).slice(0, -1);
- val = await this.parser.execute(code, this.pyMethod, ind);
- }
- val = val.replace(/'/g, "\\'").replace(/\n/g, '\\n');
- values.set(idx, "'" + val + "'");
- }
- }
- re = /\$(\d+)/g;
- // tslint:disable-next-line: no-conditional-assignment
- while (r = re.exec(body)) {
- let idx = parseInt(r[1], 10);
- if (!values.has(idx)) {
- values.set(idx, "''");
- }
- }
- let len = values.size == 0 ? 0 : Math.max.apply(null, Array.from(values.keys()));
- let vals = (new Array(len)).fill('""');
- for (let [idx, val] of values.entries()) {
- vals[idx] = val;
- }
- let pyCodes = [];
- pyCodes.push('import re, os, vim, string, random');
- pyCodes.push(`t = ('', ${vals.join(',')})`);
- pyCodes.push(`fn = '${path_1.default.basename(filepath)}'`);
- pyCodes.push(`path = '${filepath}'`);
- if (context) {
- pyCodes.push(`snip = ContextSnippet()`);
- pyCodes.push(`context = ${context}`);
- }
- else {
- pyCodes.push(`context = {}`);
- }
- let start = `(${range.start.line},${Buffer.byteLength(line.slice(0, range.start.character))})`;
- let end = `(${range.end.line},${Buffer.byteLength(line.slice(0, range.end.character))})`;
- pyCodes.push(`snip = SnippetUtil('${ind}', ${start}, ${end}, context)`);
- if (originRegex) {
- pyCodes.push(`pattern = re.compile(r"${originRegex.replace(/"/g, '\\"')}")`);
- pyCodes.push(`match = pattern.search("${line.replace(/"/g, '\\"')}")`);
- }
- try {
- await nvim.command(`${this.pyMethod} ${pyCodes.join('\n')}`);
- }
- catch (e) {
- this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}]: ${e.message}`);
- this.channel.appendLine(`code: ${pyCodes.join('\n')}`);
- }
- }
- return this.parser.resolveUltisnipsBody(body);
- }
- async checkContext(context) {
- let { nvim } = coc_nvim_1.workspace;
- let pyCodes = [];
- pyCodes.push('import re, os, vim, string, random');
- pyCodes.push(`snip = ContextSnippet()`);
- pyCodes.push(`context = ${context}`);
- await nvim.command(`${this.pyMethod} ${pyCodes.join('\n')}`);
- let res = await nvim.call(`${this.pyMethod}eval`, 'True if context else False');
- return res;
- }
- async getTriggerSnippets(document, position, autoTrigger) {
- let snippets = await this.getSnippets(document.filetype);
- let line = document.getline(position.line);
- line = line.slice(0, position.character);
- if (!line || line[line.length - 1] == ' ')
- return [];
- snippets = snippets.filter(s => {
- let { prefix, regex } = s;
- if (autoTrigger && !s.autoTrigger)
- return false;
- if (regex) {
- let ms = line.match(regex);
- if (!ms)
- return false;
- prefix = ms[0];
- }
- if (!line.endsWith(prefix))
- return false;
- if (s.triggerKind == types_1.TriggerKind.InWord)
- return true;
- let pre = line.slice(0, line.length - prefix.length);
- if (s.triggerKind == types_1.TriggerKind.LineBegin)
- return pre.trim() == '';
- if (s.triggerKind == types_1.TriggerKind.SpaceBefore)
- return pre.length == 0 || /\s/.test(pre[pre.length - 1]);
- if (s.triggerKind == types_1.TriggerKind.WordBoundary)
- return pre.length == 0 || !document.isWord(pre[pre.length - 1]);
- return false;
- });
- snippets.sort((a, b) => {
- if (a.context && !b.context)
- return -1;
- if (b.context && !a.context)
- return 1;
- return 0;
- });
- let edits = [];
- let contextPrefixes = [];
- for (let s of snippets) {
- let character;
- if (s.context) {
- let valid = await this.checkContext(s.context);
- if (!valid)
- continue;
- contextPrefixes.push(s.context);
- }
- else if (contextPrefixes.indexOf(s.prefix) !== -1) {
- continue;
- }
- if (s.regex == null) {
- character = position.character - s.prefix.length;
- }
- else {
- let len = line.match(s.regex)[0].length;
- character = position.character - len;
- }
- let range = vscode_languageserver_types_1.Range.create(position.line, character, position.line, position.character);
- let newText = await this.resolveSnippetBody(s, range, line);
- edits.push({
- prefix: s.prefix,
- description: s.description,
- location: s.filepath,
- priority: s.priority,
- range,
- newText,
- });
- }
- return edits;
- }
- async getSnippetFiles(filetype) {
- let filetypes = this.getFiletypes(filetype);
- let res = [];
- for (let s of this.snippetFiles) {
- if (filetypes.indexOf(s.filetype) !== -1) {
- res.push(s.filepath);
- }
- }
- return res;
- }
- async getSnippets(filetype) {
- let filetypes = this.getFiletypes(filetype);
- filetypes.push('all');
- let snippetFiles = this.snippetFiles.filter(o => filetypes.indexOf(o.filetype) !== -1);
- let min = null;
- let result = [];
- snippetFiles.sort((a, b) => {
- if (a.filetype == b.filetype)
- return 1;
- if (a.filetype == filetype)
- return -1;
- return 1;
- });
- for (let file of snippetFiles) {
- let { snippets, clearsnippets } = file;
- if (typeof clearsnippets == 'number') {
- min = min ? Math.max(min, clearsnippets) : clearsnippets;
- }
- for (let snip of snippets) {
- if (snip.regex || snip.context) {
- result.push(snip);
- }
- else {
- let idx = result.findIndex(o => o.prefix == snip.prefix && o.triggerKind == snip.triggerKind);
- if (idx == -1) {
- result.push(snip);
- }
- else {
- let item = result[idx];
- if (snip.priority > item.priority) {
- result[idx] = item;
- }
- }
- }
- }
- }
- if (min != null)
- result = result.filter(o => o.priority >= min);
- result.sort((a, b) => {
- if (a.context && !b.context)
- return -1;
- if (b.context && !a.context)
- return 1;
- return 0;
- });
- return result;
- }
- async getAllSnippetFiles(runtimepath) {
- let { directories } = this;
- let res = [];
- for (let directory of directories) {
- if (path_1.default.isAbsolute(directory)) {
- let items = await this.getSnippetFileItems(directory);
- res.push(...items);
- }
- }
- let subFolders = await this.getSubFolders();
- let rtps = runtimepath.split(',');
- this.runtimeDirs = rtps;
- for (let rtp of rtps) {
- let items = await this.getSnippetsFromPlugin(rtp, subFolders);
- res.push(...items);
- }
- return res;
- }
- async getSubFolders() {
- let { directories } = this;
- directories = directories.filter(s => !path_1.default.isAbsolute(s));
- // use UltiSnipsSnippetDirectories
- let dirs = await coc_nvim_1.workspace.nvim.eval('get(g:, "UltiSnipsSnippetDirectories", [])');
- for (let dir of dirs) {
- if (directories.indexOf(dir) == -1) {
- directories.push(dir);
- }
- }
- return directories;
- }
- async getSnippetsFromPlugin(directory, subFolders) {
- let res = [];
- for (let folder of subFolders) {
- let items = await this.getSnippetFileItems(path_1.default.join(directory, folder));
- res.push(...items);
- }
- return res;
- }
- async getSnippetFileItems(directory) {
- let res = [];
- let stat = await util_1.statAsync(directory);
- if (stat && stat.isDirectory()) {
- let files = await util_1.readdirAsync(directory);
- if (files.length) {
- for (let f of files) {
- let file = path_1.default.join(directory, f);
- if (file.endsWith('.snippets')) {
- let basename = path_1.default.basename(f, '.snippets');
- let filetype = basename.split('_', 2)[0];
- res.push({ filepath: file, directory, filetype });
- }
- else {
- let stat = await util_1.statAsync(file);
- if (stat && stat.isDirectory()) {
- let files = await util_1.readdirAsync(file);
- for (let filename of files) {
- if (filename.endsWith('.snippets')) {
- res.push({ filepath: path_1.default.join(file, filename), directory, filetype: f });
- }
- }
- }
- }
- }
- }
- }
- return res;
- }
- async executePythonCode(pythonCode) {
- try {
- let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
- if (!fs_1.default.existsSync(dir))
- fs_1.default.mkdirSync(dir);
- let tmpfile = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`, `coc-ultisnips-${util_1.uid()}.py`);
- fs_1.default.writeFileSync(tmpfile, '# -*- coding: utf-8 -*-\n' + pythonCode, 'utf8');
- await coc_nvim_1.workspace.nvim.command(`exe '${this.pyMethod}file '.fnameescape('${tmpfile}')`);
- pythonCodes.clear();
- }
- catch (e) {
- this.channel.appendLine(`Error on execute python script:`);
- this.channel.append(e.message);
- coc_nvim_1.workspace.showMessage(`Error on execute python script: ${e.message}`, 'error');
- }
- }
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- }
- }
- exports.UltiSnippetsProvider = UltiSnippetsProvider;
-
-
- /***/ }),
- /* 50 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /******************************************************************
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
- *******************************************************************/
- const child_process_1 = __webpack_require__(51);
- const coc_nvim_1 = __webpack_require__(1);
- const fs_1 = __importDefault(__webpack_require__(3));
- const pify_1 = __importDefault(__webpack_require__(38));
- const readline_1 = __importDefault(__webpack_require__(40));
- const parser_1 = __importDefault(__webpack_require__(42));
- const types_1 = __webpack_require__(36);
- const util_1 = __webpack_require__(37);
- class UltiSnipsParser {
- constructor(pyMethod, channel, trace = 'error') {
- this.pyMethod = pyMethod;
- this.channel = channel;
- this.trace = trace;
- }
- parseUltisnipsFile(filepath) {
- const rl = readline_1.default.createInterface({
- input: fs_1.default.createReadStream(filepath, 'utf8'),
- crlfDelay: Infinity
- });
- let pycodes = [];
- let snippets = [];
- let block;
- let preLines = [];
- let first;
- let priority = 0;
- let lnum = 0;
- let clearsnippets = null;
- let parsedContext = null;
- let extendFiletypes = [];
- rl.on('line', line => {
- lnum += 1;
- if (!block && (line.startsWith('#') || line.length == 0))
- return;
- const [head, tail] = util_1.headTail(line);
- if (!block) {
- switch (head) {
- case 'priority':
- let n = parseInt(tail.trim(), 10);
- if (!isNaN(n))
- priority = n;
- break;
- case 'extends':
- let fts = tail.trim().split(/,\s+/);
- for (let ft of fts) {
- if (extendFiletypes.indexOf(ft) == -1) {
- extendFiletypes.push(ft);
- }
- }
- break;
- case 'clearsnippets':
- clearsnippets = priority;
- break;
- case 'context':
- parsedContext = tail.replace(/^"(.+)"$/, '$1');
- break;
- case 'snippet':
- case 'global':
- block = head;
- first = tail;
- break;
- }
- return;
- }
- if (head == 'endglobal' && block == 'global') {
- block = null;
- pycodes.push(...preLines);
- preLines = [];
- return;
- }
- if (head == 'endsnippet' && block == 'snippet') {
- block = null;
- try {
- let originRegex;
- let body = preLines.join('\n');
- // convert placeholder regex to javascript regex
- body = body.replace(/((?:[^\\]?\$\{\w+?)\/)([^\n]*?[^\\])(?=\/)/g, (_match, p1, p2) => {
- return p1 + util_1.convertRegex(p2);
- });
- let ms = first.match(/^(.+?)(?:\s+(?:"(.*?)")?(?:\s+"(.*?)")?(?:\s+(\w+))?)?\s*$/);
- let prefix = ms[1];
- let description = ms[2] || '';
- let context = ms[3];
- let option = ms[4] || '';
- if (prefix.length > 2 && prefix[0] == prefix[prefix.length - 1] && !/\w/.test(prefix[0])) {
- prefix = prefix.slice(1, prefix.length - 1);
- }
- let isExpression = option.indexOf('r') !== -1;
- let regex = null;
- if (isExpression) {
- originRegex = prefix;
- prefix = util_1.convertRegex(prefix);
- prefix = prefix.endsWith('$') ? prefix : prefix + '$';
- try {
- regex = new RegExp(prefix);
- // get the real text
- prefix = util_1.getRegexText(prefix);
- }
- catch (e) {
- this.error(`Convert regex error for: ${prefix}`);
- }
- }
- if (parsedContext) {
- context = parsedContext;
- }
- else if (option.indexOf('e') == -1) {
- context = null;
- }
- let snippet = {
- filepath,
- context,
- originRegex,
- autoTrigger: option.indexOf('A') !== -1,
- lnum: lnum - preLines.length - 2,
- triggerKind: getTriggerKind(option),
- prefix,
- description,
- regex,
- body,
- priority
- };
- snippets.push(snippet);
- }
- catch (e) {
- this.error(`Create snippet error on: ${filepath}:${lnum - preLines.length - 1} ${e.message}`);
- }
- finally {
- parsedContext = null;
- preLines = [];
- }
- }
- if (block == 'snippet' || block == 'global') {
- preLines.push(line);
- return;
- }
- });
- return new Promise(resolve => {
- rl.on('close', async () => {
- resolve({ snippets, clearsnippets, pythonCode: pycodes.join('\n'), extendFiletypes });
- });
- });
- }
- async resolveUltisnipsBody(body) {
- let { pyMethod } = this;
- let parser = new parser_1.default(body);
- let resolved = '';
- while (!parser.eof()) {
- let p = parser.prev();
- if (parser.curr == '`' && (!p || p != '\\')) {
- let idx = parser.nextIndex('`', true, false);
- if (idx == -1) {
- resolved = resolved + parser.eatTo(parser.len);
- break;
- }
- let code = parser.eatTo(idx + 1);
- code = code.slice(1, -1);
- let indent = resolved.split(/\n/).slice(-1)[0].match(/^\s*/)[0];
- resolved = resolved + await this.execute(code, pyMethod, indent);
- continue;
- }
- else if (parser.curr == '$') {
- let text = parser.next(7);
- if (text.startsWith('VISUAL') || text.startsWith('{VISUAL')) {
- parser.eat(8);
- resolved += '$' + text.replace('VISUAL', 'TM_SELECTED_TEXT');
- }
- else if (!/^\d/.test(text) && !text.startsWith('{') && p != '\\') {
- // escape $ if it's not escaped and not a placeholder, ultisnips sucks
- resolved += '\\' + parser.eat(1);
- }
- else {
- // skip current
- resolved += parser.eat(1);
- }
- }
- let prev = parser.prev() || '';
- parser.iterate(ch => {
- if (prev !== '\\' && (ch == '`' || ch == '$')) {
- return false;
- }
- else {
- resolved = resolved + ch;
- }
- prev = ch;
- return true;
- });
- }
- resolved = decode(resolved);
- this.debug(`resolved: ${resolved}`);
- return resolved;
- }
- async execute(code, pyMethod, indent) {
- let { nvim } = coc_nvim_1.workspace;
- let res = '';
- if (code.startsWith('!')) {
- code = code.trim().slice(1);
- if (code.startsWith('p')) {
- code = code.slice(1).trim();
- let lines = code.split('\n');
- lines = lines.map(line => line.replace(/\t/g, ' '));
- lines = lines.map(line => ` ${line}`);
- lines.unshift('try:');
- lines.unshift('import traceback');
- lines.push('except Exception as e:');
- lines.push(' snip.rv = traceback.format_exc()');
- await nvim.command(`${pyMethod} ${lines.join('\n')}`);
- res = await nvim.call(`${pyMethod}eval`, 'snip.rv');
- }
- else if (code.startsWith('v')) {
- code = code.replace(/^v\s*/, '');
- try {
- res = await nvim.eval(code);
- }
- catch (e) {
- res = `Error: ${e.message}`;
- this.error(e.stack);
- }
- }
- }
- else {
- try {
- res = await pify_1.default(child_process_1.exec)(code);
- }
- catch (e) {
- res = `Error: ${e.message}`;
- this.error(`Error on eval ${code}: ` + e.stack);
- }
- }
- res = res.toString();
- res = res.replace(/\r?\n$/, '');
- let parts = res.split(/\r?\n/);
- if (parts.length > 1) {
- res = parts.map((s, idx) => {
- if (idx == 0 || s.length == 0)
- return s;
- return `${indent}${s}`;
- }).join('\n');
- }
- return res;
- }
- error(str) {
- if (!this.channel)
- return;
- this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] ${str}`);
- }
- debug(str) {
- if (!this.channel || this.trace == 'error')
- return;
- this.channel.appendLine(`[Debug ${(new Date()).toLocaleTimeString()}] ${str}`);
- }
- }
- exports.default = UltiSnipsParser;
- function decode(str) {
- return str.replace(/\\`/g, '`').replace(/\\{/g, '{');
- }
- function getTriggerKind(option) {
- if (option.indexOf('w') !== -1) {
- return types_1.TriggerKind.WordBoundary;
- }
- if (option.indexOf('b') !== -1) {
- return types_1.TriggerKind.LineBegin;
- }
- if (option.indexOf('i') !== -1) {
- return types_1.TriggerKind.InWord;
- }
- return types_1.TriggerKind.SpaceBefore;
- }
-
-
- /***/ }),
- /* 51 */
- /***/ (function(module, exports) {
-
- module.exports = require("child_process");
-
- /***/ }),
- /* 52 */
- /***/ (function(module, exports) {
-
- /**
- * Returns a function, that, as long as it continues to be invoked, will not
- * be triggered. The function will be called after it stops being called for
- * N milliseconds. If `immediate` is passed, trigger the function on the
- * leading edge, instead of the trailing. The function also has a property 'clear'
- * that is a function which will clear the timer to prevent previously scheduled executions.
- *
- * @source underscore.js
- * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
- * @param {Function} function to wrap
- * @param {Number} timeout in ms (`100`)
- * @param {Boolean} whether to execute at the beginning (`false`)
- * @api public
- */
- function debounce(func, wait, immediate){
- var timeout, args, context, timestamp, result;
- if (null == wait) wait = 100;
-
- function later() {
- var last = Date.now() - timestamp;
-
- if (last < wait && last >= 0) {
- timeout = setTimeout(later, wait - last);
- } else {
- timeout = null;
- if (!immediate) {
- result = func.apply(context, args);
- context = args = null;
- }
- }
- };
-
- var debounced = function(){
- context = this;
- args = arguments;
- timestamp = Date.now();
- var callNow = immediate && !timeout;
- if (!timeout) timeout = setTimeout(later, wait);
- if (callNow) {
- result = func.apply(context, args);
- context = args = null;
- }
-
- return result;
- };
-
- debounced.clear = function() {
- if (timeout) {
- clearTimeout(timeout);
- timeout = null;
- }
- };
-
- debounced.flush = function() {
- if (timeout) {
- result = func.apply(context, args);
- context = args = null;
-
- clearTimeout(timeout);
- timeout = null;
- }
- };
-
- return debounced;
- };
-
- // Adds compatibility for ES modules
- debounce.debounce = debounce;
-
- module.exports = debounce;
-
-
- /***/ }),
- /* 53 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(8);
- const util_1 = __webpack_require__(37);
- const codesMap = new Map();
- codesMap.set(1, 'invalid snippet line, trigger requried.');
- codesMap.set(2, 'invalid snippet option, option "$1" not supported.');
- codesMap.set(3, 'invalid python expression, $1');
- codesMap.set(4, 'invalid code interpolation, #! not supported.');
- const validOptions = ['b', 'i', 'w', 'r', 'e', 'A'];
- class LanguageProvider {
- constructor(channel, trace = 'error') {
- this.channel = channel;
- this.trace = trace;
- this.disposables = [];
- this.collection = coc_nvim_1.languages.createDiagnosticCollection('snippets');
- for (let doc of coc_nvim_1.workspace.documents) {
- if (this.shouldValidate(doc.uri)) {
- this.validate(doc.uri, doc.getDocumentContent()).catch(e => {
- channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}]: ${e.message}`);
- });
- }
- }
- coc_nvim_1.workspace.onDidOpenTextDocument(async (textDocument) => {
- let doc = coc_nvim_1.workspace.getDocument(textDocument.uri);
- if (!this.shouldValidate(doc.uri))
- return;
- await this.validate(doc.uri, doc.getDocumentContent());
- }, null, this.disposables);
- coc_nvim_1.workspace.onDidChangeTextDocument(async (ev) => {
- let doc = coc_nvim_1.workspace.getDocument(ev.textDocument.uri);
- if (!doc || !this.shouldValidate(doc.uri))
- return;
- await this.validate(doc.uri, doc.getDocumentContent());
- }, null, this.disposables);
- coc_nvim_1.workspace.onDidCloseTextDocument(e => {
- this.collection.delete(e.uri);
- }, null, this.disposables);
- }
- shouldValidate(uri) {
- return uri.endsWith('.snippets');
- }
- async validate(uri, content) {
- let lines = content.split('\n');
- let diagnostics = [];
- let curr = 0;
- for (let line of lines) {
- if (/^snippet\s*$/.test(line)) {
- let range = vscode_languageserver_protocol_1.Range.create(curr, 0, curr, line.length);
- diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, codesMap.get(1), vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 1));
- continue;
- }
- if (line.startsWith('snippet ')) {
- let content = util_1.headTail(line)[1];
- let ms = content.match(/^(.+?)(?:\s+(?:"(.*?)")?(?:\s+"(.*?)")?(?:\s+(\w+))?)?$/);
- let prefix = ms[1];
- if (prefix.length > 2 && prefix[0] == prefix[prefix.length - 1] && !/\w/.test(prefix[0])) {
- prefix = prefix.slice(1, prefix.length - 1);
- }
- let option = ms[4] || '';
- let isExpression = option.indexOf('r') !== -1;
- let startCharacter = line.length - option.length;
- for (let ch of option) {
- if (validOptions.indexOf(ch) == -1) {
- let range = vscode_languageserver_protocol_1.Range.create(curr, startCharacter, curr, startCharacter + 1);
- let message = codesMap.get(2).replace('$1', ch);
- diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 2));
- }
- startCharacter = startCharacter + 1;
- }
- if (isExpression) {
- try {
- util_1.convertRegex(prefix);
- }
- catch (e) {
- let start = line.indexOf(prefix);
- let range = vscode_languageserver_protocol_1.Range.create(curr, start, curr, start + prefix.length);
- let message = codesMap.get(3).replace('$1', e.message);
- diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 3));
- }
- }
- }
- else {
- let idx = line.indexOf('`#!');
- if (idx !== -1) {
- let range = vscode_languageserver_protocol_1.Range.create(curr, idx, curr, idx + 3);
- let message = codesMap.get(4);
- diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 4));
- }
- }
- curr++;
- }
- if (this.trace == 'verbose') {
- this.channel.appendLine(`[Debug ${(new Date()).toLocaleTimeString()}] diagnostics of ${uri} -> ${JSON.stringify(diagnostics)}`);
- }
- this.collection.set(uri, diagnostics);
- }
- provideCompletionItems(_document, position, _token, context) {
- let { input, col } = context.option;
- if (context.triggerCharacter == '$') {
- return [{
- label: '$VISUAL',
- kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
- // tslint:disable-next-line: no-invalid-template-strings
- detail: '${VISUAL}',
- insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet,
- textEdit: {
- range: vscode_languageserver_protocol_1.Range.create(position.line, position.character - 1, position.line, position.character),
- // tslint:disable-next-line: no-invalid-template-strings
- newText: '\\${VISUAL${1::default}\\}'
- }
- }];
- }
- if (col == 0 && 'snippet'.startsWith(input)) {
- return [{
- label: 'snippet',
- kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
- detail: 'Snippet definition',
- insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet,
- // tslint:disable-next-line: no-invalid-template-strings
- insertText: 'snippet ${1:Tab_trigger} "${2:Description}" ${3:b}\n$0\nendsnippet'
- }];
- }
- return [];
- }
- async resolveCompletionItem(item) {
- // tslint:disable-next-line: deprecation
- let text = item.insertText || item.textEdit.newText;
- // tslint:disable-next-line: deprecation
- let snip = await Promise.resolve(coc_nvim_1.snippetManager.resolveSnippet(text));
- item.documentation = {
- kind: 'markdown',
- value: util_1.markdownBlock(snip.toString(), 'snippets')
- };
- return item;
- }
- }
- exports.default = LanguageProvider;
-
-
- /***/ })
- /******/ ])));
|