bim.c 335 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001
  1. /* Bim - A Text Editor
  2. *
  3. * Copyright (C) 2012-2021 K. Lange
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include "bim.h"
  18. #define BIM_VERSION "3.1.0" TAG
  19. #define BIM_COPYRIGHT "Copyright 2012-2021 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  20. #include <kuroko/kuroko.h>
  21. #include <kuroko/vm.h>
  22. #include <kuroko/debug.h>
  23. #include <kuroko/util.h>
  24. #include <kuroko/scanner.h>
  25. global_config_t global_config = {
  26. /* State */
  27. .term_width = 0,
  28. .term_height = 0,
  29. .bottom_size = 2,
  30. .yanks = NULL,
  31. .yank_count = 0,
  32. .yank_is_full_lines = 0,
  33. .tty_in = STDIN_FILENO,
  34. .bimrc_path = "~/.bim3rc",
  35. .syntax_fallback = NULL, /* Syntax to fall back to if no other match applies */
  36. .search = NULL,
  37. .overlay_mode = OVERLAY_MODE_NONE,
  38. .command_buffer = NULL,
  39. .command_offset = 0,
  40. .command_col_no = 0,
  41. .history_point = -1,
  42. .search_point = -1,
  43. /* Bitset starts here */
  44. .highlight_on_open = 1,
  45. .initial_file_is_read_only = 0,
  46. .go_to_line = 1,
  47. .break_from_selection = 1,
  48. /* Terminal capabilities */
  49. .can_scroll = 1,
  50. .can_hideshow = 1,
  51. .can_altscreen = 1,
  52. .can_mouse = 1,
  53. .can_unicode = 1,
  54. .can_bright = 1,
  55. .can_title = 1,
  56. .can_bce = 1,
  57. .can_24bit = 1, /* can use 24-bit color */
  58. .can_256color = 1, /* can use 265 colors */
  59. .can_italic = 1, /* can use italics (without inverting) */
  60. .can_insert = 0, /* ^[[L */
  61. .can_bracketedpaste = 0, /* puts escapes before and after pasted stuff */
  62. .can_sgrmouse = 0, /* Whether SGR mouse mode is availabe (large coordinates) */
  63. /* Configuration options */
  64. .history_enabled = 1,
  65. .highlight_parens = 1, /* highlight parens/braces when cursor moves */
  66. .smart_case = 1, /* smart case-sensitivity while searching */
  67. .highlight_current_line = 1,
  68. .shift_scrolling = 1, /* shift rather than moving cursor*/
  69. .check_git = 0,
  70. .color_gutter = 1, /* shows modified lines */
  71. .relative_lines = 0,
  72. .numbers = 1,
  73. .horizontal_shift_scrolling = 0, /* Whether to shift the whole screen when scrolling horizontally */
  74. .hide_statusbar = 0,
  75. .tabs_visible = 1,
  76. .autohide_tabs = 0,
  77. .smart_complete = 0,
  78. .has_terminal = 0,
  79. .search_wraps = 1,
  80. .had_error = 0,
  81. .use_biminfo = 1,
  82. /* Integer config values */
  83. .cursor_padding = 4,
  84. .split_percent = 50,
  85. .scroll_amount = 5,
  86. .tab_offset = 0,
  87. .background_task = NULL,
  88. .tail_task = NULL,
  89. };
  90. struct key_name_map KeyNames[] = {
  91. {KEY_TIMEOUT, "[timeout]"},
  92. {KEY_BACKSPACE, "<backspace>"},
  93. {KEY_ENTER, "<enter>"},
  94. {KEY_ESCAPE, "<escape>"},
  95. {KEY_TAB, "<tab>"},
  96. {' ', "<space>"},
  97. /* These are mostly here for markdown output. */
  98. {'`', "<backtick>"},
  99. {'|', "<pipe>"},
  100. {KEY_DELETE, "<del>"},
  101. {KEY_MOUSE, "<mouse>"},
  102. {KEY_MOUSE_SGR, "<mouse-sgr>"},
  103. {KEY_F1, "<f1>"},{KEY_F2, "<f2>"},{KEY_F3, "<f3>"},{KEY_F4, "<f4>"},
  104. {KEY_F5, "<f5>"},{KEY_F6, "<f6>"},{KEY_F7, "<f7>"},{KEY_F8, "<f8>"},
  105. {KEY_F9, "<f9>"},{KEY_F10, "<f10>"},{KEY_F11, "<f11>"},{KEY_F12, "<f12>"},
  106. {KEY_HOME,"<home>"},{KEY_END,"<end>"},{KEY_PAGE_UP,"<page-up>"},{KEY_PAGE_DOWN,"<page-down>"},
  107. {KEY_UP, "<up>"},{KEY_DOWN, "<down>"},{KEY_RIGHT, "<right>"},{KEY_LEFT, "<left>"},
  108. {KEY_SHIFT_UP, "<shift-up>"},{KEY_SHIFT_DOWN, "<shift-down>"},{KEY_SHIFT_RIGHT, "<shift-right>"},{KEY_SHIFT_LEFT, "<shift-left>"},
  109. {KEY_CTRL_UP, "<ctrl-up>"},{KEY_CTRL_DOWN, "<ctrl-down>"},{KEY_CTRL_RIGHT, "<ctrl-right>"},{KEY_CTRL_LEFT, "<ctrl-left>"},
  110. {KEY_ALT_UP, "<alt-up>"},{KEY_ALT_DOWN, "<alt-down>"},{KEY_ALT_RIGHT, "<alt-right>"},{KEY_ALT_LEFT, "<alt-left>"},
  111. {KEY_ALT_SHIFT_UP, "<alt-shift-up>"},{KEY_ALT_SHIFT_DOWN, "<alt-shift-down>"},{KEY_ALT_SHIFT_RIGHT, "<alt-shift-right>"},{KEY_ALT_SHIFT_LEFT, "<alt-shift-left>"},
  112. {KEY_SHIFT_TAB,"<shift-tab>"},
  113. {KEY_PASTE_BEGIN,"<paste-begin>"},{KEY_PASTE_END,"<paste-end>"},
  114. };
  115. char * name_from_key(enum Key keycode) {
  116. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  117. if (KeyNames[i].keycode == keycode) return KeyNames[i].name;
  118. }
  119. static char keyNameTmp[8] = {0};
  120. if (keycode <= KEY_CTRL_UNDERSCORE) {
  121. keyNameTmp[0] = '^';
  122. keyNameTmp[1] = '@' + keycode;
  123. keyNameTmp[2] = 0;
  124. return keyNameTmp;
  125. }
  126. to_eight(keycode, keyNameTmp);
  127. return keyNameTmp;
  128. }
  129. #define S(c) (krk_copyString(c,sizeof(c)-1))
  130. static KrkClass * syntaxStateClass = NULL;
  131. struct SyntaxState {
  132. KrkInstance inst;
  133. struct syntax_state state;
  134. };
  135. static void schedule_complete_recalc(void);
  136. /**
  137. * Theming data
  138. *
  139. * This default set is pretty simple "default foreground on default background"
  140. * except for search and selections which are black-on-white specifically.
  141. *
  142. * The theme colors get set by separate configurable theme scripts.
  143. */
  144. const char * COLOR_FG = "@9";
  145. const char * COLOR_BG = "@9";
  146. const char * COLOR_ALT_FG = "@9";
  147. const char * COLOR_ALT_BG = "@9";
  148. const char * COLOR_NUMBER_FG = "@9";
  149. const char * COLOR_NUMBER_BG = "@9";
  150. const char * COLOR_STATUS_FG = "@9";
  151. const char * COLOR_STATUS_BG = "@9";
  152. const char * COLOR_STATUS_ALT= "@9";
  153. const char * COLOR_TABBAR_BG = "@9";
  154. const char * COLOR_TAB_BG = "@9";
  155. const char * COLOR_ERROR_FG = "@9";
  156. const char * COLOR_ERROR_BG = "@9";
  157. const char * COLOR_SEARCH_FG = "@0";
  158. const char * COLOR_SEARCH_BG = "@17";
  159. const char * COLOR_KEYWORD = "@9";
  160. const char * COLOR_STRING = "@9";
  161. const char * COLOR_COMMENT = "@9";
  162. const char * COLOR_TYPE = "@9";
  163. const char * COLOR_PRAGMA = "@9";
  164. const char * COLOR_NUMERAL = "@9";
  165. const char * COLOR_SELECTFG = "@0";
  166. const char * COLOR_SELECTBG = "@17";
  167. const char * COLOR_RED = "@1";
  168. const char * COLOR_GREEN = "@2";
  169. const char * COLOR_BOLD = "@9";
  170. const char * COLOR_LINK = "@9";
  171. const char * COLOR_ESCAPE = "@9";
  172. const char * current_theme = "none";
  173. struct ColorName color_names[] = {
  174. {"text-fg", &COLOR_FG},
  175. {"text-bg", &COLOR_BG},
  176. {"alternate-fg", &COLOR_ALT_FG},
  177. {"alternate-bg", &COLOR_ALT_BG},
  178. {"number-fg", &COLOR_NUMBER_FG},
  179. {"number-bg", &COLOR_NUMBER_BG},
  180. {"status-fg", &COLOR_STATUS_FG},
  181. {"status-bg", &COLOR_STATUS_BG},
  182. {"status-alt", &COLOR_STATUS_ALT},
  183. {"tabbar-bg", &COLOR_TABBAR_BG},
  184. {"tab-bg", &COLOR_TAB_BG},
  185. {"error-fg", &COLOR_ERROR_FG},
  186. {"error-bg", &COLOR_ERROR_BG},
  187. {"search-fg", &COLOR_SEARCH_FG},
  188. {"search-bg", &COLOR_SEARCH_BG},
  189. {"keyword", &COLOR_KEYWORD},
  190. {"string", &COLOR_STRING},
  191. {"comment", &COLOR_COMMENT},
  192. {"type", &COLOR_TYPE},
  193. {"pragma", &COLOR_PRAGMA},
  194. {"numeral", &COLOR_NUMERAL},
  195. {"select-fg", &COLOR_SELECTFG},
  196. {"select-bg", &COLOR_SELECTBG},
  197. {"red", &COLOR_RED},
  198. {"green", &COLOR_GREEN},
  199. {"bold", &COLOR_BOLD},
  200. {"link", &COLOR_LINK},
  201. {"escape", &COLOR_ESCAPE},
  202. {NULL,NULL},
  203. };
  204. #define FLEXIBLE_ARRAY(name, add_name, type, zero) \
  205. int flex_ ## name ## _count = 0; \
  206. int flex_ ## name ## _space = 0; \
  207. type * name = NULL; \
  208. void add_name (type input) { \
  209. if (flex_ ## name ## _space == 0) { \
  210. flex_ ## name ## _space = 4; \
  211. name = calloc(sizeof(type), flex_ ## name ## _space); \
  212. } else if (flex_ ## name ## _count + 1 == flex_ ## name ## _space) { \
  213. flex_ ## name ## _space *= 2; \
  214. name = realloc(name, sizeof(type) * flex_ ## name ## _space); \
  215. for (int i = flex_ ## name ## _count; i < flex_ ## name ## _space; ++i) name[i] = zero; \
  216. } \
  217. name[flex_ ## name ## _count] = input; \
  218. flex_ ## name ## _count ++; \
  219. }
  220. FLEXIBLE_ARRAY(mappable_actions, add_action, struct action_def, ((struct action_def){NULL,NULL,0,NULL}))
  221. FLEXIBLE_ARRAY(regular_commands, add_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  222. FLEXIBLE_ARRAY(prefix_commands, add_prefix_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  223. FLEXIBLE_ARRAY(themes, add_colorscheme, struct theme_def, ((struct theme_def){NULL,NULL}))
  224. /**
  225. * Special implementation of getch with a timeout
  226. */
  227. int _bim_unget = -1;
  228. void bim_unget(int c) {
  229. _bim_unget = c;
  230. }
  231. void redraw_statusbar(void);
  232. int bim_getch_timeout(int timeout) {
  233. fflush(stdout);
  234. if (_bim_unget != -1) {
  235. int out = _bim_unget;
  236. _bim_unget = -1;
  237. return out;
  238. }
  239. struct pollfd fds[1];
  240. fds[0].fd = global_config.tty_in;
  241. fds[0].events = POLLIN;
  242. int ret = poll(fds,1,timeout);
  243. if (ret > 0 && fds[0].revents & POLLIN) {
  244. unsigned char buf[1];
  245. read(global_config.tty_in, buf, 1);
  246. return buf[0];
  247. } else {
  248. background_task_t * task = global_config.background_task;
  249. if (task) {
  250. global_config.background_task = task->next;
  251. task->func(task);
  252. free(task);
  253. if (!global_config.background_task) {
  254. global_config.tail_task = NULL;
  255. redraw_statusbar();
  256. }
  257. }
  258. return -1;
  259. }
  260. }
  261. /**
  262. * UTF-8 parser state
  263. */
  264. static uint32_t codepoint_r;
  265. static uint32_t state = 0;
  266. #define UTF8_ACCEPT 0
  267. #define UTF8_REJECT 1
  268. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  269. static int state_table[32] = {
  270. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  271. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  272. 2,2,2,2, /* 110xxxxx */
  273. 3,3, /* 1110xxxx */
  274. 4, /* 11110xxx */
  275. 1 /* 11111xxx */
  276. };
  277. static int mask_bytes[32] = {
  278. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  279. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  280. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  281. 0x1F,0x1F,0x1F,0x1F,
  282. 0x0F,0x0F,
  283. 0x07,
  284. 0x00
  285. };
  286. static int next[5] = {
  287. 0,
  288. 1,
  289. 0,
  290. 2,
  291. 3
  292. };
  293. if (*state == UTF8_ACCEPT) {
  294. *codep = byte & mask_bytes[byte >> 3];
  295. *state = state_table[byte >> 3];
  296. } else if (*state > 0) {
  297. *codep = (byte & 0x3F) | (*codep << 6);
  298. *state = next[*state];
  299. }
  300. return *state;
  301. }
  302. #define shift_key(i) _shift_key((i), this_buf, &timeout);
  303. int _shift_key(int i, int this_buf[20], int *timeout) {
  304. int thing = this_buf[*timeout-1];
  305. (*timeout) = 0;
  306. switch (thing) {
  307. /* There are other combinations we can handle... */
  308. case '2': return i + 4;
  309. case '5': return i + 8;
  310. case '3': return i + 12;
  311. case '4': return i + 16;
  312. default: return i;
  313. }
  314. }
  315. int bim_getkey(int read_timeout) {
  316. int timeout = 0;
  317. int this_buf[20];
  318. int cin;
  319. uint32_t c;
  320. uint32_t istate = 0;
  321. while ((cin = bim_getch_timeout((timeout == 1) ? 50 : read_timeout))) {
  322. if (cin == -1) {
  323. if (timeout && this_buf[timeout-1] == '\033')
  324. return KEY_ESCAPE;
  325. return KEY_TIMEOUT;
  326. }
  327. if (!decode(&istate, &c, cin)) {
  328. if (timeout == 0) {
  329. switch (c) {
  330. case '\033':
  331. if (timeout == 0) {
  332. this_buf[timeout] = c;
  333. timeout++;
  334. }
  335. continue;
  336. case KEY_LINEFEED: return KEY_ENTER;
  337. case KEY_DELETE: return KEY_BACKSPACE;
  338. }
  339. return c;
  340. } else {
  341. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '\033') {
  342. bim_unget(c);
  343. timeout = 0;
  344. return KEY_ESCAPE;
  345. }
  346. if (timeout >= 1 && this_buf[0] == '\033' && c == 'O') {
  347. this_buf[timeout] = c;
  348. timeout++;
  349. continue;
  350. }
  351. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == 'O') {
  352. switch (c) {
  353. case 'P': return KEY_F1;
  354. case 'Q': return KEY_F2;
  355. case 'R': return KEY_F3;
  356. case 'S': return KEY_F4;
  357. }
  358. timeout = 0;
  359. continue;
  360. }
  361. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c != '[') {
  362. timeout = 0;
  363. bim_unget(c);
  364. return KEY_ESCAPE;
  365. }
  366. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '[') {
  367. timeout = 1;
  368. this_buf[timeout] = c;
  369. timeout++;
  370. continue;
  371. }
  372. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  373. (isdigit(c) || (c == ';'))) {
  374. this_buf[timeout] = c;
  375. timeout++;
  376. continue;
  377. }
  378. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  379. switch (c) {
  380. case 'M': return KEY_MOUSE;
  381. case '<': return KEY_MOUSE_SGR;
  382. case 'A': return shift_key(KEY_UP);
  383. case 'B': return shift_key(KEY_DOWN);
  384. case 'C': return shift_key(KEY_RIGHT);
  385. case 'D': return shift_key(KEY_LEFT);
  386. case 'H': return KEY_HOME;
  387. case 'F': return KEY_END;
  388. case 'I': return KEY_PAGE_UP;
  389. case 'G': return KEY_PAGE_DOWN;
  390. case 'Z': return KEY_SHIFT_TAB;
  391. case '~':
  392. if (timeout == 3) {
  393. switch (this_buf[2]) {
  394. case '1': return KEY_HOME;
  395. case '3': return KEY_DELETE;
  396. case '4': return KEY_END;
  397. case '5': return KEY_PAGE_UP;
  398. case '6': return KEY_PAGE_DOWN;
  399. }
  400. } else if (timeout == 5) {
  401. if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '0') {
  402. return KEY_PASTE_BEGIN;
  403. } else if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '1') {
  404. return KEY_PASTE_END;
  405. }
  406. } else if (this_buf[2] == '1') {
  407. switch (this_buf[3]) {
  408. case '5': return KEY_F5;
  409. case '7': return KEY_F6;
  410. case '8': return KEY_F7;
  411. case '9': return KEY_F8;
  412. }
  413. } else if (this_buf[2] == '2') {
  414. switch (this_buf[3]) {
  415. case '0': return KEY_F9;
  416. case '1': return KEY_F10;
  417. case '3': return KEY_F11;
  418. case '4': return KEY_F12;
  419. }
  420. }
  421. break;
  422. }
  423. }
  424. timeout = 0;
  425. continue;
  426. }
  427. } else if (istate == UTF8_REJECT) {
  428. istate = 0;
  429. }
  430. }
  431. return KEY_TIMEOUT;
  432. }
  433. enum Key key_from_name(char * name) {
  434. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  435. if (!strcmp(KeyNames[i].name, name)) return KeyNames[i].keycode;
  436. }
  437. if (name[0] == '^' && name[1] && !name[2]) {
  438. return name[1] - '@';
  439. }
  440. if (!name[1]) return name[0];
  441. /* Try decoding */
  442. uint32_t c, state = 0;
  443. int candidate = -1;
  444. while (*name) {
  445. if (!decode(&state, &c, (unsigned char)*name)) {
  446. if (candidate == -1) candidate = c;
  447. else return -1; /* Reject `name` if it is multiple codepoints */
  448. } else if (state == UTF8_REJECT) {
  449. return -1;
  450. }
  451. }
  452. return candidate;
  453. }
  454. /**
  455. * Pointer to current active buffer
  456. */
  457. buffer_t * env = NULL;
  458. buffer_t * left_buffer = NULL;
  459. buffer_t * right_buffer = NULL;
  460. /**
  461. * A buffer for holding a number (line, repetition count)
  462. */
  463. #define NAV_BUFFER_MAX 10
  464. char nav_buf[NAV_BUFFER_MAX+1];
  465. int nav_buffer = 0;
  466. /**
  467. * Available buffers
  468. */
  469. int buffers_len = 0;
  470. int buffers_avail = 0;
  471. buffer_t ** buffers = NULL;
  472. /**
  473. * Create a new buffer
  474. */
  475. buffer_t * buffer_new(void) {
  476. if (buffers_len == buffers_avail) {
  477. /* If we are out of buffer space, expand the buffers vector */
  478. buffers_avail *= 2;
  479. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  480. }
  481. /* TODO: Clean up split support and support multiple splits... */
  482. if (left_buffer) {
  483. left_buffer->left = 0;
  484. left_buffer->width = global_config.term_width;
  485. right_buffer->left = 0;
  486. right_buffer->width = global_config.term_width;
  487. left_buffer = NULL;
  488. right_buffer = NULL;
  489. }
  490. /* Allocate a new buffer */
  491. buffers[buffers_len] = malloc(sizeof(buffer_t));
  492. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  493. buffers[buffers_len]->left = 0;
  494. buffers[buffers_len]->width = global_config.term_width;
  495. buffers[buffers_len]->highlighting_paren = -1;
  496. buffers[buffers_len]->numbers = global_config.numbers;
  497. buffers[buffers_len]->gutter = 1;
  498. buffers_len++;
  499. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  500. return buffers[buffers_len-1];
  501. }
  502. /**
  503. * Open the biminfo file.
  504. */
  505. FILE * open_biminfo(void) {
  506. if (!global_config.use_biminfo) return NULL;
  507. char * home = getenv("HOME");
  508. if (!home) {
  509. /* ... but since it's not, we need $HOME, so fail if it isn't set. */
  510. return NULL;
  511. }
  512. /* biminfo lives at ~/.biminfo */
  513. char biminfo_path[PATH_MAX+1] = {0};
  514. sprintf(biminfo_path,"%s/.biminfo",home);
  515. /* Try to open normally first... */
  516. FILE * biminfo = fopen(biminfo_path,"r+");
  517. if (!biminfo) {
  518. /* Otherwise, try to create it. */
  519. biminfo = fopen(biminfo_path,"w+");
  520. }
  521. return biminfo;
  522. }
  523. /**
  524. * Check if a file is open by examining the biminfo file
  525. */
  526. int file_is_open(char * file_name) {
  527. /* Get the absolute path of the file to normalize for lookup */
  528. char tmp_path[PATH_MAX+2];
  529. if (!realpath(file_name, tmp_path)) {
  530. return 0; /* Assume not */
  531. }
  532. strcat(tmp_path," ");
  533. FILE * biminfo = open_biminfo();
  534. if (!biminfo) return 0; /* Assume not */
  535. /* Scan */
  536. char line[PATH_MAX+64];
  537. while (!feof(biminfo)) {
  538. fpos_t start_of_line;
  539. fgetpos(biminfo, &start_of_line);
  540. fgets(line, PATH_MAX+63, biminfo);
  541. if (line[0] != '%') {
  542. continue;
  543. }
  544. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  545. /* File is currently open */
  546. int pid = -1;
  547. sscanf(line+1+strlen(tmp_path)+1,"%d",&pid);
  548. if (pid != -1 && pid != getpid()) {
  549. if (!kill(pid, 0)) {
  550. int key = 0;
  551. render_error("biminfo indicates another instance may already be editing this file");
  552. render_commandline_message("\n");
  553. render_commandline_message("file path = %s\n", tmp_path);
  554. render_commandline_message("pid = %d (still running)\n", pid);
  555. render_commandline_message("Open file anyway? (y/N)");
  556. while ((key = bim_getkey(DEFAULT_KEY_WAIT)) == KEY_TIMEOUT);
  557. if (key != 'y') {
  558. fclose(biminfo);
  559. return 1;
  560. }
  561. }
  562. }
  563. fclose(biminfo);
  564. return 0;
  565. }
  566. }
  567. fclose(biminfo);
  568. return 0;
  569. }
  570. /**
  571. * Fetch the cursor position from a biminfo file
  572. */
  573. int fetch_from_biminfo(buffer_t * buf) {
  574. /* Can't fetch if we don't have a filename */
  575. if (!buf->file_name) return 1;
  576. /* Get the absolute path of the file to normalize for lookup */
  577. char tmp_path[PATH_MAX+2];
  578. if (!realpath(buf->file_name, tmp_path)) {
  579. return 1;
  580. }
  581. strcat(tmp_path," ");
  582. FILE * biminfo = open_biminfo();
  583. if (!biminfo) return 1;
  584. /* Scan */
  585. char line[PATH_MAX+64];
  586. while (!feof(biminfo)) {
  587. fpos_t start_of_line;
  588. fgetpos(biminfo, &start_of_line);
  589. fgets(line, PATH_MAX+63, biminfo);
  590. if (line[0] != '>') {
  591. continue;
  592. }
  593. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  594. /* Read */
  595. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  596. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  597. if (buf->line_no > buf->line_count) buf->line_no = buf->line_count;
  598. if (buf->col_no > buf->lines[buf->line_no-1]->actual) buf->col_no = buf->lines[buf->line_no-1]->actual;
  599. try_to_center();
  600. fclose(biminfo);
  601. return 0;
  602. }
  603. }
  604. fclose(biminfo);
  605. return 0;
  606. }
  607. /**
  608. * Write a file containing the last cursor position of a buffer.
  609. */
  610. int update_biminfo(buffer_t * buf, int is_open) {
  611. if (!buf->file_name) return 1;
  612. /* Get the absolute path of the file to normalize for lookup */
  613. char tmp_path[PATH_MAX+1];
  614. if (!realpath(buf->file_name, tmp_path)) {
  615. return 1;
  616. }
  617. strcat(tmp_path," ");
  618. FILE * biminfo = open_biminfo();
  619. if (!biminfo) return 1;
  620. /* Scan */
  621. char line[PATH_MAX+64];
  622. while (!feof(biminfo)) {
  623. fpos_t start_of_line;
  624. fgetpos(biminfo, &start_of_line);
  625. fgets(line, PATH_MAX+63, biminfo);
  626. if (line[0] != '>' && line[0] != '%') {
  627. continue;
  628. }
  629. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  630. /* Update */
  631. fsetpos(biminfo, &start_of_line);
  632. fprintf(biminfo,"%c%s %20d %20d\n", is_open ? '%' : '>', tmp_path,
  633. is_open ? getpid() : buf->line_no, buf->col_no);
  634. goto _done;
  635. }
  636. }
  637. if (ftell(biminfo) == 0) {
  638. /* New biminfo */
  639. fprintf(biminfo, "# This is a biminfo file.\n");
  640. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  641. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  642. }
  643. /* If we reach this point, we didn't find a record for this file
  644. * and the write cursor should be at the end, so just add a new line */
  645. fprintf(biminfo,"%c%s %20d %20d\n", is_open ? '%' : '>', tmp_path,
  646. is_open ? getpid() : buf->line_no, buf->col_no);
  647. _done:
  648. fclose(biminfo);
  649. return 0;
  650. }
  651. void cancel_background_tasks(buffer_t * buf) {
  652. background_task_t * t = global_config.background_task;
  653. background_task_t * last = NULL;
  654. while (t) {
  655. if (t->env == buf) {
  656. if (last) {
  657. last->next = t->next;
  658. } else {
  659. global_config.background_task = t->next;
  660. }
  661. if (!t->next) {
  662. global_config.tail_task = last;
  663. }
  664. background_task_t * tmp = t->next;
  665. free(t);
  666. t = tmp;
  667. } else {
  668. last = t;
  669. t = t->next;
  670. }
  671. }
  672. }
  673. /**
  674. * Close a buffer
  675. */
  676. buffer_t * buffer_close(buffer_t * buf) {
  677. int i;
  678. /* Locate the buffer in the buffer list */
  679. for (i = 0; i < buffers_len; i++) {
  680. if (buf == buffers[i])
  681. break;
  682. }
  683. /* This buffer doesn't exist? */
  684. if (i == buffers_len) {
  685. return NULL;
  686. }
  687. /* Cancel any background tasks for this env */
  688. cancel_background_tasks(buf);
  689. update_biminfo(buf, 0);
  690. /* Clean up lines used by old buffer */
  691. for (int i = 0; i < buf->line_count; ++i) {
  692. free(buf->lines[i]);
  693. }
  694. free(buf->lines);
  695. if (buf->file_name) {
  696. free(buf->file_name);
  697. }
  698. history_t * h = buf->history;
  699. while (h->next) {
  700. h = h->next;
  701. }
  702. while (h) {
  703. history_t * x = h->previous;
  704. free(h);
  705. h = x;
  706. }
  707. /* Clean up the old buffer */
  708. free(buf);
  709. /* Remove the buffer from the vector, moving others up */
  710. if (i != buffers_len - 1) {
  711. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i - 1));
  712. }
  713. /* There is one less buffer */
  714. buffers_len--;
  715. if (buffers_len && global_config.tab_offset >= buffers_len) global_config.tab_offset--;
  716. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  717. if (!buffers_len) {
  718. /* There are no more buffers. */
  719. return NULL;
  720. }
  721. /* If this was the last buffer in the list, return the previous last buffer */
  722. if (i == buffers_len) {
  723. return buffers[buffers_len-1];
  724. }
  725. /* Otherwise return the buffer in the same location */
  726. return buffers[i];
  727. }
  728. /**
  729. * Convert syntax highlighting flag to color code
  730. */
  731. const char * flag_to_color(int _flag) {
  732. int flag = _flag & FLAG_MASK_COLORS;
  733. switch (flag) {
  734. case FLAG_KEYWORD:
  735. return COLOR_KEYWORD;
  736. case FLAG_STRING:
  737. return COLOR_STRING;
  738. case FLAG_COMMENT:
  739. return COLOR_COMMENT;
  740. case FLAG_TYPE:
  741. return COLOR_TYPE;
  742. case FLAG_NUMERAL:
  743. return COLOR_NUMERAL;
  744. case FLAG_PRAGMA:
  745. return COLOR_PRAGMA;
  746. case FLAG_DIFFPLUS:
  747. return COLOR_GREEN;
  748. case FLAG_DIFFMINUS:
  749. return COLOR_RED;
  750. case FLAG_SELECT:
  751. return COLOR_FG;
  752. case FLAG_BOLD:
  753. return COLOR_BOLD;
  754. case FLAG_LINK_COLOR:
  755. return COLOR_LINK;
  756. case FLAG_ESCAPE:
  757. return COLOR_ESCAPE;
  758. default:
  759. return COLOR_FG;
  760. }
  761. }
  762. /**
  763. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  764. * so it can be used for prefix checking for things that need further special handling.
  765. */
  766. static int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  767. if (keyword_qualifier(lastchar())) return 0;
  768. if (!keyword_qualifier(charat())) return 0;
  769. int i = state->i;
  770. int slen = 0;
  771. while (i < state->line->actual || *keyword == '\0') {
  772. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  773. for (int j = 0; j < slen; ++j) {
  774. paint(1, flag);
  775. }
  776. return 1;
  777. }
  778. if (*keyword != state->line->text[i].codepoint) return 0;
  779. i++;
  780. keyword++;
  781. slen++;
  782. }
  783. return 0;
  784. }
  785. /**
  786. * This is a basic character matcher for "keyword" characters.
  787. */
  788. static int simple_keyword_qualifier(int c) {
  789. return isalnum(c) || (c == '_');
  790. }
  791. /**
  792. * These words can appear in comments and should be highlighted.
  793. * Since there are a lot of comment highlighters, this is provided
  794. * as a common function that can be used by multiple highlighters.
  795. */
  796. static int common_comment_buzzwords(struct syntax_state * state) {
  797. if (match_and_paint(state, "TODO", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  798. else if (match_and_paint(state, "XXX", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  799. else if (match_and_paint(state, "FIXME", FLAG_ERROR, simple_keyword_qualifier)) { return 1; }
  800. return 0;
  801. }
  802. /**
  803. * Paint a comment until end of line; assumes this comment can not continue.
  804. * (Some languages have comments that can continue with a \ - don't use this!)
  805. * Assumes you've already painted your comment start characters.
  806. */
  807. static int paint_comment(struct syntax_state * state) {
  808. while (charat() != -1) {
  809. if (common_comment_buzzwords(state)) continue;
  810. else { paint(1, FLAG_COMMENT); }
  811. }
  812. return -1;
  813. }
  814. /**
  815. * Find and return a highlighter by name, or return NULL if none was found.
  816. */
  817. static struct syntax_definition * find_syntax_calculator(const char * name) {
  818. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  819. if (!strcmp(s->name, name)) {
  820. return s;
  821. }
  822. }
  823. return NULL;
  824. }
  825. int syntax_count = 0;
  826. int syntax_space = 0;
  827. struct syntax_definition * syntaxes = NULL;
  828. void add_syntax(struct syntax_definition def) {
  829. /* See if a name match already exists for this def. */
  830. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  831. if (!strcmp(def.name,s->name)) {
  832. *s = def;
  833. return;
  834. }
  835. }
  836. if (syntax_space == 0) {
  837. syntax_space = 4;
  838. syntaxes = calloc(sizeof(struct syntax_definition), syntax_space);
  839. } else if (syntax_count +1 == syntax_space) {
  840. syntax_space *= 2;
  841. syntaxes = realloc(syntaxes, sizeof(struct syntax_definition) * syntax_space);
  842. for (int i = syntax_count; i < syntax_space; ++i) syntaxes[i].name = NULL;
  843. }
  844. syntaxes[syntax_count] = def;
  845. syntax_count++;
  846. }
  847. void redraw_all(void);
  848. /**
  849. * Calculate syntax highlighting for the given line, and lines after
  850. * if their initial syntax state has changed by this recalculation.
  851. *
  852. * If `line_no` is -1, this line is taken to be a special line and not
  853. * part of a buffer; search highlighting will not be processed and syntax
  854. * highlighting will halt after the line is finished.
  855. *
  856. * If `env->slowop` is currently enabled, recalculation is skipped.
  857. */
  858. void recalculate_syntax(line_t * line, int line_no) {
  859. if (env->slowop) return;
  860. /* Clear syntax for this line first */
  861. int is_original = 1;
  862. while (1) {
  863. for (int i = 0; i < line->actual; ++i) {
  864. line->text[i].flags = line->text[i].flags & (3 << 5);
  865. }
  866. if (!env->syntax) {
  867. if (line_no != -1) rehighlight_search(line);
  868. return;
  869. }
  870. /* Start from the line's stored in initial state */
  871. struct SyntaxState * s = (void*)krk_newInstance(env->syntax->krkClass);
  872. s->state.env = env;
  873. s->state.line = line;
  874. s->state.line_no = line_no;
  875. s->state.state = line->istate;
  876. s->state.i = 0;
  877. while (1) {
  878. struct termios old, new;
  879. tcgetattr(global_config.tty_in, &old);
  880. new = old; new.c_lflag |= ISIG;
  881. tcsetattr(global_config.tty_in, TCSANOW, &new);
  882. ptrdiff_t before = krk_currentThread.stackTop - krk_currentThread.stack;
  883. krk_push(OBJECT_VAL(env->syntax->krkFunc));
  884. krk_push(OBJECT_VAL(s));
  885. KrkValue result = krk_callStack(1);
  886. tcsetattr(global_config.tty_in, TCSANOW, &old);
  887. krk_currentThread.stackTop = krk_currentThread.stack + before;
  888. if (IS_NONE(result) && (krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION)) {
  889. render_error("Exception occurred in plugin: %s", AS_INSTANCE(krk_currentThread.currentException)->_class->name->chars);
  890. render_commandline_message("\n");
  891. krk_dumpTraceback();
  892. goto _syntaxError;
  893. } else if (!IS_NONE(result) && !IS_INTEGER(result)) {
  894. render_error("Instead of an integer, got %s", krk_typeName(result));
  895. render_commandline_message("\n");
  896. goto _syntaxError;
  897. }
  898. s->state.state = IS_NONE(result) ? -1 : AS_INTEGER(result);
  899. if (s->state.state != 0) {
  900. if (line_no == -1) return;
  901. rehighlight_search(line);
  902. if (!is_original) {
  903. redraw_line(line_no);
  904. }
  905. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != s->state.state) {
  906. line_no++;
  907. line = env->lines[line_no];
  908. line->istate = s->state.state;
  909. if (env->loading) return;
  910. is_original = 0;
  911. goto _next;
  912. }
  913. return;
  914. }
  915. }
  916. _next:
  917. (void)0;
  918. }
  919. _syntaxError:
  920. krk_resetStack();
  921. fprintf(stderr,"This syntax highlighter will be disabled in this environment.");
  922. env->syntax = NULL;
  923. cancel_background_tasks(env);
  924. pause_for_key();
  925. redraw_all();
  926. }
  927. /**
  928. * Recalculate tab widths.
  929. */
  930. void recalculate_tabs(line_t * line) {
  931. if (env->loading) return;
  932. int j = 0;
  933. for (int i = 0; i < line->actual; ++i) {
  934. if (line->text[i].codepoint == '\t') {
  935. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  936. }
  937. j += line->text[i].display_width;
  938. }
  939. }
  940. /**
  941. * The next section contains the basic editing primitives. All other
  942. * actions are built out of these primitives, and they are the basic
  943. * instructions that get stored in history to be undone (or redone).
  944. *
  945. * Primitives may recalculate syntax or redraw lines, if needed, but only
  946. * when conditions for redrawing are met (such as not being in `slowop`,
  947. * or loading the file; also replaying history, or when loading files).
  948. *
  949. * At the moment, primitives and most other functions do not take the current
  950. * buffer (environment) as an argument and instead rely on a global variable;
  951. * this should definitely be fixed at some point...
  952. */
  953. /**
  954. * When a new action that produces history happens and there is forward
  955. * history that can be redone, we need to erase it as our tree has branched.
  956. * If we wanted, we could actually story things in a tree structure so that
  957. * the new branch and the old branch can both stick around, and that should
  958. * probably be explored in the future...
  959. */
  960. void history_free(history_t * root) {
  961. if (!root->next) return;
  962. /* Find the last entry so we can free backwards */
  963. history_t * n = root->next;
  964. while (n->next) {
  965. n = n->next;
  966. }
  967. /* Free everything after the root, including stored content. */
  968. while (n != root) {
  969. history_t * p = n->previous;
  970. switch (n->type) {
  971. case HISTORY_REPLACE_LINE:
  972. free(n->contents.remove_replace_line.contents);
  973. /* fall-through */
  974. case HISTORY_REMOVE_LINE:
  975. free(n->contents.remove_replace_line.old_contents);
  976. break;
  977. default:
  978. /* Nothing extra to free */
  979. break;
  980. }
  981. free(n);
  982. n = p;
  983. }
  984. root->next = NULL;
  985. }
  986. /**
  987. * This macro is called by primitives to insert history elements for each
  988. * primitive action when performing in edit modes.
  989. */
  990. #define HIST_APPEND(e) do { \
  991. e->col = env->col_no; \
  992. e->line = env->line_no; \
  993. if (env->history) { \
  994. e->previous = env->history; \
  995. history_free(env->history); \
  996. env->history->next = e; \
  997. e->next = NULL; \
  998. } \
  999. env->history = e; \
  1000. } while (0)
  1001. /**
  1002. * Mark a point where a complete set of actions has ended.
  1003. * Individual history entries include things like "insert one character"
  1004. * but a user action that should be undone is "insert several characters";
  1005. * breaks should be inserted after a series of primitives when there is
  1006. * a clear "end", such as when switching out of insert mode after typing.
  1007. */
  1008. void set_history_break(void) {
  1009. if (!global_config.history_enabled) return;
  1010. /* Do not produce duplicate breaks, or add breaks if we are at a sentinel. */
  1011. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1012. history_t * e = malloc(sizeof(history_t));
  1013. e->type = HISTORY_BREAK;
  1014. HIST_APPEND(e);
  1015. }
  1016. }
  1017. /**
  1018. * (Primitive) Insert a character into an existing line.
  1019. *
  1020. * This is the most basic primitive action: Take a line, and insert a codepoint
  1021. * into it at a given offset. If `lineno` is not -1, the line is assumed to
  1022. * be part of the active buffer. If inserting a character means the line needs
  1023. * to grow, then it will be reallocated, so the return value of the new line
  1024. * must ALWAYS be used. This primitive will NOT automatically update the
  1025. * buffer with the new pointer, so if you are calling insert on a buffer you
  1026. * MUST update env->lines[lineno-1] yourself.
  1027. */
  1028. __attribute__((warn_unused_result)) line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1029. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1030. history_t * e = malloc(sizeof(history_t));
  1031. e->type = HISTORY_INSERT;
  1032. e->contents.insert_delete_replace.lineno = lineno;
  1033. e->contents.insert_delete_replace.offset = offset;
  1034. e->contents.insert_delete_replace.codepoint = c.codepoint;
  1035. HIST_APPEND(e);
  1036. }
  1037. /* If there is not enough space... */
  1038. if (line->actual == line->available) {
  1039. /* Expand the line buffer */
  1040. if (line->available == 0) {
  1041. line->available = 8;
  1042. } else {
  1043. line->available *= 2;
  1044. }
  1045. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1046. }
  1047. /* If this was not the last character, then shift remaining characters forward. */
  1048. if (offset < line->actual) {
  1049. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1050. }
  1051. /* Insert the new character */
  1052. line->text[offset] = c;
  1053. /* There is one new character in the line */
  1054. line->actual += 1;
  1055. if (!env->loading) {
  1056. line->rev_status = 2; /* Modified */
  1057. recalculate_tabs(line);
  1058. recalculate_syntax(line, lineno);
  1059. }
  1060. return line;
  1061. }
  1062. /**
  1063. * (Primitive) Delete a character from a line.
  1064. *
  1065. * Remove the character at the given offset. We never shrink lines, so this
  1066. * does not have a return value, and delete should never be called during
  1067. * a loading operation (though it may be called during a history replay).
  1068. */
  1069. void line_delete(line_t * line, int offset, int lineno) {
  1070. /* Can't delete character before start of line. */
  1071. if (offset == 0) return;
  1072. /* Can't delete past end of line either */
  1073. if (offset > line->actual) return;
  1074. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1075. history_t * e = malloc(sizeof(history_t));
  1076. e->type = HISTORY_DELETE;
  1077. e->contents.insert_delete_replace.lineno = lineno;
  1078. e->contents.insert_delete_replace.offset = offset;
  1079. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1080. HIST_APPEND(e);
  1081. }
  1082. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1083. if (offset < line->actual) {
  1084. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1085. }
  1086. /* The line is one character shorter */
  1087. line->actual -= 1;
  1088. line->rev_status = 2;
  1089. recalculate_tabs(line);
  1090. recalculate_syntax(line, lineno);
  1091. }
  1092. /**
  1093. * (Primitive) Replace a character in a line.
  1094. *
  1095. * Replaces the codepoint at the given offset with a new character. Since this
  1096. * does not involve any size changes, it does not have a return value.
  1097. * Since a replacement character may be a tab, we do still need to recalculate
  1098. * character widths for tabs as they may change.
  1099. */
  1100. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1101. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1102. history_t * e = malloc(sizeof(history_t));
  1103. e->type = HISTORY_REPLACE;
  1104. e->contents.insert_delete_replace.lineno = lineno;
  1105. e->contents.insert_delete_replace.offset = offset;
  1106. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  1107. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1108. HIST_APPEND(e);
  1109. }
  1110. line->text[offset] = _c;
  1111. if (!env->loading) {
  1112. line->rev_status = 2; /* Modified */
  1113. recalculate_tabs(line);
  1114. recalculate_syntax(line, lineno);
  1115. }
  1116. }
  1117. /**
  1118. * (Primitive) Remove a line from the active buffer
  1119. *
  1120. * This primitive is only valid for a buffer. Delete a line, or if this is the
  1121. * only line in the buffer, clear it but keep the line around with no
  1122. * characters. We use the `line_delete` primitive to clear that line,
  1123. * otherwise we are our own primitive and produce history entries.
  1124. *
  1125. * While we do not shrink the `lines` array, it is returned here anyway.
  1126. */
  1127. line_t ** remove_line(line_t ** lines, int offset) {
  1128. /* If there is only one line, clear it instead of removing it. */
  1129. if (env->line_count == 1) {
  1130. while (lines[offset]->actual > 0) {
  1131. line_delete(lines[offset], lines[offset]->actual, offset);
  1132. }
  1133. return lines;
  1134. }
  1135. /* When a line is removed, we need to keep its contents so we
  1136. * can un-remove it on redo... */
  1137. if (!env->loading && global_config.history_enabled) {
  1138. history_t * e = malloc(sizeof(history_t));
  1139. e->type = HISTORY_REMOVE_LINE;
  1140. e->contents.remove_replace_line.lineno = offset;
  1141. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1142. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1143. HIST_APPEND(e);
  1144. }
  1145. /* Otherwise, free the data used by the line */
  1146. free(lines[offset]);
  1147. /* Move other lines up */
  1148. if (offset < env->line_count-1) {
  1149. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1150. lines[env->line_count-1] = NULL;
  1151. }
  1152. /* There is one less line */
  1153. env->line_count -= 1;
  1154. return lines;
  1155. }
  1156. /**
  1157. * (Primitive) Add a new line to the active buffer.
  1158. *
  1159. * Inserts a new line into a buffer at the given line offset.
  1160. * Since this grows the buffer, it will return the new line array
  1161. * after reallocation if needed.
  1162. */
  1163. line_t ** add_line(line_t ** lines, int offset) {
  1164. /* Invalid offset? */
  1165. if (offset > env->line_count) return lines;
  1166. if (!env->loading && global_config.history_enabled) {
  1167. history_t * e = malloc(sizeof(history_t));
  1168. e->type = HISTORY_ADD_LINE;
  1169. e->contents.add_merge_split_lines.lineno = offset;
  1170. HIST_APPEND(e);
  1171. }
  1172. /* Not enough space */
  1173. if (env->line_count == env->line_avail) {
  1174. /* Allocate more space */
  1175. env->line_avail *= 2;
  1176. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1177. }
  1178. /* If this isn't the last line, move other lines down */
  1179. if (offset < env->line_count) {
  1180. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1181. }
  1182. /* Allocate the new line */
  1183. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1184. lines[offset]->available = 32;
  1185. /* There is one new line */
  1186. env->line_count += 1;
  1187. env->lines = lines;
  1188. if (!env->loading) {
  1189. lines[offset]->rev_status = 2; /* Modified */
  1190. }
  1191. if (offset > 0 && !env->loading) {
  1192. recalculate_syntax(lines[offset-1],offset-1);
  1193. }
  1194. return lines;
  1195. }
  1196. /**
  1197. * (Primitive) Replace a line with data from another line.
  1198. *
  1199. * This is only called when pasting yanks after calling `add_line`,
  1200. * but it allows us to have simpler history for that action.
  1201. */
  1202. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1203. if (!env->loading && global_config.history_enabled) {
  1204. history_t * e = malloc(sizeof(history_t));
  1205. e->type = HISTORY_REPLACE_LINE;
  1206. e->contents.remove_replace_line.lineno = offset;
  1207. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1208. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1209. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1210. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1211. HIST_APPEND(e);
  1212. }
  1213. if (lines[offset]->available < replacement->actual) {
  1214. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1215. lines[offset]->available = replacement->available;
  1216. }
  1217. lines[offset]->actual = replacement->actual;
  1218. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1219. if (!env->loading) {
  1220. lines[offset]->rev_status = 2;
  1221. recalculate_syntax(lines[offset],offset);
  1222. }
  1223. }
  1224. /**
  1225. * (Primitive) Merge two consecutive lines.
  1226. *
  1227. * Take two lines in a buffer and turn them into one line.
  1228. * `lineb` is the offset of the second line... or the
  1229. * line number of the first line, depending on which indexing
  1230. * system you prefer to think about. This won't grow `lines`,
  1231. * but it will likely modify it and can reallocate individual
  1232. * lines as well.
  1233. */
  1234. line_t ** merge_lines(line_t ** lines, int lineb) {
  1235. /* linea is the line immediately before lineb */
  1236. int linea = lineb - 1;
  1237. if (!env->loading && global_config.history_enabled) {
  1238. history_t * e = malloc(sizeof(history_t));
  1239. e->type = HISTORY_MERGE_LINES;
  1240. e->contents.add_merge_split_lines.lineno = lineb;
  1241. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  1242. HIST_APPEND(e);
  1243. }
  1244. /* If there isn't enough space in linea hold both... */
  1245. if (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1246. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1247. /* ... allocate more space until it fits */
  1248. if (lines[linea]->available == 0) {
  1249. lines[linea]->available = 8;
  1250. } else {
  1251. lines[linea]->available *= 2;
  1252. }
  1253. }
  1254. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1255. }
  1256. /* Copy the second line into the first line */
  1257. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1258. /* The first line is now longer */
  1259. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1260. if (!env->loading) {
  1261. lines[linea]->rev_status = 2;
  1262. recalculate_tabs(lines[linea]);
  1263. recalculate_syntax(lines[linea], linea);
  1264. }
  1265. /* Remove the second line */
  1266. free(lines[lineb]);
  1267. /* Move other lines up */
  1268. if (lineb < env->line_count) {
  1269. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1270. lines[env->line_count-1] = NULL;
  1271. }
  1272. /* There is one less line */
  1273. env->line_count -= 1;
  1274. return lines;
  1275. }
  1276. /**
  1277. * (Primitive) Split a line into two lines at the given column.
  1278. *
  1279. * Takes one line and makes it two lines. There are some optimizations
  1280. * if you are trying to "split" at the first or last column, which
  1281. * are both just treated as add_line.
  1282. */
  1283. line_t ** split_line(line_t ** lines, int line, int split) {
  1284. /* If we're trying to split from the start, just add a new blank line before */
  1285. if (split == 0) {
  1286. return add_line(lines, line);
  1287. }
  1288. if (!env->loading && global_config.history_enabled) {
  1289. history_t * e = malloc(sizeof(history_t));
  1290. e->type = HISTORY_SPLIT_LINE;
  1291. e->contents.add_merge_split_lines.lineno = line;
  1292. e->contents.add_merge_split_lines.split = split;
  1293. HIST_APPEND(e);
  1294. }
  1295. if (!env->loading) {
  1296. unhighlight_matching_paren();
  1297. }
  1298. /* Allocate more space as needed */
  1299. if (env->line_count == env->line_avail) {
  1300. env->line_avail *= 2;
  1301. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1302. }
  1303. /* Shift later lines down */
  1304. if (line < env->line_count) {
  1305. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1306. }
  1307. int remaining = lines[line]->actual - split;
  1308. /* This is some wacky math to get a good power-of-two */
  1309. int v = remaining;
  1310. v--;
  1311. v |= v >> 1;
  1312. v |= v >> 2;
  1313. v |= v >> 4;
  1314. v |= v >> 8;
  1315. v |= v >> 16;
  1316. v++;
  1317. /* Allocate space for the new line */
  1318. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  1319. lines[line+1]->available = v;
  1320. lines[line+1]->actual = remaining;
  1321. /* Move the data from the old line into the new line */
  1322. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1323. lines[line]->actual = split;
  1324. if (!env->loading) {
  1325. lines[line]->rev_status = 2;
  1326. lines[line+1]->rev_status = 2;
  1327. recalculate_tabs(lines[line]);
  1328. recalculate_tabs(lines[line+1]);
  1329. recalculate_syntax(lines[line], line);
  1330. recalculate_syntax(lines[line+1], line+1);
  1331. }
  1332. /* There is one new line */
  1333. env->line_count += 1;
  1334. /* We may have reallocated lines */
  1335. return lines;
  1336. }
  1337. /**
  1338. * Primitives end here. Everything after this point that wants to
  1339. * perform modifications must be built on these primitives and
  1340. * should never directly modify env->lines or the contents thereof,
  1341. * outside of syntax highlighting flag changes.
  1342. */
  1343. /**
  1344. * The following section is where we implement "smart" automatic
  1345. * indentation. A lot of this is hacked-together nonsense and "smart"
  1346. * is a bit of an overstatement.
  1347. */
  1348. /**
  1349. * Understand spaces and comments and check if the previous line
  1350. * ended with a brace or a colon.
  1351. */
  1352. int line_ends_with_brace(line_t * line) {
  1353. int i = line->actual-1;
  1354. while (i >= 0) {
  1355. if ((line->text[i].flags & 0x1F) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  1356. i--;
  1357. } else {
  1358. break;
  1359. }
  1360. }
  1361. if (i < 0) return 0;
  1362. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':') ? i+1 : 0;
  1363. }
  1364. /**
  1365. * Determine if a given line is a comment by checking its initial
  1366. * syntax highlighting state value. This is used by automatic indentation
  1367. * to continue block comments in languages like C.
  1368. *
  1369. * TODO: Why isn't this a syntax-> method?
  1370. */
  1371. int line_is_comment(line_t * line) {
  1372. if (!env->syntax) return 0;
  1373. if (!strcmp(env->syntax->name,"c")) {
  1374. if (line->istate == 1) return 1;
  1375. } else if (!strcmp(env->syntax->name,"java")) {
  1376. if (line->istate == 1) return 1;
  1377. } else if (!strcmp(env->syntax->name,"kotlin")) {
  1378. if (line->istate == 1) return 1;
  1379. } else if (!strcmp(env->syntax->name,"rust")) {
  1380. if (line->istate > 0) return 1;
  1381. }
  1382. return 0;
  1383. }
  1384. /**
  1385. * Figure out where the indentation for a brace belongs by finding
  1386. * where the start of the line is after whitespace. This is called
  1387. * by default when we insert } and tries to align it with the indentation
  1388. * of the matching opening {.
  1389. */
  1390. int find_brace_line_start(int line, int col) {
  1391. int ncol = col - 1;
  1392. while (ncol > 0) {
  1393. if (env->lines[line-1]->text[ncol-1].codepoint == ')') {
  1394. int t_line_no = env->line_no;
  1395. int t_col_no = env->col_no;
  1396. env->line_no = line;
  1397. env->col_no = ncol;
  1398. int paren_match_line = -1, paren_match_col = -1;
  1399. find_matching_paren(&paren_match_line, &paren_match_col, 1);
  1400. if (paren_match_line != -1) {
  1401. line = paren_match_line;
  1402. }
  1403. env->line_no = t_line_no;
  1404. env->col_no = t_col_no;
  1405. break;
  1406. } else if (env->lines[line-1]->text[ncol-1].codepoint == ' ') {
  1407. ncol--;
  1408. } else {
  1409. break;
  1410. }
  1411. }
  1412. return line;
  1413. }
  1414. /**
  1415. * Add indentation from the previous (temporally) line.
  1416. *
  1417. * By "temporally", we mean not necessarily the line above, but
  1418. * potentially the line below if we are inserting a line above
  1419. * the cursor.
  1420. */
  1421. void add_indent(int new_line, int old_line, int ignore_brace) {
  1422. if (env->indent) {
  1423. int changed = 0;
  1424. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  1425. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1426. if (env->lines[old_line]->text[i].codepoint == '/') {
  1427. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  1428. /* Insert ' * ' */
  1429. char_t space = {1,FLAG_COMMENT,' '};
  1430. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1431. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1432. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1433. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1434. env->col_no += 3;
  1435. }
  1436. break;
  1437. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  1438. /* Insert ' * ' */
  1439. char_t space = {1,FLAG_COMMENT,' '};
  1440. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1441. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1442. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1443. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1444. env->col_no += 3;
  1445. break;
  1446. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1447. env->lines[old_line]->text[i].codepoint == '\t' ||
  1448. env->lines[old_line]->text[i].codepoint == '*') {
  1449. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1450. env->col_no++;
  1451. changed = 1;
  1452. } else {
  1453. break;
  1454. }
  1455. }
  1456. } else {
  1457. int line_to_copy_from = old_line;
  1458. int col;
  1459. if (old_line < new_line &&
  1460. !ignore_brace &&
  1461. (col = line_ends_with_brace(env->lines[old_line])) &&
  1462. env->lines[old_line]->text[col-1].codepoint == '{') {
  1463. line_to_copy_from = find_brace_line_start(old_line+1, col)-1;
  1464. }
  1465. for (int i = 0; i < env->lines[line_to_copy_from]->actual; ++i) {
  1466. if (line_to_copy_from < new_line && i == env->lines[line_to_copy_from]->actual - 3 &&
  1467. env->lines[line_to_copy_from]->text[i].codepoint == ' ' &&
  1468. env->lines[line_to_copy_from]->text[i+1].codepoint == '*' &&
  1469. env->lines[line_to_copy_from]->text[i+2].codepoint == '/') {
  1470. break;
  1471. } else if (env->lines[line_to_copy_from]->text[i].codepoint == ' ' ||
  1472. env->lines[line_to_copy_from]->text[i].codepoint == '\t') {
  1473. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[line_to_copy_from]->text[i],i,new_line);
  1474. env->col_no++;
  1475. changed = 1;
  1476. } else {
  1477. break;
  1478. }
  1479. }
  1480. }
  1481. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  1482. if (env->tabs) {
  1483. char_t c = {0};
  1484. c.codepoint = '\t';
  1485. c.display_width = env->tabstop;
  1486. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1487. env->col_no++;
  1488. changed = 1;
  1489. } else {
  1490. for (int j = 0; j < env->tabstop; ++j) {
  1491. char_t c = {0};
  1492. c.codepoint = ' ';
  1493. c.display_width = 1;
  1494. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1495. env->col_no++;
  1496. }
  1497. changed = 1;
  1498. }
  1499. }
  1500. int was_whitespace = 1;
  1501. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1502. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  1503. env->lines[old_line]->text[i].codepoint != '\t') {
  1504. was_whitespace = 0;
  1505. break;
  1506. }
  1507. }
  1508. if (was_whitespace) {
  1509. while (env->lines[old_line]->actual) {
  1510. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  1511. }
  1512. }
  1513. if (changed) {
  1514. recalculate_syntax(env->lines[new_line],new_line);
  1515. }
  1516. }
  1517. }
  1518. /**
  1519. * Initialize a buffer with default values.
  1520. *
  1521. * Should be called after creating a buffer.
  1522. */
  1523. void setup_buffer(buffer_t * env) {
  1524. /* If this buffer was already initialized, clear out its line data */
  1525. if (env->lines) {
  1526. for (int i = 0; i < env->line_count; ++i) {
  1527. free(env->lines[i]);
  1528. }
  1529. free(env->lines);
  1530. }
  1531. /* Default state parameters */
  1532. env->line_no = 1; /* Default cursor position */
  1533. env->col_no = 1;
  1534. env->line_count = 1; /* Buffers always have at least one line */
  1535. env->modified = 0;
  1536. env->readonly = 0;
  1537. env->offset = 0;
  1538. env->line_avail = 8; /* Default line buffer capacity */
  1539. env->tabs = 1; /* Tabs by default */
  1540. env->tabstop = 4; /* Tab stop width */
  1541. env->indent = 1; /* Auto-indent by default */
  1542. env->history = malloc(sizeof(struct history));
  1543. memset(env->history, 0, sizeof(struct history));
  1544. env->last_save_history = env->history;
  1545. /* Allocate line buffer */
  1546. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1547. /* Initialize the first line */
  1548. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1549. env->lines[0]->available = 32;
  1550. }
  1551. /**
  1552. * Toggle buffered / unbuffered modes
  1553. */
  1554. struct termios old;
  1555. void get_initial_termios(void) {
  1556. tcgetattr(STDOUT_FILENO, &old);
  1557. }
  1558. void set_unbuffered(void) {
  1559. struct termios new = old;
  1560. new.c_iflag &= (~ICRNL) & (~IXON);
  1561. new.c_lflag &= (~ICANON) & (~ECHO) & (~ISIG);
  1562. #ifdef VLNEXT
  1563. new.c_cc[VLNEXT] = 0;
  1564. #endif
  1565. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1566. }
  1567. void set_buffered(void) {
  1568. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1569. }
  1570. /**
  1571. * Convert codepoint to utf-8 string
  1572. */
  1573. int to_eight(uint32_t codepoint, char * out) {
  1574. memset(out, 0x00, 7);
  1575. if (codepoint < 0x0080) {
  1576. out[0] = (char)codepoint;
  1577. } else if (codepoint < 0x0800) {
  1578. out[0] = 0xC0 | (codepoint >> 6);
  1579. out[1] = 0x80 | (codepoint & 0x3F);
  1580. } else if (codepoint < 0x10000) {
  1581. out[0] = 0xE0 | (codepoint >> 12);
  1582. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1583. out[2] = 0x80 | (codepoint & 0x3F);
  1584. } else if (codepoint < 0x200000) {
  1585. out[0] = 0xF0 | (codepoint >> 18);
  1586. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1587. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1588. out[3] = 0x80 | ((codepoint) & 0x3F);
  1589. } else if (codepoint < 0x4000000) {
  1590. out[0] = 0xF8 | (codepoint >> 24);
  1591. out[1] = 0x80 | (codepoint >> 18);
  1592. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1593. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1594. out[4] = 0x80 | ((codepoint) & 0x3F);
  1595. } else {
  1596. out[0] = 0xF8 | (codepoint >> 30);
  1597. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1598. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1599. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1600. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1601. out[5] = 0x80 | ((codepoint) & 0x3F);
  1602. }
  1603. return strlen(out);
  1604. }
  1605. /**
  1606. * Get the presentation width of a codepoint
  1607. */
  1608. int codepoint_width(wchar_t codepoint) {
  1609. if (codepoint == '\t') {
  1610. return 1; /* Recalculate later */
  1611. }
  1612. if (codepoint < 32) {
  1613. /* We render these as ^@ */
  1614. return 2;
  1615. }
  1616. if (codepoint == 0x7F) {
  1617. /* Renders as ^? */
  1618. return 2;
  1619. }
  1620. if (codepoint > 0x7f && codepoint < 0xa0) {
  1621. /* Upper control bytes <xx> */
  1622. return 4;
  1623. }
  1624. if (codepoint == 0xa0) {
  1625. /* Non-breaking space _ */
  1626. return 1;
  1627. }
  1628. /* Skip wcwidth for anything under 256 */
  1629. if (codepoint > 127) {
  1630. if (global_config.can_unicode) {
  1631. /* Higher codepoints may be wider (eg. Japanese) */
  1632. int out = wcwidth(codepoint);
  1633. if (out >= 1) return out;
  1634. }
  1635. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1636. return (codepoint < 0x10000) ? 8 : 10;
  1637. }
  1638. return 1;
  1639. }
  1640. /**
  1641. * The following section contains methods for crafting terminal escapes
  1642. * for rendering the display. We do not use curses or any similar
  1643. * library, so we have to generate these sequences ourself based on
  1644. * some assumptions about the target terminal.
  1645. */
  1646. /**
  1647. * Move the terminal cursor
  1648. */
  1649. void place_cursor(int x, int y) {
  1650. printf("\033[%d;%dH", y, x);
  1651. }
  1652. /**
  1653. * Given two color codes from a theme, convert them to an escape
  1654. * sequence to set the foreground and background color. This allows
  1655. * us to support basic 16, xterm 256, and true color in themes.
  1656. */
  1657. char * color_string(const char * fg, const char * bg) {
  1658. static char output[100];
  1659. char * t = output;
  1660. t += sprintf(t,"\033[22;23;");
  1661. if (*bg == '@') {
  1662. int _bg = atoi(bg+1);
  1663. if (_bg < 10) {
  1664. t += sprintf(t, "4%d;", _bg);
  1665. } else {
  1666. t += sprintf(t, "10%d;", _bg-10);
  1667. }
  1668. } else {
  1669. t += sprintf(t, "48;%s;", bg);
  1670. }
  1671. if (*fg == '@') {
  1672. int _fg = atoi(fg+1);
  1673. if (_fg < 10) {
  1674. t += sprintf(t, "3%dm", _fg);
  1675. } else {
  1676. t += sprintf(t, "9%dm", _fg-10);
  1677. }
  1678. } else {
  1679. t += sprintf(t, "38;%sm", fg);
  1680. }
  1681. return output;
  1682. }
  1683. /**
  1684. * Set text colors
  1685. *
  1686. * Normally, text colors are just strings, but if they
  1687. * start with @ they will be parsed as integers
  1688. * representing one of the 16 standard colors, suitable
  1689. * for terminals without support for the 256- or 24-bit
  1690. * color modes.
  1691. */
  1692. void set_colors(const char * fg, const char * bg) {
  1693. printf("%s", color_string(fg, bg));
  1694. }
  1695. /**
  1696. * Set just the foreground color
  1697. *
  1698. * (See set_colors above)
  1699. */
  1700. void set_fg_color(const char * fg) {
  1701. printf("\033[22;23;");
  1702. if (*fg == '@') {
  1703. int _fg = atoi(fg+1);
  1704. if (_fg < 10) {
  1705. printf("3%dm", _fg);
  1706. } else {
  1707. printf("9%dm", _fg-10);
  1708. }
  1709. } else {
  1710. printf("38;%sm", fg);
  1711. }
  1712. }
  1713. /**
  1714. * Clear the rest of this line
  1715. */
  1716. void clear_to_end(void) {
  1717. if (global_config.can_bce) {
  1718. printf("\033[K");
  1719. }
  1720. }
  1721. /**
  1722. * For terminals without bce, prepaint the whole line, so we don't have to track
  1723. * where the cursor is for everything. Inefficient, but effective.
  1724. */
  1725. void paint_line(const char * bg) {
  1726. if (!global_config.can_bce) {
  1727. set_colors(COLOR_FG, bg);
  1728. for (int i = 0; i < global_config.term_width; ++i) {
  1729. printf(" ");
  1730. }
  1731. printf("\r");
  1732. }
  1733. }
  1734. /**
  1735. * Enable bold text display
  1736. */
  1737. void set_bold(void) {
  1738. printf("\033[1m");
  1739. }
  1740. /**
  1741. * Disable bold
  1742. */
  1743. void unset_bold(void) {
  1744. printf("\033[22m");
  1745. }
  1746. /**
  1747. * Enable underlined text display
  1748. */
  1749. void set_underline(void) {
  1750. printf("\033[4m");
  1751. }
  1752. /**
  1753. * Disable underlined text display
  1754. */
  1755. void unset_underline(void) {
  1756. printf("\033[24m");
  1757. }
  1758. /**
  1759. * Reset text display attributes
  1760. */
  1761. void reset(void) {
  1762. printf("\033[0m");
  1763. }
  1764. /**
  1765. * Clear the entire screen
  1766. */
  1767. void clear_screen(void) {
  1768. printf("\033[H\033[2J");
  1769. }
  1770. /**
  1771. * Hide the cursor
  1772. */
  1773. void hide_cursor(void) {
  1774. if (global_config.can_hideshow) {
  1775. printf("\033[?25l");
  1776. }
  1777. }
  1778. /**
  1779. * Show the cursor
  1780. */
  1781. void show_cursor(void) {
  1782. if (global_config.can_hideshow) {
  1783. printf("\033[?25h");
  1784. }
  1785. }
  1786. /**
  1787. * Store the cursor position
  1788. */
  1789. void store_cursor(void) {
  1790. printf("\0337");
  1791. }
  1792. /**
  1793. * Restore the cursor position.
  1794. */
  1795. void restore_cursor(void) {
  1796. printf("\0338");
  1797. }
  1798. /**
  1799. * Request mouse events
  1800. */
  1801. void mouse_enable(void) {
  1802. if (global_config.can_mouse) {
  1803. printf("\033[?1000h");
  1804. if (global_config.can_sgrmouse) {
  1805. printf("\033[?1006h");
  1806. }
  1807. }
  1808. }
  1809. /**
  1810. * Stop mouse events
  1811. */
  1812. void mouse_disable(void) {
  1813. if (global_config.can_mouse) {
  1814. if (global_config.can_sgrmouse) {
  1815. printf("\033[?1006l");
  1816. }
  1817. printf("\033[?1000l");
  1818. }
  1819. }
  1820. /**
  1821. * Shift the screen up one line
  1822. */
  1823. void shift_up(int amount) {
  1824. printf("\033[%dS", amount);
  1825. }
  1826. /**
  1827. * Shift the screen down one line.
  1828. */
  1829. void shift_down(int amount) {
  1830. printf("\033[%dT", amount);
  1831. }
  1832. void insert_lines_at(int line, int count) {
  1833. place_cursor(1, line);
  1834. printf("\033[%dL", count);
  1835. }
  1836. void delete_lines_at(int line, int count) {
  1837. place_cursor(1, line);
  1838. printf("\033[%dM", count);
  1839. }
  1840. /**
  1841. * Switch to the alternate terminal screen.
  1842. */
  1843. void set_alternate_screen(void) {
  1844. if (global_config.can_altscreen) {
  1845. printf("\033[?1049h");
  1846. }
  1847. }
  1848. /**
  1849. * Restore the standard terminal screen.
  1850. */
  1851. void unset_alternate_screen(void) {
  1852. if (global_config.can_altscreen) {
  1853. printf("\033[?1049l");
  1854. }
  1855. }
  1856. /**
  1857. * Enable bracketed paste mode.
  1858. */
  1859. void set_bracketed_paste(void) {
  1860. if (global_config.can_bracketedpaste) {
  1861. printf("\033[?2004h");
  1862. }
  1863. }
  1864. /**
  1865. * Disable bracketed paste mode.
  1866. */
  1867. void unset_bracketed_paste(void) {
  1868. if (global_config.can_bracketedpaste) {
  1869. printf("\033[?2004l");
  1870. }
  1871. }
  1872. /**
  1873. * Get the name of just a file from a full path.
  1874. * Returns a pointer within the original string.
  1875. *
  1876. * Called in a few different places where the name of a file
  1877. * is needed from its full path, such as drawing tab names or
  1878. * building HTML files.
  1879. */
  1880. char * file_basename(char * file) {
  1881. char * c = strrchr(file, '/');
  1882. if (!c) return file;
  1883. return (c+1);
  1884. }
  1885. /**
  1886. * Print a tab name with fixed width and modifiers
  1887. * into an output buffer and return the written width.
  1888. */
  1889. int draw_tab_name(buffer_t * _env, char * out, int max_width, int * width) {
  1890. uint32_t c, state = 0;
  1891. char * t = _env->file_name ? file_basename(_env->file_name) : "[No Name]";
  1892. #define ADD(c) do { \
  1893. *o = c; \
  1894. o++; \
  1895. *o = '\0'; \
  1896. bytes++; \
  1897. } while (0)
  1898. char * o = out;
  1899. *o = '\0';
  1900. int bytes = 0;
  1901. if (max_width < 2) return 1;
  1902. ADD(' ');
  1903. (*width)++;
  1904. if (_env->modified) {
  1905. if (max_width < 4) return 1;
  1906. ADD('+');
  1907. (*width)++;
  1908. ADD(' ');
  1909. (*width)++;
  1910. }
  1911. while (*t) {
  1912. /* File names can definitely by UTF-8, and we need to
  1913. * understand their display width... */
  1914. if (!decode(&state, &c, (unsigned char)*t)) {
  1915. /* But our displayed tab name is also just stored
  1916. * as UTF-8 again, so we essentially rebuild it... */
  1917. char tmp[7];
  1918. int size = to_eight(c, tmp);
  1919. if (bytes + size > 62) break;
  1920. if (*width + size >= max_width) return 1;
  1921. for (int i = 0; i < size; ++i) {
  1922. ADD(tmp[i]);
  1923. }
  1924. (*width) += codepoint_width(c);
  1925. } else if (state == UTF8_REJECT) {
  1926. state = 0;
  1927. }
  1928. t++;
  1929. }
  1930. if (max_width == *width + 1) return 1;
  1931. ADD(' ');
  1932. (*width)++;
  1933. #undef ADD
  1934. return 0;
  1935. }
  1936. /**
  1937. * Redraw the tabbar, with a tab for each buffer.
  1938. *
  1939. * The active buffer is highlighted.
  1940. */
  1941. void redraw_tabbar(void) {
  1942. if (!global_config.tabs_visible) return;
  1943. /* Hide cursor while rendering UI */
  1944. hide_cursor();
  1945. /* Move to upper left */
  1946. place_cursor(1,1);
  1947. paint_line(COLOR_TABBAR_BG);
  1948. /* For each buffer... */
  1949. int offset = 0;
  1950. if (global_config.tab_offset) {
  1951. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  1952. printf("<");
  1953. offset++;
  1954. }
  1955. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  1956. buffer_t * _env = buffers[i];
  1957. if (_env == env) {
  1958. /* If this is the active buffer, highlight it */
  1959. reset();
  1960. set_colors(COLOR_FG, COLOR_BG);
  1961. set_bold();
  1962. } else {
  1963. /* Otherwise use default tab color */
  1964. reset();
  1965. set_colors(COLOR_FG, COLOR_TAB_BG);
  1966. set_underline();
  1967. }
  1968. if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  1969. if (global_config.command_buffer->actual) {
  1970. char * f = _env->file_name ? file_basename(_env->file_name) : "";
  1971. /* TODO: Support unicode input here; needs conversion */
  1972. int i = 0;
  1973. for (; i < global_config.command_buffer->actual &&
  1974. f[i] == global_config.command_buffer->text[i].codepoint; ++i);
  1975. if (global_config.command_buffer->actual == i) {
  1976. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  1977. }
  1978. }
  1979. }
  1980. char title[64];
  1981. int size = 0;
  1982. int filled = draw_tab_name(_env, title, global_config.term_width - offset, &size);
  1983. if (filled) {
  1984. offset += size;
  1985. printf("%s", title);
  1986. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  1987. while (offset != global_config.term_width - 1) {
  1988. printf(" ");
  1989. offset++;
  1990. }
  1991. printf(">");
  1992. break;
  1993. }
  1994. printf("%s", title);
  1995. offset += size;
  1996. }
  1997. /* Reset bold/underline */
  1998. reset();
  1999. /* Fill the rest of the tab bar */
  2000. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  2001. clear_to_end();
  2002. }
  2003. /**
  2004. * Braindead log10 implementation for figuring out the width of the
  2005. * line number column.
  2006. */
  2007. int log_base_10(unsigned int v) {
  2008. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2009. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2010. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2011. return r;
  2012. }
  2013. /**
  2014. * Render a line of text.
  2015. *
  2016. * This handles rendering the actual text content. A full line of text
  2017. * also includes a line number and some padding, but those elements
  2018. * are rendered elsewhere; this method can be used for lines that are
  2019. * not attached to a buffer such as command input lines.
  2020. *
  2021. * width: width of the text display region (term width - line number width)
  2022. * offset: how many cells into the line to start rendering at
  2023. */
  2024. void render_line(line_t * line, int width, int offset, int line_no) {
  2025. int i = 0; /* Offset in char_t line data entries */
  2026. int j = 0; /* Offset in terminal cells */
  2027. const char * last_color = NULL;
  2028. int was_selecting = 0, was_searching = 0, was_underlining = 0;
  2029. /* Set default text colors */
  2030. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2031. /*
  2032. * When we are rendering in the middle of a wide character,
  2033. * we render -'s to fill the remaining amount of the character's width.
  2034. */
  2035. int remainder = 0;
  2036. int is_spaces = 1;
  2037. /* For each character in the line ... */
  2038. while (i < line->actual) {
  2039. /* If there is remaining text... */
  2040. if (remainder) {
  2041. /* If we should be drawing by now... */
  2042. if (j >= offset) {
  2043. if (was_underlining) printf("\033[24m");
  2044. /* Fill remainder with -'s */
  2045. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2046. printf("-");
  2047. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2048. }
  2049. /* One less remaining width cell to fill */
  2050. remainder--;
  2051. /* Terminal offset moves forward */
  2052. j++;
  2053. /*
  2054. * If this was the last remaining character, move to
  2055. * the next codepoint in the line
  2056. */
  2057. if (remainder == 0) {
  2058. i++;
  2059. }
  2060. continue;
  2061. }
  2062. /* Get the next character to draw */
  2063. char_t c = line->text[i];
  2064. if (c.codepoint != ' ') is_spaces = 0;
  2065. /* If we should be drawing by now... */
  2066. if (j >= offset) {
  2067. /* If this character is going to fall off the edge of the screen... */
  2068. if (j - offset + c.display_width >= width) {
  2069. /* We draw this with special colors so it isn't ambiguous */
  2070. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2071. if (was_underlining) printf("\033[24m");
  2072. /* If it's wide, draw ---> as needed */
  2073. while (j - offset < width - 1) {
  2074. printf("-");
  2075. j++;
  2076. }
  2077. /* End the line with a > to show it overflows */
  2078. printf(">");
  2079. set_colors(COLOR_FG, COLOR_BG);
  2080. return;
  2081. }
  2082. /* Syntax highlighting */
  2083. const char * color = flag_to_color(c.flags);
  2084. if (c.flags & FLAG_SELECT) {
  2085. if ((c.flags & FLAG_MASK_COLORS) == FLAG_NONE) color = COLOR_SELECTFG;
  2086. set_colors(color, COLOR_SELECTBG);
  2087. was_selecting = 1;
  2088. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  2089. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2090. was_searching = 1;
  2091. } else if (c.flags == FLAG_ERROR) {
  2092. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2093. was_searching = 1; /* co-opting this should work... */
  2094. } else {
  2095. if (was_selecting || was_searching) {
  2096. was_selecting = 0;
  2097. was_searching = 0;
  2098. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2099. last_color = color;
  2100. } else if (!last_color || strcmp(color, last_color)) {
  2101. set_fg_color(color);
  2102. last_color = color;
  2103. }
  2104. }
  2105. if ((c.flags & FLAG_UNDERLINE) && !was_underlining) {
  2106. printf("\033[4m");
  2107. was_underlining = 1;
  2108. } else if (!(c.flags & FLAG_UNDERLINE) && was_underlining) {
  2109. printf("\033[24m");
  2110. was_underlining = 0;
  2111. }
  2112. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2113. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2114. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2115. ((j == env->sel_col) ||
  2116. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  2117. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2118. was_selecting = 1;
  2119. }
  2120. #define _set_colors(fg,bg) \
  2121. if (!(c.flags & FLAG_SELECT) && !(c.flags & FLAG_SEARCH) && !(was_selecting)) { \
  2122. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  2123. }
  2124. /* Render special characters */
  2125. if (c.codepoint == '\t') {
  2126. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2127. printf("%s", global_config.tab_indicator);
  2128. for (int i = 1; i < c.display_width; ++i) {
  2129. printf("%s" ,global_config.space_indicator);
  2130. }
  2131. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2132. } else if (c.codepoint < 32) {
  2133. /* Codepoints under 32 to get converted to ^@ escapes */
  2134. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2135. printf("^%c", '@' + c.codepoint);
  2136. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2137. } else if (c.codepoint == 0x7f) {
  2138. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2139. printf("^?");
  2140. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2141. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  2142. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2143. printf("<%2x>", c.codepoint);
  2144. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2145. } else if (c.codepoint == 0xa0) {
  2146. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2147. printf("_");
  2148. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2149. } else if (c.display_width == 8) {
  2150. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2151. printf("[U+%04x]", c.codepoint);
  2152. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2153. } else if (c.display_width == 10) {
  2154. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2155. printf("[U+%06x]", c.codepoint);
  2156. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2157. } else if (i > 0 && is_spaces && c.codepoint == ' ' && !(i % env->tabstop)) {
  2158. _set_colors(COLOR_ALT_FG, COLOR_BG); /* Normal background so this is more subtle */
  2159. if (global_config.can_unicode) {
  2160. printf("▏");
  2161. } else {
  2162. printf("|");
  2163. }
  2164. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2165. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  2166. /* Special case: space at end of line */
  2167. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2168. printf("%s",global_config.space_indicator);
  2169. _set_colors(COLOR_FG, COLOR_BG);
  2170. } else {
  2171. /* Normal characters get output */
  2172. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  2173. to_eight(c.codepoint, tmp);
  2174. printf("%s", tmp);
  2175. }
  2176. /* Advance the terminal cell offset by the render width of this character */
  2177. j += c.display_width;
  2178. /* Advance to the next character */
  2179. i++;
  2180. } else if (c.display_width > 1) {
  2181. /*
  2182. * If this is a wide character but we aren't ready to render yet,
  2183. * we may need to draw some filler text for the remainder of its
  2184. * width to ensure we don't jump around when horizontally scrolling
  2185. * past wide characters.
  2186. */
  2187. remainder = c.display_width - 1;
  2188. j++;
  2189. } else {
  2190. /* Regular character, not ready to draw, advance without doing anything */
  2191. j++;
  2192. i++;
  2193. }
  2194. }
  2195. if (was_underlining) printf("\033[24m");
  2196. /**
  2197. * Determine what color the rest of the line should be.
  2198. */
  2199. if (env->mode != MODE_LINE_SELECTION) {
  2200. /* If we are not selecting, then use the normal background or highlight
  2201. * the current line if that feature is enabled. */
  2202. if (line->is_current) {
  2203. set_colors(COLOR_FG, COLOR_ALT_BG);
  2204. } else {
  2205. set_colors(COLOR_FG, COLOR_BG);
  2206. }
  2207. } else {
  2208. /* If this line was empty but was part of the selection, we didn't
  2209. * set the selection color already, so we need to do that here. */
  2210. if (!line->actual) {
  2211. if (env->line_no == line_no ||
  2212. (env->start_line > env->line_no &&
  2213. (line_no >= env->line_no && line_no <= env->start_line)) ||
  2214. (env->start_line < env->line_no &&
  2215. (line_no >= env->start_line && line_no <= env->line_no))) {
  2216. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2217. }
  2218. }
  2219. }
  2220. /**
  2221. * In column modes, we may need to draw a column select beyond the end
  2222. * of a given line, so we need to draw up to that point first.
  2223. */
  2224. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2225. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2226. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2227. j <= env->sel_col &&
  2228. env->sel_col < width) {
  2229. set_colors(COLOR_FG, COLOR_BG);
  2230. while (j < env->sel_col) {
  2231. printf(" ");
  2232. j++;
  2233. }
  2234. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2235. printf(" ");
  2236. j++;
  2237. set_colors(COLOR_FG, COLOR_BG);
  2238. }
  2239. /*
  2240. * `maxcolumn` renders the background outside of the requested line length
  2241. * in a different color, with a line at the border between the two.
  2242. */
  2243. if (env->maxcolumn && line_no > -1 /* ensures we don't do this for command line */) {
  2244. /* Fill out the normal background */
  2245. if (j < offset) j = offset;
  2246. for (; j < width + offset && j < env->maxcolumn; ++j) {
  2247. printf(" ");
  2248. }
  2249. /* Draw the line */
  2250. if (j < width + offset && j == env->maxcolumn) {
  2251. j++;
  2252. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2253. if (global_config.can_unicode) {
  2254. printf("▏"); /* Should this be configurable? */
  2255. } else {
  2256. printf("|");
  2257. }
  2258. }
  2259. /* Fill the rest with the alternate background color */
  2260. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2261. }
  2262. /**
  2263. * Clear out the rest of the line. If we are the only buffer or the right split,
  2264. * and our terminal supports `bce`, we can just bce; otherwise write spaces
  2265. * until we reach the right side of the screen.
  2266. */
  2267. if (global_config.can_bce && (line_no == -1 || env->left + env->width == global_config.term_width)) {
  2268. clear_to_end();
  2269. } else {
  2270. /* Paint the rest of the line */
  2271. if (j < offset) j = offset;
  2272. for (; j < width + offset; ++j) {
  2273. printf(" ");
  2274. }
  2275. }
  2276. }
  2277. /**
  2278. * Get the width of the line number region
  2279. */
  2280. int num_width(void) {
  2281. if (!env->numbers) return 0;
  2282. int w = log_base_10(env->line_count) + 3;
  2283. if (w < 4) return 4;
  2284. return w;
  2285. }
  2286. /**
  2287. * Display width of the revision status gutter.
  2288. */
  2289. int gutter_width(void) {
  2290. return env->gutter;
  2291. }
  2292. /**
  2293. * Draw the gutter and line numbers.
  2294. */
  2295. void draw_line_number(int x) {
  2296. if (!env->numbers) return;
  2297. /* Draw the line number */
  2298. if (env->lines[x]->is_current) {
  2299. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  2300. } else {
  2301. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2302. }
  2303. if (global_config.relative_lines && x+1 != env->line_no) {
  2304. x = x+1 - env->line_no;
  2305. x = ((x < 0) ? -x : x)-1;
  2306. }
  2307. int num_size = num_width() - 2; /* Padding */
  2308. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2309. printf(" ");
  2310. }
  2311. printf("%d%c", x + 1, ((x+1 == env->line_no || global_config.horizontal_shift_scrolling) && env->coffset > 0) ? '<' : ' ');
  2312. }
  2313. /**
  2314. * Used to highlight the current line after moving the cursor.
  2315. */
  2316. void recalculate_current_line(void) {
  2317. int something_changed = 0;
  2318. if (global_config.highlight_current_line) {
  2319. for (int i = 0; i < env->line_count; ++i) {
  2320. if (env->lines[i]->is_current && i != env->line_no-1) {
  2321. env->lines[i]->is_current = 0;
  2322. something_changed = 1;
  2323. redraw_line(i);
  2324. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  2325. env->lines[i]->is_current = 1;
  2326. something_changed = 1;
  2327. redraw_line(i);
  2328. }
  2329. }
  2330. } else {
  2331. something_changed = 1;
  2332. }
  2333. if (something_changed && global_config.relative_lines) {
  2334. for (int i = env->offset; i < env->offset + global_config.term_height - global_config.bottom_size - 1 && i < env->line_count; ++i) {
  2335. /* Place cursor for line number */
  2336. place_cursor(1 + gutter_width() + env->left, (i)-env->offset + 1 + global_config.tabs_visible);
  2337. draw_line_number(i);
  2338. }
  2339. }
  2340. }
  2341. /**
  2342. * Redraw line.
  2343. *
  2344. * This draws the line number as well as the actual text.
  2345. */
  2346. void redraw_line(int x) {
  2347. if (env->loading) return;
  2348. /* Determine if this line is visible. */
  2349. if (x - env->offset < 0 || x - env->offset > global_config.term_height - global_config.bottom_size - 1 - global_config.tabs_visible) {
  2350. return;
  2351. }
  2352. /* Calculate offset in screen */
  2353. int j = x - env->offset;
  2354. /* Hide cursor when drawing */
  2355. hide_cursor();
  2356. /* Move cursor to upper left most cell of this line */
  2357. place_cursor(1 + env->left,1 + global_config.tabs_visible + j);
  2358. /* Draw a gutter on the left. */
  2359. if (env->gutter) {
  2360. switch (env->lines[x]->rev_status) {
  2361. case 1:
  2362. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  2363. printf(" ");
  2364. break;
  2365. case 2:
  2366. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  2367. printf(" ");
  2368. break;
  2369. case 3:
  2370. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  2371. printf(" ");
  2372. break;
  2373. case 4:
  2374. set_colors(COLOR_ALT_FG, COLOR_RED);
  2375. printf("▆");
  2376. break;
  2377. case 5:
  2378. set_colors(COLOR_KEYWORD, COLOR_RED);
  2379. printf("▆");
  2380. break;
  2381. default:
  2382. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2383. printf(" ");
  2384. break;
  2385. }
  2386. }
  2387. draw_line_number(x);
  2388. int should_shift = x + 1 == env->line_no || global_config.horizontal_shift_scrolling ||
  2389. ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2390. x + 1 >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2391. x + 1 <= ((env->start_line < env->line_no) ? env->line_no : env->start_line));
  2392. /*
  2393. * Draw the line text
  2394. * If this is the active line, the current character cell offset should be used.
  2395. * (Non-active lines are not shifted and always render from the start of the line)
  2396. */
  2397. render_line(env->lines[x], env->width - gutter_width() - num_width(), should_shift ? env->coffset : 0, x+1);
  2398. }
  2399. /**
  2400. * Draw a ~ line where there is no buffer text.
  2401. */
  2402. void draw_excess_line(int j) {
  2403. place_cursor(1+env->left,1 + global_config.tabs_visible + j);
  2404. paint_line(COLOR_ALT_BG);
  2405. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2406. printf("~");
  2407. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2408. clear_to_end();
  2409. } else {
  2410. /* Paint the rest of the line */
  2411. for (int x = 1; x < env->width; ++x) {
  2412. printf(" ");
  2413. }
  2414. }
  2415. }
  2416. /**
  2417. * Redraw the entire text area
  2418. */
  2419. void redraw_text(void) {
  2420. if (!env) return;
  2421. if (!global_config.has_terminal) return;
  2422. /* Hide cursor while rendering */
  2423. hide_cursor();
  2424. /* Figure out the available size of the text region */
  2425. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  2426. int j = 0;
  2427. /* Draw each line */
  2428. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2429. redraw_line(x);
  2430. j++;
  2431. }
  2432. /* Draw the rest of the text region as ~ lines */
  2433. for (; j < l; ++j) {
  2434. draw_excess_line(j);
  2435. }
  2436. }
  2437. static int view_left_offset = 0;
  2438. static int view_right_offset = 0;
  2439. /**
  2440. * When in split view, draw the other buffer.
  2441. * Has special handling for when the split is
  2442. * on a single buffer.
  2443. */
  2444. void redraw_alt_buffer(buffer_t * buf) {
  2445. if (left_buffer == right_buffer) {
  2446. /* draw the opposite view */
  2447. int left, width, offset;
  2448. left = env->left;
  2449. width = env->width;
  2450. offset = env->offset;
  2451. if (left == 0) {
  2452. /* Draw the right side */
  2453. env->left = width;
  2454. env->width = global_config.term_width - width;
  2455. env->offset = view_right_offset;
  2456. view_left_offset = offset;
  2457. } else {
  2458. env->left = 0;
  2459. env->width = global_config.term_width * global_config.split_percent / 100;
  2460. env->offset = view_left_offset;
  2461. view_right_offset = offset;
  2462. }
  2463. redraw_text();
  2464. env->left = left;
  2465. env->width = width;
  2466. env->offset = offset;
  2467. }
  2468. /* Swap out active buffer */
  2469. buffer_t * tmp = env;
  2470. env = buf;
  2471. /* Redraw text */
  2472. redraw_text();
  2473. /* Return original active buffer */
  2474. env = tmp;
  2475. }
  2476. /**
  2477. * Basically wcswidth() but implemented internally using our
  2478. * own utf-8 decoder to ensure it works properly.
  2479. */
  2480. int display_width_of_string(const char * str) {
  2481. uint8_t * s = (uint8_t *)str;
  2482. int out = 0;
  2483. uint32_t c, state = 0;
  2484. while (*s) {
  2485. if (!decode(&state, &c, *s)) {
  2486. out += codepoint_width(c);
  2487. } else if (state == UTF8_REJECT) {
  2488. state = 0;
  2489. }
  2490. s++;
  2491. }
  2492. return out;
  2493. }
  2494. int statusbar_append_status(int *remaining_width, size_t *filled, char * output, char * base, ...) {
  2495. va_list args;
  2496. va_start(args, base);
  2497. char tmp[100] = {0}; /* should be big enough */
  2498. vsnprintf(tmp, 100, base, args);
  2499. va_end(args);
  2500. int width = display_width_of_string(tmp) + 2;
  2501. size_t totalWidth = strlen(tmp);
  2502. totalWidth += strlen(color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2503. totalWidth += strlen(color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2504. totalWidth += strlen(color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2505. totalWidth += 3;
  2506. if (totalWidth + *filled >= 2047) {
  2507. return 0;
  2508. }
  2509. if (width < *remaining_width) {
  2510. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2511. strcat(output,"[");
  2512. strcat(output,color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2513. strcat(output, tmp);
  2514. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2515. strcat(output,"]");
  2516. (*remaining_width) -= width;
  2517. (*filled) += totalWidth;
  2518. return width;
  2519. } else {
  2520. return 0;
  2521. }
  2522. }
  2523. int statusbar_build_right(char * right_hand) {
  2524. char tmp[1024] = {0};
  2525. sprintf(tmp, " Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2526. int out = display_width_of_string(tmp);
  2527. char * s = right_hand;
  2528. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2529. s += sprintf(s, " Line ");
  2530. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2531. s += sprintf(s, "%d/%d ", env->line_no, env->line_count);
  2532. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2533. s += sprintf(s, " Col: ");
  2534. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2535. s += sprintf(s, "%d ", env->col_no);
  2536. return out;
  2537. }
  2538. /**
  2539. * Draw the status bar
  2540. *
  2541. * The status bar shows the name of the file, whether it has modifications,
  2542. * and (in the future) what syntax highlighting mode is enabled.
  2543. *
  2544. * The right side of the status bar shows the line number and column.
  2545. */
  2546. void redraw_statusbar(void) {
  2547. if (global_config.hide_statusbar) return;
  2548. if (!global_config.has_terminal) return;
  2549. if (!env) return;
  2550. /* Hide cursor while rendering */
  2551. hide_cursor();
  2552. /* Move cursor to the status bar line (second from bottom */
  2553. place_cursor(1, global_config.term_height - 1);
  2554. /* Set background colors for status line */
  2555. paint_line(COLOR_STATUS_BG);
  2556. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2557. /* Pre-render the right hand side of the status bar */
  2558. char right_hand[1024] = {0};
  2559. int right_width = statusbar_build_right(right_hand);
  2560. char status_bits[2048] = {0}; /* Sane maximum */
  2561. size_t filled = 0;
  2562. int status_bits_width = 0;
  2563. int remaining_width = global_config.term_width - right_width;
  2564. #define ADD(...) do { status_bits_width += statusbar_append_status(&remaining_width, &filled, status_bits, __VA_ARGS__); } while (0)
  2565. if (env->syntax) {
  2566. ADD("%s",env->syntax->name);
  2567. }
  2568. /* Print file status indicators */
  2569. if (env->modified) {
  2570. ADD("+");
  2571. }
  2572. if (env->readonly) {
  2573. ADD("ro");
  2574. }
  2575. if (env->crnl) {
  2576. ADD("crnl");
  2577. }
  2578. if (env->tabs) {
  2579. ADD("tabs");
  2580. } else {
  2581. ADD("spaces=%d", env->tabstop);
  2582. }
  2583. if (global_config.yanks) {
  2584. ADD("y:%ld", global_config.yank_count);
  2585. }
  2586. if (env->indent) {
  2587. ADD("indent");
  2588. }
  2589. if (global_config.smart_complete) {
  2590. ADD("complete");
  2591. }
  2592. if (global_config.background_task) {
  2593. ADD("working");
  2594. }
  2595. #undef ADD
  2596. uint8_t * file_name = (uint8_t *)(env->file_name ? env->file_name : "[No Name]");
  2597. int file_name_width = display_width_of_string((char*)file_name);
  2598. if (remaining_width > 3) {
  2599. int is_chopped = 0;
  2600. while (remaining_width < file_name_width + 3) {
  2601. is_chopped = 1;
  2602. if ((*file_name & 0xc0) == 0xc0) { /* First byte of a multibyte character */
  2603. file_name++;
  2604. while ((*file_name & 0xc0) == 0x80) file_name++;
  2605. } else {
  2606. file_name++;
  2607. }
  2608. file_name_width = display_width_of_string((char*)file_name);
  2609. }
  2610. if (is_chopped) {
  2611. set_colors(COLOR_ALT_FG, COLOR_STATUS_BG);
  2612. printf("<");
  2613. }
  2614. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2615. printf("%s ", file_name);
  2616. }
  2617. printf("%s", status_bits);
  2618. /* Clear the rest of the status bar */
  2619. clear_to_end();
  2620. /* Move the cursor appropriately to draw it */
  2621. place_cursor(global_config.term_width - right_width, global_config.term_height - 1);
  2622. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2623. printf("%s",right_hand);
  2624. }
  2625. /**
  2626. * Redraw the navigation numbers on the right side of the command line
  2627. */
  2628. void redraw_nav_buffer() {
  2629. if (!global_config.has_terminal) return;
  2630. if (nav_buffer) {
  2631. store_cursor();
  2632. place_cursor(global_config.term_width - nav_buffer - 2, global_config.term_height);
  2633. printf("%s", nav_buf);
  2634. clear_to_end();
  2635. restore_cursor();
  2636. }
  2637. }
  2638. /**
  2639. * Draw the command line
  2640. *
  2641. * The command line either has input from the user (:quit, :!make, etc.)
  2642. * or shows the INSERT (or VISUAL in the future) mode name.
  2643. */
  2644. void redraw_commandline(void) {
  2645. if (!global_config.has_terminal) return;
  2646. if (!env) return;
  2647. /* Hide cursor while rendering */
  2648. hide_cursor();
  2649. /* Move cursor to the last line */
  2650. place_cursor(1, global_config.term_height);
  2651. /* Set background color */
  2652. paint_line(COLOR_BG);
  2653. set_colors(COLOR_FG, COLOR_BG);
  2654. /* If we are in an edit mode, note that. */
  2655. if (env->mode == MODE_INSERT) {
  2656. set_bold();
  2657. printf("-- INSERT --");
  2658. clear_to_end();
  2659. unset_bold();
  2660. } else if (env->mode == MODE_LINE_SELECTION) {
  2661. set_bold();
  2662. printf("-- LINE SELECTION -- (%d:%d)",
  2663. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2664. (env->start_line < env->line_no) ? env->line_no : env->start_line
  2665. );
  2666. clear_to_end();
  2667. unset_bold();
  2668. } else if (env->mode == MODE_COL_SELECTION) {
  2669. set_bold();
  2670. printf("-- COL SELECTION -- (%d:%d %d)",
  2671. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2672. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2673. (env->sel_col)
  2674. );
  2675. clear_to_end();
  2676. unset_bold();
  2677. } else if (env->mode == MODE_COL_INSERT) {
  2678. set_bold();
  2679. printf("-- COL INSERT -- (%d:%d %d)",
  2680. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2681. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2682. (env->sel_col)
  2683. );
  2684. clear_to_end();
  2685. unset_bold();
  2686. } else if (env->mode == MODE_REPLACE) {
  2687. set_bold();
  2688. printf("-- REPLACE --");
  2689. clear_to_end();
  2690. unset_bold();
  2691. } else if (env->mode == MODE_CHAR_SELECTION) {
  2692. set_bold();
  2693. printf("-- CHAR SELECTION -- ");
  2694. clear_to_end();
  2695. unset_bold();
  2696. } else if (env->mode == MODE_DIRECTORY_BROWSE) {
  2697. set_bold();
  2698. printf("-- DIRECTORY BROWSE --");
  2699. clear_to_end();
  2700. unset_bold();
  2701. } else {
  2702. clear_to_end();
  2703. }
  2704. redraw_nav_buffer();
  2705. }
  2706. /**
  2707. * Draw a message on the command line.
  2708. */
  2709. void render_commandline_message(char * message, ...) {
  2710. /* varargs setup */
  2711. va_list args;
  2712. va_start(args, message);
  2713. /* Hide cursor while rendering */
  2714. hide_cursor();
  2715. /* Move cursor to the last line */
  2716. place_cursor(1, global_config.term_height);
  2717. /* Set background color */
  2718. paint_line(COLOR_BG);
  2719. set_colors(COLOR_FG, COLOR_BG);
  2720. vprintf(message, args);
  2721. va_end(args);
  2722. /* Clear the rest of the status bar */
  2723. clear_to_end();
  2724. redraw_nav_buffer();
  2725. }
  2726. BIM_ACTION(redraw_all, 0,
  2727. "Repaint the screen."
  2728. )(void) {
  2729. if (!env) return;
  2730. redraw_tabbar();
  2731. redraw_text();
  2732. if (left_buffer) {
  2733. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  2734. }
  2735. redraw_statusbar();
  2736. redraw_commandline();
  2737. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND ||
  2738. global_config.overlay_mode == OVERLAY_MODE_SEARCH ||
  2739. global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  2740. render_command_input_buffer();
  2741. }
  2742. }
  2743. void pause_for_key(void) {
  2744. int c;
  2745. while ((c = bim_getch())== -1);
  2746. bim_unget(c);
  2747. redraw_all();
  2748. }
  2749. /**
  2750. * Redraw all screen elements except the other split view.
  2751. */
  2752. void redraw_most(void) {
  2753. redraw_tabbar();
  2754. redraw_text();
  2755. redraw_statusbar();
  2756. redraw_commandline();
  2757. }
  2758. /**
  2759. * Disable screen splitting.
  2760. */
  2761. void unsplit(void) {
  2762. if (left_buffer) {
  2763. left_buffer->left = 0;
  2764. left_buffer->width = global_config.term_width;
  2765. }
  2766. if (right_buffer) {
  2767. right_buffer->left = 0;
  2768. right_buffer->width = global_config.term_width;
  2769. }
  2770. left_buffer = NULL;
  2771. right_buffer = NULL;
  2772. redraw_all();
  2773. }
  2774. /**
  2775. * Update the terminal title bar
  2776. */
  2777. void update_title(void) {
  2778. if (!global_config.can_title) return;
  2779. char cwd[1024] = {'/',0};
  2780. getcwd(cwd, 1024);
  2781. for (int i = 1; i < 3; ++i) {
  2782. printf("\033]%d;%s%s (%s) - Bim\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  2783. }
  2784. }
  2785. /**
  2786. * Mark this buffer as modified and
  2787. * redraw the status and tabbar if needed.
  2788. */
  2789. void set_modified(void) {
  2790. /* If it was already marked modified, no need to do anything */
  2791. if (env->modified) return;
  2792. /* Mark as modified */
  2793. env->modified = 1;
  2794. /* Redraw some things */
  2795. update_title();
  2796. redraw_tabbar();
  2797. redraw_statusbar();
  2798. }
  2799. /**
  2800. * Draw a message on the status line
  2801. */
  2802. void render_status_message(char * message, ...) {
  2803. if (!env) return; /* Don't print when there's no active environment; this usually means a bimrc command tried to print something */
  2804. /* varargs setup */
  2805. va_list args;
  2806. va_start(args, message);
  2807. /* Hide cursor while rendering */
  2808. hide_cursor();
  2809. /* Move cursor to the status bar line (second from bottom */
  2810. place_cursor(1, global_config.term_height - 1);
  2811. /* Set background colors for status line */
  2812. paint_line(COLOR_STATUS_BG);
  2813. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2814. /* Process format string */
  2815. vprintf(message, args);
  2816. va_end(args);
  2817. /* Clear the rest of the status bar */
  2818. clear_to_end();
  2819. }
  2820. /**
  2821. * Draw an error message to the command line.
  2822. */
  2823. void render_error(char * message, ...) {
  2824. /* varargs setup */
  2825. va_list args;
  2826. va_start(args, message);
  2827. if (env) {
  2828. /* Hide cursor while rendering */
  2829. hide_cursor();
  2830. /* Move cursor to the command line */
  2831. place_cursor(1, global_config.term_height);
  2832. /* Set appropriate error message colors */
  2833. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2834. /* Draw the message */
  2835. vprintf(message, args);
  2836. va_end(args);
  2837. global_config.had_error = 1;
  2838. } else {
  2839. printf("bim: error during startup: ");
  2840. vprintf(message, args);
  2841. va_end(args);
  2842. printf("\n");
  2843. }
  2844. }
  2845. char * paren_pairs = "()[]{}<>";
  2846. int is_paren(int c) {
  2847. char * p = paren_pairs;
  2848. while (*p) {
  2849. if (c == *p) return 1;
  2850. p++;
  2851. }
  2852. return 0;
  2853. }
  2854. #define _rehighlight_parens() do { \
  2855. if (i < 0 || i >= env->line_count) break; \
  2856. for (int j = 0; j < env->lines[i]->actual; ++j) { \
  2857. if (i == line-1 && j == col-1) { \
  2858. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT; \
  2859. continue; \
  2860. } else { \
  2861. env->lines[i]->text[j].flags &= (~FLAG_SELECT); \
  2862. } \
  2863. } \
  2864. redraw_line(i); \
  2865. } while (0)
  2866. /**
  2867. * If the config option is enabled, find the matching
  2868. * paren character and highlight it with the SELECT
  2869. * colors, clearing out other SELECT values. As we
  2870. * co-opt the SELECT flag, don't do this in selection
  2871. * modes - only in normal and insert modes.
  2872. */
  2873. void highlight_matching_paren(void) {
  2874. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  2875. if (!global_config.highlight_parens) return;
  2876. int line = -1, col = -1;
  2877. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  2878. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  2879. find_matching_paren(&line, &col, 1);
  2880. } else if (env->line_no <= env->line_count && env->col_no > 1 && is_paren(env->lines[env->line_no-1]->text[env->col_no-2].codepoint)) {
  2881. find_matching_paren(&line, &col, 2);
  2882. }
  2883. if (env->highlighting_paren == -1 && line == -1) return;
  2884. if (env->highlighting_paren > 0) {
  2885. int i = env->highlighting_paren - 1;
  2886. _rehighlight_parens();
  2887. }
  2888. if (env->highlighting_paren != line && line != -1) {
  2889. int i = line - 1;
  2890. _rehighlight_parens();
  2891. }
  2892. env->highlighting_paren = line;
  2893. }
  2894. /**
  2895. * Recalculate syntax for the matched paren.
  2896. * Useful when entering selection modes.
  2897. */
  2898. void unhighlight_matching_paren(void) {
  2899. if (env->highlighting_paren > 0 && env->highlighting_paren <= env->line_count) {
  2900. for (int i = 0; i < env->line_count; i++) {
  2901. for (int j = 0; j < env->lines[i]->actual; ++j) {
  2902. env->lines[i]->text[j].flags &= ~(FLAG_SELECT);
  2903. }
  2904. }
  2905. env->highlighting_paren = -1;
  2906. }
  2907. }
  2908. /**
  2909. * Move the cursor to the appropriate location based
  2910. * on where it is in the text region.
  2911. *
  2912. * This does some additional math to set the text
  2913. * region horizontal offset.
  2914. */
  2915. void place_cursor_actual(void) {
  2916. /* Invalid positions */
  2917. if (env->line_no < 1) env->line_no = 1;
  2918. if (env->col_no < 1) env->col_no = 1;
  2919. /* Account for the left hand gutter */
  2920. int num_size = num_width() + gutter_width();
  2921. int x = num_size + 1 - env->coffset;
  2922. /* Determine where the cursor is physically */
  2923. for (int i = 0; i < env->col_no - 1; ++i) {
  2924. char_t * c = &env->lines[env->line_no-1]->text[i];
  2925. x += c->display_width;
  2926. }
  2927. /* y is a bit easier to calculate */
  2928. int y = env->line_no - env->offset + 1;
  2929. int needs_redraw = 0;
  2930. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  2931. y++;
  2932. env->offset--;
  2933. needs_redraw = 1;
  2934. }
  2935. while (y > 1 + global_config.term_height - global_config.bottom_size - global_config.cursor_padding - global_config.tabs_visible) {
  2936. y--;
  2937. env->offset++;
  2938. needs_redraw = 1;
  2939. }
  2940. if (needs_redraw) {
  2941. redraw_text();
  2942. redraw_tabbar();
  2943. redraw_statusbar();
  2944. redraw_commandline();
  2945. }
  2946. /* If the cursor has gone off screen to the right... */
  2947. if (x > env->width - 1) {
  2948. /* Adjust the offset appropriately to scroll horizontally */
  2949. int diff = x - (env->width - 1);
  2950. env->coffset += diff;
  2951. x -= diff;
  2952. redraw_text();
  2953. }
  2954. /* Same for scrolling horizontally to the left */
  2955. if (x < num_size + 1) {
  2956. int diff = (num_size + 1) - x;
  2957. env->coffset -= diff;
  2958. x += diff;
  2959. redraw_text();
  2960. }
  2961. highlight_matching_paren();
  2962. recalculate_current_line();
  2963. /* Move the actual terminal cursor */
  2964. place_cursor(x+env->left,y - !global_config.tabs_visible);
  2965. /* Show the cursor */
  2966. show_cursor();
  2967. }
  2968. /**
  2969. * If the screen is split, update the split sizes based
  2970. * on the new terminal width and the user's split_percent setting.
  2971. */
  2972. void update_split_size(void) {
  2973. if (!left_buffer) return;
  2974. if (left_buffer == right_buffer) {
  2975. if (left_buffer->left == 0) {
  2976. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  2977. } else {
  2978. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  2979. right_buffer->width = global_config.term_width - right_buffer->left;
  2980. }
  2981. return;
  2982. }
  2983. left_buffer->left = 0;
  2984. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  2985. right_buffer->left = left_buffer->width;
  2986. right_buffer->width = global_config.term_width - left_buffer->width;
  2987. }
  2988. /**
  2989. * Update screen size
  2990. */
  2991. void update_screen_size(void) {
  2992. struct winsize w;
  2993. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  2994. global_config.term_width = w.ws_col;
  2995. global_config.term_height = w.ws_row;
  2996. if (env) {
  2997. if (left_buffer) {
  2998. update_split_size();
  2999. } else if (env != left_buffer && env != right_buffer) {
  3000. env->width = w.ws_col;
  3001. }
  3002. }
  3003. for (int i = 0; i < buffers_len; ++i) {
  3004. if (buffers[i] != left_buffer && buffers[i] != right_buffer) {
  3005. buffers[i]->width = w.ws_col;
  3006. }
  3007. }
  3008. }
  3009. /**
  3010. * Handle terminal size changes
  3011. */
  3012. void SIGWINCH_handler(int sig) {
  3013. (void)sig;
  3014. update_screen_size();
  3015. redraw_all();
  3016. signal(SIGWINCH, SIGWINCH_handler);
  3017. }
  3018. /**
  3019. * Handle suspend
  3020. */
  3021. void SIGTSTP_handler(int sig) {
  3022. (void)sig;
  3023. mouse_disable();
  3024. set_buffered();
  3025. reset();
  3026. clear_screen();
  3027. show_cursor();
  3028. unset_bracketed_paste();
  3029. unset_alternate_screen();
  3030. fflush(stdout);
  3031. signal(SIGTSTP, SIG_DFL);
  3032. raise(SIGTSTP);
  3033. }
  3034. void SIGCONT_handler(int sig) {
  3035. (void)sig;
  3036. set_alternate_screen();
  3037. set_bracketed_paste();
  3038. set_unbuffered();
  3039. update_screen_size();
  3040. mouse_enable();
  3041. redraw_all();
  3042. update_title();
  3043. signal(SIGCONT, SIGCONT_handler);
  3044. signal(SIGTSTP, SIGTSTP_handler);
  3045. }
  3046. void SIGINT_handler(int sig) {
  3047. krk_currentThread.flags |= KRK_THREAD_SIGNALLED;
  3048. signal(SIGINT, SIGINT_handler);
  3049. }
  3050. void try_to_center() {
  3051. int half_a_screen = (global_config.term_height - 3) / 2;
  3052. if (half_a_screen < env->line_no) {
  3053. env->offset = env->line_no - half_a_screen;
  3054. } else {
  3055. env->offset = 0;
  3056. }
  3057. }
  3058. BIM_ACTION(suspend, 0,
  3059. "Suspend bim and the rest of the job it was run in."
  3060. )(void) {
  3061. kill(0, SIGTSTP);
  3062. }
  3063. /**
  3064. * Move the cursor to a specific line.
  3065. */
  3066. BIM_ACTION(goto_line, ARG_IS_CUSTOM,
  3067. "Jump to the requested line."
  3068. )(int line) {
  3069. if (line == -1) line = env->line_count;
  3070. /* Respect file bounds */
  3071. if (line < 1) line = 1;
  3072. if (line > env->line_count) line = env->line_count;
  3073. /* Move the cursor / text region offsets */
  3074. env->coffset = 0;
  3075. env->line_no = line;
  3076. env->col_no = 1;
  3077. if (!env->loading) {
  3078. if (line > env->offset && line < env->offset + global_config.term_height - global_config.bottom_size) {
  3079. place_cursor_actual();
  3080. } else {
  3081. try_to_center();
  3082. }
  3083. redraw_most();
  3084. } else {
  3085. try_to_center();
  3086. }
  3087. }
  3088. /**
  3089. * Process (part of) a file and add it to a buffer.
  3090. */
  3091. void add_buffer(uint8_t * buf, int size) {
  3092. for (int i = 0; i < size; ++i) {
  3093. if (!decode(&state, &codepoint_r, buf[i])) {
  3094. uint32_t c = codepoint_r;
  3095. if (c == '\n') {
  3096. if (!env->crnl && env->lines[env->line_no-1]->actual && env->lines[env->line_no-1]->text[env->lines[env->line_no-1]->actual-1].codepoint == '\r') {
  3097. env->lines[env->line_no-1]->actual--;
  3098. env->crnl = 1;
  3099. }
  3100. env->lines = add_line(env->lines, env->line_no);
  3101. env->col_no = 1;
  3102. env->line_no += 1;
  3103. } else if (env->crnl && c == '\r') {
  3104. continue;
  3105. } else {
  3106. char_t _c;
  3107. _c.codepoint = (uint32_t)c;
  3108. _c.flags = 0;
  3109. _c.display_width = codepoint_width((wchar_t)c);
  3110. line_t * line = env->lines[env->line_no - 1];
  3111. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  3112. if (line != nline) {
  3113. env->lines[env->line_no - 1] = nline;
  3114. }
  3115. env->col_no += 1;
  3116. }
  3117. } else if (state == UTF8_REJECT) {
  3118. state = 0;
  3119. }
  3120. }
  3121. }
  3122. /**
  3123. * Add a raw string to a buffer. Convenience wrapper
  3124. * for add_buffer for nil-terminated strings.
  3125. */
  3126. void add_string(char * string) {
  3127. add_buffer((uint8_t*)string,strlen(string));
  3128. }
  3129. int str_ends_with(const char * haystack, const char * needle) {
  3130. int i = strlen(haystack);
  3131. int j = strlen(needle);
  3132. do {
  3133. if (haystack[i] != needle[j]) return 0;
  3134. if (j == 0) return 1;
  3135. if (i == 0) return 0;
  3136. i--;
  3137. j--;
  3138. } while (1);
  3139. }
  3140. /**
  3141. * Find a syntax highlighter for the given filename.
  3142. */
  3143. struct syntax_definition * match_syntax(char * file) {
  3144. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3145. for (char ** ext = s->ext; *ext; ++ext) {
  3146. if (str_ends_with(file, *ext)) return s;
  3147. }
  3148. }
  3149. return NULL;
  3150. }
  3151. /**
  3152. * Set the syntax configuration by the name of the syntax highlighter.
  3153. */
  3154. void set_syntax_by_name(const char * name) {
  3155. if (!strcmp(name,"none")) {
  3156. for (int i = 0; i < env->line_count; ++i) {
  3157. env->lines[i]->istate = -1;
  3158. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3159. env->lines[i]->text[j].flags &= (3 << 5);
  3160. }
  3161. }
  3162. env->syntax = NULL;
  3163. redraw_all();
  3164. return;
  3165. }
  3166. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3167. if (!strcmp(name,s->name)) {
  3168. env->syntax = s;
  3169. for (int i = 0; i < env->line_count; ++i) {
  3170. env->lines[i]->istate = -1;
  3171. }
  3172. schedule_complete_recalc();
  3173. redraw_all();
  3174. return;
  3175. }
  3176. }
  3177. render_error("unrecognized syntax type");
  3178. }
  3179. /**
  3180. * Check if a string is all numbers.
  3181. */
  3182. int is_all_numbers(const char * c) {
  3183. while (*c) {
  3184. if (!isdigit(*c)) return 0;
  3185. c++;
  3186. }
  3187. return 1;
  3188. }
  3189. struct file_listing {
  3190. int type;
  3191. char * filename;
  3192. };
  3193. int sort_files(const void * a, const void * b) {
  3194. struct file_listing * _a = (struct file_listing *)a;
  3195. struct file_listing * _b = (struct file_listing *)b;
  3196. if (_a->type == _b->type) {
  3197. return strcmp(_a->filename, _b->filename);
  3198. } else {
  3199. return _a->type - _b->type;
  3200. }
  3201. }
  3202. void read_directory_into_buffer(char * file) {
  3203. DIR * dirp = opendir(file);
  3204. if (!dirp) {
  3205. env->loading = 0;
  3206. return;
  3207. }
  3208. add_string("# Directory listing for `");
  3209. add_string(file);
  3210. add_string("`\n");
  3211. /* Flexible array to hold directory contents */
  3212. int available = 32;
  3213. int count = 0;
  3214. struct file_listing * files = calloc(sizeof(struct file_listing), available);
  3215. /* Read directory */
  3216. struct dirent * ent = readdir(dirp);
  3217. while (ent) {
  3218. struct stat statbuf;
  3219. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);
  3220. snprintf(tmp, strlen(file) + 1 + strlen(ent->d_name) + 1, "%s/%s", file, ent->d_name);
  3221. stat(tmp, &statbuf);
  3222. int type = (S_ISDIR(statbuf.st_mode)) ? 'd' : 'f';
  3223. if (count + 1 == available) {
  3224. available *= 2; \
  3225. files = realloc(files, sizeof(struct file_listing) * available); \
  3226. } \
  3227. files[count].type = type;
  3228. files[count].filename = strdup(ent->d_name);
  3229. count++;
  3230. ent = readdir(dirp);
  3231. free(tmp);
  3232. }
  3233. closedir(dirp);
  3234. /* Sort directory entries */
  3235. qsort(files, count, sizeof(struct file_listing), sort_files);
  3236. for (int i = 0; i < count; ++i) {
  3237. add_string(files[i].type == 'd' ? "d" : "f");
  3238. add_string(" ");
  3239. add_string(files[i].filename);
  3240. add_string("\n");
  3241. free(files[i].filename);
  3242. }
  3243. free(files);
  3244. env->file_name = strdup(file);
  3245. env->syntax = find_syntax_calculator("dirent");
  3246. schedule_complete_recalc();
  3247. env->readonly = 1;
  3248. env->loading = 0;
  3249. env->mode = MODE_DIRECTORY_BROWSE;
  3250. env->line_no = 1;
  3251. redraw_all();
  3252. }
  3253. BIM_ACTION(open_file_from_line, 0,
  3254. "When browsing a directory, open the file under the cursor."
  3255. )(void) {
  3256. if (env->lines[env->line_no-1]->actual < 1) return;
  3257. if (env->lines[env->line_no-1]->text[0].codepoint != 'd' &&
  3258. env->lines[env->line_no-1]->text[0].codepoint != 'f') return;
  3259. /* Collect file name */
  3260. char * tmp = malloc(strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7); /* Should be enough */
  3261. memset(tmp, 0, strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7);
  3262. char * t = tmp;
  3263. /* Start by copying the filename */
  3264. t += sprintf(t, "%s/", env->file_name);
  3265. /* Start from character 2 to skip d/f and space */
  3266. for (int i = 2; i < env->lines[env->line_no-1]->actual; ++i) {
  3267. t += to_eight(env->lines[env->line_no-1]->text[i].codepoint, t);
  3268. }
  3269. *t = '\0';
  3270. /* Normalize */
  3271. char tmp_path[PATH_MAX+1];
  3272. if (!realpath(tmp, tmp_path)) {
  3273. free(tmp);
  3274. return;
  3275. }
  3276. free(tmp);
  3277. /* Open file */
  3278. buffer_t * old_buffer = env;
  3279. open_file(tmp_path);
  3280. buffer_close(old_buffer);
  3281. update_title();
  3282. redraw_all();
  3283. }
  3284. int line_matches(line_t * line, char * string) {
  3285. uint32_t c = 0, state = 0;
  3286. int i = 0;
  3287. while (*string) {
  3288. if (!decode(&state, &c, *string)) {
  3289. if (i >= line->actual) return 0;
  3290. if (line->text[i].codepoint != c) return 0;
  3291. string++;
  3292. i++;
  3293. } else if (state == UTF8_REJECT) {
  3294. state = 0;
  3295. }
  3296. }
  3297. return 1;
  3298. }
  3299. void run_onload(buffer_t * env) {
  3300. /* TODO */
  3301. KrkValue onLoad;
  3302. if (krk_tableGet_fast(&krk_currentThread.module->fields, S("onload"), &onLoad)) {
  3303. krk_push(onLoad);
  3304. krk_push(krk_dict_of(0,NULL,0));
  3305. if (env->file_name) {
  3306. krk_attachNamedObject(AS_DICT(krk_peek(0)), "filename",
  3307. (KrkObj*)krk_copyString(env->file_name,strlen(env->file_name)));
  3308. }
  3309. if (env->syntax && env->syntax->krkClass) {
  3310. krk_attachNamedObject(AS_DICT(krk_peek(0)), "highlighter",
  3311. (KrkObj*)env->syntax->krkClass);
  3312. }
  3313. krk_callStack(1);
  3314. krk_resetStack();
  3315. }
  3316. }
  3317. static void render_syntax_async(background_task_t * task) {
  3318. buffer_t * old_env = env;
  3319. env = task->env;
  3320. int line_no = task->_private_i;
  3321. if (env->line_count && line_no < env->line_count) {
  3322. int tmp = env->loading;
  3323. env->loading = 1;
  3324. recalculate_syntax(env->lines[line_no], line_no);
  3325. env->loading = tmp;
  3326. if (env == old_env) {
  3327. redraw_line(line_no);
  3328. }
  3329. }
  3330. env = old_env;
  3331. }
  3332. static void schedule_complete_recalc(void) {
  3333. if (env->line_count < 1000) {
  3334. for (int i = 0; i < env->line_count; ++i) {
  3335. recalculate_syntax(env->lines[i], i);
  3336. }
  3337. return;
  3338. }
  3339. /* TODO see if there's already a redraw scheduled */
  3340. for (int i = 0; i < env->line_count; ++i) {
  3341. background_task_t * task = malloc(sizeof(background_task_t));
  3342. task->env = env;
  3343. task->_private_i = i;
  3344. task->func = render_syntax_async;
  3345. task->next = NULL;
  3346. if (global_config.tail_task) {
  3347. global_config.tail_task->next = task;
  3348. }
  3349. global_config.tail_task = task;
  3350. if (!global_config.background_task) {
  3351. global_config.background_task = task;
  3352. }
  3353. }
  3354. redraw_statusbar();
  3355. }
  3356. /**
  3357. * Create a new buffer from a file.
  3358. */
  3359. void open_file(char * file) {
  3360. env = buffer_new();
  3361. env->width = global_config.term_width;
  3362. env->left = 0;
  3363. env->loading = 1;
  3364. setup_buffer(env);
  3365. FILE * f;
  3366. int init_line = -1;
  3367. if (!strcmp(file,"-")) {
  3368. /**
  3369. * Read file from stdin. stderr provides terminal input.
  3370. */
  3371. if (isatty(STDIN_FILENO)) {
  3372. if (buffers_len == 1) {
  3373. quit("stdin is a terminal and you tried to open -; not letting you do that");
  3374. }
  3375. close_buffer();
  3376. render_error("stdin is a terminal and you tried to open -; not letting you do that");
  3377. return;
  3378. }
  3379. f = stdin;
  3380. env->modified = 1;
  3381. } else {
  3382. char * l = strrchr(file, ':');
  3383. if (l && is_all_numbers(l+1)) {
  3384. *l = '\0';
  3385. l++;
  3386. init_line = atoi(l);
  3387. }
  3388. char * _file = file;
  3389. if (file[0] == '~') {
  3390. char * home = getenv("HOME");
  3391. if (home) {
  3392. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3393. sprintf(_file, "%s%s", home, file+1);
  3394. }
  3395. }
  3396. if (file_is_open(_file)) {
  3397. if (file != _file) free(_file);
  3398. close_buffer();
  3399. return;
  3400. }
  3401. struct stat statbuf;
  3402. if (!stat(_file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  3403. read_directory_into_buffer(_file);
  3404. if (file != _file) free(_file);
  3405. return;
  3406. }
  3407. f = fopen(_file, "r");
  3408. if (file != _file) free(_file);
  3409. if (!f && errno != ENOENT) {
  3410. render_error("%s: %s", file, strerror(errno));
  3411. pause_for_key();
  3412. close_buffer();
  3413. return;
  3414. }
  3415. env->file_name = strdup(file);
  3416. }
  3417. if (!f) {
  3418. if (global_config.highlight_on_open) {
  3419. env->syntax = match_syntax(file);
  3420. }
  3421. env->loading = 0;
  3422. if (global_config.go_to_line) {
  3423. goto_line(1);
  3424. }
  3425. if (env->syntax && env->syntax->prefers_spaces) {
  3426. env->tabs = 0;
  3427. }
  3428. update_biminfo(env, 1);
  3429. run_onload(env);
  3430. return;
  3431. }
  3432. uint8_t buf[BLOCK_SIZE];
  3433. state = 0;
  3434. while (!feof(f) && !ferror(f)) {
  3435. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  3436. add_buffer(buf, r);
  3437. }
  3438. if (ferror(f)) {
  3439. env->loading = 0;
  3440. return;
  3441. }
  3442. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  3443. /* Remove blank line from end */
  3444. env->lines = remove_line(env->lines, env->line_no-1);
  3445. }
  3446. if (global_config.highlight_on_open) {
  3447. env->syntax = match_syntax(file);
  3448. if (!env->syntax) {
  3449. if (line_matches(env->lines[0], "<?xml")) set_syntax_by_name("xml");
  3450. else if (line_matches(env->lines[0], "<!doctype")) set_syntax_by_name("xml");
  3451. else if (line_matches(env->lines[0], "#!/usr/bin/env bash")) set_syntax_by_name("bash");
  3452. else if (line_matches(env->lines[0], "#!/bin/bash")) set_syntax_by_name("bash");
  3453. else if (line_matches(env->lines[0], "#!/bin/sh")) set_syntax_by_name("bash");
  3454. else if (line_matches(env->lines[0], "#!/usr/bin/env python")) set_syntax_by_name("py");
  3455. else if (line_matches(env->lines[0], "#!/usr/bin/env groovy")) set_syntax_by_name("groovy");
  3456. }
  3457. if (!env->syntax && global_config.syntax_fallback) {
  3458. set_syntax_by_name(global_config.syntax_fallback);
  3459. }
  3460. schedule_complete_recalc();
  3461. }
  3462. /* Try to automatically figure out tabs vs. spaces */
  3463. int tabs = 0, spaces = 0;
  3464. for (int i = 0; i < env->line_count; ++i) {
  3465. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  3466. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  3467. if (env->lines[i]->text[0].codepoint == ' ' &&
  3468. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  3469. spaces++;
  3470. }
  3471. }
  3472. if (spaces > tabs) {
  3473. env->tabs = 0;
  3474. } else if (spaces == tabs && env->syntax) {
  3475. env->tabs = env->syntax->prefers_spaces;
  3476. }
  3477. if (spaces > tabs) {
  3478. int one = 0, two = 0, three = 0, four = 0; /* If you use more than that, I don't like you. */
  3479. int lastCount = 0;
  3480. for (int i = 0; i < env->line_count; ++i) {
  3481. if (env->lines[i]->actual > 1 && !line_is_comment(env->lines[i])) {
  3482. /* Count spaces at beginning */
  3483. int c = 0, diff = 0;
  3484. while (c < env->lines[i]->actual && env->lines[i]->text[c].codepoint == ' ') c++;
  3485. if (c > lastCount) {
  3486. diff = c - lastCount;
  3487. } else if (c < lastCount) {
  3488. diff = lastCount - c;
  3489. }
  3490. if (diff == 1) one++;
  3491. if (diff == 2) two++;
  3492. if (diff == 3) three++;
  3493. if (diff == 4) four++;
  3494. lastCount = c;
  3495. }
  3496. }
  3497. if (four > three && four > two && four > one) {
  3498. env->tabstop = 4;
  3499. } else if (three > two && three > one) {
  3500. env->tabstop = 3;
  3501. } else if (two > one) {
  3502. env->tabstop = 2;
  3503. } else {
  3504. env->tabstop = 1;
  3505. }
  3506. }
  3507. env->loading = 0;
  3508. if (global_config.check_git) {
  3509. env->checkgitstatusonwrite = 1;
  3510. git_examine(file);
  3511. }
  3512. for (int i = 0; i < env->line_count; ++i) {
  3513. recalculate_tabs(env->lines[i]);
  3514. }
  3515. if (global_config.go_to_line) {
  3516. if (init_line != -1) {
  3517. goto_line(init_line);
  3518. } else {
  3519. env->line_no = 1;
  3520. env->col_no = 1;
  3521. fetch_from_biminfo(env);
  3522. place_cursor_actual();
  3523. redraw_all();
  3524. set_preferred_column();
  3525. }
  3526. }
  3527. update_biminfo(env, 1);
  3528. fclose(f);
  3529. run_onload(env);
  3530. }
  3531. /**
  3532. * Clean up the terminal and exit the editor.
  3533. */
  3534. void quit(const char * message) {
  3535. mouse_disable();
  3536. set_buffered();
  3537. reset();
  3538. clear_screen();
  3539. show_cursor();
  3540. unset_bracketed_paste();
  3541. unset_alternate_screen();
  3542. krk_freeVM();
  3543. if (message) {
  3544. fprintf(stdout, "%s\n", message);
  3545. }
  3546. exit(0);
  3547. }
  3548. /**
  3549. * Try to quit, but don't continue if there are
  3550. * modified buffers open.
  3551. */
  3552. void try_quit(void) {
  3553. for (int i = 0; i < buffers_len; i++ ) {
  3554. buffer_t * _env = buffers[i];
  3555. if (_env->modified) {
  3556. if (_env->file_name) {
  3557. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  3558. } else {
  3559. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  3560. }
  3561. return;
  3562. }
  3563. }
  3564. /* Close all buffers */
  3565. while (buffers_len) {
  3566. buffer_close(buffers[0]);
  3567. }
  3568. quit(NULL);
  3569. }
  3570. /**
  3571. * Switch to the previous buffer
  3572. */
  3573. BIM_ACTION(previous_tab, 0,
  3574. "Switch the previous tab"
  3575. )(void) {
  3576. buffer_t * last = NULL;
  3577. for (int i = 0; i < buffers_len; i++) {
  3578. buffer_t * _env = buffers[i];
  3579. if (_env == env) {
  3580. if (last) {
  3581. /* Wrap around */
  3582. env = last;
  3583. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3584. redraw_all();
  3585. update_title();
  3586. return;
  3587. } else {
  3588. env = buffers[buffers_len-1];
  3589. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3590. redraw_all();
  3591. update_title();
  3592. return;
  3593. }
  3594. }
  3595. last = _env;
  3596. }
  3597. }
  3598. /**
  3599. * Switch to the next buffer
  3600. */
  3601. BIM_ACTION(next_tab, 0,
  3602. "Switch to the next tab"
  3603. )(void) {
  3604. for (int i = 0; i < buffers_len; i++) {
  3605. buffer_t * _env = buffers[i];
  3606. if (_env == env) {
  3607. if (i != buffers_len - 1) {
  3608. env = buffers[i+1];
  3609. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3610. redraw_all();
  3611. update_title();
  3612. return;
  3613. } else {
  3614. /* Wrap around */
  3615. env = buffers[0];
  3616. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3617. redraw_all();
  3618. update_title();
  3619. return;
  3620. }
  3621. }
  3622. }
  3623. }
  3624. /**
  3625. * Check for modified lines in a file by examining `git diff` output.
  3626. * This can be enabled globally in bimrc or per environment with the 'git' option.
  3627. */
  3628. int git_examine(char * filename) {
  3629. if (env->modified) return 1;
  3630. int fds[2];
  3631. pipe(fds);
  3632. int child = fork();
  3633. if (child == 0) {
  3634. FILE * dev_null = fopen("/dev/null","w");
  3635. close(fds[0]);
  3636. dup2(fds[1], STDOUT_FILENO);
  3637. dup2(fileno(dev_null), STDERR_FILENO);
  3638. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  3639. exit(execvp("git",args));
  3640. } else if (child < 0) {
  3641. return 1;
  3642. }
  3643. close(fds[1]);
  3644. FILE * f = fdopen(fds[0],"r");
  3645. int line_offset = 0;
  3646. while (!feof(f)) {
  3647. int c = fgetc(f);
  3648. if (c < 0) break;
  3649. if (c == '@' && line_offset == 0) {
  3650. /* Read line offset, count */
  3651. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  3652. /* This algorithm is borrowed from Kakoune and only requires us to parse the @@ line */
  3653. int from_line = 0;
  3654. int from_count = 0;
  3655. int to_line = 0;
  3656. int to_count = 0;
  3657. fscanf(f,"%d",&from_line);
  3658. if (fgetc(f) == ',') {
  3659. fscanf(f,"%d",&from_count);
  3660. } else {
  3661. from_count = 1;
  3662. }
  3663. fscanf(f,"%d",&to_line);
  3664. if (fgetc(f) == ',') {
  3665. fscanf(f,"%d",&to_count);
  3666. } else {
  3667. to_count = 1;
  3668. }
  3669. if (to_line > env->line_count) continue;
  3670. if (from_count == 0 && to_count > 0) {
  3671. /* No -, all + means all of to_count is green */
  3672. for (int i = 0; i < to_count; ++i) {
  3673. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3674. }
  3675. } else if (from_count > 0 && to_count == 0) {
  3676. /*
  3677. * No +, all - means we have a deletion. We mark the next line such that it has a red bar at the top
  3678. * Note that to_line is one lower than the affected line, so we don't need to mess with indexes.
  3679. */
  3680. if (to_line >= env->line_count) continue;
  3681. env->lines[to_line]->rev_status = 4; /* Red */
  3682. } else if (from_count > 0 && from_count == to_count) {
  3683. /* from = to, all modified */
  3684. for (int i = 0; i < to_count; ++i) {
  3685. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3686. }
  3687. } else if (from_count > 0 && from_count < to_count) {
  3688. /* from < to, some modified, some added */
  3689. for (int i = 0; i < from_count; ++i) {
  3690. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3691. }
  3692. for (int i = from_count; i < to_count; ++i) {
  3693. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3694. }
  3695. } else if (to_count > 0 && from_count > to_count) {
  3696. /* from > to, we deleted but also modified some lines */
  3697. env->lines[to_line-1]->rev_status = 5; /* Red + Blue */
  3698. for (int i = 1; i < to_count; ++i) {
  3699. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3700. }
  3701. }
  3702. }
  3703. }
  3704. if (c == '\n') {
  3705. line_offset = 0;
  3706. continue;
  3707. }
  3708. line_offset++;
  3709. }
  3710. fclose(f);
  3711. waitpid(-1,NULL,WNOHANG);
  3712. return 0;
  3713. }
  3714. /**
  3715. * Write file contents to FILE
  3716. */
  3717. void output_file(buffer_t * env, FILE * f) {
  3718. int i, j;
  3719. for (i = 0; i < env->line_count; ++i) {
  3720. line_t * line = env->lines[i];
  3721. line->rev_status = 0;
  3722. for (j = 0; j < line->actual; j++) {
  3723. char_t c = line->text[j];
  3724. if (c.codepoint == 0) {
  3725. char buf[1] = {0};
  3726. fwrite(buf, 1, 1, f);
  3727. } else {
  3728. char tmp[8] = {0};
  3729. int i = to_eight(c.codepoint, tmp);
  3730. fwrite(tmp, i, 1, f);
  3731. }
  3732. }
  3733. if (env->crnl) fputc('\r', f);
  3734. fputc('\n', f);
  3735. }
  3736. }
  3737. /**
  3738. * Write active buffer to file
  3739. */
  3740. void write_file(char * file) {
  3741. if (!file) {
  3742. render_error("Need a file to write to.");
  3743. return;
  3744. }
  3745. char * _file = file;
  3746. if (file[0] == '~') {
  3747. char * home = getenv("HOME");
  3748. if (home) {
  3749. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3750. sprintf(_file, "%s%s", home, file+1);
  3751. }
  3752. }
  3753. FILE * f = fopen(_file, "w+");
  3754. if (file != _file) free(_file);
  3755. if (!f) {
  3756. render_error("Failed to open file for writing.");
  3757. return;
  3758. }
  3759. /* Go through each line and convert it back to UTF-8 */
  3760. output_file(env, f);
  3761. fclose(f);
  3762. /* Mark it no longer modified */
  3763. env->modified = 0;
  3764. env->last_save_history = env->history;
  3765. /* If there was no file name set, set one */
  3766. if (!env->file_name) {
  3767. env->file_name = malloc(strlen(file) + 1);
  3768. memcpy(env->file_name, file, strlen(file) + 1);
  3769. }
  3770. if (env->checkgitstatusonwrite) {
  3771. git_examine(file);
  3772. }
  3773. update_title();
  3774. redraw_all();
  3775. }
  3776. /**
  3777. * Close the active buffer
  3778. */
  3779. void close_buffer(void) {
  3780. buffer_t * previous_env = env;
  3781. buffer_t * new_env = buffer_close(env);
  3782. if (new_env == previous_env) {
  3783. /* ?? Failed to close buffer */
  3784. render_error("lolwat");
  3785. }
  3786. if (left_buffer && env == left_buffer) {
  3787. left_buffer = NULL;
  3788. right_buffer->left = 0;
  3789. right_buffer->width = global_config.term_width;
  3790. right_buffer = NULL;
  3791. } else if (left_buffer && env == right_buffer) {
  3792. right_buffer = NULL;
  3793. left_buffer->left = 0;
  3794. left_buffer->width = global_config.term_width;
  3795. left_buffer = NULL;
  3796. }
  3797. /* No more buffers, exit */
  3798. if (!new_env) {
  3799. quit(NULL);
  3800. }
  3801. /* Set the new active buffer */
  3802. env = new_env;
  3803. /* Redraw the screen */
  3804. redraw_all();
  3805. update_title();
  3806. }
  3807. /**
  3808. * Set the visual column the cursor should attempt to keep
  3809. * when moving up and down based on where the cursor currently is.
  3810. * This should happen whenever the user intentionally changes
  3811. * the cursor's horizontal positioning, such as with left/right
  3812. * arrow keys, word-move, search, mouse, etc.
  3813. */
  3814. void set_preferred_column(void) {
  3815. int c = 0;
  3816. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  3817. c += env->lines[env->line_no-1]->text[i].display_width;
  3818. }
  3819. env->preferred_column = c;
  3820. }
  3821. BIM_ACTION(cursor_down, 0,
  3822. "Move the cursor one line down."
  3823. )(void) {
  3824. /* If this isn't already the last line... */
  3825. if (env->line_no < env->line_count) {
  3826. /* Move the cursor down */
  3827. env->line_no += 1;
  3828. /* Try to place the cursor horizontally at the preferred column */
  3829. int _x = 0;
  3830. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3831. char_t * c = &env->lines[env->line_no-1]->text[i];
  3832. _x += c->display_width;
  3833. env->col_no = i+1;
  3834. if (_x > env->preferred_column) {
  3835. break;
  3836. }
  3837. }
  3838. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3839. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3840. }
  3841. /*
  3842. * If the horizontal cursor position exceeds the width the new line,
  3843. * then move the cursor left to the extent of the new line.
  3844. *
  3845. * If we're in insert mode, we can go one cell beyond the end of the line
  3846. */
  3847. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3848. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3849. if (env->col_no == 0) env->col_no = 1;
  3850. }
  3851. if (env->loading) return;
  3852. /*
  3853. * If the screen was scrolled horizontally, unscroll it;
  3854. * if it will be scrolled on this line as well, that will
  3855. * be handled by place_cursor_actual
  3856. */
  3857. int redraw = 0;
  3858. if (env->coffset != 0) {
  3859. env->coffset = 0;
  3860. redraw = 1;
  3861. }
  3862. /* If we've scrolled past the bottom of the screen, scroll the screen */
  3863. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  3864. env->offset += 1;
  3865. /* Tell terminal to scroll */
  3866. if (global_config.can_scroll && !left_buffer) {
  3867. if (!global_config.can_insert) {
  3868. shift_up(1);
  3869. redraw_tabbar();
  3870. } else {
  3871. delete_lines_at(global_config.tabs_visible ? 2 : 1, 1);
  3872. }
  3873. /* A new line appears on screen at the bottom, draw it */
  3874. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  3875. if (env->offset + l < env->line_count + 1) {
  3876. redraw_line(env->offset + l-1);
  3877. } else {
  3878. draw_excess_line(l - 1);
  3879. }
  3880. } else {
  3881. redraw_text();
  3882. }
  3883. redraw_statusbar();
  3884. redraw_commandline();
  3885. place_cursor_actual();
  3886. return;
  3887. } else if (redraw) {
  3888. /* Otherwise, if we need to redraw because of coffset change, do that */
  3889. redraw_text();
  3890. }
  3891. set_history_break();
  3892. /* Update the status bar */
  3893. redraw_statusbar();
  3894. /* Place the terminal cursor again */
  3895. place_cursor_actual();
  3896. }
  3897. }
  3898. BIM_ACTION(cursor_up, 0,
  3899. "Move the cursor up one line."
  3900. )(void) {
  3901. /* If this isn't the first line already */
  3902. if (env->line_no > 1) {
  3903. /* Move the cursor down */
  3904. env->line_no -= 1;
  3905. /* Try to place the cursor horizontally at the preferred column */
  3906. int _x = 0;
  3907. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3908. char_t * c = &env->lines[env->line_no-1]->text[i];
  3909. _x += c->display_width;
  3910. env->col_no = i+1;
  3911. if (_x > env->preferred_column) {
  3912. break;
  3913. }
  3914. }
  3915. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3916. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3917. }
  3918. /*
  3919. * If the horizontal cursor position exceeds the width the new line,
  3920. * then move the cursor left to the extent of the new line.
  3921. *
  3922. * If we're in insert mode, we can go one cell beyond the end of the line
  3923. */
  3924. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3925. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3926. if (env->col_no == 0) env->col_no = 1;
  3927. }
  3928. if (env->loading) return;
  3929. /*
  3930. * If the screen was scrolled horizontally, unscroll it;
  3931. * if it will be scrolled on this line as well, that will
  3932. * be handled by place_cursor_actual
  3933. */
  3934. int redraw = 0;
  3935. if (env->coffset != 0) {
  3936. env->coffset = 0;
  3937. redraw = 1;
  3938. }
  3939. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  3940. if (env->line_no <= e) {
  3941. env->offset -= 1;
  3942. /* Tell terminal to scroll */
  3943. if (global_config.can_scroll && !left_buffer) {
  3944. if (!global_config.can_insert) {
  3945. shift_down(1);
  3946. redraw_tabbar();
  3947. } else {
  3948. insert_lines_at(global_config.tabs_visible ? 2 : 1, 1);
  3949. }
  3950. /*
  3951. * The line at the top of the screen should always be real
  3952. * so we can just call redraw_line here
  3953. */
  3954. redraw_line(env->offset);
  3955. } else {
  3956. redraw_tabbar();
  3957. redraw_text();
  3958. }
  3959. redraw_statusbar();
  3960. redraw_commandline();
  3961. place_cursor_actual();
  3962. return;
  3963. } else if (redraw) {
  3964. /* Otherwise, if we need to redraw because of coffset change, do that */
  3965. redraw_text();
  3966. }
  3967. set_history_break();
  3968. /* Update the status bar */
  3969. redraw_statusbar();
  3970. /* Place the terminal cursor again */
  3971. place_cursor_actual();
  3972. }
  3973. }
  3974. BIM_ACTION(cursor_left, 0,
  3975. "Move the cursor one character to the left."
  3976. )(void) {
  3977. if (env->col_no > 1) {
  3978. env->col_no -= 1;
  3979. /* Update the status bar */
  3980. redraw_statusbar();
  3981. /* Place the terminal cursor again */
  3982. place_cursor_actual();
  3983. }
  3984. set_history_break();
  3985. set_preferred_column();
  3986. }
  3987. BIM_ACTION(cursor_right, 0,
  3988. "Move the cursor one character to the right."
  3989. )(void) {
  3990. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  3991. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  3992. env->col_no += 1;
  3993. /* Update the status bar */
  3994. redraw_statusbar();
  3995. /* Place the terminal cursor again */
  3996. place_cursor_actual();
  3997. }
  3998. set_history_break();
  3999. set_preferred_column();
  4000. }
  4001. BIM_ACTION(cursor_home, 0,
  4002. "Move the cursor to the beginning of the line."
  4003. )(void) {
  4004. env->col_no = 1;
  4005. set_history_break();
  4006. set_preferred_column();
  4007. /* Update the status bar */
  4008. redraw_statusbar();
  4009. /* Place the terminal cursor again */
  4010. place_cursor_actual();
  4011. }
  4012. BIM_ACTION(cursor_end, 0,
  4013. "Move the cursor to the end of the line, or past the end in insert mode."
  4014. )(void) {
  4015. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  4016. set_history_break();
  4017. set_preferred_column();
  4018. /* Update the status bar */
  4019. redraw_statusbar();
  4020. /* Place the terminal cursor again */
  4021. place_cursor_actual();
  4022. }
  4023. BIM_ACTION(leave_insert, 0,
  4024. "Leave insert modes and return to normal mode."
  4025. )(void) {
  4026. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4027. env->col_no = env->lines[env->line_no-1]->actual;
  4028. if (env->col_no == 0) env->col_no = 1;
  4029. set_preferred_column();
  4030. }
  4031. set_history_break();
  4032. env->mode = MODE_NORMAL;
  4033. redraw_commandline();
  4034. }
  4035. struct MatchQualifier {
  4036. int (*matchFunc)(struct MatchQualifier*,uint32_t,int);
  4037. union {
  4038. uint32_t matchChar;
  4039. struct {
  4040. uint32_t * start;
  4041. uint32_t * end;
  4042. } matchSquares;
  4043. };
  4044. };
  4045. /**
  4046. * Helper for handling smart case sensitivity.
  4047. */
  4048. int match_char(struct MatchQualifier * self, uint32_t b, int mode) {
  4049. if (mode == 0) {
  4050. return self->matchChar == b;
  4051. } else if (mode == 1) {
  4052. return tolower(self->matchChar) == tolower(b);
  4053. }
  4054. return 0;
  4055. }
  4056. int match_squares(struct MatchQualifier * self, uint32_t c, int mode) {
  4057. uint32_t * start = self->matchSquares.start;
  4058. uint32_t * end = self->matchSquares.end;
  4059. uint32_t * t = start;
  4060. int good = 1;
  4061. if (*t == '^') { t++; good = 0; }
  4062. while (t != end) {
  4063. uint32_t test = *t++;
  4064. if (test == '\\' && *t && strchr("\\]",*t)) {
  4065. test = *t++;
  4066. } else if (test == '\\' && *t == 't') {
  4067. test = '\t'; t++;
  4068. }
  4069. if (*t == '-') {
  4070. t++;
  4071. if (t == end) return 0;
  4072. uint32_t right = *t++;
  4073. if (right == '\\' && *t && strchr("\\]",*t)) {
  4074. right = *t++;
  4075. } else if (right == '\\' && *t == 't') {
  4076. right = '\t'; t++;
  4077. }
  4078. if (mode ? (tolower(c) >= tolower(test) && tolower(c) <= tolower(right)) : (c >= test && c <= right)) return good;
  4079. } else {
  4080. if (mode ? (tolower(c) == tolower(test)) : (c == test)) return good;
  4081. }
  4082. }
  4083. return !good;
  4084. }
  4085. int match_dot(struct MatchQualifier * self, uint32_t c, int mode) {
  4086. return 1;
  4087. }
  4088. struct BackRef {
  4089. int start;
  4090. int len;
  4091. uint32_t * copy;
  4092. };
  4093. #define MAX_REFS 10
  4094. int regex_matches(line_t * line, int j, uint32_t * needle, int ignorecase, int *len, uint32_t **needleout, int refindex, struct BackRef * refs) {
  4095. int k = j;
  4096. uint32_t * match = needle;
  4097. if (*match == '^') {
  4098. if (j != 0) return 0;
  4099. match++;
  4100. }
  4101. while (k < line->actual + 1) {
  4102. if (needleout && *match == ')') {
  4103. *needleout = match + 1;
  4104. if (len) *len = k - j;
  4105. return 1;
  4106. }
  4107. if (*match == '\0') {
  4108. if (needleout) return 0;
  4109. if (len) *len = k - j;
  4110. return 1;
  4111. }
  4112. if (*match == '$') {
  4113. if (k != line->actual) return 0;
  4114. match++;
  4115. continue;
  4116. }
  4117. if (k == line->actual) break;
  4118. struct MatchQualifier matcher = {match_char, .matchChar=*match};
  4119. if (*match == '.') {
  4120. matcher.matchFunc = match_dot;
  4121. match++;
  4122. } else if (*match == '\\' && strchr("$^/\\.[?]*+()",match[1]) != NULL) {
  4123. matcher.matchChar = match[1];
  4124. match += 2;
  4125. } else if (*match == '\\' && match[1] == 't') {
  4126. matcher.matchChar = '\t';
  4127. match += 2;
  4128. } else if (*match == '[') {
  4129. uint32_t * s = match+1;
  4130. uint32_t * e = s;
  4131. while (*e && *e != ']') {
  4132. if (*e == '\\' && e[1] == ']') e++;
  4133. e++;
  4134. }
  4135. if (!*e) break; /* fail match on unterminated [] sequence */
  4136. match = e + 1;
  4137. matcher.matchFunc = match_squares;
  4138. matcher.matchSquares.start = s;
  4139. matcher.matchSquares.end = e;
  4140. } else if (*match == '(') {
  4141. match++;
  4142. int _len;
  4143. uint32_t * newmatch;
  4144. if (!regex_matches(line, k, match, ignorecase, &_len, &newmatch, 0, NULL)) break;
  4145. match = newmatch;
  4146. if (refindex && refindex < MAX_REFS) {
  4147. refs[refindex].start = k;
  4148. refs[refindex].len = _len;
  4149. refindex++;
  4150. }
  4151. k += _len;
  4152. continue;
  4153. } else {
  4154. match++;
  4155. }
  4156. if (*match == '?') {
  4157. /* Optional */
  4158. match++;
  4159. if (matcher.matchFunc(&matcher, line->text[k].codepoint, ignorecase)) {
  4160. int _len;
  4161. if (regex_matches(line,k+1,match,ignorecase,&_len, needleout, refindex, refs)) {
  4162. if (len) *len = _len + k + 1 - j;
  4163. return 1;
  4164. }
  4165. }
  4166. continue;
  4167. } else if (*match == '+' || *match == '*') {
  4168. /* Must match at least one */
  4169. if (*match == '+') {
  4170. if (!matcher.matchFunc(&matcher, line->text[k].codepoint, ignorecase)) break;
  4171. k++;
  4172. }
  4173. /* Match any */
  4174. match++;
  4175. int greedy = 1;
  4176. if (*match == '?') {
  4177. /* non-greedy */
  4178. match++;
  4179. greedy = 0;
  4180. }
  4181. int _j = k;
  4182. while (_j < line->actual + 1) {
  4183. int _len;
  4184. if (!greedy && regex_matches(line, _j, match, ignorecase, &_len, needleout, refindex, refs)) {
  4185. if (len) *len = _len + _j - j;
  4186. return 1;
  4187. }
  4188. if (_j < line->actual && !matcher.matchFunc(&matcher, line->text[_j].codepoint, ignorecase)) break;
  4189. _j++;
  4190. }
  4191. if (!greedy) return 0;
  4192. while (_j >= k) {
  4193. int _len;
  4194. if (regex_matches(line, _j, match, ignorecase, &_len, needleout, refindex, refs)) {
  4195. if (len) *len = _len + _j - j;
  4196. return 1;
  4197. }
  4198. _j--;
  4199. }
  4200. return 0;
  4201. } else {
  4202. if (!matcher.matchFunc(&matcher, line->text[k].codepoint, ignorecase)) break;
  4203. k++;
  4204. }
  4205. }
  4206. return 0;
  4207. }
  4208. int subsearch_matches(line_t * line, int j, uint32_t * needle, int ignorecase, int *len) {
  4209. return regex_matches(line, j, needle, ignorecase, len, NULL, 0, NULL);
  4210. }
  4211. /**
  4212. * Replace text on a given line with other text.
  4213. */
  4214. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col, int *line_out) {
  4215. line_t * line = env->lines[line_no-1];
  4216. int j = col;
  4217. while (j < line->actual + 1) {
  4218. int match_len;
  4219. struct BackRef refs[MAX_REFS] = {0};
  4220. if (regex_matches(line,j,needle,ignorecase,&match_len,NULL,1,refs)) {
  4221. refs[0].start = j;
  4222. refs[0].len = match_len;
  4223. for (int i = 0; i < MAX_REFS; ++i) {
  4224. refs[i].copy = malloc(sizeof(uint32_t) * refs[i].len);
  4225. for (int j = 0; j < refs[i].len; ++j) {
  4226. refs[i].copy[j] = line->text[j+refs[i].start].codepoint;
  4227. }
  4228. }
  4229. /* Perform replacement */
  4230. for (int i = 0; i < match_len; ++i) {
  4231. line_delete(line, j+1, line_no-1);
  4232. }
  4233. int t = 0;
  4234. for (uint32_t * r = replacement; *r; ++r) {
  4235. uint32_t rep = *r;
  4236. char_t _c;
  4237. _c.flags = 0;
  4238. line_t * nline = line;
  4239. if (*r == '\\' && r[1] == 't') {
  4240. rep = '\t';
  4241. ++r;
  4242. } else if (*r == '\\' && (r[1] == '\\')) {
  4243. rep = r[1];
  4244. ++r;
  4245. } else if (*r == '\\' && (r[1] >= '0' && r[1] <= '9')) {
  4246. int i = r[1] - '0';
  4247. ++r;
  4248. nline = line;
  4249. for (int k = 0; k < refs[i].len; ++k) {
  4250. _c.codepoint = refs[i].copy[k];
  4251. _c.display_width = codepoint_width(refs[i].copy[k]);
  4252. nline = line_insert(nline, _c, j + t + k, line_no -1);
  4253. }
  4254. t += refs[i].len;
  4255. rep = 0;
  4256. } else if (*r == '\\' && (r[1] == 'n')) {
  4257. ++r;
  4258. env->lines = split_line(env->lines, line_no - 1, j + t);
  4259. line_no++;
  4260. line = env->lines[line_no-1];
  4261. j = 0;
  4262. t = 0;
  4263. continue;
  4264. }
  4265. if (rep) {
  4266. _c.codepoint = rep;
  4267. _c.display_width = codepoint_width(rep);
  4268. nline = line_insert(nline, _c, j + t, line_no -1);
  4269. t++;
  4270. }
  4271. if (line != nline) {
  4272. env->lines[line_no-1] = nline;
  4273. line = nline;
  4274. }
  4275. }
  4276. *out_col = j + t;
  4277. *line_out = line_no;
  4278. set_modified();
  4279. for (int i = 0; i < MAX_REFS; ++i) {
  4280. free(refs[i].copy);
  4281. }
  4282. return;
  4283. }
  4284. j++;
  4285. }
  4286. *out_col = -1;
  4287. }
  4288. #define COMMAND_HISTORY_MAX 255
  4289. unsigned char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  4290. unsigned char * search_history[COMMAND_HISTORY_MAX] = {NULL};
  4291. /**
  4292. * Add a command to the history. If that command was
  4293. * already in history, it is moved to the front of the list;
  4294. * otherwise, the whole list is shifted backwards and
  4295. * overflow is freed up.
  4296. */
  4297. void insert_command_history(unsigned char ** which_history, char * cmd) {
  4298. /* See if this is already in the history. */
  4299. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  4300. for (int i = 0; i < COMMAND_HISTORY_MAX && which_history[i]; ++i) {
  4301. if (!strcmp((char*)which_history[i], cmd)) {
  4302. free(which_history[i]);
  4303. amount_to_shift = i;
  4304. break;
  4305. }
  4306. }
  4307. /* Remove last entry that will roll off the stack */
  4308. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  4309. if (which_history[COMMAND_HISTORY_MAX-1]) free(which_history[COMMAND_HISTORY_MAX-1]);
  4310. }
  4311. /* Roll the history */
  4312. memmove(&which_history[1], &which_history[0], sizeof(char *) * (amount_to_shift));
  4313. which_history[0] = (unsigned char*)strdup(cmd);
  4314. }
  4315. static uint32_t term_colors[] = {
  4316. 0x000000, 0xcc0000, 0x3e9a06, 0xc4a000, 0x3465a4, 0x75507b, 0x06989a, 0xeeeeec, 0x555753, 0xef2929, 0x8ae234, 0xfce94f, 0x729fcf, 0xad7fa8, 0x34e2e2,
  4317. 0xFFFFFF, 0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff, 0x008700, 0x00875f,
  4318. 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff, 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7,
  4319. 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f,
  4320. 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, 0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7,
  4321. 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff, 0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f,
  4322. 0x870087, 0x8700af, 0x8700d7, 0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, 0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7,
  4323. 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f,
  4324. 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7,
  4325. 0xaf5fff, 0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff, 0xafd700, 0xafd75f,
  4326. 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff, 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7,
  4327. 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, 0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f,
  4328. 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, 0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7,
  4329. 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff, 0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f,
  4330. 0xff8787, 0xff87af, 0xff87d7, 0xff87ff, 0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7,
  4331. 0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e,
  4332. 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2, 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4,
  4333. 0xeeeeee,
  4334. };
  4335. /**
  4336. * Convert a color setting from terminal format
  4337. * to a hexadecimal color code and add it to the current
  4338. * buffer. This is used for HTML conversion, but could
  4339. * possibly be used for other purposes.
  4340. */
  4341. static void html_convert_color(const char * color_string) {
  4342. char tmp[100];
  4343. if (!strncmp(color_string,"2;",2)) {
  4344. /* 24-bit color */
  4345. int red, green, blue;
  4346. sscanf(color_string+2,"%d;%d;%d",&red,&green,&blue);
  4347. sprintf(tmp, "#%02x%02x%02x;", red,green,blue);
  4348. } else if (!strncmp(color_string,"5;",2)) {
  4349. /* 256 colors; needs lookup table */
  4350. int index;
  4351. sscanf(color_string+2,"%d",&index);
  4352. sprintf(tmp,"#%06x;", (unsigned int)term_colors[(index >= 0 && index <= 255) ? index : 0]);
  4353. } else {
  4354. /* 16 colors; needs lookup table */
  4355. int index;
  4356. uint32_t color;
  4357. sscanf(color_string+1,"%d",&index);
  4358. if (index >= 10) {
  4359. index -= 10;
  4360. color = term_colors[index+8];
  4361. } else if (index == 9) {
  4362. color = term_colors[0];
  4363. } else {
  4364. color = term_colors[index];
  4365. }
  4366. sprintf(tmp,"#%06x;", (unsigned int)color);
  4367. }
  4368. add_string(tmp);
  4369. char * italic = strstr(color_string,";3");
  4370. if (italic && italic[2] == '\0') {
  4371. add_string(" font-style: oblique;");
  4372. }
  4373. char * bold = strstr(color_string,";1");
  4374. if (bold && bold[2] == '\0') {
  4375. add_string(" font-weight: bold;");
  4376. }
  4377. char * underline = strstr(color_string,";4");
  4378. if (underline && underline[2] == '\0') {
  4379. add_string(" font-decoration: underline;");
  4380. }
  4381. }
  4382. int convert_to_html(void) {
  4383. buffer_t * old = env;
  4384. env = buffer_new();
  4385. setup_buffer(env);
  4386. env->loading = 1;
  4387. add_string("<!doctype html>\n");
  4388. add_string("<html>\n");
  4389. add_string(" <head>\n");
  4390. add_string(" <meta charset=\"UTF-8\">\n");
  4391. if (old->file_name) {
  4392. add_string(" <title>");
  4393. add_string(file_basename(old->file_name));
  4394. add_string("</title>\n");
  4395. }
  4396. add_string(" <style>\n");
  4397. add_string(" body {\n");
  4398. add_string(" margin: 0;\n");
  4399. add_string(" -webkit-text-size-adjust: none;\n");
  4400. add_string(" counter-reset: line-no;\n");
  4401. add_string(" background-color: ");
  4402. /* Convert color */
  4403. html_convert_color(COLOR_BG);
  4404. add_string("\n");
  4405. add_string(" }\n");
  4406. add_string(" .ul { text-decoration: underline; }\n");
  4407. for (int i = 0; i < 15; ++i) {
  4408. /* For each of the relevant flags... */
  4409. char tmp[20];
  4410. sprintf(tmp," .s%d { color: ", i);
  4411. add_string(tmp);
  4412. /* These are special */
  4413. if (i == FLAG_NOTICE) {
  4414. html_convert_color(COLOR_SEARCH_FG);
  4415. add_string(" background-color: ");
  4416. html_convert_color(COLOR_SEARCH_BG);
  4417. } else if (i == FLAG_ERROR) {
  4418. html_convert_color(COLOR_ERROR_FG);
  4419. add_string(" background-color: ");
  4420. html_convert_color(COLOR_ERROR_BG);
  4421. } else {
  4422. html_convert_color(flag_to_color(i));
  4423. }
  4424. add_string("}\n");
  4425. }
  4426. add_string(" pre {\n");
  4427. add_string(" margin: 0;\n");
  4428. add_string(" white-space: pre-wrap;\n");
  4429. add_string(" font-family: \"DejaVu Sans Mono\", Courier, monospace;\n");
  4430. add_string(" font-size: 10pt;\n");
  4431. add_string(" }\n");
  4432. add_string(" pre>span {\n");
  4433. add_string(" display: inline-block;\n");
  4434. add_string(" width: 100%;\n");
  4435. add_string(" }\n");
  4436. add_string(" pre>span>a::before {\n");
  4437. add_string(" counter-increment: line-no;\n");
  4438. add_string(" content: counter(line-no);\n");
  4439. add_string(" padding-right: 1em;\n");
  4440. add_string(" width: 3em;\n");
  4441. add_string(" display: inline-block;\n");
  4442. add_string(" text-align: right;\n");
  4443. add_string(" background-color: ");
  4444. html_convert_color(COLOR_NUMBER_BG);
  4445. add_string("\n");
  4446. add_string(" color: ");
  4447. html_convert_color(COLOR_NUMBER_FG);
  4448. add_string("\n");
  4449. add_string(" }\n");
  4450. add_string(" pre>span:target {\n");
  4451. add_string(" background-color: ");
  4452. html_convert_color(COLOR_ALT_BG);
  4453. add_string("\n");
  4454. add_string(" }\n");
  4455. add_string(" pre>span:target>a::before {\n");
  4456. add_string(" background-color: ");
  4457. html_convert_color(COLOR_NUMBER_FG);
  4458. add_string("\n");
  4459. add_string(" color: ");
  4460. html_convert_color(COLOR_NUMBER_BG);
  4461. add_string("\n");
  4462. add_string(" }\n");
  4463. for (int i = 1; i <= env->tabstop; ++i) {
  4464. char tmp[20];
  4465. sprintf(tmp, ".tab%d", i);
  4466. add_string(" ");
  4467. add_string(tmp);
  4468. add_string(">span {\n");
  4469. add_string(" display: inline-block;\n");
  4470. add_string(" overflow: hidden;\n");
  4471. add_string(" width: 0;\n");
  4472. add_string(" height: 0;\n");
  4473. add_string(" }\n");
  4474. add_string(" ");
  4475. add_string(tmp);
  4476. add_string("::after {\n");
  4477. add_string(" content: '»");
  4478. for (int j = 1; j < i; ++j) {
  4479. add_string("·");
  4480. }
  4481. add_string("';\n");
  4482. add_string(" background-color: ");
  4483. html_convert_color(COLOR_ALT_BG);
  4484. add_string("\n");
  4485. add_string(" color: ");
  4486. html_convert_color(COLOR_ALT_FG);
  4487. add_string("\n");
  4488. add_string(" }\n");
  4489. }
  4490. add_string(" .space {\n");
  4491. add_string(" border-left: 1px solid ");
  4492. html_convert_color(COLOR_ALT_FG);
  4493. add_string("\n");
  4494. add_string(" margin-left: -1px;\n");
  4495. add_string(" }\n");
  4496. add_string(" </style>\n");
  4497. add_string(" </head>\n");
  4498. add_string(" <body><pre>\n");
  4499. for (int i = 0; i < old->line_count; ++i) {
  4500. char tmp[100];
  4501. sprintf(tmp, "<span id=\"L%d\"><a href=\"#L%d\"></a>", i+1, i+1);
  4502. add_string(tmp);
  4503. int last_flag = -1;
  4504. int opened = 0;
  4505. int all_spaces = 1;
  4506. for (int j = 0; j < old->lines[i]->actual; ++j) {
  4507. char_t c = old->lines[i]->text[j];
  4508. if (c.codepoint != ' ') all_spaces = 0;
  4509. if (last_flag == -1 || last_flag != (c.flags & 0x1F)) {
  4510. if (opened) add_string("</span>");
  4511. opened = 1;
  4512. char tmp[100];
  4513. sprintf(tmp, "<span class=\"s%d%s\">",
  4514. c.flags & FLAG_MASK_COLORS,
  4515. (c.flags & FLAG_UNDERLINE) ? " ul" : "");
  4516. add_string(tmp);
  4517. last_flag = (c.flags & 0x1F);
  4518. }
  4519. if (c.codepoint == '<') {
  4520. add_string("&lt;");
  4521. } else if (c.codepoint == '>') {
  4522. add_string("&gt;");
  4523. } else if (c.codepoint == '&') {
  4524. add_string("&amp;");
  4525. } else if (c.codepoint == '\t') {
  4526. char tmp[100];
  4527. sprintf(tmp, "<span class=\"tab%d\"><span> </span></span>",c.display_width);
  4528. add_string(tmp);
  4529. } else if (j > 0 && c.codepoint == ' ' && all_spaces && !(j % old->tabstop)) {
  4530. add_string("<span class=\"space\"> </span>");
  4531. } else {
  4532. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  4533. to_eight(c.codepoint, tmp);
  4534. add_string(tmp);
  4535. }
  4536. }
  4537. if (opened) {
  4538. add_string("</span>");
  4539. } else {
  4540. add_string("<wbr>");
  4541. }
  4542. add_string("</span>\n");
  4543. }
  4544. add_string("</pre></body>\n");
  4545. add_string("</html>\n");
  4546. env->loading = 0;
  4547. env->modified = 1;
  4548. if (old->file_name) {
  4549. char * base = file_basename(old->file_name);
  4550. char * tmp = malloc(strlen(base) + 5);
  4551. *tmp = '\0';
  4552. strcat(tmp, base);
  4553. strcat(tmp, ".htm");
  4554. env->file_name = tmp;
  4555. }
  4556. for (int i = 0; i < env->line_count; ++i) {
  4557. recalculate_tabs(env->lines[i]);
  4558. }
  4559. env->syntax = match_syntax(".htm");
  4560. schedule_complete_recalc();
  4561. return 0;
  4562. }
  4563. /**
  4564. * Based on vim's :TOhtml
  4565. * Convert syntax-highlighted buffer contents to HTML.
  4566. */
  4567. BIM_COMMAND(tohtml,"tohtml","Convert the document to an HTML representation with syntax highlighting.") {
  4568. convert_to_html();
  4569. redraw_all();
  4570. return 0;
  4571. }
  4572. BIM_ALIAS("TOhtml",tohtml,tohtml)
  4573. int _prefix_command_run_script(char * cmd) {
  4574. if (env->mode == MODE_LINE_SELECTION) {
  4575. int range_top, range_bot;
  4576. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4577. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4578. int in[2];
  4579. pipe(in);
  4580. int out[2];
  4581. pipe(out);
  4582. int child = fork();
  4583. /* Open child process and set up pipes */
  4584. if (child == 0) {
  4585. FILE * dev_null = fopen("/dev/null","w"); /* for stderr */
  4586. close(out[0]);
  4587. close(in[1]);
  4588. dup2(out[1], STDOUT_FILENO);
  4589. dup2(in[0], STDIN_FILENO);
  4590. dup2(fileno(dev_null), STDERR_FILENO);
  4591. system(&cmd[1]); /* Yes we can just do this */
  4592. exit(1);
  4593. } else if (child < 0) {
  4594. render_error("Failed to fork");
  4595. return 1;
  4596. }
  4597. close(out[1]);
  4598. close(in[0]);
  4599. /* Write lines to child process */
  4600. FILE * f = fdopen(in[1],"w");
  4601. for (int i = range_top; i <= range_bot; ++i) {
  4602. line_t * line = env->lines[i-1];
  4603. for (int j = 0; j < line->actual; j++) {
  4604. char_t c = line->text[j];
  4605. if (c.codepoint == 0) {
  4606. char buf[1] = {0};
  4607. fwrite(buf, 1, 1, f);
  4608. } else {
  4609. char tmp[8] = {0};
  4610. int i = to_eight(c.codepoint, tmp);
  4611. fwrite(tmp, i, 1, f);
  4612. }
  4613. }
  4614. fputc('\n', f);
  4615. }
  4616. fclose(f);
  4617. close(in[1]);
  4618. /* Read results from child process into a new buffer */
  4619. FILE * result = fdopen(out[0],"r");
  4620. buffer_t * old = env;
  4621. env = buffer_new();
  4622. setup_buffer(env);
  4623. env->loading = 1;
  4624. uint8_t buf[BLOCK_SIZE];
  4625. state = 0;
  4626. while (!feof(result) && !ferror(result)) {
  4627. size_t r = fread(buf, 1, BLOCK_SIZE, result);
  4628. add_buffer(buf, r);
  4629. }
  4630. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  4631. env->lines = remove_line(env->lines, env->line_no-1);
  4632. }
  4633. fclose(result);
  4634. waitpid(-1,NULL,WNOHANG);
  4635. env->loading = 0;
  4636. /* Return to the original buffer and replace the selected lines with the output */
  4637. buffer_t * new = env;
  4638. env = old;
  4639. for (int i = range_top; i <= range_bot; ++i) {
  4640. /* Remove the existing lines */
  4641. env->lines = remove_line(env->lines, range_top-1);
  4642. }
  4643. for (int i = 0; i < new->line_count; ++i) {
  4644. /* Add the new lines */
  4645. env->lines = add_line(env->lines, range_top + i - 1);
  4646. replace_line(env->lines, range_top + i - 1, new->lines[i]);
  4647. recalculate_tabs(env->lines[range_top+i-1]);
  4648. }
  4649. env->modified = 1;
  4650. /* Close the temporary buffer */
  4651. buffer_close(new);
  4652. } else {
  4653. /* Reset and draw some line feeds */
  4654. reset();
  4655. printf("\n\n");
  4656. /* Set buffered for shell application */
  4657. set_buffered();
  4658. /* Call the shell and wait for completion */
  4659. system(&cmd[1]);
  4660. /* Return to the editor, wait for user to press enter. */
  4661. set_unbuffered();
  4662. printf("\n\nPress ENTER to continue.");
  4663. int c;
  4664. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4665. /* Redraw the screen */
  4666. redraw_all();
  4667. }
  4668. /* Done processing command */
  4669. return 0;
  4670. }
  4671. int replace_text(int range_top, int range_bot, char divider, char * needle) {
  4672. char * c = needle;
  4673. char * replacement = NULL;
  4674. char * options = "";
  4675. while (*c) {
  4676. if (*c == divider) {
  4677. *c = '\0';
  4678. replacement = c + 1;
  4679. break;
  4680. }
  4681. c++;
  4682. }
  4683. if (!replacement) {
  4684. render_error("nothing to replace with");
  4685. return 1;
  4686. }
  4687. c = replacement;
  4688. while (*c) {
  4689. if (*c == divider) {
  4690. *c = '\0';
  4691. options = c + 1;
  4692. break;
  4693. }
  4694. c++;
  4695. }
  4696. int global = 0;
  4697. int case_insensitive = 0;
  4698. /* Parse options */
  4699. while (*options) {
  4700. switch (*options) {
  4701. case 'g':
  4702. global = 1;
  4703. break;
  4704. case 'i':
  4705. case_insensitive = 1;
  4706. break;
  4707. }
  4708. options++;
  4709. }
  4710. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4711. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4712. {
  4713. int i = 0;
  4714. uint32_t c, state = 0;
  4715. for (char * cin = needle; *cin; cin++) {
  4716. if (!decode(&state, &c, *cin)) {
  4717. needle_c[i] = c;
  4718. i++;
  4719. } else if (state == UTF8_REJECT) {
  4720. state = 0;
  4721. }
  4722. }
  4723. needle_c[i] = 0;
  4724. i = 0;
  4725. c = 0;
  4726. state = 0;
  4727. for (char * cin = replacement; *cin; cin++) {
  4728. if (!decode(&state, &c, *cin)) {
  4729. replacement_c[i] = c;
  4730. i++;
  4731. } else if (state == UTF8_REJECT) {
  4732. state = 0;
  4733. }
  4734. }
  4735. replacement_c[i] = 0;
  4736. }
  4737. int replacements = 0;
  4738. for (int line = range_top; line <= range_bot; ++line) {
  4739. int col = 0;
  4740. while (col != -1) {
  4741. int _line = line;
  4742. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col, &_line);
  4743. if (col != -1) replacements++;
  4744. if (_line > line) {
  4745. range_bot += _line - line;
  4746. line = _line;
  4747. }
  4748. if (!global) break;
  4749. }
  4750. }
  4751. if (env->mode == MODE_LINE_SELECTION) {
  4752. env->start_line = env->start_line < env->line_no ? range_top : range_bot;
  4753. env->line_no = env->start_line < env->line_no ? range_bot : range_top;
  4754. }
  4755. free(needle_c);
  4756. free(replacement_c);
  4757. if (replacements) {
  4758. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4759. set_history_break();
  4760. redraw_text();
  4761. } else {
  4762. render_error("Pattern not found: %s", needle);
  4763. }
  4764. return 0;
  4765. }
  4766. BIM_PREFIX_COMMAND(repsome,"s","Perform a replacement over selected lines") {
  4767. int range_top, range_bot;
  4768. if (env->mode == MODE_LINE_SELECTION) {
  4769. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4770. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4771. } else {
  4772. range_top = env->line_no;
  4773. range_bot = env->line_no;
  4774. }
  4775. return replace_text(range_top, range_bot, cmd[1], &cmd[2]);
  4776. }
  4777. BIM_PREFIX_COMMAND(repall,"%s","Perform a replacement over the entire file.") {
  4778. return replace_text(1, env->line_count, cmd[2], &cmd[3]);
  4779. }
  4780. BIM_COMMAND(e,"e","Open a file") {
  4781. if (argc > 1) {
  4782. /* This actually opens a new tab */
  4783. open_file(argv[1]);
  4784. update_title();
  4785. } else {
  4786. if (env->modified) {
  4787. render_error("File is modified, can not reload.");
  4788. return 1;
  4789. }
  4790. buffer_t * old_env = env;
  4791. open_file(env->file_name);
  4792. buffer_t * new_env = env;
  4793. env = old_env;
  4794. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4795. SWAP(line_t **, env->lines, new_env->lines);
  4796. SWAP(int, env->line_count, new_env->line_count);
  4797. SWAP(int, env->line_avail, new_env->line_avail);
  4798. SWAP(history_t *, env->history, new_env->history);
  4799. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4800. schedule_complete_recalc();
  4801. redraw_all();
  4802. }
  4803. return 0;
  4804. }
  4805. BIM_COMMAND(tabnew,"tabnew","Open a new tab") {
  4806. if (argc > 1) {
  4807. open_file(argv[1]);
  4808. update_title();
  4809. } else {
  4810. env = buffer_new();
  4811. setup_buffer(env);
  4812. redraw_all();
  4813. update_title();
  4814. }
  4815. return 0;
  4816. }
  4817. BIM_COMMAND(w,"w","Write a file") {
  4818. /* w: write file */
  4819. if (argc > 1) {
  4820. write_file(argv[1]);
  4821. } else {
  4822. write_file(env->file_name);
  4823. }
  4824. return 0;
  4825. }
  4826. BIM_COMMAND(wq,"wq","Write and close buffer") {
  4827. write_file(env->file_name);
  4828. close_buffer();
  4829. return 0;
  4830. }
  4831. BIM_COMMAND(history,"history","Display command history") {
  4832. render_commandline_message(""); /* To clear command line */
  4833. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4834. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4835. }
  4836. render_commandline_message("\n");
  4837. redraw_tabbar();
  4838. redraw_commandline();
  4839. pause_for_key();
  4840. return 0;
  4841. }
  4842. BIM_COMMAND(q,"q","Close buffer") {
  4843. if (left_buffer && left_buffer == right_buffer) {
  4844. unsplit();
  4845. return 0;
  4846. }
  4847. if (env->modified) {
  4848. render_error("No write since last change. Use :q! to force exit.");
  4849. } else {
  4850. close_buffer();
  4851. }
  4852. update_title();
  4853. return 0;
  4854. }
  4855. BIM_COMMAND(qbang,"q!","Force close buffer") {
  4856. close_buffer();
  4857. update_title();
  4858. return 0;
  4859. }
  4860. BIM_COMMAND(qa,"qa","Try to close all buffers") {
  4861. try_quit();
  4862. return 0;
  4863. }
  4864. BIM_ALIAS("qall",qall,qa)
  4865. BIM_COMMAND(qabang,"qa!","Force exit") {
  4866. /* Forcefully exit editor */
  4867. while (buffers_len) {
  4868. buffer_close(buffers[0]);
  4869. }
  4870. quit(NULL);
  4871. return 1; /* doesn't return */
  4872. }
  4873. BIM_COMMAND(tabp,"tabp","Previous tab") {
  4874. previous_tab();
  4875. update_title();
  4876. return 0;
  4877. }
  4878. BIM_COMMAND(tabn,"tabn","Next tab") {
  4879. next_tab();
  4880. update_title();
  4881. return 0;
  4882. }
  4883. BIM_COMMAND(tabm,"tabm","Move the current tab to a new index") {
  4884. /* Figure out the current index */
  4885. int i = 0;
  4886. for (; i < buffers_len; i++) {
  4887. if (buffers[i] == env) break;
  4888. }
  4889. if (i == buffers_len) {
  4890. render_status_message("(invalid state?)");
  4891. return 1;
  4892. }
  4893. if (argc < 2) {
  4894. render_status_message("tab = %d", i);
  4895. return 1;
  4896. }
  4897. int newIndex = atoi(argv[1]);
  4898. if (newIndex == i) {
  4899. return 0;
  4900. }
  4901. /* Okay, this is stupid, but, remove the buffer */
  4902. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i -1));
  4903. /* Then make space at the destination */
  4904. memmove(&buffers[newIndex+1], &buffers[newIndex], sizeof(*buffers) * (buffers_len - newIndex -1));
  4905. buffers[newIndex] = env;
  4906. redraw_tabbar();
  4907. update_title();
  4908. return 0;
  4909. }
  4910. BIM_COMMAND(tab,"tab", "Open a specific tab") {
  4911. if (argc < 2) return bim_command_tabm("tabm", argc, argv);
  4912. int i = atoi(argv[1]);
  4913. if (i < 0 || i > buffers_len) {
  4914. render_error("Invalid tab index");
  4915. return 1;
  4916. }
  4917. env = buffers[i];
  4918. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  4919. redraw_all();
  4920. update_title();
  4921. return 0;
  4922. }
  4923. BIM_COMMAND(tabindicator,"tabindicator","Set the tab indicator") {
  4924. if (argc < 2) {
  4925. render_status_message("tabindicator=%s", global_config.tab_indicator);
  4926. return 0;
  4927. }
  4928. if (!global_config.can_unicode && strlen(argv[1]) != 1) return 0;
  4929. if (display_width_of_string(argv[1]) != 1) {
  4930. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4931. return 1;
  4932. }
  4933. if (global_config.tab_indicator) free(global_config.tab_indicator);
  4934. global_config.tab_indicator = strdup(argv[1]);
  4935. return 0;
  4936. }
  4937. BIM_COMMAND(spaceindicator,"spaceindicator","Set the space indicator") {
  4938. if (argc < 2) {
  4939. render_status_message("spaceindicator=%s", global_config.space_indicator);
  4940. return 0;
  4941. }
  4942. if (!global_config.can_unicode && strlen(argv[1]) != 1) return 0;
  4943. if (display_width_of_string(argv[1]) != 1) {
  4944. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4945. return 1;
  4946. }
  4947. if (global_config.space_indicator) free(global_config.space_indicator);
  4948. global_config.space_indicator = strdup(argv[1]);
  4949. return 0;
  4950. }
  4951. BIM_COMMAND(global_git,"global.git","Show or change the default status of git integration") {
  4952. if (argc < 2) {
  4953. render_status_message("global.git=%d", global_config.check_git);
  4954. } else {
  4955. global_config.check_git = !!atoi(argv[1]);
  4956. }
  4957. return 0;
  4958. }
  4959. BIM_COMMAND(git,"git","Show or change status of git integration") {
  4960. if (!env) {
  4961. render_error("requires environment (did you mean global.git?)");
  4962. return 1;
  4963. }
  4964. if (argc < 2) {
  4965. render_status_message("git=%d", env->checkgitstatusonwrite);
  4966. } else {
  4967. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4968. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4969. git_examine(env->file_name);
  4970. redraw_text();
  4971. }
  4972. }
  4973. return 0;
  4974. }
  4975. BIM_COMMAND(colorgutter,"colorgutter","Show or change status of gutter colorization for unsaved modifications") {
  4976. if (argc < 2) {
  4977. render_status_message("colorgutter=%d", global_config.color_gutter);
  4978. } else {
  4979. global_config.color_gutter = !!atoi(argv[1]);
  4980. redraw_text();
  4981. }
  4982. return 0;
  4983. }
  4984. BIM_COMMAND(indent,"indent","Enable smart indentation") {
  4985. env->indent = 1;
  4986. redraw_statusbar();
  4987. return 0;
  4988. }
  4989. BIM_COMMAND(noindent,"noindent","Disable smart indentation") {
  4990. env->indent = 0;
  4991. redraw_statusbar();
  4992. return 0;
  4993. }
  4994. /* TODO: global.maxcolumn */
  4995. BIM_COMMAND(maxcolumn,"maxcolumn","Highlight past the given column to indicate maximum desired line length") {
  4996. if (argc < 2) {
  4997. render_status_message("maxcolumn=%d",env->maxcolumn);
  4998. return 0;
  4999. }
  5000. env->maxcolumn = atoi(argv[1]);
  5001. redraw_text();
  5002. return 0;
  5003. }
  5004. BIM_COMMAND(cursorcolumn,"cursorcolumn","Show the visual column offset of the cursor.") {
  5005. render_status_message("cursorcolumn=%d", env->preferred_column);
  5006. return 0;
  5007. }
  5008. BIM_COMMAND(noh,"noh","Clear search term") {
  5009. if (global_config.search) {
  5010. free(global_config.search);
  5011. global_config.search = NULL;
  5012. for (int i = 0; i < env->line_count; ++i) {
  5013. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5014. env->lines[i]->text[j].flags &= ~(FLAG_SEARCH);
  5015. }
  5016. }
  5017. redraw_text();
  5018. }
  5019. return 0;
  5020. }
  5021. BIM_COMMAND(help,"help","Show help text.") {
  5022. if (argc < 2) {
  5023. render_commandline_message(""); /* To clear command line */
  5024. render_commandline_message("\n");
  5025. render_commandline_message(" \033[1mbim - a text editor \033[22m\n");
  5026. render_commandline_message("\n");
  5027. render_commandline_message(" Available commands:\n");
  5028. render_commandline_message(" Quit with \033[3m:q\033[23m, \033[3m:qa\033[23m, \033[3m:q!\033[23m, \033[3m:qa!\033[23m\n");
  5029. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  5030. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  5031. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  5032. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  5033. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  5034. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  5035. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  5036. render_commandline_message("\n");
  5037. render_commandline_message(" Bim %s%s\n", BIM_VERSION, BIM_BUILD_DATE);
  5038. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  5039. render_commandline_message("\n");
  5040. } else {
  5041. int found = 0;
  5042. for (struct command_def * c = regular_commands; !found && regular_commands && c->name; ++c) {
  5043. if (!strcmp(c->name, argv[1])) {
  5044. render_commandline_message(""); /* To clear command line */
  5045. render_commandline_message("Help description for `%s`:\n", c->name);
  5046. render_commandline_message(" %s\n", c->description);
  5047. found = 1;
  5048. break;
  5049. }
  5050. }
  5051. for (struct command_def * c = prefix_commands; !found && prefix_commands && c->name; ++c) {
  5052. if (!strcmp(c->name, argv[1])) {
  5053. render_commandline_message(""); /* To clear command line */
  5054. render_commandline_message("Help description for `%s`:\n", c->name);
  5055. render_commandline_message(" %s\n", c->description);
  5056. found = 1;
  5057. break;
  5058. }
  5059. }
  5060. if (!found) {
  5061. render_error("Unknown command: %s", argv[1]);
  5062. return 1;
  5063. }
  5064. }
  5065. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  5066. redraw_tabbar();
  5067. redraw_commandline();
  5068. /* Wait for a character so we can redraw the screen before continuing */
  5069. pause_for_key();
  5070. return 0;
  5071. }
  5072. BIM_COMMAND(version,"version","Show version information.") {
  5073. render_status_message("Bim %s%s", BIM_VERSION, BIM_BUILD_DATE);
  5074. return 0;
  5075. }
  5076. BIM_COMMAND(theme,"theme","Set color theme") {
  5077. if (argc < 2) {
  5078. render_status_message("theme=%s", current_theme);
  5079. } else {
  5080. for (struct theme_def * d = themes; themes && d->name; ++d) {
  5081. if (!strcmp(argv[1], d->name)) {
  5082. ptrdiff_t before = krk_currentThread.stackTop - krk_currentThread.stack;
  5083. krk_push(OBJECT_VAL(d->callable));
  5084. KrkValue result = krk_callStack(0);
  5085. krk_currentThread.stackTop = krk_currentThread.stack + before;
  5086. if (IS_NONE(result) && (krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION)) {
  5087. render_error("Exception occurred in theme: %s", AS_INSTANCE(krk_currentThread.currentException)->_class->name->chars);
  5088. krk_dumpTraceback();
  5089. int key = 0;
  5090. while ((key = bim_getkey(DEFAULT_KEY_WAIT)) == KEY_TIMEOUT);
  5091. }
  5092. redraw_all();
  5093. return 0;
  5094. }
  5095. }
  5096. }
  5097. return 0;
  5098. }
  5099. BIM_ALIAS("colorscheme",colorscheme,theme)
  5100. BIM_COMMAND(splitpercent,"splitpercent","Display or change view split") {
  5101. if (argc < 2) {
  5102. render_status_message("splitpercent=%d", global_config.split_percent);
  5103. return 0;
  5104. } else {
  5105. global_config.split_percent = atoi(argv[1]);
  5106. if (left_buffer) {
  5107. update_split_size();
  5108. redraw_all();
  5109. }
  5110. }
  5111. return 0;
  5112. }
  5113. BIM_COMMAND(split,"split","Split the current view.") {
  5114. buffer_t * original = env;
  5115. if (argc > 1) {
  5116. int is_not_number = 0;
  5117. for (char * c = argv[1]; *c; ++c) is_not_number |= !isdigit(*c);
  5118. if (is_not_number) {
  5119. /* Open a file for the new split */
  5120. open_file(argv[1]);
  5121. right_buffer = buffers[buffers_len-1];
  5122. } else {
  5123. /* Use an existing buffer for the new split */
  5124. int other = atoi(argv[1]);
  5125. if (other >= buffers_len || other < 0) {
  5126. render_error("Invalid buffer number: %d", other);
  5127. return 1;
  5128. }
  5129. right_buffer = buffers[other];
  5130. }
  5131. } else {
  5132. /* Use the current buffer for the new split */
  5133. right_buffer = original;
  5134. }
  5135. left_buffer = original;
  5136. update_split_size();
  5137. redraw_all();
  5138. return 0;
  5139. }
  5140. BIM_COMMAND(unsplit,"unsplit","Show only one buffer on screen") {
  5141. unsplit();
  5142. return 0;
  5143. }
  5144. BIM_COMMAND(horizontalscrolling,"horizontalscrolling","Set the horizontal scrolling mode") {
  5145. if (argc < 2) {
  5146. render_status_message("horizontalscrolling=%d", global_config.horizontal_shift_scrolling);
  5147. return 0;
  5148. } else {
  5149. global_config.horizontal_shift_scrolling = !!atoi(argv[1]);
  5150. redraw_all();
  5151. }
  5152. return 0;
  5153. }
  5154. BIM_COMMAND(syntax,"syntax","Show or set the active syntax highlighter") {
  5155. if (argc < 2) {
  5156. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  5157. } else {
  5158. set_syntax_by_name(argv[1]);
  5159. }
  5160. return 0;
  5161. }
  5162. BIM_COMMAND(recalc,"recalc","Recalculate syntax for the entire file.") {
  5163. schedule_complete_recalc();
  5164. redraw_all();
  5165. return 0;
  5166. }
  5167. BIM_COMMAND(tabstop,"tabstop","Show or set the tabstop (width of an indentation unit)") {
  5168. if (argc < 2) {
  5169. render_status_message("tabstop=%d", env->tabstop);
  5170. } else {
  5171. int t = atoi(argv[1]);
  5172. if (t > 0 && t < 12) {
  5173. env->tabstop = t;
  5174. for (int i = 0; i < env->line_count; ++i) {
  5175. recalculate_tabs(env->lines[i]);
  5176. }
  5177. redraw_all();
  5178. } else {
  5179. render_error("Invalid tabstop: %s", argv[1]);
  5180. }
  5181. }
  5182. return 0;
  5183. }
  5184. BIM_COMMAND(spaces,"spaces","Use spaces for indentation") {
  5185. env->tabs = 0;
  5186. if (argc > 1) {
  5187. bim_command_tabstop("tabstop", argc, argv);
  5188. }
  5189. redraw_statusbar();
  5190. return 0;
  5191. }
  5192. BIM_COMMAND(tabs,"tabs","Use tabs for indentation") {
  5193. env->tabs = 1;
  5194. if (argc > 1) {
  5195. bim_command_tabstop("tabstop", argc, argv);
  5196. }
  5197. redraw_statusbar();
  5198. return 0;
  5199. }
  5200. BIM_COMMAND(clearyear,"clearyank","Clear the yank buffer") {
  5201. if (global_config.yanks) {
  5202. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5203. free(global_config.yanks[i]);
  5204. }
  5205. free(global_config.yanks);
  5206. global_config.yanks = NULL;
  5207. global_config.yank_count = 0;
  5208. redraw_statusbar();
  5209. }
  5210. return 0;
  5211. }
  5212. BIM_COMMAND(padding,"padding","Show or set cursor padding when scrolling vertically") {
  5213. if (argc < 2) {
  5214. render_status_message("padding=%d", global_config.cursor_padding);
  5215. } else {
  5216. global_config.cursor_padding = atoi(argv[1]);
  5217. if (env) {
  5218. place_cursor_actual();
  5219. }
  5220. }
  5221. return 0;
  5222. }
  5223. BIM_COMMAND(smartcase,"smartcase","Show or set the status of the smartcase search option") {
  5224. if (argc < 2) {
  5225. render_status_message("smartcase=%d", global_config.smart_case);
  5226. } else {
  5227. global_config.smart_case = atoi(argv[1]);
  5228. if (env) place_cursor_actual();
  5229. }
  5230. return 0;
  5231. }
  5232. BIM_COMMAND(hlparen,"hlparen","Show or set the configuration option to highlight matching braces") {
  5233. if (argc < 2) {
  5234. render_status_message("hlparen=%d", global_config.highlight_parens);
  5235. } else {
  5236. global_config.highlight_parens = atoi(argv[1]);
  5237. if (env) {
  5238. for (int i = 0; i < env->line_count; ++i) {
  5239. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5240. env->lines[i]->text[j].flags &= (~FLAG_SELECT);
  5241. }
  5242. }
  5243. redraw_text();
  5244. place_cursor_actual();
  5245. }
  5246. }
  5247. return 0;
  5248. }
  5249. BIM_COMMAND(hlcurrent,"hlcurrent","Show or set the configuration option to highlight the current line") {
  5250. if (argc < 2) {
  5251. render_status_message("hlcurrent=%d", global_config.highlight_current_line);
  5252. } else {
  5253. global_config.highlight_current_line = atoi(argv[1]);
  5254. if (env) {
  5255. if (!global_config.highlight_current_line) {
  5256. for (int i = 0; i < env->line_count; ++i) {
  5257. env->lines[i]->is_current = 0;
  5258. }
  5259. }
  5260. redraw_text();
  5261. place_cursor_actual();
  5262. }
  5263. }
  5264. return 0;
  5265. }
  5266. BIM_COMMAND(crnl,"crnl","Show or set the line ending mode") {
  5267. if (argc < 2) {
  5268. render_status_message("crnl=%d", env->crnl);
  5269. } else {
  5270. env->crnl = !!atoi(argv[1]);
  5271. redraw_statusbar();
  5272. }
  5273. return 0;
  5274. }
  5275. BIM_COMMAND(global_numbers,"global.numbers","Set whether numbers are displayed by default") {
  5276. if (argc < 2) {
  5277. render_status_message("global.numbers=%d", global_config.numbers);
  5278. } else {
  5279. global_config.numbers = !!atoi(argv[1]);
  5280. redraw_all();
  5281. }
  5282. return 0;
  5283. }
  5284. BIM_COMMAND(global_statusbar,"global.statusbar","Show or set whether to display the statusbar") {
  5285. if (argc < 2) {
  5286. render_status_message("global.statusbar=%d",!global_config.hide_statusbar);
  5287. } else {
  5288. global_config.hide_statusbar = !atoi(argv[1]);
  5289. global_config.bottom_size = global_config.hide_statusbar ? 1 : 2;
  5290. redraw_all();
  5291. }
  5292. return 0;
  5293. }
  5294. BIM_COMMAND(global_search_wraps,"wrapsearch","Enable search wrapping around from top or bottom") {
  5295. if (argc < 2) {
  5296. render_status_message("wrapsearch=%d",global_config.search_wraps);
  5297. } else {
  5298. global_config.search_wraps = !!atoi(argv[1]);
  5299. }
  5300. return 0;
  5301. }
  5302. BIM_COMMAND(smartcomplete,"smartcomplete","Enable autocompletion while typing") {
  5303. if (argc < 2) {
  5304. render_status_message("smartcomplete=%d",global_config.smart_complete);
  5305. } else {
  5306. global_config.smart_complete = !!atoi(argv[1]);
  5307. }
  5308. return 0;
  5309. }
  5310. BIM_COMMAND(global_autohide_tabs,"global.autohidetabs","Whether to show the tab bar when there is only one tab") {
  5311. if (argc < 2) {
  5312. render_status_message("global.autohidetabs=%d", global_config.autohide_tabs);
  5313. } else {
  5314. global_config.autohide_tabs = !!atoi(argv[1]);
  5315. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  5316. redraw_all();
  5317. }
  5318. return 0;
  5319. }
  5320. BIM_COMMAND(numbers,"numbers","Show or set the display of line numbers") {
  5321. if (argc < 2) {
  5322. render_status_message("numbers=%d", env->numbers);
  5323. } else {
  5324. env->numbers = !!atoi(argv[1]);
  5325. redraw_all();
  5326. }
  5327. return 0;
  5328. }
  5329. BIM_COMMAND(relativenumbers,"relativenumbers","Show or set the display of relative line numbers") {
  5330. if (argc < 2) {
  5331. render_status_message("relativenumber=%d", global_config.relative_lines);
  5332. } else {
  5333. global_config.relative_lines = atoi(argv[1]);
  5334. if (env) {
  5335. if (!global_config.relative_lines) {
  5336. for (int i = 0; i < env->line_count; ++i) {
  5337. env->lines[i]->is_current = 0;
  5338. }
  5339. }
  5340. redraw_text();
  5341. place_cursor_actual();
  5342. }
  5343. }
  5344. return 0;
  5345. }
  5346. BIM_COMMAND(buffers,"buffers","Show the open buffers") {
  5347. for (int i = 0; i < buffers_len; ++i) {
  5348. render_commandline_message("%d: %s\n", i, buffers[i]->file_name ? buffers[i]->file_name : "(no name)");
  5349. }
  5350. redraw_tabbar();
  5351. redraw_commandline();
  5352. pause_for_key();
  5353. return 0;
  5354. }
  5355. BIM_COMMAND(keyname,"keyname","Press and key and get its name.") {
  5356. int c;
  5357. render_commandline_message("(press a key)");
  5358. while ((c = bim_getkey(DEFAULT_KEY_WAIT)) == KEY_TIMEOUT);
  5359. render_commandline_message("%d = %s", c, name_from_key(c));
  5360. return 0;
  5361. }
  5362. int isSubstitutionSymbol(int c) {
  5363. if (c >= '!' && c <= '/') return 1;
  5364. if (c >= ':' && c <= '@') return 1;
  5365. if (c >= '[' && c <= '`') return 1;
  5366. if (c >= '{' && c <= '~') return 1;
  5367. return 0;
  5368. }
  5369. int alldigits(const char * c) {
  5370. while (*c) {
  5371. if (!isdigit(*c)) return 0;
  5372. c++;
  5373. }
  5374. return 1;
  5375. }
  5376. /**
  5377. * Process a user command.
  5378. */
  5379. int process_krk_command(const char * cmd, KrkValue * outVal);
  5380. int process_command(char * cmd) {
  5381. if (cmd[0] == '-' && alldigits(&cmd[1])) {
  5382. goto_line(env->line_no-atoi(&cmd[1]));
  5383. return 0;
  5384. } else if (cmd[0] == '+' && alldigits(&cmd[1])) {
  5385. goto_line(env->line_no+atoi(&cmd[1]));
  5386. return 0;
  5387. } else if (alldigits(cmd)) {
  5388. goto_line(atoi(cmd));
  5389. return 0;
  5390. } else if (cmd[0] == '!') {
  5391. return _prefix_command_run_script(cmd);
  5392. } else if (cmd[0] == 's' && isSubstitutionSymbol(cmd[1])) {
  5393. return bim_command_repsome(cmd, 0, NULL);
  5394. } else if (cmd[0] == '%' && cmd[1] == 's') {
  5395. return bim_command_repall(cmd, 0, NULL);
  5396. }
  5397. /* See if it's a bim command in the classic format */
  5398. {
  5399. char * argv[3] = {NULL, NULL, NULL};
  5400. int argc = !!(*cmd);
  5401. char cmd_name[512] = {0};
  5402. for (char * c = (char*)cmd; *c; ++c) {
  5403. if (c-cmd == 511) break;
  5404. if (*c == ' ') {
  5405. cmd_name[c-cmd] = '\0';
  5406. while (*c == ' ') c++;
  5407. argv[1] = c;
  5408. if (*argv[1]) argc++;
  5409. break;
  5410. }
  5411. cmd_name[c-cmd] = *c;
  5412. }
  5413. argv[0] = cmd_name;
  5414. argv[argc] = NULL;
  5415. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5416. if (!strcmp(argv[0], c->name)) {
  5417. krk_resetStack();
  5418. return c->command((char*)cmd, argc, argv);
  5419. }
  5420. }
  5421. }
  5422. int retval = process_krk_command(cmd, NULL);
  5423. return retval;
  5424. }
  5425. struct Candidate {
  5426. char * text;
  5427. int type;
  5428. };
  5429. /**
  5430. * Wrap strcmp for use with qsort.
  5431. */
  5432. int compare_candidate(const void * a, const void * b) {
  5433. const struct Candidate *_a = a;
  5434. const struct Candidate *_b = b;
  5435. return strcmp(_a->text, _b->text);
  5436. }
  5437. /**
  5438. * List of file extensions to ignore when tab completing.
  5439. */
  5440. const char * tab_complete_ignore[] = {".o",".lo",NULL};
  5441. /**
  5442. * Wrapper around krk_valueGetAttribute...
  5443. */
  5444. static KrkValue findFromProperty(KrkValue current, KrkToken next) {
  5445. KrkValue member = OBJECT_VAL(krk_copyString(next.start, next.literalWidth));
  5446. krk_push(member);
  5447. KrkValue value = krk_valueGetAttribute_default(current, AS_CSTRING(member), NONE_VAL());
  5448. krk_pop();
  5449. return value;
  5450. }
  5451. /**
  5452. * Tab completion for command mode.
  5453. */
  5454. void command_tab_complete(char * buffer) {
  5455. /* Figure out which argument this is and where it starts */
  5456. int arg = 0;
  5457. char * buf = strdup(buffer);
  5458. char * b = buf;
  5459. int args_count = 0;
  5460. int args_space = 4;
  5461. char ** args = malloc(sizeof(char*)*args_space);
  5462. #define add_arg(argument) \
  5463. do { \
  5464. if (args_count == args_space) { \
  5465. args_space *= 2; \
  5466. args = realloc(args, sizeof(char*) * args_space); \
  5467. } \
  5468. args[args_count++] = argument; \
  5469. } while (0)
  5470. int candidate_count= 0;
  5471. int candidate_space = 4;
  5472. struct Candidate * candidates = malloc(sizeof(struct Candidate)*candidate_space);
  5473. /* Accept whitespace before first argument */
  5474. while (*b == ' ') b++;
  5475. char * start = b;
  5476. add_arg(start);
  5477. while (*b && *b != ' ') b++;
  5478. while (*b) {
  5479. while (*b == ' ') {
  5480. *b = '\0';
  5481. b++;
  5482. }
  5483. start = b;
  5484. arg++;
  5485. add_arg(start);
  5486. break;
  5487. }
  5488. /**
  5489. * Check a possible candidate and add it to the
  5490. * candidates list, expanding as necessary,
  5491. * if it matches for the current argument.
  5492. */
  5493. #define add_candidate(candidate,candtype) \
  5494. do { \
  5495. char * _arg = args[arg]; \
  5496. int r = strncmp(_arg, candidate, strlen(_arg)); \
  5497. if (!r) { \
  5498. int skip = 0; \
  5499. for (int i = 0; i < candidate_count; ++i) { \
  5500. if (!strcmp(candidates[i].text,candidate)) { skip = 1; break; } \
  5501. } \
  5502. if (skip) break; \
  5503. if (candidate_count == candidate_space) { \
  5504. candidate_space *= 2; \
  5505. candidates = realloc(candidates,sizeof(struct Candidate) * candidate_space); \
  5506. } \
  5507. candidates[candidate_count].text = strdup(candidate); \
  5508. candidates[candidate_count].type = candtype; \
  5509. candidate_count++; \
  5510. } \
  5511. } while (0)
  5512. #define Candidate_Normal 0
  5513. #define Candidate_Command 1
  5514. #define Candidate_Builtin 2
  5515. int _candidates_are_files = 0;
  5516. if (arg == 0 || (arg == 1 && !strcmp(args[0], "help"))) {
  5517. /* Complete command names */
  5518. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5519. add_candidate(c->name,Candidate_Command);
  5520. }
  5521. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5522. add_candidate(c->name,Candidate_Command);
  5523. }
  5524. goto _try_kuroko;
  5525. }
  5526. if (arg == 1 && !strcmp(args[0], "syntax")) {
  5527. /* Complete syntax options */
  5528. add_candidate("none", Candidate_Builtin);
  5529. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  5530. add_candidate(s->name, Candidate_Builtin);
  5531. }
  5532. goto _accept_candidate;
  5533. }
  5534. if (arg == 1 && (!strcmp(args[0], "theme") || !strcmp(args[0], "colorscheme"))) {
  5535. /* Complete color theme names */
  5536. for (struct theme_def * s = themes; themes && s->name; ++s) {
  5537. add_candidate(s->name, Candidate_Builtin);
  5538. }
  5539. goto _accept_candidate;
  5540. }
  5541. if (arg == 1 && (!strcmp(args[0], "setcolor"))) {
  5542. for (struct ColorName * c = color_names; c->name; ++c) {
  5543. add_candidate(c->name, Candidate_Builtin);
  5544. }
  5545. goto _accept_candidate;
  5546. }
  5547. if (arg == 1 && (!strcmp(args[0], "action"))) {
  5548. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5549. add_candidate(a->name, Candidate_Builtin);
  5550. }
  5551. goto _accept_candidate;
  5552. }
  5553. if (arg == 1 && (!strcmp(args[0], "mapkey"))) {
  5554. for (int i = 0; args[arg][i]; ++i) {
  5555. if (args[arg][i] == ' ') {
  5556. while (args[arg][i] == ' ') {
  5557. args[arg][i] = '\0';
  5558. i++;
  5559. }
  5560. start = &args[arg][i];
  5561. arg++;
  5562. add_arg(start);
  5563. i = 0;
  5564. }
  5565. }
  5566. if (arg == 1) {
  5567. for (struct mode_names * m = mode_names; m->name; ++m) {
  5568. add_candidate(m->name, Candidate_Builtin);
  5569. }
  5570. } else if (arg == 2) {
  5571. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  5572. add_candidate(KeyNames[i].name, Candidate_Builtin);
  5573. }
  5574. } else if (arg == 3) {
  5575. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5576. add_candidate(a->name, Candidate_Builtin);
  5577. }
  5578. add_candidate("none", Candidate_Builtin);
  5579. } else if (arg == 4) {
  5580. for (char * c = "racnwmb"; *c; ++c) {
  5581. char tmp[] = {*c,'\0'};
  5582. add_candidate(tmp, Candidate_Builtin);
  5583. }
  5584. }
  5585. goto _accept_candidate;
  5586. }
  5587. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") ||
  5588. !strcmp(args[0],"split") || !strcmp(args[0],"w") || !strcmp(args[0],"runscript") ||
  5589. !strcmp(args[0],"rundir") || args[0][0] == '!')) {
  5590. /* Complete file paths */
  5591. /* First, find the deepest directory match */
  5592. char * tmp = strdup(args[arg]);
  5593. char * last_slash = strrchr(tmp, '/');
  5594. DIR * dirp;
  5595. if (last_slash) {
  5596. *last_slash = '\0';
  5597. if (last_slash == tmp) {
  5598. /* Started with slash, and it was the only slash */
  5599. dirp = opendir("/");
  5600. } else {
  5601. char * home;
  5602. if (*tmp == '~' && (home = getenv("HOME"))) {
  5603. char * t = malloc(strlen(tmp) + strlen(home) + 4);
  5604. sprintf(t, "%s%s",home,tmp+1);
  5605. dirp = opendir(t);
  5606. free(t);
  5607. } else {
  5608. dirp = opendir(tmp);
  5609. }
  5610. }
  5611. } else {
  5612. /* No directory match, completing from current directory */
  5613. dirp = opendir(".");
  5614. tmp[0] = '\0';
  5615. }
  5616. if (!dirp) {
  5617. /* Directory match doesn't exist, no candidates to populate */
  5618. free(tmp);
  5619. goto done;
  5620. }
  5621. _candidates_are_files = 1;
  5622. struct dirent * ent = readdir(dirp);
  5623. while (ent != NULL) {
  5624. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  5625. struct stat statbuf;
  5626. /* Figure out if this file is a directory */
  5627. if (last_slash) {
  5628. char * x;
  5629. char * home;
  5630. if (tmp[0] == '~' && (home = getenv("HOME"))) {
  5631. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1);
  5632. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1, "%s%s/%s",home,tmp+1,ent->d_name);
  5633. } else {
  5634. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  5635. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  5636. }
  5637. stat(x, &statbuf);
  5638. free(x);
  5639. } else {
  5640. stat(ent->d_name, &statbuf);
  5641. }
  5642. /* Build the complete argument name to tab complete */
  5643. int type = Candidate_Normal;
  5644. char s[1024] = {0};
  5645. if (last_slash == tmp) {
  5646. strcat(s,"/");
  5647. } else if (*tmp) {
  5648. strcat(s,tmp);
  5649. strcat(s,"/");
  5650. }
  5651. strcat(s,ent->d_name);
  5652. /*
  5653. * If it is a directory, add a / to the end so the next completion
  5654. * attempt will complete the directory's contents.
  5655. */
  5656. if (S_ISDIR(statbuf.st_mode)) {
  5657. strcat(s,"/");
  5658. type = Candidate_Command;
  5659. }
  5660. int skip = 0;
  5661. for (const char ** c = tab_complete_ignore; *c; ++c) {
  5662. if (str_ends_with(s, *c)) {
  5663. skip = 1;
  5664. break;
  5665. }
  5666. }
  5667. if (!skip) {
  5668. add_candidate(s, type);
  5669. }
  5670. }
  5671. ent = readdir(dirp);
  5672. }
  5673. closedir(dirp);
  5674. free(tmp);
  5675. goto _accept_candidate;
  5676. }
  5677. /* Hacky port of the kuroko repl completer */
  5678. _try_kuroko:
  5679. {
  5680. KrkScanner scanner = krk_initScanner(buffer);
  5681. KrkToken * space = malloc(sizeof(KrkToken) * (strlen(buffer) + 2));
  5682. int count = 0;
  5683. do {
  5684. space[count++] = krk_scanToken(&scanner);
  5685. } while (space[count-1].type != TOKEN_EOF && space[count-1].type != TOKEN_ERROR);
  5686. if (count == 1) {
  5687. goto _cleanup;
  5688. }
  5689. int base = 2;
  5690. int n = base;
  5691. if (space[count-base].type == TOKEN_DOT) {
  5692. /* Dots we need to look back at the previous tokens for */
  5693. n--;
  5694. base--;
  5695. } else if (space[count-base].type >= TOKEN_IDENTIFIER && space[count-base].type <= TOKEN_WITH) {
  5696. /* Something alphanumeric; only for the last element */
  5697. } else {
  5698. /* Some other symbol */
  5699. goto _cleanup;
  5700. }
  5701. while (n < count) {
  5702. if (space[count-n-1].type != TOKEN_DOT) break;
  5703. n++;
  5704. if (n == count) break;
  5705. if (space[count-n-1].type != TOKEN_IDENTIFIER) break;
  5706. n++;
  5707. }
  5708. if (n <= count) {
  5709. /* Now work forwards, starting from the current globals. */
  5710. KrkValue root = OBJECT_VAL(krk_currentThread.module);
  5711. int isGlobal = 1;
  5712. while (n > base) {
  5713. /* And look at the potential fields for instances/classes */
  5714. KrkValue next = findFromProperty(root, space[count-n]);
  5715. if (IS_NONE(next)) {
  5716. /* If we hit None, we found something invalid (or literally hit a None
  5717. * object, but really the difference is minimal in this case: Nothing
  5718. * useful to tab complete from here. */
  5719. if (!isGlobal) goto _cleanup;
  5720. /* Does this match a builtin? */
  5721. if (!krk_tableGet_fast(&vm.builtins->fields,
  5722. krk_copyString(space[count-n].start,space[count-n].literalWidth), &next) || IS_NONE(next)) {
  5723. goto _cleanup;
  5724. }
  5725. }
  5726. isGlobal = 0;
  5727. root = next;
  5728. n -= 2; /* To skip every other dot. */
  5729. }
  5730. if (isGlobal && n < count && (space[count-n-1].type == TOKEN_IMPORT || space[count-n-1].type == TOKEN_FROM)) {
  5731. KrkInstance * modules = krk_newInstance(vm.baseClasses->objectClass);
  5732. root = OBJECT_VAL(modules);
  5733. krk_push(root);
  5734. for (size_t i = 0; i < vm.modules.capacity; ++i) {
  5735. KrkTableEntry * entry = &vm.modules.entries[i];
  5736. if (IS_KWARGS(entry->key)) continue;
  5737. krk_attachNamedValue(&modules->fields, AS_CSTRING(entry->key), NONE_VAL());
  5738. }
  5739. }
  5740. /* Now figure out what we're completing - did we already have a partial symbol name? */
  5741. int length = (space[count-base].type == TOKEN_DOT) ? 0 : (space[count-base].length);
  5742. isGlobal = isGlobal && (length != 0);
  5743. /* Take the last symbol name from the chain and get its member list from dir() */
  5744. static char * syn_krk_keywords[] = {
  5745. "and","class","def","else","for","if","in","import","del",
  5746. "let","not","or","return","while","try","except","raise",
  5747. "continue","break","as","from","elif","lambda","with","is",
  5748. "pass","assert","yield","finally","async","await",
  5749. NULL
  5750. };
  5751. KrkInstance * fakeKeywordsObject = NULL;
  5752. for (;;) {
  5753. KrkValue dirList = krk_dirObject(1,(KrkValue[]){root},0);
  5754. krk_push(dirList);
  5755. if (!IS_INSTANCE(dirList)) {
  5756. render_error("Internal error while tab completing.");
  5757. goto _cleanup;
  5758. }
  5759. for (size_t i = 0; i < AS_LIST(dirList)->count; ++i) {
  5760. KrkString * s = AS_STRING(AS_LIST(dirList)->values[i]);
  5761. krk_push(OBJECT_VAL(s));
  5762. KrkToken asToken = {.start = s->chars, .literalWidth = s->length};
  5763. KrkValue thisValue = findFromProperty(root, asToken);
  5764. krk_push(thisValue);
  5765. if (IS_CLOSURE(thisValue) || IS_BOUND_METHOD(thisValue) || IS_NATIVE(thisValue)) {
  5766. size_t allocSize = s->length + 2;
  5767. char * tmp = malloc(allocSize);
  5768. size_t len = snprintf(tmp, allocSize, "%s(", s->chars);
  5769. s = krk_takeString(tmp, len);
  5770. krk_pop();
  5771. krk_push(OBJECT_VAL(s));
  5772. }
  5773. /* If this symbol is shorter than the current submatch, skip it. */
  5774. if (length && (int)s->length < length) continue;
  5775. if (!memcmp(s->chars, space[count-base].start, length)) {
  5776. char * tmp = malloc(strlen(args[arg]) + s->length + 1);
  5777. sprintf(tmp,"%s%s", args[arg], s->chars + length);
  5778. int type = Candidate_Normal;
  5779. if (IS_OBJECT(root) && AS_OBJECT(root) == (KrkObj*)vm.builtins) {
  5780. type = Candidate_Builtin;
  5781. } else if (IS_OBJECT(root) && AS_OBJECT(root) == (KrkObj*)fakeKeywordsObject) {
  5782. type = Candidate_Command;
  5783. }
  5784. add_candidate(tmp, type);
  5785. free(tmp);
  5786. }
  5787. }
  5788. /*
  5789. * If the object we were scanning was the current module,
  5790. * then we should also throw the builtins into the ring.
  5791. */
  5792. if (isGlobal && AS_OBJECT(root) == (KrkObj*)krk_currentThread.module) {
  5793. root = OBJECT_VAL(vm.builtins);
  5794. continue;
  5795. } else if (isGlobal && AS_OBJECT(root) == (KrkObj*)vm.builtins) {
  5796. fakeKeywordsObject = krk_newInstance(vm.baseClasses->objectClass);
  5797. root = OBJECT_VAL(fakeKeywordsObject);
  5798. krk_push(root);
  5799. for (char ** keyword = syn_krk_keywords; *keyword; keyword++) {
  5800. krk_attachNamedValue(&fakeKeywordsObject->fields, *keyword, NONE_VAL());
  5801. }
  5802. continue;
  5803. } else {
  5804. break;
  5805. }
  5806. }
  5807. }
  5808. _cleanup:
  5809. free(space);
  5810. krk_resetStack();
  5811. }
  5812. _accept_candidate:
  5813. if (candidate_count == 0) {
  5814. redraw_statusbar();
  5815. goto done;
  5816. }
  5817. if (candidate_count == 1) {
  5818. /* Only one completion possibility */
  5819. redraw_statusbar();
  5820. /* Fill out the rest of the command */
  5821. char * cstart = (buffer) + (start - buf);
  5822. for (unsigned int i = 0; i < strlen(candidates[0].text); ++i) {
  5823. *cstart = candidates[0].text[i];
  5824. cstart++;
  5825. }
  5826. *cstart = '\0';
  5827. } else {
  5828. /* Sort candidates */
  5829. qsort(candidates, candidate_count, sizeof(candidates[0]), compare_candidate);
  5830. /* Print candidates in status bar */
  5831. char * tmp = malloc(global_config.term_width+1 + candidate_count * 100);
  5832. memset(tmp, 0, global_config.term_width+1);
  5833. int offset = 0;
  5834. for (int i = 0; i < candidate_count; ++i) {
  5835. char * printed_candidate = candidates[i].text;
  5836. if (_candidates_are_files) {
  5837. for (char * c = printed_candidate; *c; ++c) {
  5838. if (c[0] == '/' && c[1] != '\0') {
  5839. printed_candidate = c+1;
  5840. }
  5841. }
  5842. } else {
  5843. for (char * c = printed_candidate; *c; ++c) {
  5844. if ((c[0] == '.' || c[0] == '(') && c[1] != '\0') {
  5845. printed_candidate = c+1;
  5846. }
  5847. }
  5848. }
  5849. if (offset + 1 + (signed)strlen(printed_candidate) > global_config.term_width - 5) {
  5850. strcat(tmp, "...");
  5851. break;
  5852. }
  5853. if (offset > 0) {
  5854. strcat(tmp, " ");
  5855. offset++;
  5856. }
  5857. const char * colorString = color_string(
  5858. candidates[i].type == Candidate_Normal ? COLOR_STATUS_FG :
  5859. candidates[i].type == Candidate_Command ? COLOR_KEYWORD :
  5860. candidates[i].type == Candidate_Builtin ? COLOR_TYPE : COLOR_STATUS_FG,
  5861. COLOR_STATUS_BG);
  5862. /* Does not affect offset */
  5863. strcat(tmp, colorString);
  5864. strcat(tmp, printed_candidate);
  5865. offset += strlen(printed_candidate);
  5866. }
  5867. render_status_message("%s", tmp);
  5868. free(tmp);
  5869. /* Complete to longest common substring */
  5870. char * cstart = (buffer) + (start - buf);
  5871. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5872. for (int j = 1; j < candidate_count; ++j) {
  5873. if (candidates[0].text[i] != candidates[j].text[i]) goto _reject;
  5874. }
  5875. *cstart = candidates[0].text[i];
  5876. cstart++;
  5877. }
  5878. /* End of longest common substring */
  5879. _reject:
  5880. *cstart = '\0';
  5881. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5882. if (start > buf) { /* Start point needs to be something other than first byte */
  5883. char * tmp = cstart - 1;
  5884. if ((*tmp & 0xC0) == 0x80) {
  5885. /* Count back until we find the start byte and make sure we have the right number */
  5886. int count = 1;
  5887. int x = 0;
  5888. while (tmp >= start) {
  5889. x++;
  5890. tmp--;
  5891. if ((*tmp & 0xC0) == 0x80) {
  5892. count++;
  5893. } else if ((*tmp & 0xC0) == 0xC0) {
  5894. /* How many should we have? */
  5895. int i = 1;
  5896. int j = *tmp;
  5897. while (j & 0x20) {
  5898. i += 1;
  5899. j <<= 1;
  5900. }
  5901. if (count != i) {
  5902. *tmp = '\0';
  5903. break;
  5904. }
  5905. break;
  5906. } else {
  5907. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5908. tmp++;
  5909. *tmp = '\0';
  5910. break;
  5911. }
  5912. }
  5913. } else if ((*tmp & 0xC0) == 0xC0) {
  5914. *tmp = '\0';
  5915. }
  5916. }
  5917. }
  5918. /* Free candidates */
  5919. for (int i = 0; i < candidate_count; ++i) {
  5920. free(candidates[i].text);
  5921. }
  5922. done:
  5923. free(candidates);
  5924. free(buf);
  5925. }
  5926. /**
  5927. * Macros for use in command mode.
  5928. */
  5929. #define _syn_command() do { env->syntax = global_config.command_syn; } while (0)
  5930. #define _syn_restore() do { env->syntax = global_config.command_syn_back; } while (0)
  5931. /**
  5932. * Draw the command buffer and any prefix.
  5933. */
  5934. void render_command_input_buffer(void) {
  5935. if (!global_config.command_buffer) return;
  5936. /* Place the cursor at the bottom of the screen */
  5937. place_cursor(1, global_config.term_height);
  5938. paint_line(COLOR_BG);
  5939. set_colors(COLOR_ALT_FG, COLOR_BG);
  5940. /* If there's a mode name to render, draw it first */
  5941. int _left_gutter = 0;
  5942. if (env->mode == MODE_LINE_SELECTION) {
  5943. _left_gutter = printf("(LINE %d:%d)",
  5944. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5945. (env->start_line < env->line_no) ? env->line_no : env->start_line);
  5946. } else if (env->mode == MODE_COL_SELECTION) {
  5947. _left_gutter = printf("(COL %d:%d %d)",
  5948. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5949. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  5950. (env->sel_col));
  5951. } else if (env->mode == MODE_CHAR_SELECTION) {
  5952. _left_gutter = printf("(CHAR)");
  5953. }
  5954. /* Figure out the cursor position and adjust the offset if necessary */
  5955. int x = 2 + _left_gutter - global_config.command_offset;
  5956. for (int i = 0; i < global_config.command_col_no - 1; ++i) {
  5957. char_t * c = &global_config.command_buffer->text[i];
  5958. x += c->display_width;
  5959. }
  5960. if (x > global_config.term_width - 1) {
  5961. int diff = x - (global_config.term_width - 1);
  5962. global_config.command_offset += diff;
  5963. x -= diff;
  5964. }
  5965. if (x < 2 + _left_gutter) {
  5966. int diff = (2 + _left_gutter) - x;
  5967. global_config.command_offset -= diff;
  5968. x += diff;
  5969. }
  5970. /* If the input buffer is horizontally shifted because it's too long, indicate that. */
  5971. if (global_config.command_offset) {
  5972. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  5973. printf("<");
  5974. } else {
  5975. /* Otherwise indicate buffer mode (search / ?, or command :) */
  5976. set_colors(COLOR_FG, COLOR_BG);
  5977. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5978. printf(global_config.search_direction == 0 ? "?" : "/");
  5979. } else if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  5980. printf("_");
  5981. } else {
  5982. printf(":");
  5983. }
  5984. }
  5985. /* Render the buffer */
  5986. render_line(global_config.command_buffer, global_config.term_width-1-_left_gutter, global_config.command_offset, -1);
  5987. /* Place and display the cursor */
  5988. place_cursor(x, global_config.term_height);
  5989. show_cursor();
  5990. }
  5991. BIM_ACTION(command_discard, 0,
  5992. "Discard the input buffer and cancel command or search."
  5993. )(void) {
  5994. free(global_config.command_buffer);
  5995. global_config.command_buffer = NULL;
  5996. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5997. env->line_no = global_config.prev_line;
  5998. env->col_no = global_config.prev_col;
  5999. /* Unhighlight search matches */
  6000. for (int i = 0; i < env->line_count; ++i) {
  6001. for (int j = 0; j < env->lines[i]->actual; ++j) {
  6002. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  6003. }
  6004. rehighlight_search(env->lines[i]);
  6005. }
  6006. }
  6007. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6008. redraw_all();
  6009. /* TODO exit some other modes? */
  6010. }
  6011. BIM_ACTION(enter_command, 0,
  6012. "Enter command input mode."
  6013. )(void) {
  6014. global_config.overlay_mode = OVERLAY_MODE_COMMAND;
  6015. global_config.command_offset = 0;
  6016. global_config.command_col_no = 1;
  6017. if (global_config.command_buffer) {
  6018. free(global_config.command_buffer);
  6019. }
  6020. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6021. global_config.command_buffer->available = 32;
  6022. global_config.command_syn_back = env->syntax;
  6023. global_config.command_syn = find_syntax_calculator("bimcmd");
  6024. global_config.history_point = -1;
  6025. render_command_input_buffer();
  6026. }
  6027. static char * command_buffer_to_utf8(void) {
  6028. size_t size = 0;
  6029. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  6030. char tmp[8] = {0};
  6031. size += to_eight(global_config.command_buffer->text[i].codepoint, tmp);
  6032. }
  6033. char * tmp = malloc(size + 8); /* for overflow from to_eight */
  6034. char * t = tmp;
  6035. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  6036. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  6037. }
  6038. *t = '\0';
  6039. return tmp;
  6040. }
  6041. BIM_ACTION(command_accept, 0,
  6042. "Accept the command input and run the requested command."
  6043. )(void) {
  6044. /* Convert command buffer to UTF-8 char-array string */
  6045. char * tmp = command_buffer_to_utf8();
  6046. /* Free the original editing buffer */
  6047. free(global_config.command_buffer);
  6048. global_config.command_buffer = NULL;
  6049. /* Run the converted command */
  6050. global_config.break_from_selection = 0;
  6051. insert_command_history(command_history, tmp);
  6052. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6053. process_command(tmp);
  6054. free(tmp);
  6055. if (!global_config.break_from_selection && env->mode != MODE_DIRECTORY_BROWSE) {
  6056. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) {
  6057. recalculate_selected_lines();
  6058. }
  6059. env->mode = MODE_NORMAL;
  6060. }
  6061. /* Leave command mode */
  6062. }
  6063. BIM_ACTION(command_word_delete, 0,
  6064. "Delete the previous word from the input buffer."
  6065. )(void) {
  6066. _syn_command();
  6067. while (global_config.command_col_no > 1 &&
  6068. (global_config.command_buffer->text[global_config.command_col_no-2].codepoint == ' ' ||
  6069. global_config.command_buffer->text[global_config.command_col_no-2].codepoint == '/')) {
  6070. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  6071. global_config.command_col_no--;
  6072. }
  6073. while (global_config.command_col_no > 1 &&
  6074. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != ' ' &&
  6075. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != '/') {
  6076. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  6077. global_config.command_col_no--;
  6078. }
  6079. _syn_restore();
  6080. }
  6081. BIM_ACTION(command_tab_complete_buffer, 0,
  6082. "Complete command names and arguments in the input buffer."
  6083. )(void) {
  6084. /* command_tab_complete should probably just be adjusted to deal with the buffer... */
  6085. char * tmp = calloc(1024,1);
  6086. char * t = tmp;
  6087. for (int i = 0; i < global_config.command_col_no-1; ++i) {
  6088. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  6089. }
  6090. *t = '\0';
  6091. _syn_command();
  6092. while (global_config.command_col_no > 1) {
  6093. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  6094. global_config.command_col_no--;
  6095. }
  6096. _syn_restore();
  6097. command_tab_complete(tmp);
  6098. _syn_command();
  6099. uint32_t state = 0, c= 0;
  6100. t = tmp;
  6101. while (*t) {
  6102. if (!decode(&state, &c, *t)) {
  6103. char_t _c = {codepoint_width(c), 0, c};
  6104. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  6105. global_config.command_col_no++;
  6106. }
  6107. t++;
  6108. }
  6109. _syn_restore();
  6110. free(tmp);
  6111. }
  6112. BIM_ACTION(command_backspace, 0,
  6113. "Erase the character before the cursor in the input buffer."
  6114. )(void) {
  6115. if (global_config.command_col_no <= 1) {
  6116. if (global_config.command_buffer->actual == 0) {
  6117. command_discard();
  6118. }
  6119. return;
  6120. }
  6121. _syn_command();
  6122. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  6123. _syn_restore();
  6124. global_config.command_col_no--;
  6125. global_config.command_offset = 0;
  6126. }
  6127. static void _restore_history(unsigned char **which_history, int point) {
  6128. unsigned char * t = which_history[point];
  6129. global_config.command_col_no = 1;
  6130. global_config.command_buffer->actual = 0;
  6131. _syn_command();
  6132. uint32_t state = 0;
  6133. uint32_t c = 0;
  6134. while (*t) {
  6135. if (!decode(&state, &c, *t)) {
  6136. char_t _c = {codepoint_width(c), 0, c};
  6137. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  6138. global_config.command_col_no++;
  6139. } else if (state == UTF8_REJECT) state = 0;
  6140. t++;
  6141. }
  6142. _syn_restore();
  6143. }
  6144. static void _scroll_history(int direction, unsigned char **which_history, int * which_point) {
  6145. if (direction == -1) {
  6146. if (which_history[*which_point+1]) {
  6147. _restore_history(which_history, *which_point+1);
  6148. (*which_point)++;
  6149. }
  6150. } else {
  6151. if (*which_point > 0) {
  6152. (*which_point)--;
  6153. _restore_history(which_history, *which_point);
  6154. } else {
  6155. *which_point = -1;
  6156. global_config.command_col_no = 1;
  6157. global_config.command_buffer->actual = 0;
  6158. }
  6159. }
  6160. }
  6161. BIM_ACTION(command_scroll_history, ARG_IS_CUSTOM,
  6162. "Scroll through command input history."
  6163. )(int direction) {
  6164. _scroll_history(direction, command_history, &global_config.history_point);
  6165. }
  6166. BIM_ACTION(command_scroll_search_history, ARG_IS_CUSTOM,
  6167. "Scroll through search input history."
  6168. )(int direction) {
  6169. _scroll_history(direction, search_history, &global_config.search_point);
  6170. }
  6171. BIM_ACTION(command_word_left, 0,
  6172. "Move to the start of the previous word in the input buffer."
  6173. )(void) {
  6174. if (global_config.command_col_no > 1) {
  6175. do {
  6176. global_config.command_col_no--;
  6177. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  6178. if (global_config.command_col_no == 1) return;
  6179. do {
  6180. global_config.command_col_no--;
  6181. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  6182. if (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no < global_config.command_buffer->actual) global_config.command_col_no++;
  6183. }
  6184. }
  6185. BIM_ACTION(command_word_right, 0,
  6186. "Move to the start of the next word in the input buffer."
  6187. )(void) {
  6188. if (global_config.command_col_no < global_config.command_buffer->actual) {
  6189. do {
  6190. global_config.command_col_no++;
  6191. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  6192. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  6193. do {
  6194. global_config.command_col_no++;
  6195. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  6196. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  6197. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; }
  6198. }
  6199. }
  6200. BIM_ACTION(command_cursor_left, 0,
  6201. "Move the cursor one character left in the input buffer."
  6202. )(void) {
  6203. if (global_config.command_col_no > 1) global_config.command_col_no--;
  6204. }
  6205. BIM_ACTION(command_cursor_right, 0,
  6206. "Move the cursor one character right in the input buffer."
  6207. )(void) {
  6208. if (global_config.command_col_no < global_config.command_buffer->actual+1) global_config.command_col_no++;
  6209. }
  6210. BIM_ACTION(command_cursor_home, 0,
  6211. "Move the cursor to the start of the input buffer."
  6212. )(void) {
  6213. global_config.command_col_no = 1;
  6214. }
  6215. BIM_ACTION(command_cursor_end, 0,
  6216. "Move the cursor to the end of the input buffer."
  6217. )(void) {
  6218. global_config.command_col_no = global_config.command_buffer->actual + 1;
  6219. }
  6220. BIM_ACTION(eat_mouse, 0,
  6221. "(temporary) Read, but ignore mouse input."
  6222. )(void) {
  6223. bim_getch();
  6224. bim_getch();
  6225. bim_getch();
  6226. }
  6227. BIM_ACTION(command_insert_char, ARG_IS_INPUT,
  6228. "Insert one character into the input buffer."
  6229. )(int c) {
  6230. char_t _c = {codepoint_width(c), 0, c};
  6231. _syn_command();
  6232. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  6233. _syn_restore();
  6234. global_config.command_col_no++;
  6235. }
  6236. /**
  6237. * Determine whether a string should be searched
  6238. * case-sensitive or not based on whether it contains
  6239. * any upper-case letters.
  6240. */
  6241. int smart_case(uint32_t * str) {
  6242. if (!global_config.smart_case) return 0;
  6243. for (uint32_t * s = str; *s; ++s) {
  6244. if (tolower(*s) != (int)*s) {
  6245. return 0;
  6246. }
  6247. }
  6248. return 1;
  6249. }
  6250. /**
  6251. * Search forward from the given cursor position
  6252. * to find a basic search match.
  6253. *
  6254. * This could be more complicated...
  6255. */
  6256. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str, int * matchlen) {
  6257. int col = from_col;
  6258. int ignorecase = smart_case(str);
  6259. for (int i = from_line; i <= env->line_count; ++i) {
  6260. line_t * line = env->lines[i - 1];
  6261. int j = col - 1;
  6262. while (j < line->actual + 1) {
  6263. if (subsearch_matches(line, j, str, ignorecase, matchlen)) {
  6264. *out_line = i;
  6265. *out_col = j + 1;
  6266. return;
  6267. }
  6268. j++;
  6269. }
  6270. col = 0;
  6271. }
  6272. }
  6273. /**
  6274. * Search backwards for matching string.
  6275. */
  6276. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  6277. int col = from_col;
  6278. int ignorecase = smart_case(str);
  6279. for (int i = from_line; i >= 1; --i) {
  6280. line_t * line = env->lines[i-1];
  6281. int j = col - 1;
  6282. while (j > -1) {
  6283. if (subsearch_matches(line, j, str, ignorecase, NULL)) {
  6284. *out_line = i;
  6285. *out_col = j + 1;
  6286. return;
  6287. }
  6288. j--;
  6289. }
  6290. col = (i > 1) ? (env->lines[i-2]->actual + 1) : -1;
  6291. }
  6292. }
  6293. /**
  6294. * Re-mark search matches while editing text.
  6295. * This gets called after recalculate_syntax, so it works as we're typing or
  6296. * whenever syntax calculation would redraw other lines.
  6297. * XXX There's a bunch of code duplication between the (now three) search match functions.
  6298. * and search should be improved to support regex anyway, so this needs to be fixed.
  6299. */
  6300. void rehighlight_search(line_t * line) {
  6301. if (!global_config.search) return;
  6302. int j = 0;
  6303. while (j < line->actual) {
  6304. line->text[j].flags &= ~(FLAG_SEARCH);
  6305. j++;
  6306. }
  6307. int ignorecase = smart_case(global_config.search);
  6308. j = 0;
  6309. while (j < line->actual) {
  6310. int matchlen = 0;
  6311. if (subsearch_matches(line, j, global_config.search, ignorecase, &matchlen)) {
  6312. for (int i = j; matchlen > 0; ++i, matchlen--) {
  6313. line->text[i].flags |= FLAG_SEARCH;
  6314. }
  6315. }
  6316. j++;
  6317. }
  6318. }
  6319. /**
  6320. * Draw the matched search result.
  6321. */
  6322. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  6323. for (int i = 0; i < env->line_count; ++i) {
  6324. for (int j = 0; j < env->lines[i]->actual; ++j) {
  6325. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  6326. }
  6327. }
  6328. int my_index = 0, match_count = 0;
  6329. int line = -1, col = -1, _line = 1, _col = 1;
  6330. do {
  6331. int matchlen;
  6332. find_match(_line, _col, &line, &col, buffer, &matchlen);
  6333. if (line != -1) {
  6334. line_t * l = env->lines[line-1];
  6335. for (int i = col; matchlen > 0; ++i, --matchlen) {
  6336. l->text[i-1].flags |= FLAG_SEARCH;
  6337. }
  6338. match_count += 1;
  6339. if (col == env->col_no && line == env->line_no) my_index = match_count;
  6340. }
  6341. _line = line;
  6342. _col = col+1;
  6343. line = -1;
  6344. col = -1;
  6345. } while (_line != -1);
  6346. redraw_text();
  6347. place_cursor_actual();
  6348. redraw_statusbar();
  6349. redraw_commandline();
  6350. set_fg_color(COLOR_ALT_FG);
  6351. printf("[%d/%d] ", my_index, match_count);
  6352. set_fg_color(COLOR_KEYWORD);
  6353. printf(redraw_buffer == 1 ? "/" : "?");
  6354. set_fg_color(COLOR_FG);
  6355. uint32_t * c = buffer;
  6356. while (*c) {
  6357. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  6358. to_eight(*c, tmp);
  6359. printf("%s", tmp);
  6360. c++;
  6361. }
  6362. }
  6363. BIM_ACTION(start_file_search, 0, "Search for open files and switch tabs quickly.")(void) {
  6364. global_config.overlay_mode = OVERLAY_MODE_FILESEARCH;
  6365. global_config.command_offset = 0;
  6366. global_config.command_col_no = 1;
  6367. if (global_config.command_buffer) {
  6368. free(global_config.command_buffer);
  6369. }
  6370. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6371. global_config.command_buffer->available = 32;
  6372. global_config.command_syn_back = env->syntax;
  6373. global_config.command_syn = NULL; /* uh, dunno for now */
  6374. render_command_input_buffer();
  6375. }
  6376. BIM_ACTION(file_search_accept, 0, "Open the requested tab")(void) {
  6377. if (!global_config.command_buffer->actual) {
  6378. goto _finish;
  6379. }
  6380. /* See if the command buffer matches any open buffers */
  6381. buffer_t * match = NULL;
  6382. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  6383. buffer_t * _env = buffers[i];
  6384. if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  6385. if (global_config.command_buffer->actual) {
  6386. char * f = _env->file_name ? file_basename(_env->file_name) : "";
  6387. /* TODO: Support unicode input here; needs conversion */
  6388. int i = 0;
  6389. for (; i < global_config.command_buffer->actual &&
  6390. f[i] == global_config.command_buffer->text[i].codepoint; ++i);
  6391. if (global_config.command_buffer->actual == i) {
  6392. match = _env;
  6393. break;
  6394. }
  6395. }
  6396. }
  6397. }
  6398. if (match) {
  6399. env = match;
  6400. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  6401. }
  6402. _finish:
  6403. /* Free the original editing buffer */
  6404. free(global_config.command_buffer);
  6405. global_config.command_buffer = NULL;
  6406. /* Leave command mode */
  6407. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6408. redraw_all();
  6409. }
  6410. BIM_ACTION(enter_search, ARG_IS_CUSTOM,
  6411. "Enter search mode."
  6412. )(int direction) {
  6413. global_config.overlay_mode = OVERLAY_MODE_SEARCH;
  6414. global_config.command_offset = 0;
  6415. global_config.command_col_no = 1;
  6416. global_config.prev_line = env->line_no;
  6417. global_config.prev_col = env->col_no;
  6418. global_config.prev_coffset = env->coffset;
  6419. global_config.prev_offset = env->offset;
  6420. global_config.search_direction = direction;
  6421. if (global_config.command_buffer) {
  6422. free(global_config.command_buffer);
  6423. }
  6424. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6425. global_config.command_buffer->available = 32;
  6426. global_config.command_syn_back = env->syntax;
  6427. global_config.command_syn = NULL; /* Disable syntax highlighting in search; maybe use buffer's mode instead? */
  6428. render_command_input_buffer();
  6429. }
  6430. BIM_ACTION(search_accept, 0,
  6431. "Accept the search term and return to the previous mode."
  6432. )(void) {
  6433. /* Store the accepted search */
  6434. if (!global_config.command_buffer->actual) {
  6435. if (global_config.search) {
  6436. search_next();
  6437. }
  6438. goto _finish;
  6439. }
  6440. if (global_config.search) {
  6441. free(global_config.search);
  6442. }
  6443. global_config.search = malloc((global_config.command_buffer->actual + 1) * sizeof(uint32_t));
  6444. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  6445. global_config.search[i] = global_config.command_buffer->text[i].codepoint;
  6446. }
  6447. global_config.search[global_config.command_buffer->actual] = 0;
  6448. char * tmp = command_buffer_to_utf8();
  6449. insert_command_history(search_history, tmp);
  6450. free(tmp);
  6451. _finish:
  6452. /* Free the original editing buffer */
  6453. free(global_config.command_buffer);
  6454. global_config.command_buffer = NULL;
  6455. /* Leave command mode */
  6456. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6457. if (global_config.search) draw_search_match(global_config.search, global_config.search_direction);
  6458. }
  6459. /**
  6460. * Find the next search result, or loop back around if at the end.
  6461. */
  6462. BIM_ACTION(search_next, 0,
  6463. "Jump to the next search match."
  6464. )(void) {
  6465. if (!global_config.search) return;
  6466. if (env->coffset) env->coffset = 0;
  6467. int line = -1, col = -1, wrapped = 0;
  6468. find_match(env->line_no, env->col_no+1, &line, &col, global_config.search, NULL);
  6469. if (line == -1) {
  6470. if (!global_config.search_wraps) return;
  6471. find_match(1,1, &line, &col, global_config.search, NULL);
  6472. if (line == -1) return;
  6473. wrapped = 1;
  6474. }
  6475. env->col_no = col;
  6476. env->line_no = line;
  6477. set_preferred_column();
  6478. draw_search_match(global_config.search, 1);
  6479. if (wrapped) {
  6480. set_fg_color(COLOR_ALT_FG);
  6481. printf(" (search wrapped to top)");
  6482. }
  6483. }
  6484. /**
  6485. * Find the previous search result, or loop to the end of the file.
  6486. */
  6487. BIM_ACTION(search_prev, 0,
  6488. "Jump to the preceding search match."
  6489. )(void) {
  6490. if (!global_config.search) return;
  6491. if (env->coffset) env->coffset = 0;
  6492. int line = -1, col = -1, wrapped = 0;
  6493. find_match_backwards(env->line_no, env->col_no-1, &line, &col, global_config.search);
  6494. if (line == -1) {
  6495. if (!global_config.search_wraps) return;
  6496. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, global_config.search);
  6497. if (line == -1) return;
  6498. wrapped = 1;
  6499. }
  6500. env->col_no = col;
  6501. env->line_no = line;
  6502. set_preferred_column();
  6503. draw_search_match(global_config.search, 0);
  6504. if (wrapped) {
  6505. set_fg_color(COLOR_ALT_FG);
  6506. printf(" (search wrapped to bottom)");
  6507. }
  6508. }
  6509. /**
  6510. * Find the matching paren for this one.
  6511. *
  6512. * This approach skips having to do its own syntax parsing
  6513. * to deal with, eg., erroneous parens in comments. It does
  6514. * this by finding the matching paren with the same flag
  6515. * value, thus parens in strings will match, parens outside
  6516. * of strings will match, but parens in strings won't
  6517. * match parens outside of strings and so on.
  6518. */
  6519. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  6520. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  6521. return; /* Invalid cursor position */
  6522. }
  6523. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  6524. int paren_match = 0;
  6525. int direction = 0;
  6526. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  6527. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0x1F;
  6528. int count = 0;
  6529. /* TODO what about unicode parens? */
  6530. for (int i = 0; paren_pairs[i]; ++i) {
  6531. if (start == paren_pairs[i]) {
  6532. direction = (i % 2 == 0) ? 1 : -1;
  6533. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  6534. break;
  6535. }
  6536. }
  6537. if (!paren_match) return;
  6538. /* Scan for match */
  6539. int line = env->line_no;
  6540. int col = env->col_no - in_col + 1;
  6541. do {
  6542. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  6543. /* Only match on same syntax */
  6544. if ((env->lines[line-1]->text[col-1].flags & 0x1F) == flags) {
  6545. /* Count up on same direction */
  6546. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  6547. /* Count down on opposite direction */
  6548. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  6549. count--;
  6550. /* When count == 0 we have a match */
  6551. if (count == 0) goto _match_found;
  6552. }
  6553. }
  6554. col += direction;
  6555. }
  6556. line += direction;
  6557. /* Reached first/last line with no match */
  6558. if (line == 0 || line == env->line_count + 1) {
  6559. return;
  6560. }
  6561. /* Reset column to start/end of line, depending on direction */
  6562. if (direction > 0) {
  6563. col = 1;
  6564. } else {
  6565. col = env->lines[line-1]->actual;
  6566. }
  6567. } while (1);
  6568. _match_found:
  6569. *out_line = line;
  6570. *out_col = col;
  6571. }
  6572. /**
  6573. * Switch to the left split view
  6574. * (Primarily to handle cases where the left and right are the same buffer)
  6575. */
  6576. BIM_ACTION(use_left_buffer, 0,
  6577. "Switch to the left split view."
  6578. )(void) {
  6579. if (left_buffer == right_buffer && env->left != 0) {
  6580. view_right_offset = env->offset;
  6581. env->width = env->left;
  6582. env->left = 0;
  6583. env->offset = view_left_offset;
  6584. }
  6585. env = left_buffer;
  6586. update_title();
  6587. }
  6588. /**
  6589. * Switch to the right split view
  6590. * (Primarily to handle cases where the left and right are the same buffer)
  6591. */
  6592. BIM_ACTION(use_right_buffer, 0,
  6593. "Switch to the right split view."
  6594. )(void) {
  6595. if (left_buffer == right_buffer && env->left == 0) {
  6596. view_left_offset = env->offset;
  6597. env->left = env->width;
  6598. env->width = global_config.term_width - env->width;
  6599. env->offset = view_right_offset;
  6600. }
  6601. env = right_buffer;
  6602. update_title();
  6603. }
  6604. void handle_common_mouse(int buttons, int x, int y) {
  6605. if (buttons == 64) {
  6606. /* Scroll up */
  6607. if (global_config.shift_scrolling) {
  6608. env->loading = 1;
  6609. int shifted = 0;
  6610. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6611. if (env->offset > 0) {
  6612. env->offset--;
  6613. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  6614. cursor_up();
  6615. }
  6616. shifted++;
  6617. }
  6618. }
  6619. env->loading = 0;
  6620. if (!shifted) return;
  6621. if (global_config.can_scroll && !left_buffer) {
  6622. if (!global_config.can_insert) {
  6623. shift_down(shifted);
  6624. redraw_tabbar();
  6625. } else {
  6626. insert_lines_at(global_config.tabs_visible ? 2 : 1, shifted);
  6627. }
  6628. for (int i = 0; i < shifted; ++i) {
  6629. redraw_line(env->offset+i);
  6630. }
  6631. } else {
  6632. redraw_tabbar();
  6633. redraw_text();
  6634. }
  6635. redraw_statusbar();
  6636. redraw_commandline();
  6637. place_cursor_actual();
  6638. } else {
  6639. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6640. cursor_up();
  6641. }
  6642. }
  6643. return;
  6644. } else if (buttons == 65) {
  6645. /* Scroll down */
  6646. if (global_config.shift_scrolling) {
  6647. env->loading = 1;
  6648. int shifted = 0;
  6649. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6650. if (env->offset < env->line_count-1) {
  6651. env->offset++;
  6652. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  6653. if (env->line_no <= e) {
  6654. cursor_down();
  6655. }
  6656. shifted++;
  6657. }
  6658. }
  6659. env->loading = 0;
  6660. if (!shifted) return;
  6661. if (global_config.can_scroll && !left_buffer) {
  6662. if (!global_config.can_insert) {
  6663. shift_up(shifted);
  6664. redraw_tabbar();
  6665. } else {
  6666. delete_lines_at(global_config.tabs_visible ? 2 : 1, shifted);
  6667. }
  6668. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  6669. for (int i = 0; i < shifted; ++i) {
  6670. if (env->offset + l - i < env->line_count + 1) {
  6671. redraw_line(env->offset + l-1-i);
  6672. } else {
  6673. draw_excess_line(l - 1 - i);
  6674. }
  6675. }
  6676. } else {
  6677. redraw_tabbar();
  6678. redraw_text();
  6679. }
  6680. redraw_statusbar();
  6681. redraw_commandline();
  6682. place_cursor_actual();
  6683. } else {
  6684. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6685. cursor_down();
  6686. }
  6687. }
  6688. return;
  6689. } else if (buttons == 3) {
  6690. /* Move cursor to position */
  6691. if (x < 0) return;
  6692. if (y < 0) return;
  6693. if (y == 1 && global_config.tabs_visible) {
  6694. /* Pick from tabs */
  6695. if (env->mode != MODE_NORMAL && env->mode != MODE_INSERT) return; /* Don't let the tab be switched in other modes for now */
  6696. int _x = 0;
  6697. if (global_config.tab_offset) _x = 1;
  6698. if (global_config.tab_offset && _x >= x) {
  6699. global_config.tab_offset--;
  6700. redraw_tabbar();
  6701. return;
  6702. }
  6703. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  6704. buffer_t * _env = buffers[i];
  6705. char tmp[64];
  6706. int size = 0;
  6707. int filled = draw_tab_name(_env, tmp, global_config.term_width - _x, &size);
  6708. _x += size;
  6709. if (_x >= x) {
  6710. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  6711. env = buffers[i];
  6712. redraw_all();
  6713. update_title();
  6714. return;
  6715. }
  6716. if (filled) break;
  6717. }
  6718. if (x > _x && global_config.tab_offset < buffers_len - 1) {
  6719. global_config.tab_offset++;
  6720. redraw_tabbar();
  6721. }
  6722. return;
  6723. }
  6724. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  6725. int current_mode = env->mode;
  6726. if (x < env->left && env == right_buffer) {
  6727. use_left_buffer();
  6728. } else if (x > env->width && env == left_buffer) {
  6729. use_right_buffer();
  6730. }
  6731. env->mode = current_mode;
  6732. redraw_all();
  6733. }
  6734. if (env->left) {
  6735. x -= env->left;
  6736. }
  6737. /* Figure out y coordinate */
  6738. int line_no = y + env->offset - global_config.tabs_visible;
  6739. int col_no = -1;
  6740. if (line_no > env->line_count) {
  6741. line_no = env->line_count;
  6742. }
  6743. if (line_no != env->line_no) {
  6744. env->coffset = 0;
  6745. }
  6746. /* Account for the left hand gutter */
  6747. int num_size = num_width() + gutter_width();
  6748. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  6749. /* Determine where the cursor is physically */
  6750. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  6751. char_t * c = &env->lines[line_no-1]->text[i];
  6752. _x += c->display_width;
  6753. if (_x > x-1) {
  6754. col_no = i+1;
  6755. break;
  6756. }
  6757. }
  6758. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  6759. col_no = env->lines[line_no-1]->actual;
  6760. }
  6761. env->line_no = line_no;
  6762. env->col_no = col_no;
  6763. set_history_break();
  6764. set_preferred_column();
  6765. redraw_statusbar();
  6766. place_cursor_actual();
  6767. }
  6768. return;
  6769. }
  6770. /**
  6771. * Handle mouse event
  6772. */
  6773. BIM_ACTION(handle_mouse, 0,
  6774. "Process mouse actions."
  6775. )(void) {
  6776. int buttons = bim_getch() - 32;
  6777. int x = bim_getch() - 32;
  6778. int y = bim_getch() - 32;
  6779. handle_common_mouse(buttons, x, y);
  6780. }
  6781. BIM_ACTION(eat_mouse_sgr, 0,
  6782. "Receive, but do not process, mouse actions."
  6783. )(void) {
  6784. do {
  6785. int _c = bim_getch();
  6786. if (_c == -1 || _c == 'm' || _c == 'M') break;
  6787. } while (1);
  6788. }
  6789. BIM_ACTION(handle_mouse_sgr, 0,
  6790. "Process SGR-style mouse actions."
  6791. )(void) {
  6792. int values[3] = {0};
  6793. char tmp[512] = {0};
  6794. char * c = tmp;
  6795. int buttons = 0;
  6796. do {
  6797. int _c = bim_getch();
  6798. if (_c == -1) {
  6799. break;
  6800. }
  6801. if (_c == 'm') {
  6802. buttons = 3;
  6803. break;
  6804. } else if (_c == 'M') {
  6805. buttons = 0;
  6806. break;
  6807. }
  6808. *c = _c;
  6809. ++c;
  6810. } while (1);
  6811. char * j = tmp;
  6812. char * last = tmp;
  6813. int i = 0;
  6814. while (*j) {
  6815. if (*j == ';') {
  6816. *j = '\0';
  6817. values[i] = atoi(last);
  6818. last = j+1;
  6819. i++;
  6820. if (i == 3) break;
  6821. }
  6822. j++;
  6823. }
  6824. if (last && i < 3) values[i] = atoi(last);
  6825. if (buttons != 3) {
  6826. buttons = values[0];
  6827. }
  6828. int x = values[1];
  6829. int y = values[2];
  6830. handle_common_mouse(buttons, x, y);
  6831. }
  6832. BIM_ACTION(insert_char, ARG_IS_INPUT | ACTION_IS_RW,
  6833. "Insert one character."
  6834. )(unsigned int c) {
  6835. if (!c) {
  6836. render_error("Inserted nil byte?");
  6837. return;
  6838. }
  6839. char_t _c;
  6840. _c.codepoint = c;
  6841. _c.flags = 0;
  6842. _c.display_width = codepoint_width(c);
  6843. line_t * line = env->lines[env->line_no - 1];
  6844. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  6845. if (line != nline) {
  6846. env->lines[env->line_no - 1] = nline;
  6847. }
  6848. env->col_no += 1;
  6849. set_preferred_column();
  6850. set_modified();
  6851. }
  6852. BIM_ACTION(replace_char, ARG_IS_PROMPT | ACTION_IS_RW,
  6853. "Replace a single character."
  6854. )(unsigned int c) {
  6855. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  6856. if (c >= KEY_ESCAPE) {
  6857. render_error("Invalid key for replacement");
  6858. return;
  6859. }
  6860. char_t _c;
  6861. _c.codepoint = c;
  6862. _c.flags = 0;
  6863. _c.display_width = codepoint_width(c);
  6864. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  6865. redraw_line(env->line_no-1);
  6866. set_modified();
  6867. }
  6868. BIM_ACTION(undo_history, ACTION_IS_RW,
  6869. "Undo history until the last breakpoint."
  6870. )(void) {
  6871. if (!global_config.history_enabled) return;
  6872. env->loading = 1;
  6873. history_t * e = env->history;
  6874. if (e->type == HISTORY_SENTINEL) {
  6875. env->loading = 0;
  6876. render_commandline_message("Already at oldest change");
  6877. return;
  6878. }
  6879. int count_chars = 0;
  6880. int count_lines = 0;
  6881. do {
  6882. if (e->type == HISTORY_SENTINEL) break;
  6883. switch (e->type) {
  6884. case HISTORY_INSERT:
  6885. /* Delete */
  6886. line_delete(
  6887. env->lines[e->contents.insert_delete_replace.lineno],
  6888. e->contents.insert_delete_replace.offset+1,
  6889. e->contents.insert_delete_replace.lineno
  6890. );
  6891. count_chars++;
  6892. break;
  6893. case HISTORY_DELETE:
  6894. {
  6895. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6896. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6897. env->lines[e->contents.insert_delete_replace.lineno],
  6898. _c,
  6899. e->contents.insert_delete_replace.offset-1,
  6900. e->contents.insert_delete_replace.lineno
  6901. );
  6902. }
  6903. count_chars++;
  6904. break;
  6905. case HISTORY_REPLACE:
  6906. {
  6907. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6908. line_replace(
  6909. env->lines[e->contents.insert_delete_replace.lineno],
  6910. _o,
  6911. e->contents.insert_delete_replace.offset,
  6912. e->contents.insert_delete_replace.lineno
  6913. );
  6914. }
  6915. count_chars++;
  6916. break;
  6917. case HISTORY_REMOVE_LINE:
  6918. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6919. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6920. count_lines++;
  6921. break;
  6922. case HISTORY_ADD_LINE:
  6923. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  6924. count_lines++;
  6925. break;
  6926. case HISTORY_REPLACE_LINE:
  6927. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6928. count_lines++;
  6929. break;
  6930. case HISTORY_SPLIT_LINE:
  6931. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  6932. count_lines++;
  6933. break;
  6934. case HISTORY_MERGE_LINES:
  6935. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  6936. count_lines++;
  6937. break;
  6938. case HISTORY_BREAK:
  6939. /* Ignore break */
  6940. break;
  6941. default:
  6942. render_error("Unknown type %d!\n", e->type);
  6943. break;
  6944. }
  6945. env->line_no = env->history->line;
  6946. env->col_no = env->history->col;
  6947. env->history = e->previous;
  6948. e = env->history;
  6949. } while (e->type != HISTORY_BREAK);
  6950. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6951. if (env->line_no < 1) env->line_no = 1;
  6952. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6953. if (env->col_no < 1) env->col_no = 1;
  6954. env->modified = (env->history != env->last_save_history);
  6955. env->loading = 0;
  6956. for (int i = 0; i < env->line_count; ++i) {
  6957. env->lines[i]->istate = 0;
  6958. recalculate_tabs(env->lines[i]);
  6959. }
  6960. schedule_complete_recalc();
  6961. place_cursor_actual();
  6962. update_title();
  6963. redraw_all();
  6964. render_commandline_message("%d character%s, %d line%s changed",
  6965. count_chars, (count_chars == 1) ? "" : "s",
  6966. count_lines, (count_lines == 1) ? "" : "s");
  6967. }
  6968. BIM_ACTION(redo_history, ACTION_IS_RW,
  6969. "Redo history until the next breakpoint."
  6970. )(void) {
  6971. if (!global_config.history_enabled) return;
  6972. env->loading = 1;
  6973. history_t * e = env->history->next;
  6974. if (!e) {
  6975. env->loading = 0;
  6976. render_commandline_message("Already at newest change");
  6977. return;
  6978. }
  6979. int count_chars = 0;
  6980. int count_lines = 0;
  6981. while (e) {
  6982. if (e->type == HISTORY_BREAK) {
  6983. env->history = e;
  6984. break;
  6985. }
  6986. switch (e->type) {
  6987. case HISTORY_INSERT:
  6988. {
  6989. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6990. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6991. env->lines[e->contents.insert_delete_replace.lineno],
  6992. _c,
  6993. e->contents.insert_delete_replace.offset,
  6994. e->contents.insert_delete_replace.lineno
  6995. );
  6996. }
  6997. count_chars++;
  6998. break;
  6999. case HISTORY_DELETE:
  7000. /* Delete */
  7001. line_delete(
  7002. env->lines[e->contents.insert_delete_replace.lineno],
  7003. e->contents.insert_delete_replace.offset,
  7004. e->contents.insert_delete_replace.lineno
  7005. );
  7006. count_chars++;
  7007. break;
  7008. case HISTORY_REPLACE:
  7009. {
  7010. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  7011. line_replace(
  7012. env->lines[e->contents.insert_delete_replace.lineno],
  7013. _o,
  7014. e->contents.insert_delete_replace.offset,
  7015. e->contents.insert_delete_replace.lineno
  7016. );
  7017. }
  7018. count_chars++;
  7019. break;
  7020. case HISTORY_ADD_LINE:
  7021. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  7022. count_lines++;
  7023. break;
  7024. case HISTORY_REMOVE_LINE:
  7025. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  7026. count_lines++;
  7027. break;
  7028. case HISTORY_REPLACE_LINE:
  7029. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  7030. count_lines++;
  7031. break;
  7032. case HISTORY_MERGE_LINES:
  7033. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  7034. count_lines++;
  7035. break;
  7036. case HISTORY_SPLIT_LINE:
  7037. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  7038. count_lines++;
  7039. break;
  7040. case HISTORY_BREAK:
  7041. /* Ignore break */
  7042. break;
  7043. default:
  7044. render_error("Unknown type %d!\n", e->type);
  7045. break;
  7046. }
  7047. env->history = e;
  7048. e = e->next;
  7049. }
  7050. env->line_no = env->history->line;
  7051. env->col_no = env->history->col;
  7052. if (env->line_no > env->line_count) env->line_no = env->line_count;
  7053. if (env->line_no < 1) env->line_no = 1;
  7054. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  7055. if (env->col_no < 1) env->col_no = 1;
  7056. env->modified = (env->history != env->last_save_history);
  7057. env->loading = 0;
  7058. for (int i = 0; i < env->line_count; ++i) {
  7059. env->lines[i]->istate = 0;
  7060. recalculate_tabs(env->lines[i]);
  7061. }
  7062. schedule_complete_recalc();
  7063. place_cursor_actual();
  7064. update_title();
  7065. redraw_all();
  7066. render_commandline_message("%d character%s, %d line%s changed",
  7067. count_chars, (count_chars == 1) ? "" : "s",
  7068. count_lines, (count_lines == 1) ? "" : "s");
  7069. }
  7070. int is_whitespace(int codepoint) {
  7071. return codepoint == ' ' || codepoint == '\t';
  7072. }
  7073. int is_normal(int codepoint) {
  7074. return isalnum(codepoint) || codepoint == '_';
  7075. }
  7076. int is_special(int codepoint) {
  7077. return !is_normal(codepoint) && !is_whitespace(codepoint);
  7078. }
  7079. BIM_ACTION(word_left, 0,
  7080. "Move the cursor left to the previous word."
  7081. )(void) {
  7082. if (!env->lines[env->line_no-1]) return;
  7083. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  7084. env->col_no -= 1;
  7085. }
  7086. if (env->col_no == 1) {
  7087. if (env->line_no == 1) goto _place;
  7088. env->line_no--;
  7089. env->col_no = env->lines[env->line_no-1]->actual;
  7090. goto _place;
  7091. }
  7092. int (*inverse_comparator)(int) = is_special;
  7093. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  7094. inverse_comparator = is_normal;
  7095. }
  7096. do {
  7097. if (env->col_no > 1) {
  7098. env->col_no -= 1;
  7099. }
  7100. } while (env->col_no > 1 && !is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint) && !inverse_comparator(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint));
  7101. _place:
  7102. set_preferred_column();
  7103. place_cursor_actual();
  7104. }
  7105. BIM_ACTION(big_word_left, 0,
  7106. "Move the cursor left to the previous WORD."
  7107. )(void) {
  7108. int line_no = env->line_no;
  7109. int col_no = env->col_no;
  7110. do {
  7111. col_no--;
  7112. while (col_no == 0) {
  7113. line_no--;
  7114. if (line_no == 0) {
  7115. goto_line(1);
  7116. set_preferred_column();
  7117. return;
  7118. }
  7119. col_no = env->lines[line_no-1]->actual;
  7120. }
  7121. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  7122. do {
  7123. col_no--;
  7124. if (col_no == 0) {
  7125. env->col_no = 1;
  7126. env->line_no = line_no;
  7127. set_preferred_column();
  7128. redraw_statusbar();
  7129. place_cursor_actual();
  7130. return;
  7131. }
  7132. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  7133. env->col_no = col_no;
  7134. env->line_no = line_no;
  7135. set_preferred_column();
  7136. cursor_right();
  7137. }
  7138. BIM_ACTION(word_right, 0,
  7139. "Move the cursor right to the start of the next word."
  7140. )(void) {
  7141. if (!env->lines[env->line_no-1]) return;
  7142. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  7143. /* next line */
  7144. if (env->line_no == env->line_count) return;
  7145. env->line_no++;
  7146. env->col_no = 0;
  7147. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  7148. goto _place;
  7149. }
  7150. }
  7151. if (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no-1]->text[env->col_no - 1].codepoint)) {
  7152. while (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no-1]->text[env->col_no - 1].codepoint)) {
  7153. env->col_no++;
  7154. }
  7155. goto _place;
  7156. }
  7157. int (*inverse_comparator)(int) = is_special;
  7158. if (is_special(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  7159. inverse_comparator = is_normal;
  7160. }
  7161. while (env->col_no < env->lines[env->line_no-1]->actual && !is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint) && !inverse_comparator(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  7162. env->col_no++;
  7163. }
  7164. while (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  7165. env->col_no++;
  7166. }
  7167. _place:
  7168. set_preferred_column();
  7169. place_cursor_actual();
  7170. }
  7171. BIM_ACTION(big_word_right, 0,
  7172. "Move the cursor right to the start of the next WORD."
  7173. )(void) {
  7174. int line_no = env->line_no;
  7175. int col_no = env->col_no;
  7176. do {
  7177. col_no++;
  7178. if (col_no > env->lines[line_no-1]->actual) {
  7179. line_no++;
  7180. if (line_no > env->line_count) {
  7181. env->line_no = env->line_count;
  7182. env->col_no = env->lines[env->line_no-1]->actual;
  7183. set_preferred_column();
  7184. redraw_statusbar();
  7185. place_cursor_actual();
  7186. return;
  7187. }
  7188. col_no = 0;
  7189. break;
  7190. }
  7191. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  7192. do {
  7193. col_no++;
  7194. while (col_no > env->lines[line_no-1]->actual) {
  7195. line_no++;
  7196. if (line_no >= env->line_count) {
  7197. env->col_no = env->lines[env->line_count-1]->actual;
  7198. env->line_no = env->line_count;
  7199. set_preferred_column();
  7200. redraw_statusbar();
  7201. place_cursor_actual();
  7202. return;
  7203. }
  7204. col_no = 1;
  7205. }
  7206. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  7207. env->col_no = col_no;
  7208. env->line_no = line_no;
  7209. set_preferred_column();
  7210. redraw_statusbar();
  7211. place_cursor_actual();
  7212. return;
  7213. }
  7214. BIM_ACTION(delete_at_cursor, ACTION_IS_RW,
  7215. "Delete the character at the cursor, or merge with previous line."
  7216. )(void) {
  7217. if (env->col_no > 1) {
  7218. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  7219. env->col_no -= 1;
  7220. if (env->coffset > 0) env->coffset--;
  7221. redraw_line(env->line_no-1);
  7222. set_modified();
  7223. redraw_statusbar();
  7224. place_cursor_actual();
  7225. } else if (env->line_no > 1) {
  7226. int tmp = env->lines[env->line_no - 2]->actual;
  7227. merge_lines(env->lines, env->line_no - 1);
  7228. env->line_no -= 1;
  7229. env->col_no = tmp+1;
  7230. set_preferred_column();
  7231. redraw_text();
  7232. set_modified();
  7233. redraw_statusbar();
  7234. place_cursor_actual();
  7235. }
  7236. }
  7237. BIM_ACTION(delete_word, ACTION_IS_RW,
  7238. "Delete the previous word."
  7239. )(void) {
  7240. if (!env->lines[env->line_no-1]) return;
  7241. if (env->col_no > 1) {
  7242. /* Start by deleting whitespace */
  7243. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  7244. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  7245. env->col_no -= 1;
  7246. if (env->coffset > 0) env->coffset--;
  7247. }
  7248. int (*inverse_comparator)(int) = is_special;
  7249. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  7250. inverse_comparator = is_normal;
  7251. }
  7252. do {
  7253. if (env->col_no > 1) {
  7254. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  7255. env->col_no -= 1;
  7256. if (env->coffset > 0) env->coffset--;
  7257. }
  7258. } while (env->col_no > 1 && !is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint) && !inverse_comparator(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint));
  7259. set_preferred_column();
  7260. redraw_text();
  7261. set_modified();
  7262. redraw_statusbar();
  7263. place_cursor_actual();
  7264. }
  7265. }
  7266. BIM_ACTION(insert_line_feed, ACTION_IS_RW,
  7267. "Insert a line break, splitting the current line into two."
  7268. )(void) {
  7269. if (env->indent) {
  7270. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  7271. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  7272. (env->col_no > 3) &&
  7273. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  7274. delete_at_cursor();
  7275. }
  7276. }
  7277. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  7278. env->lines = add_line(env->lines, env->line_no);
  7279. } else {
  7280. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  7281. }
  7282. unhighlight_matching_paren();
  7283. env->coffset = 0;
  7284. env->col_no = 1;
  7285. env->line_no += 1;
  7286. set_preferred_column();
  7287. add_indent(env->line_no-1,env->line_no-2,0);
  7288. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7289. env->offset += 1;
  7290. }
  7291. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7292. set_modified();
  7293. }
  7294. BIM_ACTION(yank_lines, 0,
  7295. "Copy lines into the paste buffer."
  7296. )(void) {
  7297. int start = env->start_line;
  7298. int end = env->line_no;
  7299. if (global_config.yanks) {
  7300. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7301. free(global_config.yanks[i]);
  7302. }
  7303. free(global_config.yanks);
  7304. }
  7305. int lines_to_yank;
  7306. int start_point;
  7307. if (start <= end) {
  7308. lines_to_yank = end - start + 1;
  7309. start_point = start - 1;
  7310. } else {
  7311. lines_to_yank = start - end + 1;
  7312. start_point = end - 1;
  7313. }
  7314. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  7315. global_config.yank_count = lines_to_yank;
  7316. global_config.yank_is_full_lines = 1;
  7317. for (int i = 0; i < lines_to_yank; ++i) {
  7318. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  7319. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  7320. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  7321. global_config.yanks[i]->istate = 0;
  7322. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  7323. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  7324. global_config.yanks[i]->text[j].flags = 0;
  7325. }
  7326. }
  7327. }
  7328. /**
  7329. * Helper to yank part of a line into a new yank line.
  7330. */
  7331. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  7332. if (start_off + count > env->lines[line_no]->actual) {
  7333. if (start_off >= env->lines[line_no]->actual) {
  7334. start_off = env->lines[line_no]->actual;
  7335. count = 0;
  7336. } else {
  7337. count = env->lines[line_no]->actual - start_off;
  7338. }
  7339. }
  7340. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  7341. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  7342. global_config.yanks[yank_no]->actual = count;
  7343. global_config.yanks[yank_no]->istate = 0;
  7344. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  7345. for (int i = 0; i < count; ++i) {
  7346. global_config.yanks[yank_no]->text[i].flags = 0;
  7347. }
  7348. }
  7349. /**
  7350. * Yank text...
  7351. */
  7352. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  7353. if (global_config.yanks) {
  7354. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7355. free(global_config.yanks[i]);
  7356. }
  7357. free(global_config.yanks);
  7358. }
  7359. int lines_to_yank = end_line - start_line + 1;
  7360. int start_point = start_line - 1;
  7361. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  7362. global_config.yank_count = lines_to_yank;
  7363. global_config.yank_is_full_lines = 0;
  7364. if (lines_to_yank == 1) {
  7365. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  7366. } else {
  7367. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  7368. /* Yank middle lines */
  7369. for (int i = 1; i < lines_to_yank - 1; ++i) {
  7370. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  7371. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  7372. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  7373. global_config.yanks[i]->istate = 0;
  7374. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  7375. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  7376. global_config.yanks[i]->text[j].flags = 0;
  7377. }
  7378. }
  7379. /* Yank end line */
  7380. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  7381. }
  7382. }
  7383. BIM_ACTION(delete_at_column, ARG_IS_CUSTOM | ACTION_IS_RW,
  7384. "Delete from the current column backwards (`<backspace>`) or forwards (`<del>`)."
  7385. )(int direction) {
  7386. if (direction == -1 && env->sel_col <= 0) return;
  7387. int prev_width = 0;
  7388. int s = (env->line_no < env->start_line) ? env->line_no : env->start_line;
  7389. int e = (env->line_no < env->start_line) ? env->start_line : env->line_no;
  7390. for (int i = s; i <= e; i++) {
  7391. line_t * line = env->lines[i - 1];
  7392. int _x = 0;
  7393. int col = 1;
  7394. int j = 0;
  7395. for (; j < line->actual; ++j) {
  7396. char_t * c = &line->text[j];
  7397. _x += c->display_width;
  7398. col = j+1;
  7399. if (_x > env->sel_col) break;
  7400. prev_width = c->display_width;
  7401. }
  7402. if ((direction == -1) && (_x == env->sel_col && j == line->actual)) {
  7403. line_delete(line, line->actual, i - 1);
  7404. set_modified();
  7405. } else if (_x > env->sel_col) {
  7406. line_delete(line, col - (direction == -1 ? 1 : 0), i - 1);
  7407. set_modified();
  7408. }
  7409. }
  7410. if (direction == -1) {
  7411. env->sel_col -= prev_width;
  7412. env->col_no--;
  7413. }
  7414. redraw_text();
  7415. }
  7416. void realign_column_cursor(void) {
  7417. line_t * line = env->lines[env->line_no - 1];
  7418. int _x = 0, col = 1, j = 0;
  7419. for (; j < line->actual; ++j) {
  7420. char_t * c = &line->text[j];
  7421. _x += c->display_width;
  7422. col = j + 1;
  7423. if (_x > env->sel_col) break;
  7424. }
  7425. env->col_no = col;
  7426. }
  7427. BIM_ACTION(column_left, 0, "Move the column cursor left.")(void) {
  7428. if (env->sel_col > 0) {
  7429. env->sel_col -= 1;
  7430. env->preferred_column = env->sel_col;
  7431. /* Figure out where the cursor should be */
  7432. realign_column_cursor();
  7433. redraw_all();
  7434. }
  7435. }
  7436. BIM_ACTION(column_right, 0, "Move the column cursor right.")(void) {
  7437. env->sel_col += 1;
  7438. env->preferred_column = env->sel_col;
  7439. /* Figure out where the cursor should be */
  7440. realign_column_cursor();
  7441. redraw_all();
  7442. }
  7443. BIM_ACTION(column_up, 0, "Move the column cursor up.")(void) {
  7444. if (env->line_no > 1 && env->start_line > 1) {
  7445. env->line_no--;
  7446. env->start_line--;
  7447. /* Figure out where the cursor should be */
  7448. realign_column_cursor();
  7449. place_cursor_actual();
  7450. redraw_all();
  7451. }
  7452. }
  7453. BIM_ACTION(column_down, 0, "Move the column cursor down.")(void) {
  7454. if (env->line_no < env->line_count && env->start_line < env->line_count) {
  7455. env->line_no++;
  7456. env->start_line++;
  7457. /* Figure out where the cursor should be */
  7458. realign_column_cursor();
  7459. place_cursor_actual();
  7460. redraw_all();
  7461. }
  7462. }
  7463. uint32_t * get_word_under_cursor(void) {
  7464. /* Figure out size */
  7465. int c_before = 0;
  7466. int c_after = 0;
  7467. int i = env->col_no;
  7468. while (i > 0) {
  7469. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7470. c_before++;
  7471. i--;
  7472. }
  7473. i = env->col_no+1;
  7474. while (i < env->lines[env->line_no-1]->actual+1) {
  7475. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7476. c_after++;
  7477. i++;
  7478. }
  7479. if (!c_before && !c_after) return NULL;
  7480. /* Populate with characters */
  7481. uint32_t * out = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  7482. int j = 0;
  7483. while (c_before) {
  7484. out[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  7485. c_before--;
  7486. j++;
  7487. }
  7488. int x = 0;
  7489. while (c_after) {
  7490. out[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  7491. j++;
  7492. x++;
  7493. c_after--;
  7494. }
  7495. out[j] = 0;
  7496. return out;
  7497. }
  7498. BIM_ACTION(search_under_cursor, 0,
  7499. "Search for the word currently under the cursor."
  7500. )(void) {
  7501. if (global_config.search) free(global_config.search);
  7502. global_config.search = get_word_under_cursor();
  7503. /* Find it */
  7504. search_next();
  7505. }
  7506. BIM_ACTION(find_character_forward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7507. "Find a character forward on the current line and place the cursor on (`f`) or before (`t`) it."
  7508. )(int type, int c) {
  7509. for (int i = env->col_no+1; i <= env->lines[env->line_no-1]->actual; ++i) {
  7510. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7511. env->col_no = i - !!(type == 't');
  7512. place_cursor_actual();
  7513. set_preferred_column();
  7514. return;
  7515. }
  7516. }
  7517. }
  7518. BIM_ACTION(find_character_backward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7519. "Find a character backward on the current line and place the cursor on (`F`) or after (`T`) it."
  7520. )(int type, int c) {
  7521. for (int i = env->col_no-1; i >= 1; --i) {
  7522. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7523. env->col_no = i + !!(type == 'T');
  7524. place_cursor_actual();
  7525. set_preferred_column();
  7526. return;
  7527. }
  7528. }
  7529. }
  7530. /**
  7531. * Clear the navigation number buffer
  7532. */
  7533. void reset_nav_buffer(int c) {
  7534. if (c == KEY_TIMEOUT) return;
  7535. if (nav_buffer && (c < '0' || c > '9')) {
  7536. nav_buffer = 0;
  7537. redraw_commandline();
  7538. }
  7539. }
  7540. /**
  7541. * Determine if a column + line number are within range of the
  7542. * current character selection specified by start_line, etc.
  7543. *
  7544. * Used to determine how syntax flags should be set when redrawing
  7545. * selected text in CHAR SELECTION mode.
  7546. */
  7547. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  7548. if (start_line == end_line) {
  7549. if ( end_col < start_col) {
  7550. int tmp = end_col;
  7551. end_col = start_col;
  7552. start_col = tmp;
  7553. }
  7554. return (col >= start_col && col <= end_col);
  7555. }
  7556. if (start_line > end_line) {
  7557. int tmp = end_line;
  7558. end_line = start_line;
  7559. start_line = tmp;
  7560. tmp = end_col;
  7561. end_col = start_col;
  7562. start_col = tmp;
  7563. }
  7564. if (line < start_line || line > end_line) return 0;
  7565. if (line == start_line) {
  7566. return col >= start_col;
  7567. }
  7568. if (line == end_line) {
  7569. return col <= end_col;
  7570. }
  7571. return 1;
  7572. }
  7573. /**
  7574. * Macro for redrawing selected lines with appropriate highlighting.
  7575. */
  7576. #define _redraw_line(line, force_start_line) \
  7577. do { \
  7578. if (!(force_start_line) && (line) == env->start_line) break; \
  7579. if ((line) > env->line_count + 1) { \
  7580. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7581. draw_excess_line((line) - env->offset - 1); \
  7582. } \
  7583. break; \
  7584. } \
  7585. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7586. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7587. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7588. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7589. env->lines[(line)-1]->text[j].flags &= ~(FLAG_SELECT); \
  7590. } \
  7591. } else { \
  7592. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7593. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7594. } \
  7595. } \
  7596. redraw_line((line)-1); \
  7597. } while (0)
  7598. #define _redraw_line_char(line, force_start_line) \
  7599. do { \
  7600. if (!(force_start_line) && (line) == env->start_line) break; \
  7601. if ((line) > env->line_count + 1) { \
  7602. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7603. draw_excess_line((line) - env->offset - 1); \
  7604. } \
  7605. break; \
  7606. } \
  7607. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7608. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7609. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7610. /* Line is completely outside selection */ \
  7611. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7612. env->lines[(line)-1]->text[j].flags &= ~(FLAG_SELECT); \
  7613. } \
  7614. } else { \
  7615. if ((line) == env->start_line || (line) == env->line_no) { \
  7616. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7617. env->lines[(line)-1]->text[j].flags &= ~(FLAG_SELECT); \
  7618. } \
  7619. } \
  7620. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7621. if (point_in_range(env->start_line, env->line_no,env->start_col, env->col_no, (line), j+1)) { \
  7622. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7623. } \
  7624. } \
  7625. } \
  7626. redraw_line((line)-1); \
  7627. } while (0)
  7628. #define _redraw_line_col(line, force_start_line) \
  7629. do {\
  7630. if (!(force_start_line) && (line) == env->start_line) break; \
  7631. if ((line) > env->line_count + 1) { \
  7632. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7633. draw_excess_line((line) - env->offset - 1); \
  7634. } \
  7635. break; \
  7636. } \
  7637. redraw_line((line)-1); \
  7638. } while (0)
  7639. BIM_ACTION(adjust_indent, ARG_IS_CUSTOM | ACTION_IS_RW,
  7640. "Adjust the indentation on the selected lines (`<tab>` for deeper, `<shift-tab>` for shallower)."
  7641. )(int direction) {
  7642. int lines_to_cover = 0;
  7643. int start_point = 0;
  7644. if (env->start_line <= env->line_no) {
  7645. start_point = env->start_line - 1;
  7646. lines_to_cover = env->line_no - env->start_line + 1;
  7647. } else {
  7648. start_point = env->line_no - 1;
  7649. lines_to_cover = env->start_line - env->line_no + 1;
  7650. }
  7651. for (int i = 0; i < lines_to_cover; ++i) {
  7652. if (env->lines[start_point + i]->actual < 1) continue;
  7653. if (direction == -1) {
  7654. if (env->tabs) {
  7655. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  7656. line_delete(env->lines[start_point + i],1,start_point+i);
  7657. _redraw_line(start_point+i+1,1);
  7658. }
  7659. } else {
  7660. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  7661. line_delete(env->lines[start_point + i],1,start_point+i);
  7662. _redraw_line(start_point+i+1,1);
  7663. } else {
  7664. for (int j = 0; j < env->tabstop; ++j) {
  7665. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  7666. line_delete(env->lines[start_point + i],1,start_point+i);
  7667. }
  7668. }
  7669. }
  7670. _redraw_line(start_point+i+1,1);
  7671. }
  7672. } else if (direction == 1) {
  7673. if (env->tabs) {
  7674. char_t c;
  7675. c.codepoint = '\t';
  7676. c.display_width = env->tabstop;
  7677. c.flags = FLAG_SELECT;
  7678. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7679. } else {
  7680. for (int j = 0; j < env->tabstop; ++j) {
  7681. char_t c;
  7682. c.codepoint = ' ';
  7683. c.display_width = 1;
  7684. c.flags = FLAG_SELECT;
  7685. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7686. }
  7687. }
  7688. _redraw_line(start_point+i+1,1);
  7689. }
  7690. }
  7691. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7692. env->col_no = env->lines[env->line_no-1]->actual;
  7693. }
  7694. set_preferred_column();
  7695. set_modified();
  7696. }
  7697. void recalculate_selected_lines(void) {
  7698. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7699. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7700. if (start < 1) start = 1;
  7701. if (start > env->line_count) start = env->line_count;
  7702. if (end < 1) end = 1;
  7703. if (end > env->line_count) end = env->line_count;
  7704. for (int i = (start > 1) ? (start-1) : (start); i <= end; ++i) {
  7705. for (int j = 0; j < env->lines[i-1]->actual; j++) {
  7706. env->lines[i-1]->text[j].flags &= ~(FLAG_SELECT);
  7707. }
  7708. }
  7709. redraw_all();
  7710. }
  7711. BIM_ACTION(enter_line_selection, 0,
  7712. "Enter line selection mode."
  7713. )(void) {
  7714. /* Set mode */
  7715. env->mode = MODE_LINE_SELECTION;
  7716. /* Store start position */
  7717. env->start_line = env->line_no;
  7718. env->prev_line = env->start_line;
  7719. env->start_col = env->col_no;
  7720. /* Redraw commandline to get -- LINE SELECTION -- text */
  7721. redraw_commandline();
  7722. unhighlight_matching_paren();
  7723. /* Set this line as selected for syntax highlighting */
  7724. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  7725. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  7726. }
  7727. /* And redraw it */
  7728. redraw_line(env->line_no-1);
  7729. }
  7730. BIM_ACTION(switch_selection_mode, ARG_IS_CUSTOM,
  7731. "Swap between LINE and CHAR selection modes."
  7732. )(int mode) {
  7733. env->mode = mode;
  7734. if (mode == MODE_LINE_SELECTION) {
  7735. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7736. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7737. for (int i = start; i <= end; ++i) {
  7738. _redraw_line(i, 1);
  7739. }
  7740. } else if (mode == MODE_CHAR_SELECTION) {
  7741. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7742. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7743. for (int i = start; i <= end; ++i) {
  7744. _redraw_line_char(i, 1);
  7745. }
  7746. }
  7747. }
  7748. BIM_ACTION(delete_and_yank_lines, 0,
  7749. "Delete and yank the selected lines."
  7750. )(void) {
  7751. yank_lines();
  7752. if (env->start_line <= env->line_no) {
  7753. int lines_to_delete = env->line_no - env->start_line + 1;
  7754. for (int i = 0; i < lines_to_delete; ++i) {
  7755. env->lines = remove_line(env->lines, env->start_line-1);
  7756. }
  7757. env->line_no = env->start_line;
  7758. } else {
  7759. int lines_to_delete = env->start_line - env->line_no + 1;
  7760. for (int i = 0; i < lines_to_delete; ++i) {
  7761. env->lines = remove_line(env->lines, env->line_no-1);
  7762. }
  7763. }
  7764. if (env->line_no > env->line_count) {
  7765. env->line_no = env->line_count;
  7766. }
  7767. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7768. env->col_no = env->lines[env->line_no-1]->actual;
  7769. }
  7770. set_preferred_column();
  7771. set_modified();
  7772. }
  7773. BIM_ACTION(enter_insert, ACTION_IS_RW,
  7774. "Enter insert mode."
  7775. )(void) {
  7776. env->mode = MODE_INSERT;
  7777. set_history_break();
  7778. }
  7779. BIM_ACTION(delete_lines_and_enter_insert, ACTION_IS_RW,
  7780. "Delete and yank the selected lines and then enter insert mode."
  7781. )(void) {
  7782. delete_and_yank_lines();
  7783. env->lines = add_line(env->lines, env->line_no-1);
  7784. redraw_text();
  7785. env->mode = MODE_INSERT;
  7786. }
  7787. BIM_ACTION(replace_chars_in_line, ARG_IS_PROMPT | ACTION_IS_RW,
  7788. "Replace characters in the selected lines."
  7789. )(int c) {
  7790. if (c >= KEY_ESCAPE) {
  7791. render_error("Invalid key for replacement");
  7792. return;
  7793. }
  7794. char_t _c = {codepoint_width(c), 0, c};
  7795. int start_point = env->start_line < env->line_no ? env->start_line : env->line_no;
  7796. int end_point = env->start_line < env->line_no ? env->line_no : env->start_line;
  7797. for (int line = start_point; line <= end_point; ++line) {
  7798. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7799. line_replace(env->lines[line-1], _c, i, line-1);
  7800. }
  7801. }
  7802. }
  7803. BIM_ACTION(leave_selection, 0,
  7804. "Leave selection modes and return to normal mode."
  7805. )(void) {
  7806. set_history_break();
  7807. env->mode = MODE_NORMAL;
  7808. recalculate_selected_lines();
  7809. }
  7810. BIM_ACTION(insert_char_at_column, ARG_IS_INPUT | ACTION_IS_RW,
  7811. "Insert a character on all lines at the current column."
  7812. )(int c) {
  7813. char_t _c;
  7814. _c.codepoint = c;
  7815. _c.flags = 0;
  7816. _c.display_width = codepoint_width(c);
  7817. int inserted_width = 0;
  7818. /* For each line */
  7819. int s = (env->line_no < env->start_line) ? env->line_no : env->start_line;
  7820. int e = (env->line_no < env->start_line) ? env->start_line : env->line_no;
  7821. for (int i = s; i <= e; i++) {
  7822. line_t * line = env->lines[i - 1];
  7823. int _x = 0;
  7824. int col = 1;
  7825. int j = 0;
  7826. for (; j < line->actual; ++j) {
  7827. char_t * c = &line->text[j];
  7828. _x += c->display_width;
  7829. col = j+1;
  7830. if (_x > env->sel_col) break;
  7831. }
  7832. if ((_x == env->sel_col && j == line->actual)) {
  7833. _x = env->sel_col + 1;
  7834. col = line->actual + 1;
  7835. }
  7836. if (_x > env->sel_col) {
  7837. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  7838. if (line != nline) {
  7839. env->lines[i - 1] = nline;
  7840. line = nline;
  7841. }
  7842. set_modified();
  7843. }
  7844. recalculate_tabs(line);
  7845. inserted_width = line->text[col-1].display_width;
  7846. if (i == env->line_no) env->col_no = col + 1;
  7847. }
  7848. env->sel_col += inserted_width;
  7849. env->preferred_column = env->sel_col;
  7850. place_cursor_actual();
  7851. }
  7852. BIM_ACTION(insert_tab_at_column, ACTION_IS_RW,
  7853. "Insert an indentation character on multiple lines."
  7854. )(void) {
  7855. if (env->tabs) {
  7856. insert_char_at_column('\t');
  7857. } else {
  7858. for (int i = 0; i < env->tabstop; ++i) {
  7859. insert_char_at_column(' ');
  7860. }
  7861. }
  7862. }
  7863. BIM_ACTION(enter_col_insert, ACTION_IS_RW,
  7864. "Enter column insert mode."
  7865. )(void) {
  7866. env->mode = MODE_COL_INSERT;
  7867. }
  7868. BIM_ACTION(enter_col_insert_after, ACTION_IS_RW,
  7869. "Enter column insert mode after the selected column."
  7870. )(void) {
  7871. env->sel_col += 1;
  7872. enter_col_insert();
  7873. }
  7874. BIM_ACTION(enter_col_selection, 0,
  7875. "Enter column selection mode."
  7876. )(void) {
  7877. /* Set mode */
  7878. env->mode = MODE_COL_SELECTION;
  7879. /* Store cursor */
  7880. env->start_line = env->line_no;
  7881. env->sel_col = env->preferred_column;
  7882. env->prev_line = env->start_line;
  7883. /* Redraw commandline */
  7884. redraw_commandline();
  7885. /* Nothing else to do here; rely on cursor */
  7886. }
  7887. BIM_ACTION(yank_characters, 0,
  7888. "Yank the selected characters to the paste buffer."
  7889. )(void) {
  7890. int end_line = env->line_no;
  7891. int end_col = env->col_no;
  7892. if (env->start_line == end_line) {
  7893. if (env->start_col > end_col) {
  7894. int tmp = env->start_col;
  7895. env->start_col = end_col;
  7896. end_col = tmp;
  7897. }
  7898. } else if (env->start_line > end_line) {
  7899. int tmp = env->start_line;
  7900. env->start_line = end_line;
  7901. end_line = tmp;
  7902. tmp = env->start_col;
  7903. env->start_col = end_col;
  7904. end_col = tmp;
  7905. }
  7906. yank_text(env->start_line, env->start_col, end_line, end_col);
  7907. }
  7908. BIM_ACTION(delete_and_yank_chars, ACTION_IS_RW,
  7909. "Delete and yank the selected characters."
  7910. )(void) {
  7911. int end_line = env->line_no;
  7912. int end_col = env->col_no;
  7913. if (env->start_line == end_line) {
  7914. if (env->start_col > end_col) {
  7915. int tmp = env->start_col;
  7916. env->start_col = end_col;
  7917. end_col = tmp;
  7918. }
  7919. yank_text(env->start_line, env->start_col, end_line, end_col);
  7920. for (int i = env->start_col; i <= end_col; ++i) {
  7921. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7922. }
  7923. env->col_no = env->start_col;
  7924. } else {
  7925. if (env->start_line > end_line) {
  7926. int tmp = env->start_line;
  7927. env->start_line = end_line;
  7928. end_line = tmp;
  7929. tmp = env->start_col;
  7930. env->start_col = end_col;
  7931. end_col = tmp;
  7932. }
  7933. /* Copy lines */
  7934. yank_text(env->start_line, env->start_col, end_line, end_col);
  7935. /* Delete lines */
  7936. for (int i = env->start_line+1; i < end_line; ++i) {
  7937. env->lines = remove_line(env->lines, env->start_line);
  7938. } /* end_line is no longer valid; should be start_line+1*/
  7939. /* Delete from env->start_col forward */
  7940. int tmp = env->lines[env->start_line-1]->actual;
  7941. for (int i = env->start_col; i <= tmp; ++i) {
  7942. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7943. }
  7944. for (int i = 1; i <= end_col; ++i) {
  7945. line_delete(env->lines[env->start_line], 1, env->start_line);
  7946. }
  7947. /* Merge start and end lines */
  7948. merge_lines(env->lines, env->start_line);
  7949. env->line_no = env->start_line;
  7950. env->col_no = env->start_col;
  7951. }
  7952. if (env->line_no > env->line_count) {
  7953. env->line_no = env->line_count;
  7954. }
  7955. set_preferred_column();
  7956. set_modified();
  7957. }
  7958. BIM_ACTION(delete_chars_and_enter_insert, ACTION_IS_RW,
  7959. "Delete and yank the selected characters and then enter insert mode."
  7960. )(void) {
  7961. delete_and_yank_chars();
  7962. redraw_text();
  7963. enter_insert();
  7964. }
  7965. BIM_ACTION(replace_chars, ARG_IS_PROMPT | ACTION_IS_RW,
  7966. "Replace the selected characters."
  7967. )(int c) {
  7968. if (c >= KEY_ESCAPE) {
  7969. render_error("Invalid key for replacement");
  7970. return;
  7971. }
  7972. char_t _c = {codepoint_width(c), 0, c};
  7973. /* This should probably be a function line "do_over_range" or something */
  7974. if (env->start_line == env->line_no) {
  7975. int s = (env->start_col < env->col_no) ? env->start_col : env->col_no;
  7976. int e = (env->start_col < env->col_no) ? env->col_no : env->start_col;
  7977. for (int i = s; i <= e; ++i) {
  7978. line_replace(env->lines[env->start_line-1], _c, i-1, env->start_line-1);
  7979. }
  7980. redraw_text();
  7981. } else {
  7982. if (env->start_line < env->line_no) {
  7983. for (int s = env->start_col-1; s < env->lines[env->start_line-1]->actual; ++s) {
  7984. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7985. }
  7986. for (int line = env->start_line + 1; line < env->line_no; ++line) {
  7987. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7988. line_replace(env->lines[line-1], _c, i, line-1);
  7989. }
  7990. }
  7991. for (int s = 0; s < env->col_no; ++s) {
  7992. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7993. }
  7994. } else {
  7995. for (int s = env->col_no-1; s < env->lines[env->line_no-1]->actual; ++s) {
  7996. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7997. }
  7998. for (int line = env->line_no + 1; line < env->start_line; ++line) {
  7999. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  8000. line_replace(env->lines[line-1], _c, i, line-1);
  8001. }
  8002. }
  8003. for (int s = 0; s < env->start_col; ++s) {
  8004. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  8005. }
  8006. }
  8007. }
  8008. }
  8009. BIM_ACTION(enter_char_selection, 0,
  8010. "Enter character selection mode."
  8011. )(void) {
  8012. /* Set mode */
  8013. env->mode = MODE_CHAR_SELECTION;
  8014. /* Set cursor positions */
  8015. env->start_line = env->line_no;
  8016. env->start_col = env->col_no;
  8017. env->prev_line = env->start_line;
  8018. /* Redraw commandline for -- CHAR SELECTION -- */
  8019. redraw_commandline();
  8020. unhighlight_matching_paren();
  8021. /* Select single character */
  8022. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  8023. redraw_line(env->line_no-1);
  8024. }
  8025. BIM_ACTION(insert_at_end_of_selection, ACTION_IS_RW,
  8026. "Move the cursor to the end of the selection and enter insert mode."
  8027. )(void) {
  8028. recalculate_selected_lines();
  8029. if (env->line_no == env->start_line) {
  8030. env->col_no = env->col_no > env->start_col ? env->col_no + 1 : env->start_col + 1;
  8031. } else if (env->line_no < env->start_line) {
  8032. env->col_no = env->start_col + 1;
  8033. env->line_no = env->start_line;
  8034. } else {
  8035. env->col_no += 1;
  8036. }
  8037. env->mode = MODE_INSERT;
  8038. }
  8039. void free_completion_match(struct completion_match * match) {
  8040. if (match->string) free(match->string);
  8041. if (match->file) free(match->file);
  8042. if (match->search) free(match->search);
  8043. }
  8044. /**
  8045. * Read ctags file to find matches for a symbol
  8046. */
  8047. int read_tags(uint32_t * comp, struct completion_match **matches, int * matches_count, int complete_match) {
  8048. int _matches_len = 4;
  8049. int *matches_len = &_matches_len;
  8050. *matches_count = 0;
  8051. *matches = malloc(sizeof(struct completion_match) * (*matches_len));
  8052. FILE * tags = fopen("tags","r");
  8053. if (tags) {
  8054. char tmp[4096]; /* max line */
  8055. while (!feof(tags) && fgets(tmp, 4096, tags)) {
  8056. if (tmp[0] == '!') continue;
  8057. int i = 0;
  8058. while (comp[i] && comp[i] == (unsigned int)tmp[i]) i++;
  8059. if (comp[i] == '\0') {
  8060. if (complete_match && tmp[i] != '\t') continue;
  8061. int j = i;
  8062. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  8063. tmp[j] = '\0'; j++;
  8064. char * file = &tmp[j];
  8065. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  8066. tmp[j] = '\0'; j++;
  8067. char * search = &tmp[j];
  8068. while (!(tmp[j] == '/' && tmp[j+1] == ';' && tmp[j+2] == '"' && tmp[j+3] == '\t') /* /normal searches/ */
  8069. && !(tmp[j] == ';' && tmp[j+1] == '"' && tmp[j+2] == '\t') /* Old ctags line number searches */
  8070. && (tmp[j] != '\n' && tmp[j] != '\0')) j++;
  8071. tmp[j] = '\0'; j++;
  8072. add_match(tmp,file,search);
  8073. }
  8074. }
  8075. fclose(tags);
  8076. }
  8077. if (env->syntax && env->syntax->completion_matcher) {
  8078. env->syntax->completion_matcher(comp,matches,matches_count,complete_match,matches_len, env);
  8079. }
  8080. return 0;
  8081. }
  8082. /**
  8083. * Draw an autocomplete popover with matches.
  8084. */
  8085. void draw_completion_matches(uint32_t * tmp, struct completion_match *matches, int matches_count, int index) {
  8086. int original_length = 0;
  8087. while (tmp[original_length]) original_length++;
  8088. int max_width = 0;
  8089. for (int i = 0; i < matches_count; ++i) {
  8090. /* TODO unicode width */
  8091. unsigned int my_width = strlen(matches[i].string) + (matches[i].file ? strlen(matches[i].file) + 1 : 0);
  8092. if (my_width > (unsigned int)max_width) {
  8093. max_width = my_width;
  8094. }
  8095. }
  8096. /* Figure out how much space we have to display the window */
  8097. int cursor_y = env->line_no - env->offset + global_config.tabs_visible;
  8098. int max_y = global_config.term_height - global_config.bottom_size - cursor_y;
  8099. /* Find a good place to put the box horizontally */
  8100. int num_size = num_width() + gutter_width();
  8101. int x = num_size + 1 - env->coffset;
  8102. /* Determine where the cursor is physically */
  8103. for (int i = 0; i < env->col_no - 1 - original_length; ++i) {
  8104. char_t * c = &env->lines[env->line_no-1]->text[i];
  8105. x += c->display_width;
  8106. }
  8107. int box_width = max_width;
  8108. int box_x = x;
  8109. int box_y = cursor_y + 1;
  8110. if (max_width > env->width - num_width() - gutter_width()) {
  8111. box_width = env->width - num_width() - gutter_width();
  8112. box_x = num_width() + gutter_width() + 1;
  8113. } else if (env->width - x < max_width) {
  8114. box_width = max_width;
  8115. box_x = env->width - max_width;
  8116. }
  8117. int max_count = (max_y < matches_count) ? max_y - 1 : matches_count;
  8118. for (int x = index; x < max_count+index; ++x) {
  8119. int i = x % matches_count;
  8120. place_cursor(box_x + env->left, box_y+x-index);
  8121. set_colors(COLOR_KEYWORD, COLOR_STATUS_BG);
  8122. /* TODO wide characters */
  8123. int match_width = strlen(matches[i].string);
  8124. int file_width = matches[i].file ? strlen(matches[i].file) : 0;
  8125. for (int j = 0; j < box_width; ++j) {
  8126. if (j == original_length) set_colors(i == index ? COLOR_NUMERAL : COLOR_STATUS_FG, COLOR_STATUS_BG);
  8127. if (j == match_width) set_colors(COLOR_TYPE, COLOR_STATUS_BG);
  8128. if (j < match_width) printf("%c", matches[i].string[j]);
  8129. else if (j > match_width && j - match_width - 1 < file_width) printf("%c", matches[i].file[j-match_width-1]);
  8130. else printf(" ");
  8131. }
  8132. }
  8133. if (max_count == 0) {
  8134. place_cursor(box_x + env->left, box_y);
  8135. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  8136. printf(" (no matches) ");
  8137. } else if (max_count != matches_count) {
  8138. place_cursor(box_x + env->left, box_y+max_count);
  8139. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  8140. printf(" (%d more) ", matches_count-max_count);
  8141. }
  8142. }
  8143. /**
  8144. * Autocomplete words (function/variable names, etc.) in input mode.
  8145. */
  8146. int omni_complete(int quit_quietly_on_none) {
  8147. int retval = 0;
  8148. int index = 0;
  8149. int c;
  8150. int (*qualifier)(int c) = simple_keyword_qualifier;
  8151. if (env->syntax && env->syntax->completion_qualifier) {
  8152. qualifier = env->syntax->completion_qualifier;
  8153. }
  8154. /* Pull the word from before the cursor */
  8155. int c_before = 0;
  8156. int i = env->col_no-1;
  8157. while (i > 0) {
  8158. int c = env->lines[env->line_no-1]->text[i-1].codepoint;
  8159. if (!qualifier(c)) break;
  8160. c_before++;
  8161. i--;
  8162. }
  8163. if (!c_before && quit_quietly_on_none) return 0;
  8164. /* Populate with characters */
  8165. uint32_t * tmp = malloc(sizeof(uint32_t) * (c_before+1));
  8166. int j = 0;
  8167. while (c_before) {
  8168. tmp[j] = env->lines[env->line_no-1]->text[env->col_no-c_before-1].codepoint;
  8169. c_before--;
  8170. j++;
  8171. }
  8172. tmp[j] = 0;
  8173. /*
  8174. * TODO matches should probably be a struct with more data than just
  8175. * the matching string; maybe offset where the needle was found,
  8176. * class information, source file information - anything we can extract
  8177. * from ctags, but also other information for other sources of completion.
  8178. */
  8179. struct completion_match *matches;
  8180. int matches_count;
  8181. /* TODO just reading ctags is rather mediocre; can we do something cool here? */
  8182. if (read_tags(tmp, &matches, &matches_count, 0)) {
  8183. goto _completion_done;
  8184. }
  8185. /* Draw box with matches at cursor-width(tmp) */
  8186. if (quit_quietly_on_none && matches_count == 0) {
  8187. free(tmp);
  8188. free(matches);
  8189. return 0;
  8190. }
  8191. draw_completion_matches(tmp, matches, matches_count, 0);
  8192. _completion_done:
  8193. place_cursor_actual();
  8194. while (1) {
  8195. c = bim_getch();
  8196. if (c == -1) continue;
  8197. if (matches_count < 1) {
  8198. redraw_all();
  8199. break;
  8200. }
  8201. if (c == 15) {
  8202. index = (index + 1) % matches_count;
  8203. draw_completion_matches(tmp, matches, matches_count, index);
  8204. place_cursor_actual();
  8205. continue;
  8206. } else if (c == '\t') {
  8207. for (unsigned int i = j; i < strlen(matches[index].string); ++i) {
  8208. insert_char(matches[index].string[i]);
  8209. }
  8210. set_preferred_column();
  8211. redraw_text();
  8212. place_cursor_actual();
  8213. goto _finish_completion;
  8214. } else if (isgraph(c) && c != '}') {
  8215. /* insert and continue matching */
  8216. insert_char(c);
  8217. set_preferred_column();
  8218. redraw_text();
  8219. place_cursor_actual();
  8220. retval = 1;
  8221. goto _finish_completion;
  8222. } else if (c == DELETE_KEY || c == BACKSPACE_KEY) {
  8223. delete_at_cursor();
  8224. set_preferred_column();
  8225. redraw_text();
  8226. place_cursor_actual();
  8227. retval = 1;
  8228. goto _finish_completion;
  8229. }
  8230. /* TODO: Keyboard navigation of the matches list would be nice */
  8231. redraw_all();
  8232. break;
  8233. }
  8234. bim_unget(c);
  8235. _finish_completion:
  8236. for (int i = 0; i < matches_count; ++i) {
  8237. free_completion_match(&matches[i]);
  8238. }
  8239. free(matches);
  8240. free(tmp);
  8241. return retval;
  8242. }
  8243. /**
  8244. * Set the search string from a UTF-8 sequence.
  8245. * Since the search string is normally a series of codepoints, this saves
  8246. * some effort when trying to search for things we pulled from the outside world.
  8247. * (eg., ctags search terms)
  8248. */
  8249. static void set_search_from_bytes(char * bytes) {
  8250. if (global_config.search) free(global_config.search);
  8251. global_config.search = malloc(sizeof(uint32_t) * (strlen(bytes) * 2 + 1));
  8252. uint32_t * s = global_config.search;
  8253. char * tmp = bytes;
  8254. uint32_t c, istate = 0;
  8255. while (*tmp) {
  8256. if (strchr("\\.()[]+*?", *tmp)) {
  8257. *s++ = '\\';
  8258. *s++ = *tmp;
  8259. *s = 0;
  8260. tmp++;
  8261. continue;
  8262. }
  8263. if (!decode(&istate, &c, *tmp)) {
  8264. *s = c;
  8265. s++;
  8266. *s = 0;
  8267. } else if (istate == UTF8_REJECT) {
  8268. istate = 0;
  8269. }
  8270. tmp++;
  8271. }
  8272. }
  8273. static void _perform_correct_search(struct completion_match * matches, int i) {
  8274. if (matches[i].search[0] == '/') {
  8275. set_search_from_bytes(&matches[i].search[1]);
  8276. search_next();
  8277. } else {
  8278. goto_line(atoi(matches[i].search));
  8279. }
  8280. }
  8281. BIM_ACTION(goto_definition, 0,
  8282. "Jump to the definition of the word under under cursor."
  8283. )(void) {
  8284. uint32_t * word = get_word_under_cursor();
  8285. if (!word) {
  8286. render_error("No match");
  8287. return;
  8288. }
  8289. struct completion_match *matches;
  8290. int matches_count;
  8291. if (read_tags(word, &matches, &matches_count, 1)) {
  8292. render_error("No tags file");
  8293. goto _done;
  8294. }
  8295. if (!matches_count) {
  8296. render_error("No match");
  8297. goto _done;
  8298. }
  8299. if (env->file_name && !strcmp(matches[0].file, env->file_name)) {
  8300. _perform_correct_search(matches, 0);
  8301. } else {
  8302. /* Check if there were other matches that are in this file */
  8303. for (int i =1; env->file_name && i < matches_count; ++i) {
  8304. if (!strcmp(matches[i].file, env->file_name)) {
  8305. _perform_correct_search(matches, i);
  8306. goto _done;
  8307. }
  8308. }
  8309. /* Check buffers */
  8310. for (int i = 0; i < buffers_len; ++i) {
  8311. if (buffers[i]->file_name && !strcmp(matches[0].file,buffers[i]->file_name)) {
  8312. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  8313. env = buffers[i];
  8314. redraw_tabbar();
  8315. _perform_correct_search(matches, i);
  8316. goto _done;
  8317. }
  8318. }
  8319. /* Okay, let's try opening */
  8320. buffer_t * old_buf = env;
  8321. open_file(matches[0].file);
  8322. if (env != old_buf) {
  8323. _perform_correct_search(matches, 0);
  8324. } else {
  8325. render_error("Could not locate file containing definition");
  8326. }
  8327. }
  8328. _done:
  8329. for (int i = 0; i < matches_count; ++i) {
  8330. free_completion_match(&matches[i]);
  8331. }
  8332. free(matches);
  8333. free(word);
  8334. }
  8335. /**
  8336. * Read one codepoint, with verbatim support.
  8337. */
  8338. int read_one_character(char * message) {
  8339. /* Read one character and replace */
  8340. if (!global_config.overlay_mode) {
  8341. render_commandline_message(message);
  8342. place_cursor_actual();
  8343. }
  8344. int c;
  8345. while ((c = bim_getkey(DEFAULT_KEY_WAIT))) {
  8346. if (c == KEY_TIMEOUT) continue;
  8347. if (c == KEY_CTRL_V) {
  8348. if (!global_config.overlay_mode) {
  8349. render_commandline_message(message);
  8350. printf(" ^V");
  8351. place_cursor_actual();
  8352. }
  8353. while ((c = bim_getch()) == -1);
  8354. break;
  8355. }
  8356. break;
  8357. }
  8358. redraw_commandline();
  8359. return c;
  8360. }
  8361. int read_one_byte(char * message) {
  8362. if (!global_config.overlay_mode) {
  8363. render_commandline_message(message);
  8364. place_cursor_actual();
  8365. }
  8366. int c;
  8367. while ((c = bim_getch())) {
  8368. if (c == -1) continue;
  8369. break;
  8370. }
  8371. redraw_commandline();
  8372. return c;
  8373. }
  8374. BIM_ACTION(cursor_left_with_wrap, 0,
  8375. "Move the cursor one position left, wrapping to the previous line."
  8376. )(void) {
  8377. if (env->line_no > 1 && env->col_no == 1) {
  8378. env->line_no--;
  8379. env->col_no = env->lines[env->line_no-1]->actual;
  8380. set_preferred_column();
  8381. place_cursor_actual();
  8382. } else {
  8383. cursor_left();
  8384. }
  8385. }
  8386. BIM_ACTION(prepend_and_insert, ACTION_IS_RW,
  8387. "Insert a new line before the current line and enter insert mode."
  8388. )(void) {
  8389. set_history_break();
  8390. env->lines = add_line(env->lines, env->line_no-1);
  8391. env->col_no = 1;
  8392. add_indent(env->line_no-1,env->line_no,0);
  8393. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  8394. redraw_text();
  8395. set_preferred_column();
  8396. set_modified();
  8397. place_cursor_actual();
  8398. env->mode = MODE_INSERT;
  8399. }
  8400. BIM_ACTION(append_and_insert, ACTION_IS_RW,
  8401. "Insert a new line after the current line and enter insert mode."
  8402. )(void) {
  8403. set_history_break();
  8404. unhighlight_matching_paren();
  8405. env->lines = add_line(env->lines, env->line_no);
  8406. env->col_no = 1;
  8407. env->line_no += 1;
  8408. add_indent(env->line_no-1,env->line_no-2,0);
  8409. set_preferred_column();
  8410. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  8411. env->offset += 1;
  8412. }
  8413. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  8414. redraw_text();
  8415. set_modified();
  8416. place_cursor_actual();
  8417. env->mode = MODE_INSERT;
  8418. }
  8419. BIM_ACTION(insert_after_cursor, ACTION_IS_RW,
  8420. "Place the cursor after the selected character and enter insert mode."
  8421. )(void) {
  8422. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  8423. env->col_no += 1;
  8424. }
  8425. enter_insert();
  8426. }
  8427. BIM_ACTION(delete_forward, ACTION_IS_RW,
  8428. "Delete the character under the cursor."
  8429. )(void) {
  8430. if (env->col_no <= env->lines[env->line_no-1]->actual) {
  8431. line_delete(env->lines[env->line_no-1], env->col_no, env->line_no-1);
  8432. redraw_text();
  8433. } else if (env->col_no == env->lines[env->line_no-1]->actual + 1 && env->line_count > env->line_no) {
  8434. merge_lines(env->lines, env->line_no);
  8435. redraw_text();
  8436. }
  8437. set_modified();
  8438. redraw_statusbar();
  8439. place_cursor_actual();
  8440. }
  8441. BIM_ACTION(delete_forward_and_insert, ACTION_IS_RW,
  8442. "Delete the character under the cursor and enter insert mode."
  8443. )(void) {
  8444. set_history_break();
  8445. delete_forward();
  8446. env->mode = MODE_INSERT;
  8447. }
  8448. BIM_ACTION(paste, ARG_IS_CUSTOM | ACTION_IS_RW,
  8449. "Paste yanked text before (`P`) or after (`p`) the cursor."
  8450. )(int direction) {
  8451. if (global_config.yanks) {
  8452. env->slowop = 1;
  8453. if (!global_config.yank_is_full_lines) {
  8454. /* Handle P for paste before, p for past after */
  8455. int target_column = (direction == -1 ? (env->col_no) : (env->col_no+1));
  8456. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  8457. target_column = env->lines[env->line_no-1]->actual + 1;
  8458. }
  8459. if (global_config.yank_count > 1) {
  8460. /* Spit the current line at the current position */
  8461. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  8462. }
  8463. /* Insert first line at current position */
  8464. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  8465. env->lines[env->line_no - 1] = line_insert(env->lines[env->line_no - 1], global_config.yanks[0]->text[i], target_column + i - 1, env->line_no - 1);
  8466. }
  8467. if (global_config.yank_count > 1) {
  8468. /* Insert full lines */
  8469. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8470. env->lines = add_line(env->lines, env->line_no);
  8471. }
  8472. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8473. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  8474. }
  8475. /* Insert characters from last line into (what was) the next line */
  8476. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  8477. env->lines[env->line_no + global_config.yank_count - 2] = line_insert(env->lines[env->line_no + global_config.yank_count - 2], global_config.yanks[global_config.yank_count-1]->text[i], i, env->line_no + global_config.yank_count - 2);
  8478. }
  8479. }
  8480. } else {
  8481. /* Insert full lines */
  8482. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8483. env->lines = add_line(env->lines, env->line_no - (direction == -1 ? 1 : 0));
  8484. }
  8485. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8486. replace_line(env->lines, env->line_no - (direction == -1 ? 1 : 0) + i, global_config.yanks[i]);
  8487. }
  8488. }
  8489. env->slowop = 0;
  8490. schedule_complete_recalc();
  8491. /* Recalculate whole document syntax */
  8492. if (direction == 1) {
  8493. if (global_config.yank_is_full_lines) {
  8494. env->line_no += 1;
  8495. } else {
  8496. if (global_config.yank_count == 1) {
  8497. env->col_no = env->col_no + global_config.yanks[0]->actual;
  8498. } else {
  8499. env->line_no = env->line_no + global_config.yank_count - 1;
  8500. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  8501. }
  8502. }
  8503. }
  8504. if (global_config.yank_is_full_lines) {
  8505. env->col_no = 1;
  8506. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8507. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8508. env->col_no = i + 1;
  8509. break;
  8510. }
  8511. }
  8512. }
  8513. set_history_break();
  8514. set_modified();
  8515. redraw_all();
  8516. }
  8517. }
  8518. BIM_ACTION(insert_at_end, ACTION_IS_RW,
  8519. "Move the cursor to the end of the current line and enter insert mode."
  8520. )(void) {
  8521. env->col_no = env->lines[env->line_no-1]->actual+1;
  8522. env->mode = MODE_INSERT;
  8523. set_history_break();
  8524. }
  8525. BIM_ACTION(enter_replace, ACTION_IS_RW,
  8526. "Enter replace mode."
  8527. )(void) {
  8528. env->mode = MODE_REPLACE;
  8529. set_history_break();
  8530. }
  8531. BIM_ACTION(toggle_numbers, 0,
  8532. "Toggle the display of line numbers."
  8533. )(void) {
  8534. env->numbers = !env->numbers;
  8535. redraw_all();
  8536. place_cursor_actual();
  8537. }
  8538. BIM_ACTION(toggle_gutter, 0,
  8539. "Toggle the display of the revision status gutter."
  8540. )(void) {
  8541. env->gutter = !env->gutter;
  8542. redraw_all();
  8543. place_cursor_actual();
  8544. }
  8545. BIM_ACTION(toggle_indent, 0,
  8546. "Toggle smart indentation."
  8547. )(void) {
  8548. env->indent = !env->indent;
  8549. redraw_statusbar();
  8550. place_cursor_actual();
  8551. }
  8552. BIM_ACTION(toggle_smartcomplete, 0,
  8553. "Toggle smart completion."
  8554. )(void) {
  8555. global_config.smart_complete = !global_config.smart_complete;
  8556. redraw_statusbar();
  8557. place_cursor_actual();
  8558. }
  8559. BIM_ACTION(expand_split_right, 0,
  8560. "Move the view split divider to the right."
  8561. )(void) {
  8562. global_config.split_percent += 1;
  8563. update_split_size();
  8564. redraw_all();
  8565. }
  8566. BIM_ACTION(expand_split_left, 0,
  8567. "Move the view split divider to the left."
  8568. )(void) {
  8569. global_config.split_percent -= 1;
  8570. update_split_size();
  8571. redraw_all();
  8572. }
  8573. BIM_ACTION(go_page_up, 0,
  8574. "Jump up a screenfull."
  8575. )(void) {
  8576. int destination = env->line_no - (global_config.term_height - 6);
  8577. if (destination < 1) destination = 1;
  8578. goto_line(destination);
  8579. }
  8580. BIM_ACTION(go_page_down, 0,
  8581. "Jump down a screenfull."
  8582. )(void) {
  8583. goto_line(env->line_no + (global_config.term_height - 6));
  8584. }
  8585. BIM_ACTION(jump_to_matching_bracket, 0,
  8586. "Find and jump to the matching bracket for the character under the cursor."
  8587. )(void) {
  8588. recalculate_selected_lines();
  8589. int paren_line = -1, paren_col = -1;
  8590. find_matching_paren(&paren_line, &paren_col, 1);
  8591. if (paren_line != -1) {
  8592. env->line_no = paren_line;
  8593. env->col_no = paren_col;
  8594. set_preferred_column();
  8595. place_cursor_actual();
  8596. redraw_statusbar();
  8597. }
  8598. }
  8599. BIM_ACTION(jump_to_previous_blank, 0,
  8600. "Jump to the preceding blank line before the cursor."
  8601. )(void) {
  8602. env->col_no = 1;
  8603. if (env->line_no == 1) return;
  8604. do {
  8605. env->line_no--;
  8606. if (env->lines[env->line_no-1]->actual == 0) break;
  8607. } while (env->line_no > 1);
  8608. set_preferred_column();
  8609. redraw_statusbar();
  8610. }
  8611. BIM_ACTION(jump_to_next_blank, 0,
  8612. "Jump to the next blank line after the cursor."
  8613. )(void) {
  8614. env->col_no = 1;
  8615. if (env->line_no == env->line_count) return;
  8616. do {
  8617. env->line_no++;
  8618. if (env->lines[env->line_no-1]->actual == 0) break;
  8619. } while (env->line_no < env->line_count);
  8620. set_preferred_column();
  8621. redraw_statusbar();
  8622. }
  8623. BIM_ACTION(first_non_whitespace, 0,
  8624. "Jump to the first non-whitespace character in the current line."
  8625. )(void) {
  8626. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8627. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8628. env->col_no = i + 1;
  8629. break;
  8630. }
  8631. }
  8632. set_preferred_column();
  8633. redraw_statusbar();
  8634. }
  8635. BIM_ACTION(next_line_non_whitespace, 0,
  8636. "Jump to the first non-whitespace character in the next next line."
  8637. )(void) {
  8638. if (env->line_no < env->line_count) {
  8639. env->line_no++;
  8640. env->col_no = 1;
  8641. } else {
  8642. return;
  8643. }
  8644. first_non_whitespace();
  8645. }
  8646. BIM_ACTION(smart_backspace, ACTION_IS_RW,
  8647. "Delete the preceding character, with special handling for indentation."
  8648. )(void) {
  8649. if (!env->tabs && env->col_no > 1) {
  8650. int i;
  8651. for (i = 0; i < env->col_no-1; ++i) {
  8652. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) break;
  8653. }
  8654. if (i == env->col_no-1) {
  8655. /* Backspace until aligned */
  8656. delete_at_cursor();
  8657. while (env->col_no > 1 && (env->col_no-1) % env->tabstop) {
  8658. delete_at_cursor();
  8659. }
  8660. return;
  8661. }
  8662. }
  8663. delete_at_cursor();
  8664. }
  8665. BIM_ACTION(perform_omni_completion, ACTION_IS_RW,
  8666. "(temporary) Perform smart symbol completion from ctags."
  8667. )(void) {
  8668. /* This should probably be a submode */
  8669. while (omni_complete(0) == 1);
  8670. }
  8671. BIM_ACTION(smart_tab, ACTION_IS_RW,
  8672. "Insert a tab or spaces depending on indent mode. (Use ^V <tab> to guarantee a literal tab)"
  8673. )(void) {
  8674. if (env->tabs) {
  8675. insert_char('\t');
  8676. } else {
  8677. for (int i = 0; i < env->tabstop; ++i) {
  8678. insert_char(' ');
  8679. }
  8680. }
  8681. }
  8682. BIM_ACTION(smart_comment_end, ARG_IS_INPUT | ACTION_IS_RW,
  8683. "Insert a `/` ending a C-style comment."
  8684. )(int c) {
  8685. /* smart *end* of comment anyway */
  8686. if (env->indent) {
  8687. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  8688. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  8689. (env->col_no > 3) &&
  8690. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  8691. env->col_no--;
  8692. replace_char('/');
  8693. env->col_no++;
  8694. place_cursor_actual();
  8695. return;
  8696. }
  8697. }
  8698. insert_char(c);
  8699. }
  8700. BIM_ACTION(smart_brace_end, ARG_IS_INPUT | ACTION_IS_RW,
  8701. "Insert a closing brace and smartly position it if it is the first character on a line."
  8702. )(int c) {
  8703. if (env->indent) {
  8704. int was_whitespace = 1;
  8705. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8706. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  8707. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  8708. was_whitespace = 0;
  8709. break;
  8710. }
  8711. }
  8712. insert_char(c);
  8713. if (was_whitespace) {
  8714. int line = -1, col = -1;
  8715. env->col_no--;
  8716. find_matching_paren(&line,&col, 1);
  8717. if (line != -1) {
  8718. line = find_brace_line_start(line, col);
  8719. while (env->lines[env->line_no-1]->actual) {
  8720. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  8721. }
  8722. add_indent(env->line_no-1,line-1,1);
  8723. env->col_no = env->lines[env->line_no-1]->actual + 1;
  8724. insert_char(c);
  8725. }
  8726. }
  8727. set_preferred_column();
  8728. return;
  8729. }
  8730. insert_char(c);
  8731. }
  8732. BIM_ACTION(enter_line_selection_and_cursor_up, 0,
  8733. "Enter line selection and move the cursor up one line."
  8734. )(void) {
  8735. enter_line_selection();
  8736. cursor_up();
  8737. }
  8738. BIM_ACTION(enter_line_selection_and_cursor_down, 0,
  8739. "Enter line selection and move the cursor down one line."
  8740. )(void) {
  8741. enter_line_selection();
  8742. cursor_down();
  8743. }
  8744. BIM_ACTION(shift_horizontally, ARG_IS_CUSTOM,
  8745. "Shift the current line or screen view horizontally, depending on settings."
  8746. )(int amount) {
  8747. env->coffset += amount;
  8748. if (env->coffset < 0) env->coffset = 0;
  8749. redraw_text();
  8750. }
  8751. static int state_before_paste = 0;
  8752. static int line_before_paste = 0;
  8753. BIM_ACTION(paste_begin, 0, "Begin bracketed paste; disable indentation, completion, etc.")(void) {
  8754. if (global_config.smart_complete) state_before_paste |= 0x01;
  8755. if (env->indent) state_before_paste |= 0x02;
  8756. global_config.smart_complete = 0;
  8757. env->indent = 0;
  8758. env->slowop = 1;
  8759. line_before_paste = env->line_no;
  8760. }
  8761. BIM_ACTION(paste_end, 0, "End bracketed paste; restore indentation, completion, etc.")(void) {
  8762. if (state_before_paste & 0x01) global_config.smart_complete = 1;
  8763. if (state_before_paste & 0x02) env->indent = 1;
  8764. env->slowop = 0;
  8765. int line_to_recalculate = (line_before_paste > 1 ? line_before_paste - 1 : 0);
  8766. recalculate_syntax(env->lines[line_to_recalculate], line_to_recalculate);
  8767. redraw_all();
  8768. }
  8769. struct action_map _NORMAL_MAP[] = {
  8770. {KEY_BACKSPACE, cursor_left_with_wrap, opt_rep, 0},
  8771. {'V', enter_line_selection, 0, 0},
  8772. {'v', enter_char_selection, 0, 0},
  8773. {KEY_CTRL_V, enter_col_selection, 0, 0},
  8774. {'O', prepend_and_insert, opt_rw, 0},
  8775. {'o', append_and_insert, opt_rw, 0},
  8776. {'a', insert_after_cursor, opt_rw, 0},
  8777. {'s', delete_forward_and_insert, opt_rw, 0},
  8778. {'x', delete_forward, opt_rep | opt_rw, 0},
  8779. {'P', paste, opt_arg | opt_rw, -1},
  8780. {'p', paste, opt_arg | opt_rw, 1},
  8781. {'r', replace_char, opt_char | opt_rw, 0},
  8782. {'A', insert_at_end, opt_rw, 0},
  8783. {'u', undo_history, opt_rw, 0},
  8784. {KEY_CTRL_R, redo_history, opt_rw, 0},
  8785. {KEY_CTRL_L, redraw_all, 0, 0},
  8786. {KEY_CTRL_G, goto_definition, 0, 0},
  8787. {'i', enter_insert, opt_rw, 0},
  8788. {'R', enter_replace, opt_rw, 0},
  8789. {KEY_SHIFT_UP, enter_line_selection_and_cursor_up, 0, 0},
  8790. {KEY_SHIFT_DOWN, enter_line_selection_and_cursor_down, 0, 0},
  8791. {KEY_ALT_UP, previous_tab, 0, 0},
  8792. {KEY_ALT_DOWN, next_tab, 0, 0},
  8793. {KEY_CTRL_UNDERSCORE, start_file_search, 0, 0},
  8794. {-1, NULL, 0, 0},
  8795. };
  8796. struct action_map _INSERT_MAP[] = {
  8797. {KEY_ESCAPE, leave_insert, 0, 0},
  8798. {KEY_DELETE, delete_forward, 0, 0},
  8799. {KEY_CTRL_C, leave_insert, 0, 0},
  8800. {KEY_BACKSPACE, smart_backspace, 0, 0},
  8801. {KEY_ENTER, insert_line_feed, 0, 0},
  8802. {KEY_CTRL_O, perform_omni_completion, 0, 0},
  8803. {KEY_CTRL_V, insert_char, opt_byte, 0},
  8804. {KEY_CTRL_W, delete_word, 0, 0},
  8805. {'\t', smart_tab, 0, 0},
  8806. {'/', smart_comment_end, opt_arg, '/'},
  8807. {'}', smart_brace_end, opt_arg, '}'},
  8808. {KEY_PASTE_BEGIN, paste_begin, 0, 0},
  8809. {KEY_PASTE_END, paste_end, 0, 0},
  8810. {-1, NULL, 0, 0},
  8811. };
  8812. struct action_map _REPLACE_MAP[] = {
  8813. {KEY_ESCAPE, leave_insert, 0, 0},
  8814. {KEY_DELETE, delete_forward, 0, 0},
  8815. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8816. {KEY_ENTER, insert_line_feed, 0, 0},
  8817. {-1, NULL, 0, 0},
  8818. };
  8819. struct action_map _LINE_SELECTION_MAP[] = {
  8820. {KEY_ESCAPE, leave_selection, 0, 0},
  8821. {KEY_CTRL_C, leave_selection, 0, 0},
  8822. {'V', leave_selection, 0, 0},
  8823. {'v', switch_selection_mode, opt_arg, MODE_CHAR_SELECTION},
  8824. {'y', yank_lines, opt_norm, 0},
  8825. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8826. {'\t', adjust_indent, opt_arg | opt_rw, 1},
  8827. {KEY_SHIFT_TAB, adjust_indent, opt_arg | opt_rw, -1},
  8828. {'D', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8829. {'d', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8830. {'x', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8831. {'s', delete_lines_and_enter_insert, opt_rw, 0},
  8832. {'r', replace_chars_in_line, opt_char | opt_rw, 0},
  8833. {KEY_SHIFT_UP, cursor_up, 0, 0},
  8834. {KEY_SHIFT_DOWN, cursor_down, 0, 0},
  8835. {-1, NULL, 0, 0},
  8836. };
  8837. struct action_map _CHAR_SELECTION_MAP[] = {
  8838. {KEY_ESCAPE, leave_selection, 0, 0},
  8839. {KEY_CTRL_C, leave_selection, 0, 0},
  8840. {'v', leave_selection, 0, 0},
  8841. {'V', switch_selection_mode, opt_arg, MODE_LINE_SELECTION},
  8842. {'y', yank_characters, opt_norm, 0},
  8843. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8844. {'D', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8845. {'d', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8846. {'x', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8847. {'s', delete_chars_and_enter_insert, opt_rw, 0},
  8848. {'r', replace_chars, opt_char | opt_rw, 0},
  8849. {'A', insert_at_end_of_selection, opt_rw, 0},
  8850. {-1, NULL, 0, 0},
  8851. };
  8852. struct action_map _COL_SELECTION_MAP[] = {
  8853. {KEY_ESCAPE, leave_selection, 0, 0},
  8854. {KEY_CTRL_C, leave_selection, 0, 0},
  8855. {KEY_CTRL_V, leave_selection, 0, 0},
  8856. {'I', enter_col_insert, opt_rw, 0},
  8857. {'a', enter_col_insert_after, opt_rw, 0},
  8858. {'d', delete_at_column, opt_arg | opt_rw, 1},
  8859. {-1, NULL, 0, 0},
  8860. };
  8861. struct action_map _COL_INSERT_MAP[] = {
  8862. {KEY_ESCAPE, leave_selection, 0, 0},
  8863. {KEY_CTRL_C, leave_selection, 0, 0},
  8864. {KEY_BACKSPACE, delete_at_column, opt_arg, -1},
  8865. {KEY_DELETE, delete_at_column, opt_arg, 1},
  8866. {KEY_ENTER, NULL, 0, 0},
  8867. {KEY_CTRL_W, NULL, 0, 0},
  8868. {KEY_CTRL_V, insert_char_at_column, opt_char, 0},
  8869. {'\t', insert_tab_at_column, 0, 0},
  8870. {KEY_LEFT, column_left, 0, 0},
  8871. {KEY_RIGHT, column_right, 0, 0},
  8872. {KEY_UP, column_up, 0, 0},
  8873. {KEY_DOWN, column_down, 0, 0},
  8874. {-1, NULL, 0, 0},
  8875. };
  8876. struct action_map _NAVIGATION_MAP[] = {
  8877. /* Common navigation */
  8878. {KEY_CTRL_B, go_page_up, opt_rep, 0},
  8879. {KEY_CTRL_F, go_page_down, opt_rep, 0},
  8880. {':', enter_command, 0, 0},
  8881. {'/', enter_search, opt_arg, 1},
  8882. {'?', enter_search, opt_arg, 0},
  8883. {'n', search_next, opt_rep, 0},
  8884. {'N', search_prev, opt_rep, 0},
  8885. {'j', cursor_down, opt_rep, 0},
  8886. {'k', cursor_up, opt_rep, 0},
  8887. {'h', cursor_left, opt_rep, 0},
  8888. {'l', cursor_right, opt_rep, 0},
  8889. {'b', word_left, opt_rep, 0},
  8890. {'w', word_right, opt_rep, 0},
  8891. {'B', big_word_left, opt_rep, 0},
  8892. {'W', big_word_right, opt_rep, 0},
  8893. {'<', shift_horizontally, opt_arg, -1},
  8894. {'>', shift_horizontally, opt_arg, 1},
  8895. {'f', find_character_forward, opt_rep | opt_arg | opt_char, 'f'},
  8896. {'F', find_character_backward, opt_rep | opt_arg | opt_char, 'F'},
  8897. {'t', find_character_forward, opt_rep | opt_arg | opt_char, 't'},
  8898. {'T', find_character_backward, opt_rep | opt_arg | opt_char, 'T'},
  8899. {'G', goto_line, opt_nav, 0},
  8900. {'*', search_under_cursor, 0, 0},
  8901. {' ', go_page_down, opt_rep, 0},
  8902. {'%', jump_to_matching_bracket, 0, 0},
  8903. {'{', jump_to_previous_blank, opt_rep, 0},
  8904. {'}', jump_to_next_blank, opt_rep, 0},
  8905. {'$', cursor_end, 0, 0},
  8906. {'|', cursor_home, 0, 0},
  8907. {KEY_ENTER, next_line_non_whitespace, opt_rep, 0},
  8908. {'^', first_non_whitespace, 0, 0},
  8909. {'0', cursor_home, 0, 0},
  8910. {-1, NULL, 0, 0},
  8911. };
  8912. struct action_map _ESCAPE_MAP[] = {
  8913. {KEY_F1, toggle_numbers, 0, 0},
  8914. {KEY_F2, toggle_indent, 0, 0},
  8915. {KEY_F3, toggle_gutter, 0, 0},
  8916. {KEY_F4, toggle_smartcomplete, 0, 0},
  8917. {KEY_MOUSE, handle_mouse, 0, 0},
  8918. {KEY_MOUSE_SGR, handle_mouse_sgr, 0, 0},
  8919. {KEY_UP, cursor_up, opt_rep, 0},
  8920. {KEY_DOWN, cursor_down, opt_rep, 0},
  8921. {KEY_RIGHT, cursor_right, opt_rep, 0},
  8922. {KEY_CTRL_RIGHT, big_word_right, opt_rep, 0},
  8923. {KEY_SHIFT_RIGHT, word_right, opt_rep, 0},
  8924. {KEY_ALT_RIGHT, expand_split_right, opt_rep, 0},
  8925. {KEY_ALT_SHIFT_RIGHT, use_right_buffer, opt_rep, 0},
  8926. {KEY_LEFT, cursor_left, opt_rep, 0},
  8927. {KEY_CTRL_LEFT, big_word_left, opt_rep, 0},
  8928. {KEY_SHIFT_LEFT, word_left, opt_rep, 0},
  8929. {KEY_ALT_LEFT, expand_split_left, opt_rep, 0},
  8930. {KEY_ALT_SHIFT_LEFT, use_left_buffer, opt_rep, 0},
  8931. {KEY_HOME, cursor_home, 0, 0},
  8932. {KEY_END, cursor_end, 0, 0},
  8933. {KEY_PAGE_UP, go_page_up, opt_rep, 0},
  8934. {KEY_PAGE_DOWN, go_page_down, opt_rep, 0},
  8935. {KEY_CTRL_Z, suspend, 0, 0},
  8936. {-1, NULL, 0, 0}
  8937. };
  8938. struct action_map _COMMAND_MAP[] = {
  8939. {KEY_ENTER, command_accept, 0, 0},
  8940. {'\t', command_tab_complete_buffer, 0, 0},
  8941. {KEY_UP, command_scroll_history, opt_arg, -1}, /* back */
  8942. {KEY_DOWN, command_scroll_history, opt_arg, 1}, /* forward */
  8943. {-1, NULL, 0, 0}
  8944. };
  8945. struct action_map _FILESEARCH_MAP[] = {
  8946. {KEY_ENTER, file_search_accept, 0, 0},
  8947. {KEY_UP, NULL, 0, 0},
  8948. {KEY_DOWN, NULL, 0, 0},
  8949. {-1, NULL, 0, 0}
  8950. };
  8951. struct action_map _SEARCH_MAP[] = {
  8952. {KEY_ENTER, search_accept, 0, 0},
  8953. {KEY_UP, command_scroll_search_history, opt_arg, -1}, /* back */
  8954. {KEY_DOWN, command_scroll_search_history, opt_arg, 1}, /* forward */
  8955. {-1, NULL, 0, 0}
  8956. };
  8957. struct action_map _INPUT_BUFFER_MAP[] = {
  8958. /* These are generic and shared with search */
  8959. {KEY_ESCAPE, command_discard, 0, 0},
  8960. {KEY_CTRL_C, command_discard, 0, 0},
  8961. {KEY_BACKSPACE, command_backspace, 0, 0},
  8962. {KEY_CTRL_W, command_word_delete, 0, 0},
  8963. {KEY_MOUSE, eat_mouse, 0, 0},
  8964. {KEY_MOUSE_SGR, eat_mouse_sgr, 0, 0},
  8965. {KEY_LEFT, command_cursor_left, 0, 0},
  8966. {KEY_CTRL_LEFT, command_word_left, 0, 0},
  8967. {KEY_RIGHT, command_cursor_right, 0, 0},
  8968. {KEY_CTRL_RIGHT,command_word_right, 0, 0},
  8969. {KEY_HOME, command_cursor_home, 0, 0},
  8970. {KEY_END, command_cursor_end, 0, 0},
  8971. {-1, NULL, 0, 0}
  8972. };
  8973. /* DIRECTORY_BROWSE_MAP is only to override KEY_ENTER and should not be remapped,
  8974. * so unlike the others it is not going to be redefined as a pointer. */
  8975. struct action_map DIRECTORY_BROWSE_MAP[] = {
  8976. {KEY_ENTER, open_file_from_line, 0, 0},
  8977. {-1, NULL, 0, 0}
  8978. };
  8979. struct action_map * NORMAL_MAP = NULL;
  8980. struct action_map * INSERT_MAP = NULL;
  8981. struct action_map * REPLACE_MAP = NULL;
  8982. struct action_map * LINE_SELECTION_MAP = NULL;
  8983. struct action_map * CHAR_SELECTION_MAP = NULL;
  8984. struct action_map * COL_SELECTION_MAP = NULL;
  8985. struct action_map * COL_INSERT_MAP = NULL;
  8986. struct action_map * NAVIGATION_MAP = NULL;
  8987. struct action_map * ESCAPE_MAP = NULL;
  8988. struct action_map * COMMAND_MAP = NULL;
  8989. struct action_map * SEARCH_MAP = NULL;
  8990. struct action_map * FILESEARCH_MAP = NULL;
  8991. struct action_map * INPUT_BUFFER_MAP = NULL;
  8992. struct mode_names mode_names[] = {
  8993. {"Normal","norm",&NORMAL_MAP},
  8994. {"Insert","insert",&INSERT_MAP},
  8995. {"Replace","replace",&REPLACE_MAP},
  8996. {"Line Selection","line",&LINE_SELECTION_MAP},
  8997. {"Char Selection","char",&CHAR_SELECTION_MAP},
  8998. {"Col Selection","col",&COL_SELECTION_MAP},
  8999. {"Col Insert","colinsert",&COL_INSERT_MAP},
  9000. {"Navigation (Select)","nav",&NAVIGATION_MAP},
  9001. {"Escape (Select, Insert)","esc",&ESCAPE_MAP},
  9002. {"Command","command",&COMMAND_MAP},
  9003. {"Search","search",&SEARCH_MAP},
  9004. {"Input (Command, Search)","input",&INPUT_BUFFER_MAP},
  9005. {NULL,NULL,NULL},
  9006. };
  9007. int handle_action(struct action_map * basemap, int key) {
  9008. for (struct action_map * map = basemap; map->key != -1; map++) {
  9009. if (map->key == key) {
  9010. if (!map->method) return 1;
  9011. if ((map->options & opt_rw) && (env->readonly)) {
  9012. render_error("Buffer is read-only");
  9013. return 2;
  9014. }
  9015. /* Determine how to format this request */
  9016. int reps = (map->options & opt_rep) ? ((nav_buffer) ? atoi(nav_buf) : 1) : 1;
  9017. int c = 0;
  9018. if (map->options & opt_char) {
  9019. c = read_one_character(name_from_key(key));
  9020. }
  9021. if (map->options & opt_byte) {
  9022. c = read_one_byte(name_from_key(key));
  9023. }
  9024. for (int i = 0; i < reps; ++i) {
  9025. if (((map->options & opt_char) || (map->options & opt_byte)) && (map->options & opt_arg)) {
  9026. map->method(map->arg, c);
  9027. } else if ((map->options & opt_char) || (map->options & opt_byte)) {
  9028. map->method(c);
  9029. } else if (map->options & opt_arg) {
  9030. map->method(map->arg);
  9031. } else if (map->options & opt_nav) {
  9032. if (nav_buffer) {
  9033. map->method(atoi(nav_buf));
  9034. reset_nav_buffer(0);
  9035. } else {
  9036. map->method(-1);
  9037. }
  9038. } else {
  9039. map->method();
  9040. }
  9041. }
  9042. if (map->options & opt_norm) {
  9043. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) leave_insert();
  9044. else if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) leave_selection();
  9045. else {
  9046. env->mode = MODE_NORMAL;
  9047. redraw_all();
  9048. }
  9049. }
  9050. return 1;
  9051. }
  9052. }
  9053. return 0;
  9054. }
  9055. int handle_nav_buffer(int key) {
  9056. if ((key >= '1' && key <= '9') || (key == '0' && nav_buffer)) {
  9057. if (nav_buffer < NAV_BUFFER_MAX) {
  9058. /* Up to NAV_BUFFER_MAX=10 characters; that should be enough for most tasks */
  9059. nav_buf[nav_buffer] = key;
  9060. nav_buf[nav_buffer+1] = 0;
  9061. nav_buffer++;
  9062. /* Print the number buffer */
  9063. redraw_commandline();
  9064. }
  9065. return 0;
  9066. }
  9067. return 1;
  9068. }
  9069. /**
  9070. * NORMAL mode
  9071. *
  9072. * Default editor mode - just cursor navigation and keybinds
  9073. * to enter the other modes.
  9074. */
  9075. void normal_mode(void) {
  9076. int last_mode = MODE_NORMAL;
  9077. int refresh = 0;
  9078. while (1) {
  9079. if (global_config.overlay_mode) {
  9080. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND) {
  9081. if (refresh) {
  9082. render_command_input_buffer();
  9083. refresh = 0;
  9084. }
  9085. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9086. if (key != KEY_TIMEOUT) {
  9087. refresh = 1;
  9088. if (!handle_action(COMMAND_MAP, key))
  9089. if (!handle_action(INPUT_BUFFER_MAP, key))
  9090. if (key < KEY_ESCAPE) command_insert_char(key);
  9091. }
  9092. continue;
  9093. } else if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  9094. if (refresh) {
  9095. redraw_tabbar();
  9096. render_command_input_buffer();
  9097. refresh = 0;
  9098. }
  9099. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9100. if (key != KEY_TIMEOUT) {
  9101. refresh = 1;
  9102. if (!handle_action(FILESEARCH_MAP, key))
  9103. if (!handle_action(INPUT_BUFFER_MAP, key))
  9104. if (key < KEY_ESCAPE) command_insert_char(key);
  9105. }
  9106. continue;
  9107. } else if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  9108. if (refresh) {
  9109. render_command_input_buffer();
  9110. refresh = 0;
  9111. }
  9112. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9113. if (key != KEY_TIMEOUT) {
  9114. refresh = 1;
  9115. if (!handle_action(SEARCH_MAP, key)) {
  9116. if (!handle_action(INPUT_BUFFER_MAP, key)) {
  9117. if (key < KEY_ESCAPE) command_insert_char(key);
  9118. }
  9119. }
  9120. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  9121. /* Find the next search match */
  9122. uint32_t * buffer = malloc(sizeof(uint32_t) * (global_config.command_buffer->actual+1));
  9123. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  9124. buffer[i] = global_config.command_buffer->text[i].codepoint;
  9125. }
  9126. buffer[global_config.command_buffer->actual] = 0;
  9127. int line = -1, col = -1;
  9128. if (global_config.search_direction == 1) {
  9129. find_match(global_config.prev_line, global_config.prev_col, &line, &col, buffer, NULL);
  9130. if (line == -1 && global_config.search_wraps) {
  9131. find_match(1, 1, &line, &col, buffer, NULL);
  9132. }
  9133. } else {
  9134. find_match_backwards(global_config.prev_line, global_config.prev_col, &line, &col, buffer);
  9135. if (line == -1 && global_config.search_wraps) {
  9136. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, buffer);
  9137. }
  9138. }
  9139. if (line != -1) {
  9140. env->col_no = col;
  9141. env->line_no = line;
  9142. set_preferred_column();
  9143. } else {
  9144. env->coffset = global_config.prev_coffset;
  9145. env->offset = global_config.prev_offset;
  9146. env->col_no = global_config.prev_col;
  9147. set_preferred_column();
  9148. env->line_no = global_config.prev_line;
  9149. }
  9150. draw_search_match(buffer, 0);
  9151. free(buffer);
  9152. }
  9153. }
  9154. continue;
  9155. }
  9156. }
  9157. if (env->mode != last_mode) {
  9158. redraw_statusbar();
  9159. redraw_commandline();
  9160. last_mode = env->mode;
  9161. }
  9162. if (env->mode == MODE_NORMAL) {
  9163. place_cursor_actual();
  9164. int key = 0;
  9165. do {
  9166. key = bim_getkey(DEFAULT_KEY_WAIT);
  9167. } while (key == KEY_TIMEOUT);
  9168. if (handle_nav_buffer(key)) {
  9169. if (!handle_action(NORMAL_MAP, key))
  9170. if (!handle_action(NAVIGATION_MAP, key))
  9171. handle_action(ESCAPE_MAP, key);
  9172. }
  9173. reset_nav_buffer(key);
  9174. } else if (env->mode == MODE_INSERT) {
  9175. if (!refresh) place_cursor_actual();
  9176. int key = bim_getkey(refresh ? 10 : DEFAULT_KEY_WAIT);
  9177. if (key == KEY_TIMEOUT) {
  9178. place_cursor_actual();
  9179. if (refresh > 1) {
  9180. redraw_text();
  9181. } else if (refresh) {
  9182. redraw_line(env->line_no-1);
  9183. }
  9184. refresh = 0;
  9185. } else if (handle_action(INSERT_MAP, key)) {
  9186. refresh = 2;
  9187. } else if (handle_action(ESCAPE_MAP, key)) {
  9188. /* Do nothing */
  9189. } else if (key < KEY_ESCAPE) {
  9190. insert_char(key);
  9191. if (global_config.smart_complete) {
  9192. redraw_line(env->line_no-1);
  9193. while (omni_complete(1) == 1);
  9194. }
  9195. refresh |= 1;
  9196. }
  9197. } else if (env->mode == MODE_REPLACE) {
  9198. place_cursor_actual();
  9199. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9200. if (key != KEY_TIMEOUT) {
  9201. if (handle_action(REPLACE_MAP, key)) {
  9202. redraw_text();
  9203. } else if (!handle_action(ESCAPE_MAP, key)) {
  9204. /* Perform replacement */
  9205. if (key < KEY_ESCAPE) {
  9206. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  9207. replace_char(key);
  9208. env->col_no += 1;
  9209. } else {
  9210. insert_char(key);
  9211. redraw_line(env->line_no-1);
  9212. }
  9213. set_preferred_column();
  9214. }
  9215. }
  9216. }
  9217. } else if (env->mode == MODE_LINE_SELECTION) {
  9218. place_cursor_actual();
  9219. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9220. if (key == KEY_TIMEOUT) continue;
  9221. if (handle_nav_buffer(key)) {
  9222. if (!handle_action(LINE_SELECTION_MAP, key))
  9223. if (!handle_action(NAVIGATION_MAP, key))
  9224. handle_action(ESCAPE_MAP, key);
  9225. }
  9226. reset_nav_buffer(key);
  9227. if (env->mode == MODE_LINE_SELECTION) {
  9228. /* Mark current line */
  9229. _redraw_line(env->line_no,0);
  9230. _redraw_line(env->start_line,1);
  9231. /* Properly mark everything in the span we just moved through */
  9232. if (env->prev_line < env->line_no) {
  9233. for (int i = env->prev_line; i < env->line_no; ++i) {
  9234. _redraw_line(i,0);
  9235. }
  9236. env->prev_line = env->line_no;
  9237. } else if (env->prev_line > env->line_no) {
  9238. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  9239. _redraw_line(i,0);
  9240. }
  9241. env->prev_line = env->line_no;
  9242. }
  9243. redraw_commandline();
  9244. }
  9245. } else if (env->mode == MODE_CHAR_SELECTION) {
  9246. place_cursor_actual();
  9247. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9248. if (key == KEY_TIMEOUT) continue;
  9249. if (handle_nav_buffer(key)) {
  9250. if (!handle_action(CHAR_SELECTION_MAP, key))
  9251. if (!handle_action(NAVIGATION_MAP, key))
  9252. handle_action(ESCAPE_MAP, key);
  9253. }
  9254. reset_nav_buffer(key);
  9255. if (env->mode == MODE_CHAR_SELECTION) {
  9256. /* Mark current line */
  9257. _redraw_line_char(env->line_no,1);
  9258. /* Properly mark everything in the span we just moved through */
  9259. if (env->prev_line < env->line_no) {
  9260. for (int i = env->prev_line; i < env->line_no; ++i) {
  9261. _redraw_line_char(i,1);
  9262. }
  9263. env->prev_line = env->line_no;
  9264. } else if (env->prev_line > env->line_no) {
  9265. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  9266. _redraw_line_char(i,1);
  9267. }
  9268. env->prev_line = env->line_no;
  9269. }
  9270. }
  9271. } else if (env->mode == MODE_COL_SELECTION) {
  9272. place_cursor_actual();
  9273. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9274. if (key == KEY_TIMEOUT) continue;
  9275. if (handle_nav_buffer(key)) {
  9276. if (!handle_action(COL_SELECTION_MAP, key))
  9277. if (!handle_action(NAVIGATION_MAP, key))
  9278. handle_action(ESCAPE_MAP, key);
  9279. }
  9280. reset_nav_buffer(key);
  9281. if (env->mode == MODE_COL_SELECTION) {
  9282. _redraw_line_col(env->line_no, 0);
  9283. /* Properly mark everything in the span we just moved through */
  9284. if (env->prev_line < env->line_no) {
  9285. for (int i = env->prev_line; i < env->line_no; ++i) {
  9286. _redraw_line_col(i,0);
  9287. }
  9288. env->prev_line = env->line_no;
  9289. } else if (env->prev_line > env->line_no) {
  9290. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  9291. _redraw_line_col(i,0);
  9292. }
  9293. env->prev_line = env->line_no;
  9294. }
  9295. redraw_commandline();
  9296. }
  9297. } else if (env->mode == MODE_COL_INSERT) {
  9298. int key = bim_getkey(refresh ? 10 : DEFAULT_KEY_WAIT);
  9299. if (key == KEY_TIMEOUT) {
  9300. if (refresh) {
  9301. redraw_commandline();
  9302. redraw_text();
  9303. }
  9304. refresh = 0;
  9305. } else if (handle_action(COL_INSERT_MAP, key)) {
  9306. refresh = 2;
  9307. } else if (key < KEY_ESCAPE) {
  9308. insert_char_at_column(key);
  9309. refresh = 1;
  9310. }
  9311. } if (env->mode == MODE_DIRECTORY_BROWSE) {
  9312. place_cursor_actual();
  9313. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9314. if (handle_nav_buffer(key)) {
  9315. if (!handle_action(DIRECTORY_BROWSE_MAP, key))
  9316. if (!handle_action(NAVIGATION_MAP, key))
  9317. handle_action(ESCAPE_MAP, key);
  9318. }
  9319. reset_nav_buffer(key);
  9320. }
  9321. }
  9322. }
  9323. KrkClass * CommandDef;
  9324. struct CommandDef {
  9325. KrkInstance inst;
  9326. struct command_def * command;
  9327. };
  9328. int process_krk_command(const char * cmd, KrkValue * outVal) {
  9329. place_cursor(global_config.term_width, global_config.term_height);
  9330. fprintf(stdout, "\n");
  9331. /* By resetting, we're at 0 frames. */
  9332. krk_resetStack();
  9333. /* Push something so we're not at the bottom of the stack when an
  9334. * exception happens, or we'll get the normal interpreter behavior
  9335. * and won't be able to examine the exception ourselves. */
  9336. krk_push(NONE_VAL());
  9337. /* If we don't set outSlots for the top frame a syntax error will
  9338. * get printed by the interpreter and we can't catch it here. */
  9339. krk_currentThread.frames[0].outSlots = 1;
  9340. /* Call the interpreter */
  9341. KrkValue out = krk_interpret(cmd,"<bim>");
  9342. /* If the user typed just a command name, try to execute it. */
  9343. if (krk_isInstanceOf(out,CommandDef)) {
  9344. krk_push(out);
  9345. out = krk_callStack(0);
  9346. }
  9347. if (outVal) *outVal = out;
  9348. int retval = (IS_INTEGER(out)) ? AS_INTEGER(out) : 0;
  9349. int hadOutput = 0;
  9350. /* If we got an exception during execution, print it now */
  9351. if (krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION) {
  9352. if (krk_isInstanceOf(krk_currentThread.currentException, vm.exceptions->syntaxError)) {
  9353. }
  9354. set_fg_color(COLOR_RED);
  9355. fflush(stdout);
  9356. krk_dumpTraceback();
  9357. set_fg_color(COLOR_FG);
  9358. fflush(stdout);
  9359. hadOutput = 1;
  9360. krk_resetStack();
  9361. }
  9362. /* Otherwise, we can look at the result here. */
  9363. if (!IS_NONE(out) && !(IS_INTEGER(out) && AS_INTEGER(out) == 0)) {
  9364. krk_attachNamedValue(&vm.builtins->fields, "_", out);
  9365. krk_push(out);
  9366. KrkValue repr = krk_callDirect(krk_getType(out)->_reprer, 1);
  9367. if (IS_STRING(repr)) {
  9368. fprintf(stdout, " => %s\n", AS_CSTRING(repr));
  9369. clear_to_end();
  9370. }
  9371. krk_resetStack();
  9372. hadOutput = 1;
  9373. }
  9374. /* If we had either an exception or a non-zero, non-None result,
  9375. * we want to wait for a key press before continuing, and avoid
  9376. * clearing the screen if the user is going to enter another command. */
  9377. if (hadOutput) {
  9378. int c;
  9379. while ((c = bim_getch())== -1);
  9380. if (c != ':') {
  9381. bim_unget(c);
  9382. } else {
  9383. enter_command();
  9384. global_config.command_offset = 0;
  9385. global_config.command_col_no = 1;
  9386. render_command_input_buffer();
  9387. return retval;
  9388. }
  9389. }
  9390. global_config.break_from_selection = 1;
  9391. if (!global_config.had_error) redraw_all();
  9392. global_config.had_error = 0;
  9393. return retval;
  9394. }
  9395. /**
  9396. * Show help text for -?
  9397. */
  9398. static void show_usage(char * argv[]) {
  9399. #define _s "\033[3m"
  9400. #define _e "\033[0m\n"
  9401. printf(
  9402. "bim - Text editor\n"
  9403. "\n"
  9404. "usage: %s [options] [file]\n"
  9405. " %s [options] -- -\n"
  9406. "\n"
  9407. " -R " _s "open initial buffer read-only" _e
  9408. " -O " _s "set various options; examples:" _e
  9409. " noaltscreen " _s "disable alternate screen buffer" _e
  9410. " nounicode " _s "disable unicode display" _e
  9411. " nosyntax " _s "disable syntax highlighting on load" _e
  9412. " nohistory " _s "disable undo/redo" _e
  9413. " nomouse " _s "disable mouse support" _e
  9414. " cansgrmouse " _s "enable SGR mouse escape sequences" _e
  9415. " -c,-C " _s "print file to stdout with syntax highlighting" _e
  9416. " " _s "-C includes line numbers, -c does not" _e
  9417. " -u " _s "override bimrc file" _e
  9418. " -? " _s "show this help text" _e
  9419. "\n"
  9420. "Long options:\n"
  9421. " --help " _s "show this help text" _e
  9422. " --version " _s "show version information and available plugins" _e
  9423. " --dump-mappings " _s "dump markdown description of key mappings" _e
  9424. " --dump-commands " _s "dump markdown description of all commands" _e
  9425. " --dump-config " _s "dump key mappings as a bimscript" _e
  9426. " --html FILE " _s "convert FILE to syntax-highlighted HTML" _e
  9427. "\n", argv[0], argv[0]);
  9428. #undef _e
  9429. #undef _s
  9430. }
  9431. BIM_COMMAND(runkrk,"runkrk", "Run a kuroko script") {
  9432. if (argc < 2) return 1;
  9433. krk_runfile(argv[1],argv[1]);
  9434. redraw_all();
  9435. return 0;
  9436. }
  9437. /**
  9438. * Enable or disable terminal features/quirks and other options.
  9439. * Used by -O and by the `quirks` bimrc command.
  9440. */
  9441. int set_capability(char * arg) {
  9442. char * argname;
  9443. int value;
  9444. if (strstr(arg,"no") == arg) {
  9445. argname = &arg[2];
  9446. value = 0;
  9447. } else if (strstr(arg,"can") == arg) {
  9448. argname = &arg[3];
  9449. value = 1;
  9450. } else {
  9451. render_error("Capabilities must by 'no{CAP}' or 'can{CAP}': %s", arg);
  9452. return 2;
  9453. }
  9454. /* Terminal features / quirks */
  9455. if (!strcmp(argname, "24bit")) global_config.can_24bit = value;
  9456. else if (!strcmp(argname, "256color")) global_config.can_256color = value;
  9457. else if (!strcmp(argname, "altscreen")) global_config.can_altscreen = value;
  9458. else if (!strcmp(argname, "bce")) global_config.can_bce = value;
  9459. else if (!strcmp(argname, "bright")) global_config.can_bright = value;
  9460. else if (!strcmp(argname, "hideshow")) global_config.can_hideshow = value;
  9461. else if (!strcmp(argname, "italic")) global_config.can_italic = value;
  9462. else if (!strcmp(argname, "mouse")) global_config.can_mouse = value;
  9463. else if (!strcmp(argname, "scroll")) global_config.can_scroll = value;
  9464. else if (!strcmp(argname, "title")) global_config.can_title = value;
  9465. else if (!strcmp(argname, "unicode")) global_config.can_unicode = value;
  9466. else if (!strcmp(argname, "insert")) global_config.can_insert = value;
  9467. else if (!strcmp(argname, "paste")) global_config.can_bracketedpaste = value;
  9468. else if (!strcmp(argname, "sgrmouse")) global_config.can_sgrmouse = value;
  9469. /* Startup options */
  9470. else if (!strcmp(argname, "syntax")) global_config.highlight_on_open = value;
  9471. else if (!strcmp(argname, "history")) global_config.history_enabled = value;
  9472. else {
  9473. render_error("Unknown capability: %s", argname);
  9474. return 1;
  9475. }
  9476. return 0;
  9477. }
  9478. BIM_COMMAND(setcap, "setcap", "Enable or disable quirks/features.") {
  9479. for (int i = 1; i < argc; ++i) {
  9480. if (set_capability(argv[i])) return 1;
  9481. }
  9482. return 0;
  9483. }
  9484. BIM_COMMAND(quirk,"quirk","Handle quirks based on environment variables") {
  9485. if (argc < 3) goto _quirk_arg_error;
  9486. char * varname = argv[1];
  9487. char * teststr = argv[2];
  9488. char * value = getenv(varname);
  9489. if (!value) return 0;
  9490. if (strstr(value, teststr) == value) {
  9491. /* Process quirk strings */
  9492. for (int i = 3; i < argc; ++i) {
  9493. set_capability(argv[i]);
  9494. }
  9495. }
  9496. return 0;
  9497. _quirk_arg_error:
  9498. render_error("Usage: quirk ENVVAR value no... can...");
  9499. return 1;
  9500. }
  9501. /**
  9502. * Load bimrc configuration file.
  9503. *
  9504. * At the moment, this a simple key=value list.
  9505. */
  9506. void load_bimrc(void) {
  9507. if (!global_config.bimrc_path) return;
  9508. /* Default is ~/.bimrc */
  9509. char * tmp = strdup(global_config.bimrc_path);
  9510. if (!*tmp) {
  9511. free(tmp);
  9512. return;
  9513. }
  9514. /* Parse ~ at the front of the path. */
  9515. if (*tmp == '~') {
  9516. char path[1024] = {0};
  9517. char * home = getenv("HOME");
  9518. if (!home) {
  9519. /* $HOME is unset? */
  9520. free(tmp);
  9521. return;
  9522. }
  9523. /* New path is $HOME/.bimrc */
  9524. snprintf(path, 1024, "%s%s", home, tmp+1);
  9525. free(tmp);
  9526. tmp = strdup(path);
  9527. }
  9528. struct stat statbuf;
  9529. if (stat(tmp, &statbuf)) {
  9530. free(tmp);
  9531. return;
  9532. }
  9533. krk_runfile(tmp,tmp);
  9534. free(tmp);
  9535. }
  9536. static int checkClass(KrkClass * _class, KrkClass * base) {
  9537. while (_class) {
  9538. if (_class == base) return 1;
  9539. _class = _class->base;
  9540. }
  9541. return 0;
  9542. }
  9543. static KrkValue krk_bim_syntax_dict;
  9544. static KrkValue krk_bim_register_syntax(int argc, const KrkValue argv[], int hasKw) {
  9545. if (argc < 1 || !IS_CLASS(argv[0]) || !checkClass(AS_CLASS(argv[0]), syntaxStateClass))
  9546. return krk_runtimeError(vm.exceptions->typeError, "Can not register '%s' as a syntax highlighter, expected subclass of SyntaxState.", krk_typeName(argv[0]));
  9547. KrkValue name = krk_valueGetAttribute_default(argv[0], "name", NONE_VAL());
  9548. KrkValue extensions = krk_valueGetAttribute_default(argv[0], "extensions", NONE_VAL());
  9549. KrkValue spaces = krk_valueGetAttribute_default(argv[0], "spaces", BOOLEAN_VAL(0));
  9550. KrkValue calculate = krk_valueGetAttribute_default(argv[0], "calculate", NONE_VAL());
  9551. if (!IS_STRING(name))
  9552. return krk_runtimeError(vm.exceptions->typeError, "%s.name must be str", AS_CLASS(argv[0])->name->chars);
  9553. if (!IS_TUPLE(extensions))
  9554. return krk_runtimeError(vm.exceptions->typeError, "%s.extensions must be tuple<str>", AS_CLASS(argv[0])->name->chars);
  9555. if (!IS_BOOLEAN(spaces))
  9556. return krk_runtimeError(vm.exceptions->typeError, "%s.spaces must be bool", AS_CLASS(argv[0])->name->chars);
  9557. if (!IS_CLOSURE(calculate))
  9558. return krk_runtimeError(vm.exceptions->typeError, "%s.calculate must be method, not '%s'", AS_CLASS(argv[0])->name->chars, krk_typeName(calculate));
  9559. /* Convert tuple of strings */
  9560. char ** ext = malloc(sizeof(char *) * (AS_TUPLE(extensions)->values.count + 1)); /* +1 for NULL */
  9561. ext[AS_TUPLE(extensions)->values.count] = NULL;
  9562. for (size_t i = 0; i < AS_TUPLE(extensions)->values.count; ++i) {
  9563. if (!IS_STRING(AS_TUPLE(extensions)->values.values[i])) {
  9564. free(ext);
  9565. return krk_runtimeError(vm.exceptions->typeError, "%s.extensions must by tuple<str>", AS_CLASS(argv[0])->name->chars);
  9566. }
  9567. ext[i] = AS_CSTRING(AS_TUPLE(extensions)->values.values[i]);
  9568. }
  9569. add_syntax((struct syntax_definition) {
  9570. AS_CSTRING(name), /* name */
  9571. ext, /* NULL-terminated array of extensions */
  9572. NULL, /* calculate function */
  9573. AS_BOOLEAN(spaces), /* spaces */
  9574. NULL, /* qualifier */
  9575. NULL, /* matcher */
  9576. AS_OBJECT(calculate), /* krkFunc */
  9577. AS_OBJECT(argv[0]),
  9578. });
  9579. /* And save it in the module stuff. */
  9580. krk_tableSet(AS_DICT(krk_bim_syntax_dict), name, argv[0]);
  9581. return NONE_VAL();
  9582. }
  9583. static KrkValue krk_bim_theme_dict;
  9584. static KrkValue krk_bim_define_theme(int argc, const KrkValue argv[], int hasKw) {
  9585. if (argc < 1 || !IS_CLOSURE(argv[0]))
  9586. return krk_runtimeError(vm.exceptions->typeError, "themes must be functions, not '%s'", krk_typeName(argv[0]));
  9587. KrkValue name = OBJECT_VAL(AS_CLOSURE(argv[0])->function->name);
  9588. add_colorscheme((struct theme_def) {
  9589. AS_CSTRING(name),