bim.c 355 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015
  1. /**
  2. * This is a baked, single-file version of bim.
  3. * It was built Tue Nov 26 10:43:47 2019
  4. * It is based on git commit e8229a256df999de290bfaa725ec5b0c8c5a32cc
  5. */
  6. #define GIT_TAG "e8229a2-baked"
  7. /* Bim - A Text Editor
  8. *
  9. * Copyright (C) 2012-2019 K. Lange
  10. *
  11. * Permission to use, copy, modify, and/or distribute this software for any
  12. * purpose with or without fee is hereby granted, provided that the above
  13. * copyright notice and this permission notice appear in all copies.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  16. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  17. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  18. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  21. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22. */
  23. /* Included from bim-core.h */
  24. #define _XOPEN_SOURCE 700
  25. #define _DARWIN_C_SOURCE
  26. #define _DEFAULT_SOURCE
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <stdarg.h>
  32. #include <unistd.h>
  33. #include <termios.h>
  34. #include <signal.h>
  35. #include <locale.h>
  36. #include <wchar.h>
  37. #include <ctype.h>
  38. #include <dirent.h>
  39. #include <poll.h>
  40. #include <limits.h>
  41. #include <sys/types.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/stat.h>
  44. #ifdef __TIMESTAMP__
  45. # define BIM_BUILD_DATE " built " __TIMESTAMP__
  46. #else
  47. # define BIM_BUILD_DATE DATE ""
  48. #endif
  49. #ifdef GIT_TAG
  50. # define TAG "-" GIT_TAG
  51. #else
  52. # define TAG ""
  53. #endif
  54. #define BIM_VERSION "2.5.0" TAG
  55. #define BIM_COPYRIGHT "Copyright 2012-2019 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  56. #define BLOCK_SIZE 4096
  57. #define ENTER_KEY '\r'
  58. #define LINE_FEED '\n'
  59. #define BACKSPACE_KEY 0x08
  60. #define DELETE_KEY 0x7F
  61. enum Key {
  62. KEY_TIMEOUT = -1,
  63. KEY_CTRL_AT = 0, /* Base */
  64. KEY_CTRL_A, KEY_CTRL_B, KEY_CTRL_C, KEY_CTRL_D, KEY_CTRL_E, KEY_CTRL_F, KEY_CTRL_G, KEY_CTRL_H,
  65. KEY_CTRL_I, KEY_CTRL_J, KEY_CTRL_K, KEY_CTRL_L, KEY_CTRL_M, KEY_CTRL_N, KEY_CTRL_O, KEY_CTRL_P,
  66. KEY_CTRL_Q, KEY_CTRL_R, KEY_CTRL_S, KEY_CTRL_T, KEY_CTRL_U, KEY_CTRL_V, KEY_CTRL_W, KEY_CTRL_X,
  67. KEY_CTRL_Y, KEY_CTRL_Z, /* Note we keep ctrl-z mapped in termios as suspend */
  68. KEY_CTRL_OPEN, KEY_CTRL_BACKSLASH, KEY_CTRL_CLOSE, KEY_CTRL_CARAT, KEY_CTRL_UNDERSCORE,
  69. /* Space... */
  70. /* Some of these are equivalent to things above */
  71. KEY_BACKSPACE = 0x08,
  72. KEY_LINEFEED = '\n',
  73. KEY_ENTER = '\r',
  74. KEY_TAB = '\t',
  75. /* Basic printable characters go here. */
  76. /* Delete is special */
  77. KEY_DELETE = 0x7F,
  78. /* Unicode codepoints go here */
  79. KEY_ESCAPE = 0x400000, /* Escape would normally be 27, but is special because reasons */
  80. KEY_F1, KEY_F2, KEY_F3, KEY_F4,
  81. KEY_F5, KEY_F6, KEY_F7, KEY_F8,
  82. KEY_F9, KEY_F10, KEY_F11, KEY_F12,
  83. /* TODO ALT, SHIFT, etc., for F keys */
  84. KEY_MOUSE, /* Must be followed with a 3-byte mouse read */
  85. KEY_HOME, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN,
  86. KEY_UP, KEY_DOWN, KEY_RIGHT, KEY_LEFT,
  87. KEY_SHIFT_UP, KEY_SHIFT_DOWN, KEY_SHIFT_RIGHT, KEY_SHIFT_LEFT,
  88. KEY_CTRL_UP, KEY_CTRL_DOWN, KEY_CTRL_RIGHT, KEY_CTRL_LEFT,
  89. KEY_ALT_UP, KEY_ALT_DOWN, KEY_ALT_RIGHT, KEY_ALT_LEFT,
  90. KEY_ALT_SHIFT_UP, KEY_ALT_SHIFT_DOWN, KEY_ALT_SHIFT_RIGHT, KEY_ALT_SHIFT_LEFT,
  91. KEY_SHIFT_TAB,
  92. };
  93. struct key_name_map {
  94. enum Key keycode;
  95. char * name;
  96. };
  97. extern struct key_name_map KeyNames[];
  98. /**
  99. * Syntax highlighting flags.
  100. */
  101. #define FLAG_NONE 0
  102. #define FLAG_KEYWORD 1
  103. #define FLAG_STRING 2
  104. #define FLAG_COMMENT 3
  105. #define FLAG_TYPE 4
  106. #define FLAG_PRAGMA 5
  107. #define FLAG_NUMERAL 6
  108. #define FLAG_ERROR 7
  109. #define FLAG_DIFFPLUS 8
  110. #define FLAG_DIFFMINUS 9
  111. #define FLAG_NOTICE 10
  112. #define FLAG_BOLD 11
  113. #define FLAG_LINK 12
  114. #define FLAG_ESCAPE 13
  115. #define FLAG_SELECT (1 << 5)
  116. #define FLAG_SEARCH (1 << 6)
  117. /**
  118. * Line buffer definitions
  119. *
  120. * Lines are essentially resizable vectors of char_t structs,
  121. * which represent single codepoints in the file.
  122. */
  123. typedef struct {
  124. uint32_t display_width:4;
  125. uint32_t flags:7;
  126. uint32_t codepoint:21;
  127. } __attribute__((packed)) char_t;
  128. /**
  129. * Lines have available and actual lengths, describing
  130. * how much space was allocated vs. how much is being
  131. * used at the moment.
  132. */
  133. typedef struct {
  134. int available;
  135. int actual;
  136. int istate;
  137. int is_current;
  138. int rev_status;
  139. char_t text[];
  140. } line_t;
  141. /**
  142. * Global configuration state
  143. *
  144. * At the moment, this is all in a global, but in the future
  145. * this should be passed around to various functions.
  146. */
  147. typedef struct {
  148. /* Terminal size */
  149. int term_width, term_height;
  150. int bottom_size;
  151. line_t ** yanks;
  152. size_t yank_count;
  153. int yank_is_full_lines;
  154. int tty_in;
  155. const char * bimrc_path;
  156. const char * syntax_fallback;
  157. uint32_t * search;
  158. int overlay_mode;
  159. line_t * command_buffer;
  160. int command_offset, command_col_no;
  161. struct syntax_definition * command_syn, * command_syn_back;
  162. int history_point;
  163. int search_direction;
  164. int prev_line, prev_col, prev_coffset, prev_offset;
  165. unsigned int highlight_on_open:1;
  166. unsigned int initial_file_is_read_only:1;
  167. unsigned int go_to_line:1;
  168. unsigned int break_from_selection:1;
  169. unsigned int can_scroll:1;
  170. unsigned int can_hideshow:1;
  171. unsigned int can_altscreen:1;
  172. unsigned int can_mouse:1;
  173. unsigned int can_unicode:1;
  174. unsigned int can_bright:1;
  175. unsigned int can_title:1;
  176. unsigned int can_bce:1;
  177. unsigned int can_24bit:1;
  178. unsigned int can_256color:1;
  179. unsigned int can_italic:1;
  180. unsigned int history_enabled:1;
  181. unsigned int highlight_parens:1;
  182. unsigned int smart_case:1;
  183. unsigned int highlight_current_line:1;
  184. unsigned int shift_scrolling:1;
  185. unsigned int check_git:1;
  186. unsigned int color_gutter:1;
  187. unsigned int relative_lines:1;
  188. unsigned int numbers:1;
  189. unsigned int horizontal_shift_scrolling:1;
  190. unsigned int hide_statusbar:1;
  191. unsigned int tabs_visible:1;
  192. unsigned int autohide_tabs:1;
  193. unsigned int smart_complete:1;
  194. unsigned int has_terminal:1;
  195. int cursor_padding;
  196. int split_percent;
  197. int scroll_amount;
  198. int tab_offset;
  199. char * tab_indicator;
  200. char * space_indicator;
  201. } global_config_t;
  202. #define OVERLAY_MODE_NONE 0
  203. #define OVERLAY_MODE_READ_ONE 1
  204. #define OVERLAY_MODE_COMMAND 2
  205. #define OVERLAY_MODE_SEARCH 3
  206. #define OVERLAY_MODE_COMPLETE 4
  207. #define HISTORY_SENTINEL 0
  208. #define HISTORY_INSERT 1
  209. #define HISTORY_DELETE 2
  210. #define HISTORY_REPLACE 3
  211. #define HISTORY_REMOVE_LINE 4
  212. #define HISTORY_ADD_LINE 5
  213. #define HISTORY_REPLACE_LINE 6
  214. #define HISTORY_MERGE_LINES 7
  215. #define HISTORY_SPLIT_LINE 8
  216. #define HISTORY_BREAK 10
  217. typedef struct history {
  218. struct history * previous;
  219. struct history * next;
  220. int type;
  221. int line;
  222. int col;
  223. union {
  224. struct {
  225. int lineno;
  226. int offset;
  227. int codepoint;
  228. int old_codepoint;
  229. } insert_delete_replace;
  230. struct {
  231. int lineno;
  232. line_t * contents;
  233. line_t * old_contents;
  234. } remove_replace_line;
  235. struct {
  236. int lineno;
  237. int split;
  238. } add_merge_split_lines;
  239. } contents;
  240. } history_t;
  241. /**
  242. * Buffer data
  243. *
  244. * A buffer describes a file, and stores
  245. * its name as well as the editor state
  246. * (cursor offsets, etc.) and the actual
  247. * line buffers.
  248. */
  249. typedef struct _env {
  250. unsigned int loading:1;
  251. unsigned int tabs:1;
  252. unsigned int modified:1;
  253. unsigned int readonly:1;
  254. unsigned int indent:1;
  255. unsigned int checkgitstatusonwrite:1;
  256. unsigned int crnl:1;
  257. unsigned int numbers:1;
  258. unsigned int gutter:1;
  259. int highlighting_paren;
  260. int maxcolumn;
  261. short mode;
  262. short tabstop;
  263. char * file_name;
  264. int offset;
  265. int coffset;
  266. int line_no;
  267. int line_count;
  268. int line_avail;
  269. int col_no;
  270. int preferred_column;
  271. struct syntax_definition * syntax;
  272. line_t ** lines;
  273. history_t * history;
  274. history_t * last_save_history;
  275. int width;
  276. int left;
  277. int start_line;
  278. int sel_col;
  279. int start_col;
  280. int prev_line;
  281. } buffer_t;
  282. struct theme_def {
  283. const char * name;
  284. void (*load)(const char * name);
  285. };
  286. extern struct theme_def * themes;
  287. extern void add_colorscheme(struct theme_def theme);
  288. struct syntax_state {
  289. line_t * line;
  290. int line_no;
  291. int state;
  292. int i;
  293. };
  294. struct completion_match {
  295. char * string;
  296. char * file;
  297. char * search;
  298. };
  299. struct syntax_definition {
  300. char * name;
  301. char ** ext;
  302. int (*calculate)(struct syntax_state *);
  303. int prefers_spaces;
  304. int (*completion_qualifier)(int c);
  305. int (*completion_matcher)(uint32_t * comp, struct completion_match ** matches, int * matches_count, int complete_match, int * matches_len);
  306. };
  307. extern struct syntax_definition * syntaxes;
  308. /**
  309. * Editor mode states
  310. */
  311. #define MODE_NORMAL 0
  312. #define MODE_INSERT 1
  313. #define MODE_LINE_SELECTION 2
  314. #define MODE_REPLACE 3
  315. #define MODE_CHAR_SELECTION 4
  316. #define MODE_COL_SELECTION 5
  317. #define MODE_COL_INSERT 6
  318. #define MODE_DIRECTORY_BROWSE 7
  319. extern global_config_t global_config;
  320. extern const char * COLOR_FG;
  321. extern const char * COLOR_BG;
  322. extern const char * COLOR_ALT_FG;
  323. extern const char * COLOR_ALT_BG;
  324. extern const char * COLOR_NUMBER_FG;
  325. extern const char * COLOR_NUMBER_BG;
  326. extern const char * COLOR_STATUS_FG;
  327. extern const char * COLOR_STATUS_BG;
  328. extern const char * COLOR_STATUS_ALT;
  329. extern const char * COLOR_TABBAR_BG;
  330. extern const char * COLOR_TAB_BG;
  331. extern const char * COLOR_ERROR_FG;
  332. extern const char * COLOR_ERROR_BG;
  333. extern const char * COLOR_SEARCH_FG;
  334. extern const char * COLOR_SEARCH_BG;
  335. extern const char * COLOR_KEYWORD;
  336. extern const char * COLOR_STRING;
  337. extern const char * COLOR_COMMENT;
  338. extern const char * COLOR_TYPE;
  339. extern const char * COLOR_PRAGMA;
  340. extern const char * COLOR_NUMERAL;
  341. extern const char * COLOR_SELECTFG;
  342. extern const char * COLOR_SELECTBG;
  343. extern const char * COLOR_RED;
  344. extern const char * COLOR_GREEN;
  345. extern const char * COLOR_BOLD;
  346. extern const char * COLOR_LINK;
  347. extern const char * COLOR_ESCAPE;
  348. extern const char * current_theme;
  349. struct action_def {
  350. char * name;
  351. void (*action)();
  352. int options;
  353. const char * description;
  354. };
  355. extern struct action_def * mappable_actions;
  356. #define ARG_IS_INPUT 0x01 /* Takes the key that triggered it as the first argument */
  357. #define ARG_IS_CUSTOM 0x02 /* Takes a custom argument which is specific to the method */
  358. #define ARG_IS_PROMPT 0x04 /* Prompts for an argument. */
  359. #define ACTION_IS_RW 0x08 /* Needs to be able to write. */
  360. #define BIM_ACTION(name, options, description) \
  361. void name (); /* Define the action with unknown arguments */ \
  362. void __attribute__((constructor)) _install_ ## name (void) { \
  363. add_action((struct action_def){#name, name, options, description}); \
  364. } \
  365. void name
  366. struct command_def {
  367. char * name;
  368. int (*command)(char *, int, char * arg[]);
  369. const char * description;
  370. };
  371. #define BIM_COMMAND(cmd_name, cmd_str, description) \
  372. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  373. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  374. add_command((struct command_def){cmd_str, bim_command_ ## cmd_name, description}); \
  375. } \
  376. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  377. #define BIM_ALIAS(alias, alias_name, cmd_name) \
  378. void __attribute__((constructor)) _install_alias_ ## alias_name (void) { \
  379. add_command((struct command_def){alias, bim_command_ ## cmd_name, "Alias for " #cmd_name}); \
  380. }
  381. #define BIM_PREFIX_COMMAND(cmd_name, cmd_prefix, description) \
  382. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  383. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  384. add_prefix_command((struct command_def){cmd_prefix, bim_command_ ## cmd_name, description}); \
  385. } \
  386. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  387. extern buffer_t * env;
  388. extern buffer_t * left_buffer;
  389. extern buffer_t * right_buffer;
  390. #define NAV_BUFFER_MAX 10
  391. extern char nav_buf[NAV_BUFFER_MAX+1];
  392. extern int nav_buffer;
  393. extern int buffers_len;
  394. extern int buffers_avail;
  395. extern buffer_t ** buffers;
  396. extern const char * flag_to_color(int _flag);
  397. extern void redraw_line(int x);
  398. extern int git_examine(char * filename);
  399. extern void search_next(void);
  400. extern void set_preferred_column(void);
  401. extern void quit(const char * message);
  402. extern void close_buffer(void);
  403. extern void set_syntax_by_name(const char * name);
  404. extern void rehighlight_search(line_t * line);
  405. extern void try_to_center();
  406. extern int read_one_character(char * message);
  407. extern void bim_unget(int c);
  408. #define bim_getch() bim_getch_timeout(200)
  409. extern int bim_getch_timeout(int timeout);
  410. extern buffer_t * buffer_new(void);
  411. extern FILE * open_biminfo(void);
  412. extern int fetch_from_biminfo(buffer_t * buf);
  413. extern int update_biminfo(buffer_t * buf);
  414. extern buffer_t * buffer_close(buffer_t * buf);
  415. extern int to_eight(uint32_t codepoint, char * out);
  416. extern char * name_from_key(enum Key keycode);
  417. extern void add_action(struct action_def action);
  418. extern void open_file(char * file);
  419. extern void recalculate_selected_lines(void);
  420. extern void add_command(struct command_def command);
  421. extern void add_prefix_command(struct command_def command);
  422. extern void render_command_input_buffer(void);
  423. extern void unhighlight_matching_paren(void);
  424. extern void add_syntax(struct syntax_definition def);
  425. struct ColorName {
  426. const char * name;
  427. const char ** value;
  428. };
  429. extern struct ColorName color_names[];
  430. struct bim_function {
  431. char * command;
  432. struct bim_function * next;
  433. };
  434. extern struct bim_function ** user_functions;
  435. extern int run_function(char * name);
  436. extern int has_function(char * name);
  437. extern void find_matching_paren(int * out_line, int * out_col, int in_col);
  438. extern void render_error(char * message, ...);
  439. extern void pause_for_key(void);
  440. #define add_match(match_string, match_file, match_search) do { \
  441. if (*matches_count == *matches_len) { \
  442. (*matches_len) *= 2; \
  443. *matches = realloc(*matches, sizeof(struct completion_match) * (*matches_len)); \
  444. } \
  445. (*matches)[*matches_count].string = strdup(match_string); \
  446. (*matches)[*matches_count].file = strdup(match_file); \
  447. (*matches)[*matches_count].search = strdup(match_search); \
  448. (*matches_count)++; \
  449. } while (0)
  450. #define add_if_match(name,desc) do { \
  451. int i = 0; \
  452. while (comp[i] && comp[i] == (unsigned char)name[i]) i++; \
  453. if (comp[i] == '\0') { \
  454. add_match(name,desc,""); \
  455. } \
  456. } while (0)
  457. struct action_map {
  458. int key;
  459. void (*method)();
  460. int options;
  461. int arg;
  462. };
  463. #define opt_rep 0x1 /* This action will be repeated */
  464. #define opt_arg 0x2 /* This action will take a specified argument */
  465. #define opt_char 0x4 /* This action will read a character to pass as an argument */
  466. #define opt_nav 0x8 /* This action will consume the nav buffer as its argument */
  467. #define opt_rw 0x10 /* Must not be read-only */
  468. #define opt_norm 0x20 /* Returns to normal mode */
  469. #define opt_byte 0x40 /* Same as opt_char but forces a byte */
  470. struct mode_names {
  471. const char * description;
  472. const char * name;
  473. struct action_map ** mode;
  474. };
  475. extern struct mode_names mode_names[];
  476. /* End of bim-core.h */
  477. /* Included from bim-syntax.h */
  478. #define BIM_SYNTAX(name, spaces) \
  479. __attribute__((constructor)) static void _load_ ## name (void) { \
  480. add_syntax((struct syntax_definition){#name, syn_ ## name ## _ext, syn_ ## name ## _calculate, spaces, NULL, NULL}); \
  481. } \
  482. #define BIM_SYNTAX_EXT(name, spaces, matcher) \
  483. __attribute__((constructor)) static void _load_ ## name (void) { \
  484. add_syntax((struct syntax_definition){#name, syn_ ## name ## _ext, syn_ ## name ## _calculate, spaces, matcher, _match_completions_ ## name}); \
  485. } \
  486. #define BIM_SYNTAX_COMPLETER(name) \
  487. static int _match_completions_ ## name ( \
  488. uint32_t * comp __attribute__((unused)), \
  489. struct completion_match **matches __attribute__((unused)), \
  490. int * matches_count __attribute__((unused)), \
  491. int complete_match __attribute__((unused)), \
  492. int *matches_len __attribute__((unused)))
  493. #define paint(length, flag) do { for (int i = 0; i < (length) && state->i < state->line->actual; i++, state->i++) { state->line->text[state->i].flags = (flag); } } while (0)
  494. #define charat() (state->i < state->line->actual ? state->line->text[(state->i)].codepoint : -1)
  495. #define nextchar() (state->i + 1 < state->line->actual ? state->line->text[(state->i+1)].codepoint : -1)
  496. #define lastchar() (state->i - 1 >= 0 ? state->line->text[(state->i-1)].codepoint : -1)
  497. #define skip() (state->i++)
  498. #define charrel(x) (state->i + (x) < state->line->actual ? state->line->text[(state->i+(x))].codepoint : -1)
  499. extern int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c));
  500. extern int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c));
  501. extern void paint_single_string(struct syntax_state * state);
  502. extern void paint_simple_string(struct syntax_state * state);
  503. extern int common_comment_buzzwords(struct syntax_state * state);
  504. extern int paint_comment(struct syntax_state * state);
  505. extern int match_forward(struct syntax_state * state, char * c);
  506. extern struct syntax_definition * find_syntax_calculator(const char * name);
  507. #define nest(lang, low) \
  508. do { \
  509. state->state = (state->state < 1 ? 0 : state->state - low); \
  510. do { state->state = lang(state); } while (state->state == 0); \
  511. if (state->state == -1) return low; \
  512. return state->state + low; \
  513. } while (0)
  514. /* Some of the C stuff is widely used */
  515. extern int c_keyword_qualifier(int c);
  516. extern int paint_c_numeral(struct syntax_state * state);
  517. extern int paint_c_comment(struct syntax_state * state);
  518. extern void paint_c_char(struct syntax_state * state);
  519. /* Hacky workaround for isdigit not really accepting Unicode stuff */
  520. static __attribute__((used)) int _isdigit(int c) { if (c > 128) return 0; return isdigit(c); }
  521. static __attribute__((used)) int _isxdigit(int c) { if (c > 128) return 0; return isxdigit(c); }
  522. #undef isdigit
  523. #undef isxdigit
  524. #define isdigit(c) _isdigit(c)
  525. #define isxdigit(c) _isxdigit(c)
  526. /* End of bim-syntax.h */
  527. global_config_t global_config = {
  528. /* State */
  529. .term_width = 0,
  530. .term_height = 0,
  531. .bottom_size = 2,
  532. .yanks = NULL,
  533. .yank_count = 0,
  534. .yank_is_full_lines = 0,
  535. .tty_in = STDIN_FILENO,
  536. .bimrc_path = "~/.bimrc",
  537. .syntax_fallback = NULL, /* syntax to fall back to if none other match applies */
  538. .search = NULL,
  539. .overlay_mode = OVERLAY_MODE_NONE,
  540. .command_buffer = NULL,
  541. .command_offset = 0,
  542. .command_col_no = 0,
  543. .history_point = -1,
  544. /* Bitset starts here */
  545. .highlight_on_open = 1,
  546. .initial_file_is_read_only = 0,
  547. .go_to_line = 1,
  548. .break_from_selection = 1,
  549. /* Terminal capabilities */
  550. .can_scroll = 1,
  551. .can_hideshow = 1,
  552. .can_altscreen = 1,
  553. .can_mouse = 1,
  554. .can_unicode = 1,
  555. .can_bright = 1,
  556. .can_title = 1,
  557. .can_bce = 1,
  558. .can_24bit = 1, /* can use 24-bit color */
  559. .can_256color = 1, /* can use 265 colors */
  560. .can_italic = 1, /* can use italics (without inverting) */
  561. /* Configuration options */
  562. .history_enabled = 1,
  563. .highlight_parens = 1, /* highlight parens/braces when cursor moves */
  564. .smart_case = 1, /* smart case-sensitivity while searching */
  565. .highlight_current_line = 1,
  566. .shift_scrolling = 1, /* shift rather than moving cursor*/
  567. .check_git = 0,
  568. .color_gutter = 1, /* shows modified lines */
  569. .relative_lines = 0,
  570. .numbers = 1,
  571. .horizontal_shift_scrolling = 0, /* Whether to shift the whole screen when scrolling horizontally */
  572. .hide_statusbar = 0,
  573. .tabs_visible = 1,
  574. .autohide_tabs = 0,
  575. .smart_complete = 0,
  576. .has_terminal = 0,
  577. /* Integer config values */
  578. .cursor_padding = 4,
  579. .split_percent = 50,
  580. .scroll_amount = 5,
  581. .tab_offset = 0,
  582. };
  583. struct key_name_map KeyNames[] = {
  584. {KEY_TIMEOUT, "[timeout]"},
  585. {KEY_BACKSPACE, "<backspace>"},
  586. {KEY_ENTER, "<enter>"},
  587. {KEY_ESCAPE, "<escape>"},
  588. {KEY_TAB, "<tab>"},
  589. {' ', "<space>"},
  590. /* These are mostly here for markdown output. */
  591. {'`', "<backtick>"},
  592. {'|', "<pipe>"},
  593. {KEY_DELETE, "<del>"},
  594. {KEY_MOUSE, "<mouse>"},
  595. {KEY_F1, "<f1>"},{KEY_F2, "<f2>"},{KEY_F3, "<f3>"},{KEY_F4, "<f4>"},
  596. {KEY_F5, "<f5>"},{KEY_F6, "<f6>"},{KEY_F7, "<f7>"},{KEY_F8, "<f8>"},
  597. {KEY_F9, "<f9>"},{KEY_F10, "<f10>"},{KEY_F11, "<f11>"},{KEY_F12, "<f12>"},
  598. {KEY_HOME,"<home>"},{KEY_END,"<end>"},{KEY_PAGE_UP,"<page-up>"},{KEY_PAGE_DOWN,"<page-down>"},
  599. {KEY_UP, "<up>"},{KEY_DOWN, "<down>"},{KEY_RIGHT, "<right>"},{KEY_LEFT, "<left>"},
  600. {KEY_SHIFT_UP, "<shift-up>"},{KEY_SHIFT_DOWN, "<shift-down>"},{KEY_SHIFT_RIGHT, "<shift-right>"},{KEY_SHIFT_LEFT, "<shift-left>"},
  601. {KEY_CTRL_UP, "<ctrl-up>"},{KEY_CTRL_DOWN, "<ctrl-down>"},{KEY_CTRL_RIGHT, "<ctrl-right>"},{KEY_CTRL_LEFT, "<ctrl-left>"},
  602. {KEY_ALT_UP, "<alt-up>"},{KEY_ALT_DOWN, "<alt-down>"},{KEY_ALT_RIGHT, "<alt-right>"},{KEY_ALT_LEFT, "<alt-left>"},
  603. {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>"},
  604. {KEY_SHIFT_TAB,"<shift-tab>"},
  605. };
  606. char * name_from_key(enum Key keycode) {
  607. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  608. if (KeyNames[i].keycode == keycode) return KeyNames[i].name;
  609. }
  610. static char keyNameTmp[8] = {0};
  611. if (keycode <= KEY_CTRL_UNDERSCORE) {
  612. keyNameTmp[0] = '^';
  613. keyNameTmp[1] = '@' + keycode;
  614. keyNameTmp[2] = 0;
  615. return keyNameTmp;
  616. }
  617. to_eight(keycode, keyNameTmp);
  618. return keyNameTmp;
  619. }
  620. struct ColorName color_names[] = {
  621. {"text-fg", &COLOR_FG},
  622. {"text-bg", &COLOR_BG},
  623. {"alternate-fg", &COLOR_ALT_FG},
  624. {"alternate-bg", &COLOR_ALT_BG},
  625. {"number-fg", &COLOR_NUMBER_FG},
  626. {"number-bg", &COLOR_NUMBER_BG},
  627. {"status-fg", &COLOR_STATUS_FG},
  628. {"status-bg", &COLOR_STATUS_BG},
  629. {"status-alt", &COLOR_STATUS_ALT},
  630. {"tabbar-bg", &COLOR_TABBAR_BG},
  631. {"tab-bg", &COLOR_TAB_BG},
  632. {"error-fg", &COLOR_ERROR_FG},
  633. {"error-bg", &COLOR_ERROR_BG},
  634. {"search-fg", &COLOR_SEARCH_FG},
  635. {"search-bg", &COLOR_SEARCH_BG},
  636. {"keyword", &COLOR_KEYWORD},
  637. {"string", &COLOR_STRING},
  638. {"comment", &COLOR_COMMENT},
  639. {"type", &COLOR_TYPE},
  640. {"pragma", &COLOR_PRAGMA},
  641. {"numeral", &COLOR_NUMERAL},
  642. {"select-fg", &COLOR_SELECTFG},
  643. {"select-bg", &COLOR_SELECTBG},
  644. {"red", &COLOR_RED},
  645. {"green", &COLOR_GREEN},
  646. {"bold", &COLOR_BOLD},
  647. {"link", &COLOR_LINK},
  648. {"escape", &COLOR_ESCAPE},
  649. {NULL,NULL},
  650. };
  651. #define FLEXIBLE_ARRAY(name, add_name, type, zero) \
  652. int flex_ ## name ## _count = 0; \
  653. int flex_ ## name ## _space = 0; \
  654. type * name = NULL; \
  655. void add_name (type input) { \
  656. if (flex_ ## name ## _space == 0) { \
  657. flex_ ## name ## _space = 4; \
  658. name = calloc(sizeof(type), flex_ ## name ## _space); \
  659. } else if (flex_ ## name ## _count + 1 == flex_ ## name ## _space) { \
  660. flex_ ## name ## _space *= 2; \
  661. name = realloc(name, sizeof(type) * flex_ ## name ## _space); \
  662. for (int i = flex_ ## name ## _count; i < flex_ ## name ## _space; ++i) name[i] = zero; \
  663. } \
  664. name[flex_ ## name ## _count] = input; \
  665. flex_ ## name ## _count ++; \
  666. }
  667. FLEXIBLE_ARRAY(mappable_actions, add_action, struct action_def, ((struct action_def){NULL,NULL,0,NULL}))
  668. FLEXIBLE_ARRAY(regular_commands, add_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  669. FLEXIBLE_ARRAY(prefix_commands, add_prefix_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  670. FLEXIBLE_ARRAY(themes, add_colorscheme, struct theme_def, ((struct theme_def){NULL,NULL}))
  671. FLEXIBLE_ARRAY(user_functions, add_user_function, struct bim_function *, NULL)
  672. /**
  673. * Special implementation of getch with a timeout
  674. */
  675. int _bim_unget = -1;
  676. void bim_unget(int c) {
  677. _bim_unget = c;
  678. }
  679. int bim_getch_timeout(int timeout) {
  680. fflush(stdout);
  681. if (_bim_unget != -1) {
  682. int out = _bim_unget;
  683. _bim_unget = -1;
  684. return out;
  685. }
  686. struct pollfd fds[1];
  687. fds[0].fd = global_config.tty_in;
  688. fds[0].events = POLLIN;
  689. int ret = poll(fds,1,timeout);
  690. if (ret > 0 && fds[0].revents & POLLIN) {
  691. unsigned char buf[1];
  692. read(global_config.tty_in, buf, 1);
  693. return buf[0];
  694. } else {
  695. return -1;
  696. }
  697. }
  698. /**
  699. * UTF-8 parser state
  700. */
  701. static uint32_t codepoint_r;
  702. static uint32_t state = 0;
  703. #define UTF8_ACCEPT 0
  704. #define UTF8_REJECT 1
  705. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  706. static int state_table[32] = {
  707. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  708. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  709. 2,2,2,2, /* 110xxxxx */
  710. 3,3, /* 1110xxxx */
  711. 4, /* 11110xxx */
  712. 1 /* 11111xxx */
  713. };
  714. static int mask_bytes[32] = {
  715. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  716. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  717. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  718. 0x1F,0x1F,0x1F,0x1F,
  719. 0x0F,0x0F,
  720. 0x07,
  721. 0x00
  722. };
  723. static int next[5] = {
  724. 0,
  725. 1,
  726. 0,
  727. 2,
  728. 3
  729. };
  730. if (*state == UTF8_ACCEPT) {
  731. *codep = byte & mask_bytes[byte >> 3];
  732. *state = state_table[byte >> 3];
  733. } else if (*state > 0) {
  734. *codep = (byte & 0x3F) | (*codep << 6);
  735. *state = next[*state];
  736. }
  737. return *state;
  738. }
  739. #define shift_key(i) _shift_key((i), this_buf, &timeout);
  740. int _shift_key(int i, int this_buf[20], int *timeout) {
  741. int thing = this_buf[*timeout-1];
  742. (*timeout) = 0;
  743. switch (thing) {
  744. /* There are other combinations we can handle... */
  745. case '2': return i + 4;
  746. case '5': return i + 8;
  747. case '3': return i + 12;
  748. case '4': return i + 16;
  749. default: return i;
  750. }
  751. }
  752. int bim_getkey(int read_timeout) {
  753. int timeout = 0;
  754. int this_buf[20];
  755. int cin;
  756. uint32_t c;
  757. uint32_t istate = 0;
  758. while ((cin = bim_getch_timeout(read_timeout))) {
  759. if (cin == -1) {
  760. if (timeout && this_buf[timeout-1] == '\033')
  761. return KEY_ESCAPE;
  762. return KEY_TIMEOUT;
  763. }
  764. if (!decode(&istate, &c, cin)) {
  765. if (timeout == 0) {
  766. switch (c) {
  767. case '\033':
  768. if (timeout == 0) {
  769. this_buf[timeout] = c;
  770. timeout++;
  771. }
  772. continue;
  773. case KEY_LINEFEED: return KEY_ENTER;
  774. case KEY_DELETE: return KEY_BACKSPACE;
  775. }
  776. return c;
  777. } else {
  778. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '\033') {
  779. bim_unget(c);
  780. timeout = 0;
  781. return KEY_ESCAPE;
  782. }
  783. if (timeout >= 1 && this_buf[0] == '\033' && c == 'O') {
  784. this_buf[timeout] = c;
  785. timeout++;
  786. continue;
  787. }
  788. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == 'O') {
  789. switch (c) {
  790. case 'P': timeout = 0; return KEY_F1;
  791. case 'Q': timeout = 0; return KEY_F2;
  792. case 'R': timeout = 0; return KEY_F3;
  793. case 'S': timeout = 0; return KEY_F4;
  794. }
  795. timeout = 0;
  796. continue;
  797. }
  798. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c != '[') {
  799. timeout = 0;
  800. bim_unget(c);
  801. return KEY_ESCAPE;
  802. }
  803. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '[') {
  804. timeout = 1;
  805. this_buf[timeout] = c;
  806. timeout++;
  807. continue;
  808. }
  809. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  810. (isdigit(c) || (c == ';'))) {
  811. this_buf[timeout] = c;
  812. timeout++;
  813. continue;
  814. }
  815. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  816. switch (c) {
  817. case 'M': timeout = 0; return KEY_MOUSE;
  818. case 'A': return shift_key(KEY_UP);
  819. case 'B': return shift_key(KEY_DOWN);
  820. case 'C': return shift_key(KEY_RIGHT);
  821. case 'D': return shift_key(KEY_LEFT);
  822. case 'H': timeout = 0; return KEY_HOME;
  823. case 'F': timeout = 0; return KEY_END;
  824. case 'I': timeout = 0; return KEY_PAGE_UP;
  825. case 'G': timeout = 0; return KEY_PAGE_DOWN;
  826. case 'Z': timeout = 0; return KEY_SHIFT_TAB;
  827. case '~':
  828. if (timeout == 3) {
  829. switch (this_buf[2]) {
  830. case '1': timeout = 0; return KEY_HOME;
  831. case '3': timeout = 0; return KEY_DELETE;
  832. case '4': timeout = 0; return KEY_END;
  833. case '5': timeout = 0; return KEY_PAGE_UP;
  834. case '6': timeout = 0; return KEY_PAGE_DOWN;
  835. }
  836. } else if (this_buf[2] == '1') {
  837. switch (this_buf[3]) {
  838. case '5': return KEY_F5;
  839. case '7': return KEY_F6;
  840. case '8': return KEY_F7;
  841. case '9': return KEY_F8;
  842. }
  843. } else if (this_buf[2] == '2') {
  844. switch (this_buf[3]) {
  845. case '0': return KEY_F9;
  846. case '1': return KEY_F10;
  847. case '3': return KEY_F11;
  848. case '4': return KEY_F12;
  849. }
  850. }
  851. break;
  852. }
  853. }
  854. timeout = 0;
  855. continue;
  856. }
  857. } else if (istate == UTF8_REJECT) {
  858. istate = 0;
  859. }
  860. }
  861. return KEY_TIMEOUT;
  862. }
  863. enum Key key_from_name(char * name) {
  864. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  865. if (!strcmp(KeyNames[i].name, name)) return KeyNames[i].keycode;
  866. }
  867. if (name[0] == '^' && name[1] && !name[2]) {
  868. return name[1] - '@';
  869. }
  870. if (!name[1]) return name[0];
  871. /* Try decoding */
  872. uint32_t c, state = 0;
  873. int candidate = -1;
  874. while (*name) {
  875. if (!decode(&state, &c, (unsigned char)*name)) {
  876. if (candidate == -1) candidate = c;
  877. else return -1; /* Multiple characters */
  878. } else if (state == UTF8_REJECT) {
  879. return -1;
  880. }
  881. }
  882. return candidate;
  883. }
  884. /**
  885. * Pointer to current active buffer
  886. */
  887. buffer_t * env = NULL;
  888. buffer_t * left_buffer = NULL;
  889. buffer_t * right_buffer = NULL;
  890. /**
  891. * A buffer for holding a number (line, repetition count)
  892. */
  893. char nav_buf[NAV_BUFFER_MAX+1];
  894. int nav_buffer = 0;
  895. /**
  896. * Available buffers
  897. */
  898. int buffers_len = 0;
  899. int buffers_avail = 0;
  900. buffer_t ** buffers = NULL;
  901. /**
  902. * Create a new buffer
  903. */
  904. buffer_t * buffer_new(void) {
  905. if (buffers_len == buffers_avail) {
  906. /* If we are out of buffer space, expand the buffers vector */
  907. buffers_avail *= 2;
  908. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  909. }
  910. /* TODO: Support having split buffers with more than two buffers open */
  911. if (left_buffer) {
  912. left_buffer->left = 0;
  913. left_buffer->width = global_config.term_width;
  914. right_buffer->left = 0;
  915. right_buffer->width = global_config.term_width;
  916. left_buffer = NULL;
  917. right_buffer = NULL;
  918. }
  919. /* Allocate a new buffer */
  920. buffers[buffers_len] = malloc(sizeof(buffer_t));
  921. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  922. buffers[buffers_len]->left = 0;
  923. buffers[buffers_len]->width = global_config.term_width;
  924. buffers[buffers_len]->highlighting_paren = -1;
  925. buffers[buffers_len]->numbers = global_config.numbers;
  926. buffers[buffers_len]->gutter = 1;
  927. buffers_len++;
  928. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  929. return buffers[buffers_len-1];
  930. }
  931. /**
  932. * Open the biminfo file.
  933. */
  934. FILE * open_biminfo(void) {
  935. /* TODO This should probably be configurable line bimrc */
  936. char * home = getenv("HOME");
  937. if (!home) {
  938. /* Since it's not, we need HOME */
  939. return NULL;
  940. }
  941. /* biminfo lives at ~/.biminfo */
  942. char biminfo_path[PATH_MAX+1] = {0};
  943. sprintf(biminfo_path,"%s/.biminfo",home);
  944. /* Try to open normally first... */
  945. FILE * biminfo = fopen(biminfo_path,"r+");
  946. if (!biminfo) {
  947. /* Otherwise, try to create it. */
  948. biminfo = fopen(biminfo_path,"w+");
  949. }
  950. return biminfo;
  951. }
  952. /**
  953. * Fetch the cursor position from a biminfo file
  954. */
  955. int fetch_from_biminfo(buffer_t * buf) {
  956. /* Can't fetch if we don't have a filename */
  957. if (!buf->file_name) return 1;
  958. /* Get the absolute name of the file */
  959. char tmp_path[PATH_MAX+2];
  960. if (!realpath(buf->file_name, tmp_path)) {
  961. return 1;
  962. }
  963. strcat(tmp_path," ");
  964. FILE * biminfo = open_biminfo();
  965. if (!biminfo) return 1;
  966. /* Scan */
  967. char line[PATH_MAX+64];
  968. while (!feof(biminfo)) {
  969. fpos_t start_of_line;
  970. fgetpos(biminfo, &start_of_line);
  971. fgets(line, PATH_MAX+63, biminfo);
  972. if (line[0] != '>') {
  973. continue;
  974. }
  975. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  976. /* Read */
  977. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  978. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  979. if (buf->line_no > buf->line_count) buf->line_no = buf->line_count;
  980. if (buf->col_no > buf->lines[buf->line_no-1]->actual) buf->col_no = buf->lines[buf->line_no-1]->actual;
  981. try_to_center();
  982. return 0;
  983. }
  984. }
  985. return 0;
  986. }
  987. /**
  988. * Write a file containing the last cursor position of a buffer.
  989. */
  990. int update_biminfo(buffer_t * buf) {
  991. if (!buf->file_name) return 1;
  992. /* Get the absolute name of the file */
  993. char tmp_path[PATH_MAX+1];
  994. if (!realpath(buf->file_name, tmp_path)) {
  995. return 1;
  996. }
  997. strcat(tmp_path," ");
  998. FILE * biminfo = open_biminfo();
  999. if (!biminfo) return 1;
  1000. /* Scan */
  1001. char line[PATH_MAX+64];
  1002. while (!feof(biminfo)) {
  1003. fpos_t start_of_line;
  1004. fgetpos(biminfo, &start_of_line);
  1005. fgets(line, PATH_MAX+63, biminfo);
  1006. if (line[0] != '>') {
  1007. continue;
  1008. }
  1009. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  1010. /* Update */
  1011. fsetpos(biminfo, &start_of_line);
  1012. fprintf(biminfo,">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  1013. goto _done;
  1014. }
  1015. }
  1016. if (ftell(biminfo) == 0) {
  1017. /* New biminfo */
  1018. fprintf(biminfo, "# This is a biminfo file.\n");
  1019. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  1020. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  1021. }
  1022. /* Haven't found what we're looking for, should be at end of file */
  1023. fprintf(biminfo, ">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  1024. _done:
  1025. fclose(biminfo);
  1026. return 0;
  1027. }
  1028. /**
  1029. * Close a buffer
  1030. */
  1031. buffer_t * buffer_close(buffer_t * buf) {
  1032. int i;
  1033. /* Locate the buffer in the buffer pointer vector */
  1034. for (i = 0; i < buffers_len; i++) {
  1035. if (buf == buffers[i])
  1036. break;
  1037. }
  1038. /* Invalid buffer? */
  1039. if (i == buffers_len) {
  1040. return env; /* wtf */
  1041. }
  1042. update_biminfo(buf);
  1043. /* Clean up lines used by old buffer */
  1044. for (int i = 0; i < buf->line_count; ++i) {
  1045. free(buf->lines[i]);
  1046. }
  1047. free(buf->lines);
  1048. if (buf->file_name) {
  1049. free(buf->file_name);
  1050. }
  1051. history_t * h = buf->history;
  1052. while (h->next) {
  1053. h = h->next;
  1054. }
  1055. while (h) {
  1056. history_t * x = h->previous;
  1057. free(h);
  1058. h = x;
  1059. }
  1060. /* Clean up the old buffer */
  1061. free(buf);
  1062. /* Remove the buffer from the vector, moving others up */
  1063. if (i != buffers_len - 1) {
  1064. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  1065. }
  1066. /* There is one less buffer */
  1067. buffers_len--;
  1068. if (buffers_len && global_config.tab_offset >= buffers_len) global_config.tab_offset--;
  1069. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  1070. if (!buffers_len) {
  1071. /* There are no more buffers. */
  1072. return NULL;
  1073. }
  1074. /* If this was the last buffer, return the previous last buffer */
  1075. if (i == buffers_len) {
  1076. return buffers[buffers_len-1];
  1077. }
  1078. /* Otherwise return the new last buffer */
  1079. return buffers[i];
  1080. }
  1081. /**
  1082. * Theming data
  1083. *
  1084. * This default set is pretty simple "default foreground on default background"
  1085. * except for search and selections which are black-on-white specifically.
  1086. *
  1087. * The theme colors get set by separate configurable themes.
  1088. */
  1089. const char * COLOR_FG = "@9";
  1090. const char * COLOR_BG = "@9";
  1091. const char * COLOR_ALT_FG = "@9";
  1092. const char * COLOR_ALT_BG = "@9";
  1093. const char * COLOR_NUMBER_FG = "@9";
  1094. const char * COLOR_NUMBER_BG = "@9";
  1095. const char * COLOR_STATUS_FG = "@9";
  1096. const char * COLOR_STATUS_BG = "@9";
  1097. const char * COLOR_STATUS_ALT= "@9";
  1098. const char * COLOR_TABBAR_BG = "@9";
  1099. const char * COLOR_TAB_BG = "@9";
  1100. const char * COLOR_ERROR_FG = "@9";
  1101. const char * COLOR_ERROR_BG = "@9";
  1102. const char * COLOR_SEARCH_FG = "@0";
  1103. const char * COLOR_SEARCH_BG = "@17";
  1104. const char * COLOR_KEYWORD = "@9";
  1105. const char * COLOR_STRING = "@9";
  1106. const char * COLOR_COMMENT = "@9";
  1107. const char * COLOR_TYPE = "@9";
  1108. const char * COLOR_PRAGMA = "@9";
  1109. const char * COLOR_NUMERAL = "@9";
  1110. const char * COLOR_SELECTFG = "@0";
  1111. const char * COLOR_SELECTBG = "@17";
  1112. const char * COLOR_RED = "@1";
  1113. const char * COLOR_GREEN = "@2";
  1114. const char * COLOR_BOLD = "@9";
  1115. const char * COLOR_LINK = "@9";
  1116. const char * COLOR_ESCAPE = "@9";
  1117. const char * current_theme = "none";
  1118. /**
  1119. * Convert syntax highlighting flag to color code
  1120. */
  1121. const char * flag_to_color(int _flag) {
  1122. int flag = _flag & 0xF;
  1123. switch (flag) {
  1124. case FLAG_KEYWORD:
  1125. return COLOR_KEYWORD;
  1126. case FLAG_STRING:
  1127. return COLOR_STRING;
  1128. case FLAG_COMMENT:
  1129. return COLOR_COMMENT;
  1130. case FLAG_TYPE:
  1131. return COLOR_TYPE;
  1132. case FLAG_NUMERAL:
  1133. return COLOR_NUMERAL;
  1134. case FLAG_PRAGMA:
  1135. return COLOR_PRAGMA;
  1136. case FLAG_DIFFPLUS:
  1137. return COLOR_GREEN;
  1138. case FLAG_DIFFMINUS:
  1139. return COLOR_RED;
  1140. case FLAG_SELECT:
  1141. return COLOR_FG;
  1142. case FLAG_BOLD:
  1143. return COLOR_BOLD;
  1144. case FLAG_LINK:
  1145. return COLOR_LINK;
  1146. case FLAG_ESCAPE:
  1147. return COLOR_ESCAPE;
  1148. default:
  1149. return COLOR_FG;
  1150. }
  1151. }
  1152. /**
  1153. * Find keywords from a list and paint them, assuming they aren't in the middle of other words.
  1154. * Returns 1 if a keyword from the last was found, otherwise 0.
  1155. */
  1156. int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c)) {
  1157. if (keyword_qualifier(lastchar())) return 0;
  1158. if (!keyword_qualifier(charat())) return 0;
  1159. for (char ** keyword = keywords; *keyword; ++keyword) {
  1160. int d = 0;
  1161. while (state->i + d < state->line->actual && state->line->text[state->i+d].codepoint == (*keyword)[d]) d++;
  1162. if ((*keyword)[d] == '\0' && (state->i + d >= state->line->actual || !keyword_qualifier(state->line->text[state->i+d].codepoint))) {
  1163. paint((int)strlen(*keyword), flag);
  1164. return 1;
  1165. }
  1166. }
  1167. return 0;
  1168. }
  1169. /**
  1170. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  1171. * so it can be used for prefix checking for things that need further special handling.
  1172. */
  1173. int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  1174. if (keyword_qualifier(lastchar())) return 0;
  1175. if (!keyword_qualifier(charat())) return 0;
  1176. int i = state->i;
  1177. int slen = 0;
  1178. while (i < state->line->actual || *keyword == '\0') {
  1179. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  1180. for (int j = 0; j < slen; ++j) {
  1181. paint(1, flag);
  1182. }
  1183. return 1;
  1184. }
  1185. if (*keyword != state->line->text[i].codepoint) return 0;
  1186. i++;
  1187. keyword++;
  1188. slen++;
  1189. }
  1190. return 0;
  1191. }
  1192. void paint_single_string(struct syntax_state * state) {
  1193. paint(1, FLAG_STRING);
  1194. while (charat() != -1) {
  1195. if (charat() == '\\' && nextchar() == '\'') {
  1196. paint(2, FLAG_ESCAPE);
  1197. } else if (charat() == '\'') {
  1198. paint(1, FLAG_STRING);
  1199. return;
  1200. } else if (charat() == '\\') {
  1201. paint(2, FLAG_ESCAPE);
  1202. } else {
  1203. paint(1, FLAG_STRING);
  1204. }
  1205. }
  1206. }
  1207. void paint_simple_string(struct syntax_state * state) {
  1208. /* Assumes you came in from a check of charat() == '"' */
  1209. paint(1, FLAG_STRING);
  1210. while (charat() != -1) {
  1211. if (charat() == '\\' && nextchar() == '"') {
  1212. paint(2, FLAG_ESCAPE);
  1213. } else if (charat() == '"') {
  1214. paint(1, FLAG_STRING);
  1215. return;
  1216. } else if (charat() == '\\') {
  1217. paint(2, FLAG_ESCAPE);
  1218. } else {
  1219. paint(1, FLAG_STRING);
  1220. }
  1221. }
  1222. }
  1223. /**
  1224. * This is a basic character matcher for "keyword" characters.
  1225. */
  1226. int simple_keyword_qualifier(int c) {
  1227. return isalnum(c) || (c == '_');
  1228. }
  1229. /**
  1230. * These words can appear in comments and should be highlighted.
  1231. * Since there are a lot of comment highlighters, let's break them out.
  1232. */
  1233. int common_comment_buzzwords(struct syntax_state * state) {
  1234. if (match_and_paint(state, "TODO", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1235. else if (match_and_paint(state, "XXX", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1236. else if (match_and_paint(state, "FIXME", FLAG_ERROR, simple_keyword_qualifier)) { return 1; }
  1237. return 0;
  1238. }
  1239. /**
  1240. * Paint a comment until end of line, assumes this comment can not continue.
  1241. * (Some languages have comments that can continue with a \ - don't use this!)
  1242. * Assumes you've already painted your comment start characters.
  1243. */
  1244. int paint_comment(struct syntax_state * state) {
  1245. while (charat() != -1) {
  1246. if (common_comment_buzzwords(state)) continue;
  1247. else { paint(1, FLAG_COMMENT); }
  1248. }
  1249. return -1;
  1250. }
  1251. /**
  1252. * Match a word forward and return whether it was matched.
  1253. */
  1254. int match_forward(struct syntax_state * state, char * c) {
  1255. int i = 0;
  1256. while (1) {
  1257. if (charrel(i) == -1 && !*c) return 1;
  1258. if (charrel(i) != *c) return 0;
  1259. c++;
  1260. i++;
  1261. }
  1262. return 0;
  1263. }
  1264. /**
  1265. * Find and return a highlighter by name, or NULL
  1266. */
  1267. struct syntax_definition * find_syntax_calculator(const char * name) {
  1268. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  1269. if (!strcmp(s->name, name)) {
  1270. return s;
  1271. }
  1272. }
  1273. return NULL;
  1274. }
  1275. int syntax_count = 0;
  1276. int syntax_space = 0;
  1277. struct syntax_definition * syntaxes = NULL;
  1278. void add_syntax(struct syntax_definition def) {
  1279. if (syntax_space == 0) {
  1280. syntax_space = 4;
  1281. syntaxes = calloc(sizeof(struct syntax_definition), syntax_space);
  1282. } else if (syntax_count +1 == syntax_space) {
  1283. syntax_space *= 2;
  1284. syntaxes = realloc(syntaxes, sizeof(struct syntax_definition) * syntax_space);
  1285. for (int i = syntax_count; i < syntax_space; ++i) syntaxes[i].name = NULL;
  1286. }
  1287. syntaxes[syntax_count] = def;
  1288. syntax_count++;
  1289. }
  1290. /**
  1291. * Calculate syntax highlighting for the given line.
  1292. */
  1293. void recalculate_syntax(line_t * line, int line_no) {
  1294. /* Clear syntax for this line first */
  1295. int is_original = 1;
  1296. while (1) {
  1297. for (int i = 0; i < line->actual; ++i) {
  1298. line->text[i].flags = 0;
  1299. }
  1300. if (!env->syntax) {
  1301. if (line_no != -1) rehighlight_search(line);
  1302. return;
  1303. }
  1304. /* Start from the line's stored in initial state */
  1305. struct syntax_state state;
  1306. state.line = line;
  1307. state.line_no = line_no;
  1308. state.state = line->istate;
  1309. state.i = 0;
  1310. while (1) {
  1311. state.state = env->syntax->calculate(&state);
  1312. if (state.state != 0) {
  1313. if (line_no == -1) return;
  1314. rehighlight_search(line);
  1315. if (!is_original) {
  1316. redraw_line(line_no);
  1317. }
  1318. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != state.state) {
  1319. line_no++;
  1320. line = env->lines[line_no];
  1321. line->istate = state.state;
  1322. if (env->loading) return;
  1323. is_original = 0;
  1324. goto _next;
  1325. }
  1326. return;
  1327. }
  1328. }
  1329. _next:
  1330. (void)0;
  1331. }
  1332. }
  1333. /**
  1334. * Recalculate tab widths.
  1335. */
  1336. void recalculate_tabs(line_t * line) {
  1337. if (env->loading) return;
  1338. int j = 0;
  1339. for (int i = 0; i < line->actual; ++i) {
  1340. if (line->text[i].codepoint == '\t') {
  1341. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  1342. }
  1343. j += line->text[i].display_width;
  1344. }
  1345. }
  1346. /**
  1347. * TODO:
  1348. *
  1349. * The line editing functions should probably take a buffer_t *
  1350. * so that they can act on buffers other than the active one.
  1351. */
  1352. void recursive_history_free(history_t * root) {
  1353. if (!root->next) return;
  1354. history_t * n = root->next;
  1355. recursive_history_free(n);
  1356. switch (n->type) {
  1357. case HISTORY_REPLACE_LINE:
  1358. free(n->contents.remove_replace_line.contents);
  1359. /* fall-through */
  1360. case HISTORY_REMOVE_LINE:
  1361. free(n->contents.remove_replace_line.old_contents);
  1362. break;
  1363. default:
  1364. /* Nothing extra to free */
  1365. break;
  1366. }
  1367. free(n);
  1368. root->next = NULL;
  1369. }
  1370. #define HIST_APPEND(e) do { \
  1371. e->col = env->col_no; \
  1372. e->line = env->line_no; \
  1373. if (env->history) { \
  1374. e->previous = env->history; \
  1375. recursive_history_free(env->history); \
  1376. env->history->next = e; \
  1377. e->next = NULL; \
  1378. } \
  1379. env->history = e; \
  1380. } while (0)
  1381. /**
  1382. * Mark a point where a complete set of actions has ended.
  1383. */
  1384. void set_history_break(void) {
  1385. if (!global_config.history_enabled) return;
  1386. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1387. history_t * e = malloc(sizeof(history_t));
  1388. e->type = HISTORY_BREAK;
  1389. HIST_APPEND(e);
  1390. }
  1391. }
  1392. /**
  1393. * Insert a character into an existing line.
  1394. */
  1395. __attribute__((warn_unused_result)) line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1396. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1397. history_t * e = malloc(sizeof(history_t));
  1398. e->type = HISTORY_INSERT;
  1399. e->contents.insert_delete_replace.lineno = lineno;
  1400. e->contents.insert_delete_replace.offset = offset;
  1401. e->contents.insert_delete_replace.codepoint = c.codepoint;
  1402. HIST_APPEND(e);
  1403. }
  1404. /* If there is not enough space... */
  1405. if (line->actual == line->available) {
  1406. /* Expand the line buffer */
  1407. if (line->available == 0) {
  1408. line->available = 8;
  1409. } else {
  1410. line->available *= 2;
  1411. }
  1412. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1413. }
  1414. /* If this was not the last character, then shift remaining characters forward. */
  1415. if (offset < line->actual) {
  1416. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1417. }
  1418. /* Insert the new character */
  1419. line->text[offset] = c;
  1420. /* There is one new character in the line */
  1421. line->actual += 1;
  1422. if (!env->loading) {
  1423. line->rev_status = 2; /* Modified */
  1424. recalculate_tabs(line);
  1425. recalculate_syntax(line, lineno);
  1426. }
  1427. return line;
  1428. }
  1429. /**
  1430. * Delete a character from a line
  1431. */
  1432. void line_delete(line_t * line, int offset, int lineno) {
  1433. /* Can't delete character before start of line. */
  1434. if (offset == 0) return;
  1435. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1436. history_t * e = malloc(sizeof(history_t));
  1437. e->type = HISTORY_DELETE;
  1438. e->contents.insert_delete_replace.lineno = lineno;
  1439. e->contents.insert_delete_replace.offset = offset;
  1440. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1441. HIST_APPEND(e);
  1442. }
  1443. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1444. if (offset < line->actual) {
  1445. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1446. }
  1447. /* The line is one character shorter */
  1448. line->actual -= 1;
  1449. line->rev_status = 2;
  1450. recalculate_tabs(line);
  1451. recalculate_syntax(line, lineno);
  1452. }
  1453. /**
  1454. * Replace a character in a line
  1455. */
  1456. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1457. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1458. history_t * e = malloc(sizeof(history_t));
  1459. e->type = HISTORY_REPLACE;
  1460. e->contents.insert_delete_replace.lineno = lineno;
  1461. e->contents.insert_delete_replace.offset = offset;
  1462. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  1463. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1464. HIST_APPEND(e);
  1465. }
  1466. line->text[offset] = _c;
  1467. if (!env->loading) {
  1468. line->rev_status = 2; /* Modified */
  1469. recalculate_tabs(line);
  1470. recalculate_syntax(line, lineno);
  1471. }
  1472. }
  1473. /**
  1474. * Remove a line from the active buffer
  1475. */
  1476. line_t ** remove_line(line_t ** lines, int offset) {
  1477. /* If there is only one line, clear it instead of removing it. */
  1478. if (env->line_count == 1) {
  1479. while (lines[offset]->actual > 0) {
  1480. line_delete(lines[offset], lines[offset]->actual, offset);
  1481. }
  1482. return lines;
  1483. }
  1484. if (!env->loading && global_config.history_enabled) {
  1485. history_t * e = malloc(sizeof(history_t));
  1486. e->type = HISTORY_REMOVE_LINE;
  1487. e->contents.remove_replace_line.lineno = offset;
  1488. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1489. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1490. HIST_APPEND(e);
  1491. }
  1492. /* Otherwise, free the data used by the line */
  1493. free(lines[offset]);
  1494. /* Move other lines up */
  1495. if (offset < env->line_count-1) {
  1496. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1497. lines[env->line_count-1] = NULL;
  1498. }
  1499. /* There is one less line */
  1500. env->line_count -= 1;
  1501. return lines;
  1502. }
  1503. /**
  1504. * Add a new line to the active buffer.
  1505. */
  1506. line_t ** add_line(line_t ** lines, int offset) {
  1507. /* Invalid offset? */
  1508. if (offset > env->line_count) return lines;
  1509. if (!env->loading && global_config.history_enabled) {
  1510. history_t * e = malloc(sizeof(history_t));
  1511. e->type = HISTORY_ADD_LINE;
  1512. e->contents.add_merge_split_lines.lineno = offset;
  1513. HIST_APPEND(e);
  1514. }
  1515. /* Not enough space */
  1516. if (env->line_count == env->line_avail) {
  1517. /* Allocate more space */
  1518. env->line_avail *= 2;
  1519. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1520. }
  1521. /* If this isn't the last line, move other lines down */
  1522. if (offset < env->line_count) {
  1523. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1524. }
  1525. /* Allocate the new line */
  1526. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1527. lines[offset]->available = 32;
  1528. /* There is one new line */
  1529. env->line_count += 1;
  1530. env->lines = lines;
  1531. if (!env->loading) {
  1532. lines[offset]->rev_status = 2; /* Modified */
  1533. }
  1534. if (offset > 0 && !env->loading) {
  1535. recalculate_syntax(lines[offset-1],offset-1);
  1536. }
  1537. return lines;
  1538. }
  1539. /**
  1540. * Replace a line with data from another line (used by paste to paste yanked lines)
  1541. */
  1542. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1543. if (!env->loading && global_config.history_enabled) {
  1544. history_t * e = malloc(sizeof(history_t));
  1545. e->type = HISTORY_REPLACE_LINE;
  1546. e->contents.remove_replace_line.lineno = offset;
  1547. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1548. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1549. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1550. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1551. HIST_APPEND(e);
  1552. }
  1553. if (lines[offset]->available < replacement->actual) {
  1554. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1555. lines[offset]->available = replacement->available;
  1556. }
  1557. lines[offset]->actual = replacement->actual;
  1558. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1559. if (!env->loading) {
  1560. lines[offset]->rev_status = 2;
  1561. recalculate_syntax(lines[offset],offset);
  1562. }
  1563. }
  1564. /**
  1565. * Merge two consecutive lines.
  1566. * lineb is the offset of the second line.
  1567. */
  1568. line_t ** merge_lines(line_t ** lines, int lineb) {
  1569. /* linea is the line immediately before lineb */
  1570. int linea = lineb - 1;
  1571. if (!env->loading && global_config.history_enabled) {
  1572. history_t * e = malloc(sizeof(history_t));
  1573. e->type = HISTORY_MERGE_LINES;
  1574. e->contents.add_merge_split_lines.lineno = lineb;
  1575. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  1576. HIST_APPEND(e);
  1577. }
  1578. /* If there isn't enough space in linea hold both... */
  1579. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1580. /* ... allocate more space until it fits */
  1581. if (lines[linea]->available == 0) {
  1582. lines[linea]->available = 8;
  1583. } else {
  1584. lines[linea]->available *= 2;
  1585. }
  1586. /* XXX why not just do this once after calculating appropriate size */
  1587. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1588. }
  1589. /* Copy the second line into the first line */
  1590. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1591. /* The first line is now longer */
  1592. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1593. if (!env->loading) {
  1594. lines[linea]->rev_status = 2;
  1595. recalculate_tabs(lines[linea]);
  1596. recalculate_syntax(lines[linea], linea);
  1597. }
  1598. /* Remove the second line */
  1599. free(lines[lineb]);
  1600. /* Move other lines up */
  1601. if (lineb < env->line_count) {
  1602. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1603. lines[env->line_count-1] = NULL;
  1604. }
  1605. /* There is one less line */
  1606. env->line_count -= 1;
  1607. return lines;
  1608. }
  1609. /**
  1610. * Split a line into two lines at the given column
  1611. */
  1612. line_t ** split_line(line_t ** lines, int line, int split) {
  1613. /* If we're trying to split from the start, just add a new blank line before */
  1614. if (split == 0) {
  1615. return add_line(lines, line);
  1616. }
  1617. if (!env->loading && global_config.history_enabled) {
  1618. history_t * e = malloc(sizeof(history_t));
  1619. e->type = HISTORY_SPLIT_LINE;
  1620. e->contents.add_merge_split_lines.lineno = line;
  1621. e->contents.add_merge_split_lines.split = split;
  1622. HIST_APPEND(e);
  1623. }
  1624. /* Allocate more space as needed */
  1625. if (env->line_count == env->line_avail) {
  1626. env->line_avail *= 2;
  1627. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1628. }
  1629. if (!env->loading) {
  1630. unhighlight_matching_paren();
  1631. }
  1632. /* Shift later lines down */
  1633. if (line < env->line_count) {
  1634. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1635. }
  1636. /* I have no idea what this is doing */
  1637. int remaining = lines[line]->actual - split;
  1638. int v = remaining;
  1639. v--;
  1640. v |= v >> 1;
  1641. v |= v >> 2;
  1642. v |= v >> 4;
  1643. v |= v >> 8;
  1644. v |= v >> 16;
  1645. v++;
  1646. /* Allocate space for the new line */
  1647. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  1648. lines[line+1]->available = v;
  1649. lines[line+1]->actual = remaining;
  1650. /* Move the data from the old line into the new line */
  1651. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1652. lines[line]->actual = split;
  1653. if (!env->loading) {
  1654. lines[line]->rev_status = 2;
  1655. lines[line+1]->rev_status = 2;
  1656. recalculate_tabs(lines[line]);
  1657. recalculate_tabs(lines[line+1]);
  1658. recalculate_syntax(lines[line], line);
  1659. recalculate_syntax(lines[line+1], line+1);
  1660. }
  1661. /* There is one new line */
  1662. env->line_count += 1;
  1663. /* We may have reallocated lines */
  1664. return lines;
  1665. }
  1666. /**
  1667. * Understand spaces and comments and check if the previous line
  1668. * ended with a brace or a colon.
  1669. */
  1670. int line_ends_with_brace(line_t * line) {
  1671. int i = line->actual-1;
  1672. while (i >= 0) {
  1673. if ((line->text[i].flags & 0x1F) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  1674. i--;
  1675. } else {
  1676. break;
  1677. }
  1678. }
  1679. if (i < 0) return 0;
  1680. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':') ? i+1 : 0;
  1681. }
  1682. int line_is_comment(line_t * line) {
  1683. if (!env->syntax) return 0;
  1684. if (!strcmp(env->syntax->name,"c")) {
  1685. if (line->istate == 1) return 1;
  1686. } else if (!strcmp(env->syntax->name,"java")) {
  1687. if (line->istate == 1) return 1;
  1688. } else if (!strcmp(env->syntax->name,"rust")) {
  1689. if (line->istate > 0) return 1;
  1690. }
  1691. return 0;
  1692. }
  1693. int find_brace_line_start(int line, int col) {
  1694. int ncol = col - 1;
  1695. while (ncol > 0) {
  1696. if (env->lines[line-1]->text[ncol-1].codepoint == ')') {
  1697. int t_line_no = env->line_no;
  1698. int t_col_no = env->col_no;
  1699. env->line_no = line;
  1700. env->col_no = ncol;
  1701. int paren_match_line = -1, paren_match_col = -1;
  1702. find_matching_paren(&paren_match_line, &paren_match_col, 1);
  1703. if (paren_match_line != -1) {
  1704. line = paren_match_line;
  1705. }
  1706. env->line_no = t_line_no;
  1707. env->col_no = t_col_no;
  1708. break;
  1709. } else if (env->lines[line-1]->text[ncol-1].codepoint == ' ') {
  1710. ncol--;
  1711. } else {
  1712. break;
  1713. }
  1714. }
  1715. return line;
  1716. }
  1717. /**
  1718. * Add indentation from the previous (temporally) line
  1719. */
  1720. void add_indent(int new_line, int old_line, int ignore_brace) {
  1721. if (env->indent) {
  1722. int changed = 0;
  1723. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  1724. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1725. if (env->lines[old_line]->text[i].codepoint == '/') {
  1726. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  1727. /* Insert ' * ' */
  1728. char_t space = {1,FLAG_COMMENT,' '};
  1729. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1730. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1731. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1732. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1733. env->col_no += 3;
  1734. }
  1735. break;
  1736. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  1737. /* Insert ' * ' */
  1738. char_t space = {1,FLAG_COMMENT,' '};
  1739. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1740. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1741. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1742. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1743. env->col_no += 3;
  1744. break;
  1745. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1746. env->lines[old_line]->text[i].codepoint == '\t' ||
  1747. env->lines[old_line]->text[i].codepoint == '*') {
  1748. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1749. env->col_no++;
  1750. changed = 1;
  1751. } else {
  1752. break;
  1753. }
  1754. }
  1755. } else {
  1756. int line_to_copy_from = old_line;
  1757. int col;
  1758. if (old_line < new_line &&
  1759. !ignore_brace &&
  1760. (col = line_ends_with_brace(env->lines[old_line])) &&
  1761. env->lines[old_line]->text[col-1].codepoint == '{') {
  1762. line_to_copy_from = find_brace_line_start(old_line+1, col)-1;
  1763. }
  1764. for (int i = 0; i < env->lines[line_to_copy_from]->actual; ++i) {
  1765. if (line_to_copy_from < new_line && i == env->lines[line_to_copy_from]->actual - 3 &&
  1766. env->lines[line_to_copy_from]->text[i].codepoint == ' ' &&
  1767. env->lines[line_to_copy_from]->text[i+1].codepoint == '*' &&
  1768. env->lines[line_to_copy_from]->text[i+2].codepoint == '/') {
  1769. break;
  1770. } else if (env->lines[line_to_copy_from]->text[i].codepoint == ' ' ||
  1771. env->lines[line_to_copy_from]->text[i].codepoint == '\t') {
  1772. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[line_to_copy_from]->text[i],i,new_line);
  1773. env->col_no++;
  1774. changed = 1;
  1775. } else {
  1776. break;
  1777. }
  1778. }
  1779. }
  1780. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  1781. if (env->tabs) {
  1782. char_t c;
  1783. c.codepoint = '\t';
  1784. c.display_width = env->tabstop;
  1785. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1786. env->col_no++;
  1787. changed = 1;
  1788. } else {
  1789. for (int j = 0; j < env->tabstop; ++j) {
  1790. char_t c;
  1791. c.codepoint = ' ';
  1792. c.display_width = 1;
  1793. c.flags = FLAG_SELECT;
  1794. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1795. env->col_no++;
  1796. }
  1797. changed = 1;
  1798. }
  1799. }
  1800. int was_whitespace = 1;
  1801. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1802. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  1803. env->lines[old_line]->text[i].codepoint != '\t') {
  1804. was_whitespace = 0;
  1805. break;
  1806. }
  1807. }
  1808. if (was_whitespace) {
  1809. while (env->lines[old_line]->actual) {
  1810. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  1811. }
  1812. }
  1813. if (changed) {
  1814. recalculate_syntax(env->lines[new_line],new_line);
  1815. }
  1816. }
  1817. }
  1818. /**
  1819. * Initialize a buffer with default values
  1820. */
  1821. void setup_buffer(buffer_t * env) {
  1822. /* If this buffer was already initialized, clear out its line data */
  1823. if (env->lines) {
  1824. for (int i = 0; i < env->line_count; ++i) {
  1825. free(env->lines[i]);
  1826. }
  1827. free(env->lines);
  1828. }
  1829. /* Default state parameters */
  1830. env->line_no = 1; /* Default cursor position */
  1831. env->col_no = 1;
  1832. env->line_count = 1; /* Buffers always have at least one line */
  1833. env->modified = 0;
  1834. env->readonly = 0;
  1835. env->offset = 0;
  1836. env->line_avail = 8; /* Default line buffer capacity */
  1837. env->tabs = 1; /* Tabs by default */
  1838. env->tabstop = 4; /* Tab stop width */
  1839. env->indent = 1; /* Auto-indent by default */
  1840. env->history = malloc(sizeof(struct history));
  1841. memset(env->history, 0, sizeof(struct history));
  1842. env->last_save_history = env->history;
  1843. /* Allocate line buffer */
  1844. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1845. /* Initialize the first line */
  1846. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1847. env->lines[0]->available = 32;
  1848. }
  1849. /**
  1850. * Toggle buffered / unbuffered modes
  1851. */
  1852. struct termios old;
  1853. void get_initial_termios(void) {
  1854. tcgetattr(STDOUT_FILENO, &old);
  1855. }
  1856. void set_unbuffered(void) {
  1857. struct termios new = old;
  1858. new.c_iflag &= (~ICRNL) & (~IXON);
  1859. new.c_lflag &= (~ICANON) & (~ECHO) & (~ISIG);
  1860. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1861. }
  1862. void set_buffered(void) {
  1863. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1864. }
  1865. /**
  1866. * Convert codepoint to utf-8 string
  1867. */
  1868. int to_eight(uint32_t codepoint, char * out) {
  1869. memset(out, 0x00, 7);
  1870. if (codepoint < 0x0080) {
  1871. out[0] = (char)codepoint;
  1872. } else if (codepoint < 0x0800) {
  1873. out[0] = 0xC0 | (codepoint >> 6);
  1874. out[1] = 0x80 | (codepoint & 0x3F);
  1875. } else if (codepoint < 0x10000) {
  1876. out[0] = 0xE0 | (codepoint >> 12);
  1877. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1878. out[2] = 0x80 | (codepoint & 0x3F);
  1879. } else if (codepoint < 0x200000) {
  1880. out[0] = 0xF0 | (codepoint >> 18);
  1881. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1882. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1883. out[3] = 0x80 | ((codepoint) & 0x3F);
  1884. } else if (codepoint < 0x4000000) {
  1885. out[0] = 0xF8 | (codepoint >> 24);
  1886. out[1] = 0x80 | (codepoint >> 18);
  1887. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1888. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1889. out[4] = 0x80 | ((codepoint) & 0x3F);
  1890. } else {
  1891. out[0] = 0xF8 | (codepoint >> 30);
  1892. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1893. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1894. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1895. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1896. out[5] = 0x80 | ((codepoint) & 0x3F);
  1897. }
  1898. return strlen(out);
  1899. }
  1900. /**
  1901. * Get the presentation width of a codepoint
  1902. */
  1903. int codepoint_width(wchar_t codepoint) {
  1904. if (codepoint == '\t') {
  1905. return 1; /* Recalculate later */
  1906. }
  1907. if (codepoint < 32) {
  1908. /* We render these as ^@ */
  1909. return 2;
  1910. }
  1911. if (codepoint == 0x7F) {
  1912. /* Renders as ^? */
  1913. return 2;
  1914. }
  1915. if (codepoint > 0x7f && codepoint < 0xa0) {
  1916. /* Upper control bytes <xx> */
  1917. return 4;
  1918. }
  1919. if (codepoint == 0xa0) {
  1920. /* Non-breaking space _ */
  1921. return 1;
  1922. }
  1923. /* Skip wcwidth for anything under 256 */
  1924. if (codepoint > 256) {
  1925. if (global_config.can_unicode) {
  1926. /* Higher codepoints may be wider (eg. Japanese) */
  1927. int out = wcwidth(codepoint);
  1928. if (out >= 1) return out;
  1929. }
  1930. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1931. return (codepoint < 0x10000) ? 8 : 10;
  1932. }
  1933. return 1;
  1934. }
  1935. /**
  1936. * Move the terminal cursor
  1937. */
  1938. void place_cursor(int x, int y) {
  1939. printf("\033[%d;%dH", y, x);
  1940. }
  1941. char * color_string(const char * fg, const char * bg) {
  1942. static char output[100];
  1943. char * t = output;
  1944. t += sprintf(t,"\033[22;23;24;");
  1945. if (*bg == '@') {
  1946. int _bg = atoi(bg+1);
  1947. if (_bg < 10) {
  1948. t += sprintf(t, "4%d;", _bg);
  1949. } else {
  1950. t += sprintf(t, "10%d;", _bg-10);
  1951. }
  1952. } else {
  1953. t += sprintf(t, "48;%s;", bg);
  1954. }
  1955. if (*fg == '@') {
  1956. int _fg = atoi(fg+1);
  1957. if (_fg < 10) {
  1958. t += sprintf(t, "3%dm", _fg);
  1959. } else {
  1960. t += sprintf(t, "9%dm", _fg-10);
  1961. }
  1962. } else {
  1963. t += sprintf(t, "38;%sm", fg);
  1964. }
  1965. return output;
  1966. }
  1967. /**
  1968. * Set text colors
  1969. *
  1970. * Normally, text colors are just strings, but if they
  1971. * start with @ they will be parsed as integers
  1972. * representing one of the 16 standard colors, suitable
  1973. * for terminals without support for the 256- or 24-bit
  1974. * color modes.
  1975. */
  1976. void set_colors(const char * fg, const char * bg) {
  1977. printf("%s", color_string(fg, bg));
  1978. }
  1979. /**
  1980. * Set just the foreground color
  1981. *
  1982. * (See set_colors above)
  1983. */
  1984. void set_fg_color(const char * fg) {
  1985. printf("\033[22;23;24;");
  1986. if (*fg == '@') {
  1987. int _fg = atoi(fg+1);
  1988. if (_fg < 10) {
  1989. printf("3%dm", _fg);
  1990. } else {
  1991. printf("9%dm", _fg-10);
  1992. }
  1993. } else {
  1994. printf("38;%sm", fg);
  1995. }
  1996. }
  1997. /**
  1998. * Clear the rest of this line
  1999. */
  2000. void clear_to_end(void) {
  2001. if (global_config.can_bce) {
  2002. printf("\033[K");
  2003. }
  2004. }
  2005. /**
  2006. * For terminals without bce,
  2007. * prepaint the whole line, so we don't have to track
  2008. * where the cursor is for everything. Inefficient,
  2009. * but effective.
  2010. */
  2011. void paint_line(const char * bg) {
  2012. if (!global_config.can_bce) {
  2013. set_colors(COLOR_FG, bg);
  2014. for (int i = 0; i < global_config.term_width; ++i) {
  2015. printf(" ");
  2016. }
  2017. printf("\r");
  2018. }
  2019. }
  2020. /**
  2021. * Enable bold text display
  2022. */
  2023. void set_bold(void) {
  2024. printf("\033[1m");
  2025. }
  2026. /**
  2027. * Disable bold
  2028. */
  2029. void unset_bold(void) {
  2030. printf("\033[22m");
  2031. }
  2032. /**
  2033. * Enable underlined text display
  2034. */
  2035. void set_underline(void) {
  2036. printf("\033[4m");
  2037. }
  2038. /**
  2039. * Disable underlined text display
  2040. */
  2041. void unset_underline(void) {
  2042. printf("\033[24m");
  2043. }
  2044. /**
  2045. * Reset text display attributes
  2046. */
  2047. void reset(void) {
  2048. printf("\033[0m");
  2049. }
  2050. /**
  2051. * Clear the entire screen
  2052. */
  2053. void clear_screen(void) {
  2054. printf("\033[H\033[2J");
  2055. }
  2056. /**
  2057. * Hide the cursor
  2058. */
  2059. void hide_cursor(void) {
  2060. if (global_config.can_hideshow) {
  2061. printf("\033[?25l");
  2062. }
  2063. }
  2064. /**
  2065. * Show the cursor
  2066. */
  2067. void show_cursor(void) {
  2068. if (global_config.can_hideshow) {
  2069. printf("\033[?25h");
  2070. }
  2071. }
  2072. /**
  2073. * Store the cursor position
  2074. */
  2075. void store_cursor(void) {
  2076. printf("\0337");
  2077. }
  2078. /**
  2079. * Restore the cursor position.
  2080. */
  2081. void restore_cursor(void) {
  2082. printf("\0338");
  2083. }
  2084. /**
  2085. * Request mouse events
  2086. */
  2087. void mouse_enable(void) {
  2088. if (global_config.can_mouse) {
  2089. printf("\033[?1000h");
  2090. }
  2091. }
  2092. /**
  2093. * Stop mouse events
  2094. */
  2095. void mouse_disable(void) {
  2096. if (global_config.can_mouse) {
  2097. printf("\033[?1000l");
  2098. }
  2099. }
  2100. /**
  2101. * Shift the screen up one line
  2102. */
  2103. void shift_up(int amount) {
  2104. printf("\033[%dS", amount);
  2105. }
  2106. /**
  2107. * Shift the screen down one line.
  2108. */
  2109. void shift_down(int amount) {
  2110. printf("\033[%dT", amount);
  2111. }
  2112. /**
  2113. * Switch to the alternate terminal screen.
  2114. */
  2115. void set_alternate_screen(void) {
  2116. if (global_config.can_altscreen) {
  2117. printf("\033[?1049h");
  2118. }
  2119. }
  2120. /**
  2121. * Restore the standard terminal screen.
  2122. */
  2123. void unset_alternate_screen(void) {
  2124. if (global_config.can_altscreen) {
  2125. printf("\033[?1049l");
  2126. }
  2127. }
  2128. /**
  2129. * Get the name of just a file from a full path.
  2130. * Returns a pointer within the original string.
  2131. */
  2132. char * file_basename(char * file) {
  2133. char * c = strrchr(file, '/');
  2134. if (!c) return file;
  2135. return (c+1);
  2136. }
  2137. /**
  2138. * Print a tab name with fixed width and modifiers
  2139. * into an output buffer and return the written width.
  2140. */
  2141. int draw_tab_name(buffer_t * _env, char * out, int max_width, int * width) {
  2142. uint32_t c, state = 0;
  2143. char * t = _env->file_name ? file_basename(_env->file_name) : "[No Name]";
  2144. #define ADD(c) do { \
  2145. *o = c; \
  2146. o++; \
  2147. *o = '\0'; \
  2148. bytes++; \
  2149. } while (0)
  2150. char * o = out;
  2151. *o = '\0';
  2152. int bytes = 0;
  2153. if (max_width < 2) return 1;
  2154. ADD(' ');
  2155. (*width)++;
  2156. if (_env->modified) {
  2157. if (max_width < 4) return 1;
  2158. ADD('+');
  2159. (*width)++;
  2160. ADD(' ');
  2161. (*width)++;
  2162. }
  2163. while (*t) {
  2164. if (!decode(&state, &c, (unsigned char)*t)) {
  2165. char tmp[7];
  2166. int size = to_eight(c, tmp);
  2167. if (bytes + size > 62) break;
  2168. if (*width + size >= max_width) return 1;
  2169. for (int i = 0; i < size; ++i) {
  2170. ADD(tmp[i]);
  2171. }
  2172. (*width) += codepoint_width(c);
  2173. } else if (state == UTF8_REJECT) {
  2174. state = 0;
  2175. }
  2176. t++;
  2177. }
  2178. if (max_width == *width + 1) return 1;
  2179. ADD(' ');
  2180. (*width)++;
  2181. #undef ADD
  2182. return 0;
  2183. }
  2184. /**
  2185. * Redaw the tabbar, with a tab for each buffer.
  2186. *
  2187. * The active buffer is highlighted.
  2188. */
  2189. void redraw_tabbar(void) {
  2190. if (!global_config.tabs_visible) return;
  2191. /* Hide cursor while rendering UI */
  2192. hide_cursor();
  2193. /* Move to upper left */
  2194. place_cursor(1,1);
  2195. paint_line(COLOR_TABBAR_BG);
  2196. /* For each buffer... */
  2197. int offset = 0;
  2198. if (global_config.tab_offset) {
  2199. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2200. printf("<");
  2201. offset++;
  2202. }
  2203. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  2204. buffer_t * _env = buffers[i];
  2205. if (_env == env) {
  2206. /* If this is the active buffer, highlight it */
  2207. reset();
  2208. set_colors(COLOR_FG, COLOR_BG);
  2209. set_bold();
  2210. } else {
  2211. /* Otherwise use default tab color */
  2212. reset();
  2213. set_colors(COLOR_FG, COLOR_TAB_BG);
  2214. set_underline();
  2215. }
  2216. char title[64];
  2217. int size = 0;
  2218. int filled = draw_tab_name(_env, title, global_config.term_width - offset, &size);
  2219. if (filled) {
  2220. offset += size;
  2221. printf("%s", title);
  2222. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2223. while (offset != global_config.term_width - 1) {
  2224. printf(" ");
  2225. offset++;
  2226. }
  2227. printf(">");
  2228. break;
  2229. }
  2230. printf("%s", title);
  2231. offset += size;
  2232. }
  2233. /* Reset bold/underline */
  2234. reset();
  2235. /* Fill the rest of the tab bar */
  2236. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  2237. clear_to_end();
  2238. }
  2239. /**
  2240. * Braindead log10 implementation for the line numbers
  2241. */
  2242. int log_base_10(unsigned int v) {
  2243. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2244. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2245. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2246. return r;
  2247. }
  2248. /**
  2249. * Render a line of text
  2250. *
  2251. * This handles rendering the actual text content. A full line of text
  2252. * also includes a line number and some padding.
  2253. *
  2254. * width: width of the text display region (term width - line number width)
  2255. * offset: how many cells into the line to start rendering at
  2256. */
  2257. void render_line(line_t * line, int width, int offset, int line_no) {
  2258. int i = 0; /* Offset in char_t line data entries */
  2259. int j = 0; /* Offset in terminal cells */
  2260. const char * last_color = NULL;
  2261. int was_selecting = 0, was_searching = 0;
  2262. /* Set default text colors */
  2263. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2264. /*
  2265. * When we are rendering in the middle of a wide character,
  2266. * we render -'s to fill the remaining amount of the
  2267. * charater's width
  2268. */
  2269. int remainder = 0;
  2270. int is_spaces = 1;
  2271. /* For each character in the line ... */
  2272. while (i < line->actual) {
  2273. /* If there is remaining text... */
  2274. if (remainder) {
  2275. /* If we should be drawing by now... */
  2276. if (j >= offset) {
  2277. /* Fill remainder with -'s */
  2278. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2279. printf("-");
  2280. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2281. }
  2282. /* One less remaining width cell to fill */
  2283. remainder--;
  2284. /* Terminal offset moves forward */
  2285. j++;
  2286. /*
  2287. * If this was the last remaining character, move to
  2288. * the next codepoint in the line
  2289. */
  2290. if (remainder == 0) {
  2291. i++;
  2292. }
  2293. continue;
  2294. }
  2295. /* Get the next character to draw */
  2296. char_t c = line->text[i];
  2297. if (c.codepoint != ' ') is_spaces = 0;
  2298. /* If we should be drawing by now... */
  2299. if (j >= offset) {
  2300. /* If this character is going to fall off the edge of the screen... */
  2301. if (j - offset + c.display_width >= width) {
  2302. /* We draw this with special colors so it isn't ambiguous */
  2303. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2304. /* If it's wide, draw ---> as needed */
  2305. while (j - offset < width - 1) {
  2306. printf("-");
  2307. j++;
  2308. }
  2309. /* End the line with a > to show it overflows */
  2310. printf(">");
  2311. set_colors(COLOR_FG, COLOR_BG);
  2312. return;
  2313. }
  2314. /* Syntax highlighting */
  2315. const char * color = flag_to_color(c.flags);
  2316. if (c.flags & FLAG_SELECT) {
  2317. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2318. was_selecting = 1;
  2319. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  2320. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2321. was_searching = 1;
  2322. } else if (c.flags == FLAG_ERROR) {
  2323. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2324. was_searching = 1; /* co-opting this should work... */
  2325. } else {
  2326. if (was_selecting || was_searching) {
  2327. was_selecting = 0;
  2328. was_searching = 0;
  2329. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2330. last_color = color;
  2331. } else if (!last_color || strcmp(color, last_color)) {
  2332. set_fg_color(color);
  2333. last_color = color;
  2334. }
  2335. }
  2336. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2337. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2338. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2339. ((j == env->sel_col) ||
  2340. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  2341. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2342. was_selecting = 1;
  2343. }
  2344. #define _set_colors(fg,bg) \
  2345. if (!(c.flags & FLAG_SELECT) && !(c.flags & FLAG_SEARCH) && !(was_selecting)) { \
  2346. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  2347. }
  2348. /* Render special characters */
  2349. if (c.codepoint == '\t') {
  2350. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2351. printf("%s", global_config.tab_indicator);
  2352. for (int i = 1; i < c.display_width; ++i) {
  2353. printf("%s" ,global_config.space_indicator);
  2354. }
  2355. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2356. } else if (c.codepoint < 32) {
  2357. /* Codepoints under 32 to get converted to ^@ escapes */
  2358. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2359. printf("^%c", '@' + c.codepoint);
  2360. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2361. } else if (c.codepoint == 0x7f) {
  2362. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2363. printf("^?");
  2364. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2365. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  2366. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2367. printf("<%2x>", c.codepoint);
  2368. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2369. } else if (c.codepoint == 0xa0) {
  2370. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2371. printf("_");
  2372. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2373. } else if (c.display_width == 8) {
  2374. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2375. printf("[U+%04x]", c.codepoint);
  2376. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2377. } else if (c.display_width == 10) {
  2378. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2379. printf("[U+%06x]", c.codepoint);
  2380. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2381. } else if (i > 0 && is_spaces && c.codepoint == ' ' && !(i % env->tabstop)) {
  2382. _set_colors(COLOR_ALT_FG, COLOR_BG); /* Normal background so this is more subtle */
  2383. if (global_config.can_unicode) {
  2384. printf("▏");
  2385. } else {
  2386. printf("|");
  2387. }
  2388. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2389. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  2390. /* Special case: space at end of line */
  2391. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2392. printf("%s",global_config.space_indicator);
  2393. _set_colors(COLOR_FG, COLOR_BG);
  2394. } else {
  2395. /* Normal characters get output */
  2396. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  2397. to_eight(c.codepoint, tmp);
  2398. printf("%s", tmp);
  2399. }
  2400. /* Advance the terminal cell offset by the render width of this character */
  2401. j += c.display_width;
  2402. /* Advance to the next character */
  2403. i++;
  2404. } else if (c.display_width > 1) {
  2405. /*
  2406. * If this is a wide character but we aren't ready to render yet,
  2407. * we may need to draw some filler text for the remainder of its
  2408. * width to ensure we don't jump around when horizontally scrolling
  2409. * past wide characters.
  2410. */
  2411. remainder = c.display_width - 1;
  2412. j++;
  2413. } else {
  2414. /* Regular character, not ready to draw, advance without doing anything */
  2415. j++;
  2416. i++;
  2417. }
  2418. }
  2419. if (env->mode != MODE_LINE_SELECTION) {
  2420. if (line->is_current) {
  2421. set_colors(COLOR_FG, COLOR_ALT_BG);
  2422. } else {
  2423. set_colors(COLOR_FG, COLOR_BG);
  2424. }
  2425. } else {
  2426. if (!line->actual) {
  2427. if (env->line_no == line_no ||
  2428. (env->start_line > env->line_no &&
  2429. (line_no >= env->line_no && line_no <= env->start_line)) ||
  2430. (env->start_line < env->line_no &&
  2431. (line_no >= env->start_line && line_no <= env->line_no))) {
  2432. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2433. }
  2434. }
  2435. }
  2436. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2437. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2438. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2439. j <= env->sel_col &&
  2440. env->sel_col < width) {
  2441. set_colors(COLOR_FG, COLOR_BG);
  2442. while (j < env->sel_col) {
  2443. printf(" ");
  2444. j++;
  2445. }
  2446. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2447. printf(" ");
  2448. j++;
  2449. set_colors(COLOR_FG, COLOR_BG);
  2450. }
  2451. if (env->maxcolumn && line_no > -1 /* ensures we don't do this for command line */) {
  2452. /* Fill out the normal background */
  2453. if (j < offset) j = offset;
  2454. for (; j < width + offset && j < env->maxcolumn; ++j) {
  2455. printf(" ");
  2456. }
  2457. /* Draw the line */
  2458. if (j < width + offset && j == env->maxcolumn) {
  2459. j++;
  2460. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2461. if (global_config.can_unicode) {
  2462. printf("▏");
  2463. } else {
  2464. printf("|");
  2465. }
  2466. }
  2467. /* Fill the rest with the alternate background color */
  2468. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2469. }
  2470. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2471. clear_to_end();
  2472. } else {
  2473. /* Paint the rest of the line */
  2474. if (j < offset) j = offset;
  2475. for (; j < width + offset; ++j) {
  2476. printf(" ");
  2477. }
  2478. }
  2479. }
  2480. /**
  2481. * Get the width of the line number region
  2482. */
  2483. int num_width(void) {
  2484. if (!env->numbers) return 0;
  2485. int w = log_base_10(env->line_count) + 3;
  2486. if (w < 4) return 4;
  2487. return w;
  2488. }
  2489. /**
  2490. * Display width of the revision status gutter.
  2491. */
  2492. int gutter_width(void) {
  2493. return env->gutter;
  2494. }
  2495. /**
  2496. * Draw the gutter and line numbers.
  2497. */
  2498. void draw_line_number(int x) {
  2499. if (!env->numbers) return;
  2500. /* Draw the line number */
  2501. if (env->lines[x]->is_current) {
  2502. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  2503. } else {
  2504. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2505. }
  2506. if (global_config.relative_lines && x+1 != env->line_no) {
  2507. x = x+1 - env->line_no;
  2508. x = ((x < 0) ? -x : x)-1;
  2509. }
  2510. int num_size = num_width() - 2; /* Padding */
  2511. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2512. printf(" ");
  2513. }
  2514. printf("%d%c", x + 1, ((x+1 == env->line_no || global_config.horizontal_shift_scrolling) && env->coffset > 0) ? '<' : ' ');
  2515. }
  2516. /**
  2517. * Used to highlight the current line after moving the cursor.
  2518. */
  2519. void recalculate_current_line(void) {
  2520. int something_changed = 0;
  2521. if (global_config.highlight_current_line) {
  2522. for (int i = 0; i < env->line_count; ++i) {
  2523. if (env->lines[i]->is_current && i != env->line_no-1) {
  2524. env->lines[i]->is_current = 0;
  2525. something_changed = 1;
  2526. redraw_line(i);
  2527. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  2528. env->lines[i]->is_current = 1;
  2529. something_changed = 1;
  2530. redraw_line(i);
  2531. }
  2532. }
  2533. } else {
  2534. something_changed = 1;
  2535. }
  2536. if (something_changed && global_config.relative_lines) {
  2537. for (int i = env->offset; i < env->offset + global_config.term_height - global_config.bottom_size - 1 && i < env->line_count; ++i) {
  2538. /* Place cursor for line number */
  2539. place_cursor(1 + gutter_width() + env->left, (i)-env->offset + 1 + global_config.tabs_visible);
  2540. draw_line_number(i);
  2541. }
  2542. }
  2543. }
  2544. /**
  2545. * Redraw line.
  2546. *
  2547. * This draws the line number as well as the actual text.
  2548. */
  2549. void redraw_line(int x) {
  2550. if (env->loading) return;
  2551. /* Determine if this line is visible. */
  2552. if (x - env->offset < 0 || x - env->offset > global_config.term_height - global_config.bottom_size - 1 - global_config.tabs_visible) {
  2553. return;
  2554. }
  2555. /* Calculate offset in screen */
  2556. int j = x - env->offset;
  2557. /* Hide cursor when drawing */
  2558. hide_cursor();
  2559. /* Move cursor to upper left most cell of this line */
  2560. place_cursor(1 + env->left,1 + global_config.tabs_visible + j);
  2561. /* Draw a gutter on the left. */
  2562. if (env->gutter) {
  2563. switch (env->lines[x]->rev_status) {
  2564. case 1:
  2565. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  2566. printf(" ");
  2567. break;
  2568. case 2:
  2569. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  2570. printf(" ");
  2571. break;
  2572. case 3:
  2573. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  2574. printf(" ");
  2575. break;
  2576. case 4:
  2577. set_colors(COLOR_ALT_FG, COLOR_RED);
  2578. printf("▆");
  2579. break;
  2580. case 5:
  2581. set_colors(COLOR_KEYWORD, COLOR_RED);
  2582. printf("▆");
  2583. break;
  2584. default:
  2585. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2586. printf(" ");
  2587. break;
  2588. }
  2589. }
  2590. draw_line_number(x);
  2591. /*
  2592. * Draw the line text
  2593. * If this is the active line, the current character cell offset should be used.
  2594. * (Non-active lines are not shifted and always render from the start of the line)
  2595. */
  2596. render_line(env->lines[x], env->width - gutter_width() - num_width(), (x + 1 == env->line_no || global_config.horizontal_shift_scrolling) ? env->coffset : 0, x+1);
  2597. }
  2598. /**
  2599. * Draw a ~ line where there is no buffer text.
  2600. */
  2601. void draw_excess_line(int j) {
  2602. place_cursor(1+env->left,1 + global_config.tabs_visible + j);
  2603. paint_line(COLOR_ALT_BG);
  2604. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2605. printf("~");
  2606. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2607. clear_to_end();
  2608. } else {
  2609. /* Paint the rest of the line */
  2610. for (int x = 1; x < env->width; ++x) {
  2611. printf(" ");
  2612. }
  2613. }
  2614. }
  2615. /**
  2616. * Redraw the entire text area
  2617. */
  2618. void redraw_text(void) {
  2619. if (!env) return;
  2620. if (!global_config.has_terminal) return;
  2621. /* Hide cursor while rendering */
  2622. hide_cursor();
  2623. /* Figure out the available size of the text region */
  2624. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  2625. int j = 0;
  2626. /* Draw each line */
  2627. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2628. redraw_line(x);
  2629. j++;
  2630. }
  2631. /* Draw the rest of the text region as ~ lines */
  2632. for (; j < l; ++j) {
  2633. draw_excess_line(j);
  2634. }
  2635. }
  2636. static int view_left_offset = 0;
  2637. static int view_right_offset = 0;
  2638. /**
  2639. * When in split view, draw the other buffer.
  2640. * Has special handling for when the split is
  2641. * on a single buffer.
  2642. */
  2643. void redraw_alt_buffer(buffer_t * buf) {
  2644. if (left_buffer == right_buffer) {
  2645. /* draw the opposite view */
  2646. int left, width, offset;
  2647. left = env->left;
  2648. width = env->width;
  2649. offset = env->offset;
  2650. if (left == 0) {
  2651. /* Draw the right side */
  2652. env->left = width;
  2653. env->width = global_config.term_width - width;
  2654. env->offset = view_right_offset;
  2655. view_left_offset = offset;
  2656. } else {
  2657. env->left = 0;
  2658. env->width = global_config.term_width * global_config.split_percent / 100;
  2659. env->offset = view_left_offset;
  2660. view_right_offset = offset;
  2661. }
  2662. redraw_text();
  2663. env->left = left;
  2664. env->width = width;
  2665. env->offset = offset;
  2666. }
  2667. /* Swap out active buffer */
  2668. buffer_t * tmp = env;
  2669. env = buf;
  2670. /* Redraw text */
  2671. redraw_text();
  2672. /* Return original active buffer */
  2673. env = tmp;
  2674. }
  2675. /**
  2676. * Basically wcswidth() but implemented internally using our
  2677. * own utf-8 decoder to ensure it works properly.
  2678. */
  2679. int display_width_of_string(char * str) {
  2680. uint8_t * s = (uint8_t *)str;
  2681. int out = 0;
  2682. uint32_t c, state = 0;
  2683. while (*s) {
  2684. if (!decode(&state, &c, *s)) {
  2685. out += codepoint_width(c);
  2686. } else if (state == UTF8_REJECT) {
  2687. state = 0;
  2688. }
  2689. s++;
  2690. }
  2691. return out;
  2692. }
  2693. int statusbar_append_status(int *remaining_width, char * output, char * base, ...) {
  2694. va_list args;
  2695. va_start(args, base);
  2696. char tmp[100]; /* should be big enough */
  2697. vsnprintf(tmp, 100, base, args);
  2698. va_end(args);
  2699. int width = display_width_of_string(tmp) + 2;
  2700. if (width < *remaining_width) {
  2701. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2702. strcat(output,"[");
  2703. strcat(output,color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2704. strcat(output, tmp);
  2705. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2706. strcat(output,"]");
  2707. (*remaining_width) -= width;
  2708. return width;
  2709. } else {
  2710. return 0;
  2711. }
  2712. }
  2713. int statusbar_build_right(char * right_hand) {
  2714. char tmp[1024];
  2715. sprintf(tmp, " Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2716. int out = display_width_of_string(tmp);
  2717. char * s = right_hand;
  2718. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2719. s += sprintf(s, " Line ");
  2720. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2721. s += sprintf(s, "%d/%d ", env->line_no, env->line_count);
  2722. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2723. s += sprintf(s, " Col: ");
  2724. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2725. s += sprintf(s, "%d ", env->col_no);
  2726. return out;
  2727. }
  2728. /**
  2729. * Draw the status bar
  2730. *
  2731. * The status bar shows the name of the file, whether it has modifications,
  2732. * and (in the future) what syntax highlighting mode is enabled.
  2733. *
  2734. * The right side of the tatus bar shows the line number and column.
  2735. */
  2736. void redraw_statusbar(void) {
  2737. if (global_config.hide_statusbar) return;
  2738. if (!env) return;
  2739. /* Hide cursor while rendering */
  2740. hide_cursor();
  2741. /* Move cursor to the status bar line (second from bottom */
  2742. place_cursor(1, global_config.term_height - 1);
  2743. /* Set background colors for status line */
  2744. paint_line(COLOR_STATUS_BG);
  2745. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2746. /* Pre-render the right hand side of the status bar */
  2747. char right_hand[1024];
  2748. int right_width = statusbar_build_right(right_hand);
  2749. char status_bits[1024] = {0}; /* Sane maximum */
  2750. int status_bits_width = 0;
  2751. int remaining_width = global_config.term_width - right_width;
  2752. #define ADD(...) do { status_bits_width += statusbar_append_status(&remaining_width, status_bits, __VA_ARGS__); } while (0)
  2753. if (env->syntax) {
  2754. ADD("%s",env->syntax->name);
  2755. }
  2756. /* Print file status indicators */
  2757. if (env->modified) {
  2758. ADD("+");
  2759. }
  2760. if (env->readonly) {
  2761. ADD("ro");
  2762. }
  2763. if (env->crnl) {
  2764. ADD("crnl");
  2765. }
  2766. if (env->tabs) {
  2767. ADD("tabs");
  2768. } else {
  2769. ADD("spaces=%d", env->tabstop);
  2770. }
  2771. if (global_config.yanks) {
  2772. ADD("y:%ld", global_config.yank_count);
  2773. }
  2774. if (env->indent) {
  2775. ADD("indent");
  2776. }
  2777. if (global_config.smart_complete) {
  2778. ADD("complete");
  2779. }
  2780. #undef ADD
  2781. uint8_t * file_name = (uint8_t *)(env->file_name ? env->file_name : "[No Name]");
  2782. int file_name_width = display_width_of_string((char*)file_name);
  2783. if (remaining_width > 3) {
  2784. int is_chopped = 0;
  2785. while (remaining_width < file_name_width + 3) {
  2786. is_chopped = 1;
  2787. if ((*file_name & 0xc0) == 0xc0) { /* First byte of a multibyte character */
  2788. file_name++;
  2789. while ((*file_name & 0xc0) == 0x80) file_name++;
  2790. } else {
  2791. file_name++;
  2792. }
  2793. file_name_width = display_width_of_string((char*)file_name);
  2794. }
  2795. if (is_chopped) {
  2796. set_colors(COLOR_ALT_FG, COLOR_STATUS_BG);
  2797. printf("<");
  2798. }
  2799. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2800. printf("%s ", file_name);
  2801. }
  2802. printf("%s", status_bits);
  2803. /* Clear the rest of the status bar */
  2804. clear_to_end();
  2805. /* Move the cursor appropriately to draw it */
  2806. place_cursor(global_config.term_width - right_width, global_config.term_height - 1);
  2807. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2808. printf("%s",right_hand);
  2809. }
  2810. /**
  2811. * Redraw the navigation numbers on the right side of the command line
  2812. */
  2813. void redraw_nav_buffer() {
  2814. if (nav_buffer) {
  2815. store_cursor();
  2816. place_cursor(global_config.term_width - nav_buffer - 2, global_config.term_height);
  2817. printf("%s", nav_buf);
  2818. clear_to_end();
  2819. restore_cursor();
  2820. }
  2821. }
  2822. /**
  2823. * Draw the command line
  2824. *
  2825. * The command line either has input from the user (:quit, :!make, etc.)
  2826. * or shows the INSERT (or VISUAL in the future) mode name.
  2827. */
  2828. void redraw_commandline(void) {
  2829. if (!env) return;
  2830. /* Hide cursor while rendering */
  2831. hide_cursor();
  2832. /* Move cursor to the last line */
  2833. place_cursor(1, global_config.term_height);
  2834. /* Set background color */
  2835. paint_line(COLOR_BG);
  2836. set_colors(COLOR_FG, COLOR_BG);
  2837. /* If we are in an edit mode, note that. */
  2838. if (env->mode == MODE_INSERT) {
  2839. set_bold();
  2840. printf("-- INSERT --");
  2841. clear_to_end();
  2842. unset_bold();
  2843. } else if (env->mode == MODE_LINE_SELECTION) {
  2844. set_bold();
  2845. printf("-- LINE SELECTION -- (%d:%d)",
  2846. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2847. (env->start_line < env->line_no) ? env->line_no : env->start_line
  2848. );
  2849. clear_to_end();
  2850. unset_bold();
  2851. } else if (env->mode == MODE_COL_SELECTION) {
  2852. set_bold();
  2853. printf("-- COL SELECTION -- (%d:%d %d)",
  2854. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2855. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2856. (env->sel_col)
  2857. );
  2858. clear_to_end();
  2859. unset_bold();
  2860. } else if (env->mode == MODE_COL_INSERT) {
  2861. set_bold();
  2862. printf("-- COL INSERT -- (%d:%d %d)",
  2863. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2864. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2865. (env->sel_col)
  2866. );
  2867. clear_to_end();
  2868. unset_bold();
  2869. } else if (env->mode == MODE_REPLACE) {
  2870. set_bold();
  2871. printf("-- REPLACE --");
  2872. clear_to_end();
  2873. unset_bold();
  2874. } else if (env->mode == MODE_CHAR_SELECTION) {
  2875. set_bold();
  2876. printf("-- CHAR SELECTION -- ");
  2877. clear_to_end();
  2878. unset_bold();
  2879. } else if (env->mode == MODE_DIRECTORY_BROWSE) {
  2880. set_bold();
  2881. printf("-- DIRECTORY BROWSE --");
  2882. clear_to_end();
  2883. unset_bold();
  2884. } else {
  2885. clear_to_end();
  2886. }
  2887. redraw_nav_buffer();
  2888. }
  2889. /**
  2890. * Draw a message on the command line.
  2891. */
  2892. void render_commandline_message(char * message, ...) {
  2893. /* varargs setup */
  2894. va_list args;
  2895. va_start(args, message);
  2896. char buf[1024];
  2897. /* Process format string */
  2898. vsnprintf(buf, 1024, message, args);
  2899. va_end(args);
  2900. /* Hide cursor while rendering */
  2901. hide_cursor();
  2902. /* Move cursor to the last line */
  2903. place_cursor(1, global_config.term_height);
  2904. /* Set background color */
  2905. paint_line(COLOR_BG);
  2906. set_colors(COLOR_FG, COLOR_BG);
  2907. printf("%s", buf);
  2908. /* Clear the rest of the status bar */
  2909. clear_to_end();
  2910. redraw_nav_buffer();
  2911. }
  2912. BIM_ACTION(redraw_all, 0,
  2913. "Repaint the screen."
  2914. )(void) {
  2915. if (!env) return;
  2916. redraw_tabbar();
  2917. redraw_text();
  2918. if (left_buffer) {
  2919. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  2920. }
  2921. redraw_statusbar();
  2922. redraw_commandline();
  2923. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND || global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  2924. render_command_input_buffer();
  2925. }
  2926. }
  2927. void pause_for_key(void) {
  2928. int c;
  2929. while ((c = bim_getch())== -1);
  2930. bim_unget(c);
  2931. redraw_all();
  2932. }
  2933. /**
  2934. * Redraw all screen elements except the other split view.
  2935. */
  2936. void redraw_most(void) {
  2937. redraw_tabbar();
  2938. redraw_text();
  2939. redraw_statusbar();
  2940. redraw_commandline();
  2941. }
  2942. /**
  2943. * Disable screen splitting.
  2944. */
  2945. void unsplit(void) {
  2946. if (left_buffer) {
  2947. left_buffer->left = 0;
  2948. left_buffer->width = global_config.term_width;
  2949. }
  2950. if (right_buffer) {
  2951. right_buffer->left = 0;
  2952. right_buffer->width = global_config.term_width;
  2953. }
  2954. left_buffer = NULL;
  2955. right_buffer = NULL;
  2956. redraw_all();
  2957. }
  2958. /**
  2959. * Update the terminal title bar
  2960. */
  2961. void update_title(void) {
  2962. if (!global_config.can_title) return;
  2963. char cwd[1024] = {'/',0};
  2964. getcwd(cwd, 1024);
  2965. for (int i = 1; i < 3; ++i) {
  2966. printf("\033]%d;%s%s (%s) - Bim\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  2967. }
  2968. }
  2969. /**
  2970. * Mark this buffer as modified and
  2971. * redraw the status and tabbar if needed.
  2972. */
  2973. void set_modified(void) {
  2974. /* If it was already marked modified, no need to do anything */
  2975. if (env->modified) return;
  2976. /* Mark as modified */
  2977. env->modified = 1;
  2978. /* Redraw some things */
  2979. update_title();
  2980. redraw_tabbar();
  2981. redraw_statusbar();
  2982. }
  2983. /**
  2984. * Draw a message on the status line
  2985. */
  2986. void render_status_message(char * message, ...) {
  2987. if (!env) return; /* Don't print when there's no active environment; this usually means a bimrc command tried to print something */
  2988. /* varargs setup */
  2989. va_list args;
  2990. va_start(args, message);
  2991. char buf[1024];
  2992. /* Process format string */
  2993. vsnprintf(buf, 1024, message, args);
  2994. va_end(args);
  2995. /* Hide cursor while rendering */
  2996. hide_cursor();
  2997. /* Move cursor to the status bar line (second from bottom */
  2998. place_cursor(1, global_config.term_height - 1);
  2999. /* Set background colors for status line */
  3000. paint_line(COLOR_STATUS_BG);
  3001. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  3002. printf("%s", buf);
  3003. /* Clear the rest of the status bar */
  3004. clear_to_end();
  3005. }
  3006. /**
  3007. * Draw an errormessage to the command line.
  3008. */
  3009. void render_error(char * message, ...) {
  3010. /* varargs setup */
  3011. va_list args;
  3012. va_start(args, message);
  3013. char buf[1024];
  3014. /* Process format string */
  3015. vsnprintf(buf, 1024, message, args);
  3016. va_end(args);
  3017. if (env) {
  3018. /* Hide cursor while rendering */
  3019. hide_cursor();
  3020. /* Move cursor to the command line */
  3021. place_cursor(1, global_config.term_height);
  3022. /* Set appropriate error message colors */
  3023. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  3024. /* Draw the message */
  3025. printf("%s", buf);
  3026. } else {
  3027. printf("bim: error during startup: %s\n", buf);
  3028. }
  3029. }
  3030. char * paren_pairs = "()[]{}<>";
  3031. int is_paren(int c) {
  3032. char * p = paren_pairs;
  3033. while (*p) {
  3034. if (c == *p) return 1;
  3035. p++;
  3036. }
  3037. return 0;
  3038. }
  3039. #define _rehighlight_parens() do { \
  3040. if (i < 0 || i >= env->line_count) break; \
  3041. for (int j = 0; j < env->lines[i]->actual; ++j) { \
  3042. if (i == line-1 && j == col-1) { \
  3043. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT; \
  3044. continue; \
  3045. } else { \
  3046. env->lines[i]->text[j].flags &= (~FLAG_SELECT); \
  3047. } \
  3048. } \
  3049. redraw_line(i); \
  3050. } while (0)
  3051. /**
  3052. * If the config option is enabled, find the matching
  3053. * paren character and highlight it with the SELECT
  3054. * colors, clearing out other SELECT values. As we
  3055. * co-opt the SELECT flag, don't do this in selection
  3056. * modes - only in normal and insert modes.
  3057. */
  3058. void highlight_matching_paren(void) {
  3059. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  3060. if (!global_config.highlight_parens) return;
  3061. int line = -1, col = -1;
  3062. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  3063. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  3064. find_matching_paren(&line, &col, 1);
  3065. } 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)) {
  3066. find_matching_paren(&line, &col, 2);
  3067. }
  3068. if (env->highlighting_paren == -1 && line == -1) return;
  3069. if (env->highlighting_paren > 0) {
  3070. int i = env->highlighting_paren - 1;
  3071. _rehighlight_parens();
  3072. }
  3073. if (env->highlighting_paren != line && line != -1) {
  3074. int i = line - 1;
  3075. _rehighlight_parens();
  3076. }
  3077. env->highlighting_paren = line;
  3078. }
  3079. /**
  3080. * Recalculate syntax for the matched paren.
  3081. * Useful when entering selection modes.
  3082. */
  3083. void unhighlight_matching_paren(void) {
  3084. if (env->highlighting_paren > 0 && env->highlighting_paren <= env->line_count) {
  3085. for (int i = env->highlighting_paren - 1; i <= env->highlighting_paren + 1; ++i) {
  3086. if (i >= 1 && i <= env->line_count) {
  3087. recalculate_syntax(env->lines[i-1], i-1);
  3088. redraw_line(i-1);
  3089. }
  3090. }
  3091. env->highlighting_paren = -1;
  3092. }
  3093. }
  3094. /**
  3095. * Move the cursor to the appropriate location based
  3096. * on where it is in the text region.
  3097. *
  3098. * This does some additional math to set the text
  3099. * region horizontal offset.
  3100. */
  3101. void place_cursor_actual(void) {
  3102. /* Invalid positions */
  3103. if (env->line_no < 1) env->line_no = 1;
  3104. if (env->col_no < 1) env->col_no = 1;
  3105. /* Account for the left hand gutter */
  3106. int num_size = num_width() + gutter_width();
  3107. int x = num_size + 1 - env->coffset;
  3108. /* Determine where the cursor is physically */
  3109. for (int i = 0; i < env->col_no - 1; ++i) {
  3110. char_t * c = &env->lines[env->line_no-1]->text[i];
  3111. x += c->display_width;
  3112. }
  3113. /* y is a bit easier to calculate */
  3114. int y = env->line_no - env->offset + 1;
  3115. int needs_redraw = 0;
  3116. while (y < 2 + global_config.tabs_visible + global_config.cursor_padding && env->offset > 0) {
  3117. y++;
  3118. env->offset--;
  3119. needs_redraw = 1;
  3120. }
  3121. while (y > global_config.term_height - global_config.bottom_size - global_config.cursor_padding) {
  3122. y--;
  3123. env->offset++;
  3124. needs_redraw = 1;
  3125. }
  3126. if (needs_redraw) {
  3127. redraw_text();
  3128. redraw_tabbar();
  3129. redraw_statusbar();
  3130. redraw_commandline();
  3131. }
  3132. /* If the cursor has gone off screen to the right... */
  3133. if (x > env->width - 1) {
  3134. /* Adjust the offset appropriately to scroll horizontally */
  3135. int diff = x - (env->width - 1);
  3136. env->coffset += diff;
  3137. x -= diff;
  3138. redraw_text();
  3139. }
  3140. /* Same for scrolling horizontally to the left */
  3141. if (x < num_size + 1) {
  3142. int diff = (num_size + 1) - x;
  3143. env->coffset -= diff;
  3144. x += diff;
  3145. redraw_text();
  3146. }
  3147. highlight_matching_paren();
  3148. recalculate_current_line();
  3149. /* Move the actual terminal cursor */
  3150. place_cursor(x+env->left,y - !global_config.tabs_visible);
  3151. /* Show the cursor */
  3152. show_cursor();
  3153. }
  3154. /**
  3155. * If the screen is split, update the split sizes based
  3156. * on the new terminal width and the user's split_percent setting.
  3157. */
  3158. void update_split_size(void) {
  3159. if (!left_buffer) return;
  3160. if (left_buffer == right_buffer) {
  3161. if (left_buffer->left == 0) {
  3162. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3163. } else {
  3164. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  3165. right_buffer->width = global_config.term_width - right_buffer->left;
  3166. }
  3167. return;
  3168. }
  3169. left_buffer->left = 0;
  3170. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3171. right_buffer->left = left_buffer->width;
  3172. right_buffer->width = global_config.term_width - left_buffer->width;
  3173. }
  3174. /**
  3175. * Update screen size
  3176. */
  3177. void update_screen_size(void) {
  3178. struct winsize w;
  3179. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  3180. global_config.term_width = w.ws_col;
  3181. global_config.term_height = w.ws_row;
  3182. if (env) {
  3183. if (left_buffer) {
  3184. update_split_size();
  3185. } else if (env != left_buffer && env != right_buffer) {
  3186. env->width = w.ws_col;
  3187. }
  3188. }
  3189. for (int i = 0; i < buffers_len; ++i) {
  3190. if (buffers[i] != left_buffer && buffers[i] != right_buffer) {
  3191. buffers[i]->width = w.ws_col;
  3192. }
  3193. }
  3194. }
  3195. /**
  3196. * Handle terminal size changes
  3197. */
  3198. void SIGWINCH_handler(int sig) {
  3199. (void)sig;
  3200. update_screen_size();
  3201. redraw_all();
  3202. signal(SIGWINCH, SIGWINCH_handler);
  3203. }
  3204. /**
  3205. * Handle suspend
  3206. */
  3207. void SIGTSTP_handler(int sig) {
  3208. (void)sig;
  3209. mouse_disable();
  3210. set_buffered();
  3211. reset();
  3212. clear_screen();
  3213. show_cursor();
  3214. unset_alternate_screen();
  3215. fflush(stdout);
  3216. signal(SIGTSTP, SIG_DFL);
  3217. raise(SIGTSTP);
  3218. }
  3219. void SIGCONT_handler(int sig) {
  3220. (void)sig;
  3221. set_alternate_screen();
  3222. set_unbuffered();
  3223. update_screen_size();
  3224. mouse_enable();
  3225. redraw_all();
  3226. update_title();
  3227. signal(SIGCONT, SIGCONT_handler);
  3228. signal(SIGTSTP, SIGTSTP_handler);
  3229. }
  3230. void try_to_center() {
  3231. int half_a_screen = (global_config.term_height - 3) / 2;
  3232. if (half_a_screen < env->line_no) {
  3233. env->offset = env->line_no - half_a_screen;
  3234. } else {
  3235. env->offset = 0;
  3236. }
  3237. }
  3238. BIM_ACTION(suspend, 0,
  3239. "Suspend bim and the rest of the job it was run in."
  3240. )(void) {
  3241. kill(0, SIGTSTP);
  3242. }
  3243. /**
  3244. * Move the cursor to a specific line.
  3245. */
  3246. BIM_ACTION(goto_line, ARG_IS_CUSTOM,
  3247. "Jump to the requested line."
  3248. )(int line) {
  3249. if (line == -1) line = env->line_count;
  3250. /* Respect file bounds */
  3251. if (line < 1) line = 1;
  3252. if (line > env->line_count) line = env->line_count;
  3253. /* Move the cursor / text region offsets */
  3254. env->coffset = 0;
  3255. env->line_no = line;
  3256. env->col_no = 1;
  3257. if (!env->loading) {
  3258. if (line > env->offset && line < env->offset + global_config.term_height - global_config.bottom_size) {
  3259. place_cursor_actual();
  3260. } else {
  3261. try_to_center();
  3262. }
  3263. redraw_most();
  3264. } else {
  3265. try_to_center();
  3266. }
  3267. }
  3268. /**
  3269. * Processs (part of) a file and add it to a buffer.
  3270. */
  3271. void add_buffer(uint8_t * buf, int size) {
  3272. for (int i = 0; i < size; ++i) {
  3273. if (!decode(&state, &codepoint_r, buf[i])) {
  3274. uint32_t c = codepoint_r;
  3275. if (c == '\n') {
  3276. 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') {
  3277. env->lines[env->line_no-1]->actual--;
  3278. env->crnl = 1;
  3279. }
  3280. env->lines = add_line(env->lines, env->line_no);
  3281. env->col_no = 1;
  3282. env->line_no += 1;
  3283. } else if (env->crnl && c == '\r') {
  3284. continue;
  3285. } else {
  3286. char_t _c;
  3287. _c.codepoint = (uint32_t)c;
  3288. _c.flags = 0;
  3289. _c.display_width = codepoint_width((wchar_t)c);
  3290. line_t * line = env->lines[env->line_no - 1];
  3291. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  3292. if (line != nline) {
  3293. env->lines[env->line_no - 1] = nline;
  3294. }
  3295. env->col_no += 1;
  3296. }
  3297. } else if (state == UTF8_REJECT) {
  3298. state = 0;
  3299. }
  3300. }
  3301. }
  3302. /**
  3303. * Add a raw string to a buffer. Convenience wrapper
  3304. * for add_buffer for nil-terminated strings.
  3305. */
  3306. void add_string(char * string) {
  3307. add_buffer((uint8_t*)string,strlen(string));
  3308. }
  3309. int str_ends_with(const char * haystack, const char * needle) {
  3310. int i = strlen(haystack);
  3311. int j = strlen(needle);
  3312. do {
  3313. if (haystack[i] != needle[j]) return 0;
  3314. if (j == 0) return 1;
  3315. if (i == 0) return 0;
  3316. i--;
  3317. j--;
  3318. } while (1);
  3319. }
  3320. /**
  3321. * Find a syntax highlighter for the given filename.
  3322. */
  3323. struct syntax_definition * match_syntax(char * file) {
  3324. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3325. for (char ** ext = s->ext; *ext; ++ext) {
  3326. if (str_ends_with(file, *ext)) return s;
  3327. }
  3328. }
  3329. return NULL;
  3330. }
  3331. /**
  3332. * Set the syntax configuration by the name of the syntax highlighter.
  3333. */
  3334. void set_syntax_by_name(const char * name) {
  3335. if (!strcmp(name,"none")) {
  3336. for (int i = 0; i < env->line_count; ++i) {
  3337. env->lines[i]->istate = -1;
  3338. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3339. env->lines[i]->text[j].flags = 0;
  3340. }
  3341. }
  3342. redraw_all();
  3343. return;
  3344. }
  3345. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3346. if (!strcmp(name,s->name)) {
  3347. env->syntax = s;
  3348. for (int i = 0; i < env->line_count; ++i) {
  3349. env->lines[i]->istate = -1;
  3350. }
  3351. for (int i = 0; i < env->line_count; ++i) {
  3352. recalculate_syntax(env->lines[i],i);
  3353. }
  3354. redraw_all();
  3355. return;
  3356. }
  3357. }
  3358. render_error("unrecognized syntax type");
  3359. }
  3360. /**
  3361. * Check if a string is all numbers.
  3362. */
  3363. int is_all_numbers(const char * c) {
  3364. while (*c) {
  3365. if (!isdigit(*c)) return 0;
  3366. c++;
  3367. }
  3368. return 1;
  3369. }
  3370. struct file_listing {
  3371. int type;
  3372. char * filename;
  3373. };
  3374. int sort_files(const void * a, const void * b) {
  3375. struct file_listing * _a = (struct file_listing *)a;
  3376. struct file_listing * _b = (struct file_listing *)b;
  3377. if (_a->type == _b->type) {
  3378. return strcmp(_a->filename, _b->filename);
  3379. } else {
  3380. return _a->type - _b->type;
  3381. }
  3382. }
  3383. void read_directory_into_buffer(char * file) {
  3384. DIR * dirp = opendir(file);
  3385. if (!dirp) {
  3386. env->loading = 0;
  3387. return;
  3388. }
  3389. add_string("# Directory listing for `");
  3390. add_string(file);
  3391. add_string("`\n");
  3392. /* Flexible array to hold directory contents */
  3393. int available = 32;
  3394. int count = 0;
  3395. struct file_listing * files = calloc(sizeof(struct file_listing), available);
  3396. /* Read directory */
  3397. struct dirent * ent = readdir(dirp);
  3398. while (ent) {
  3399. struct stat statbuf;
  3400. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);
  3401. snprintf(tmp, strlen(file) + 1 + strlen(ent->d_name) + 1, "%s/%s", file, ent->d_name);
  3402. stat(tmp, &statbuf);
  3403. int type = (S_ISDIR(statbuf.st_mode)) ? 'd' : 'f';
  3404. if (count + 1 == available) {
  3405. available *= 2; \
  3406. files = realloc(files, sizeof(struct file_listing) * available); \
  3407. } \
  3408. files[count].type = type;
  3409. files[count].filename = strdup(ent->d_name);
  3410. count++;
  3411. ent = readdir(dirp);
  3412. }
  3413. closedir(dirp);
  3414. /* Sort directory entries */
  3415. qsort(files, count, sizeof(struct file_listing), sort_files);
  3416. for (int i = 0; i < count; ++i) {
  3417. add_string(files[i].type == 'd' ? "d" : "f");
  3418. add_string(" ");
  3419. add_string(files[i].filename);
  3420. add_string("\n");
  3421. free(files[i].filename);
  3422. }
  3423. free(files);
  3424. env->file_name = strdup(file);
  3425. env->syntax = find_syntax_calculator("dirent");
  3426. for (int i = 0; i < env->line_count; ++i) {
  3427. recalculate_syntax(env->lines[i],i);
  3428. }
  3429. env->readonly = 1;
  3430. env->loading = 0;
  3431. env->mode = MODE_DIRECTORY_BROWSE;
  3432. env->line_no = 1;
  3433. redraw_all();
  3434. }
  3435. BIM_ACTION(open_file_from_line, 0,
  3436. "When browsing a directory, open the file under the cursor."
  3437. )(void) {
  3438. if (env->lines[env->line_no-1]->actual < 1) return;
  3439. if (env->lines[env->line_no-1]->text[0].codepoint != 'd' &&
  3440. env->lines[env->line_no-1]->text[0].codepoint != 'f') return;
  3441. /* Collect file name */
  3442. char * tmp = malloc(strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7); /* Should be enough */
  3443. memset(tmp, 0, strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7);
  3444. char * t = tmp;
  3445. /* Start by copying the filename */
  3446. t += sprintf(t, "%s/", env->file_name);
  3447. /* Start from character 2 to skip d/f and space */
  3448. for (int i = 2; i < env->lines[env->line_no-1]->actual; ++i) {
  3449. t += to_eight(env->lines[env->line_no-1]->text[i].codepoint, t);
  3450. }
  3451. *t = '\0';
  3452. /* Normalize */
  3453. char tmp_path[PATH_MAX+1];
  3454. if (!realpath(tmp, tmp_path)) {
  3455. free(tmp);
  3456. return;
  3457. }
  3458. free(tmp);
  3459. /* Open file */
  3460. buffer_t * old_buffer = env;
  3461. open_file(tmp_path);
  3462. buffer_close(old_buffer);
  3463. update_title();
  3464. redraw_all();
  3465. }
  3466. int line_matches(line_t * line, char * string) {
  3467. uint32_t c, state = 0;
  3468. int i = 0;
  3469. while (*string) {
  3470. if (!decode(&state, &c, *string)) {
  3471. if (i >= line->actual) return 0;
  3472. if (line->text[i].codepoint != c) return 0;
  3473. string++;
  3474. i++;
  3475. } else if (state == UTF8_REJECT) {
  3476. state = 0;
  3477. }
  3478. }
  3479. return 1;
  3480. }
  3481. void run_onload(buffer_t * env) {
  3482. if (has_function("onload:*")) {
  3483. run_function("onload:*");
  3484. }
  3485. if (env->syntax) {
  3486. char tmp[512];
  3487. sprintf(tmp, "onload:%s", env->syntax->name);
  3488. if (has_function(tmp)) {
  3489. run_function(tmp);
  3490. }
  3491. }
  3492. }
  3493. /**
  3494. * Create a new buffer from a file.
  3495. */
  3496. void open_file(char * file) {
  3497. env = buffer_new();
  3498. env->width = global_config.term_width;
  3499. env->left = 0;
  3500. env->loading = 1;
  3501. setup_buffer(env);
  3502. FILE * f;
  3503. int init_line = -1;
  3504. if (!strcmp(file,"-")) {
  3505. /**
  3506. * Read file from stdin. stderr provides terminal input.
  3507. */
  3508. if (isatty(STDIN_FILENO)) {
  3509. if (buffers_len == 1) {
  3510. quit("stdin is a terminal and you tried to open -; not letting you do that");
  3511. }
  3512. close_buffer();
  3513. render_error("stdin is a terminal and you tried to open -; not letting you do that");
  3514. return;
  3515. }
  3516. f = stdin;
  3517. env->modified = 1;
  3518. } else {
  3519. char * l = strrchr(file, ':');
  3520. if (l && is_all_numbers(l+1)) {
  3521. *l = '\0';
  3522. l++;
  3523. init_line = atoi(l);
  3524. }
  3525. char * _file = file;
  3526. if (file[0] == '~') {
  3527. char * home = getenv("HOME");
  3528. if (home) {
  3529. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3530. sprintf(_file, "%s%s", home, file+1);
  3531. }
  3532. }
  3533. struct stat statbuf;
  3534. if (!stat(_file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  3535. read_directory_into_buffer(_file);
  3536. if (file != _file) free(_file);
  3537. return;
  3538. }
  3539. f = fopen(_file, "r");
  3540. if (file != _file) free(_file);
  3541. env->file_name = strdup(file);
  3542. }
  3543. if (!f) {
  3544. if (global_config.highlight_on_open) {
  3545. env->syntax = match_syntax(file);
  3546. }
  3547. env->loading = 0;
  3548. if (global_config.go_to_line) {
  3549. goto_line(1);
  3550. }
  3551. if (env->syntax && env->syntax->prefers_spaces) {
  3552. env->tabs = 0;
  3553. }
  3554. run_onload(env);
  3555. return;
  3556. }
  3557. uint8_t buf[BLOCK_SIZE];
  3558. state = 0;
  3559. while (!feof(f) && !ferror(f)) {
  3560. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  3561. add_buffer(buf, r);
  3562. }
  3563. if (ferror(f)) {
  3564. env->loading = 0;
  3565. return;
  3566. }
  3567. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  3568. /* Remove blank line from end */
  3569. env->lines = remove_line(env->lines, env->line_no-1);
  3570. }
  3571. if (global_config.highlight_on_open) {
  3572. env->syntax = match_syntax(file);
  3573. if (!env->syntax) {
  3574. if (line_matches(env->lines[0], "<?xml")) set_syntax_by_name("xml");
  3575. else if (line_matches(env->lines[0], "<!doctype")) set_syntax_by_name("xml");
  3576. else if (line_matches(env->lines[0], "#!/usr/bin/env bash")) set_syntax_by_name("bash");
  3577. else if (line_matches(env->lines[0], "#!/bin/bash")) set_syntax_by_name("bash");
  3578. else if (line_matches(env->lines[0], "#!/bin/sh")) set_syntax_by_name("bash");
  3579. else if (line_matches(env->lines[0], "#!/usr/bin/env python")) set_syntax_by_name("py");
  3580. else if (line_matches(env->lines[0], "#!/usr/bin/env groovy")) set_syntax_by_name("groovy");
  3581. }
  3582. if (!env->syntax && global_config.syntax_fallback) {
  3583. set_syntax_by_name(global_config.syntax_fallback);
  3584. }
  3585. for (int i = 0; i < env->line_count; ++i) {
  3586. recalculate_syntax(env->lines[i],i);
  3587. }
  3588. }
  3589. /* Try to automatically figure out tabs vs. spaces */
  3590. int tabs = 0, spaces = 0;
  3591. for (int i = 0; i < env->line_count; ++i) {
  3592. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  3593. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  3594. if (env->lines[i]->text[0].codepoint == ' ' &&
  3595. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  3596. spaces++;
  3597. }
  3598. }
  3599. if (spaces > tabs) {
  3600. env->tabs = 0;
  3601. } else if (spaces == tabs && env->syntax) {
  3602. env->tabs = env->syntax->prefers_spaces;
  3603. }
  3604. /* TODO figure out tabstop for spaces? */
  3605. env->loading = 0;
  3606. if (global_config.check_git) {
  3607. env->checkgitstatusonwrite = 1;
  3608. git_examine(file);
  3609. }
  3610. for (int i = 0; i < env->line_count; ++i) {
  3611. recalculate_tabs(env->lines[i]);
  3612. }
  3613. if (global_config.go_to_line) {
  3614. if (init_line != -1) {
  3615. goto_line(init_line);
  3616. } else {
  3617. env->line_no = 1;
  3618. env->col_no = 1;
  3619. fetch_from_biminfo(env);
  3620. place_cursor_actual();
  3621. redraw_all();
  3622. set_preferred_column();
  3623. }
  3624. }
  3625. fclose(f);
  3626. run_onload(env);
  3627. }
  3628. /**
  3629. * Clean up the terminal and exit the editor.
  3630. */
  3631. void quit(const char * message) {
  3632. mouse_disable();
  3633. set_buffered();
  3634. reset();
  3635. clear_screen();
  3636. show_cursor();
  3637. unset_alternate_screen();
  3638. if (message) {
  3639. fprintf(stdout, "%s\n", message);
  3640. }
  3641. exit(0);
  3642. }
  3643. /**
  3644. * Try to quit, but don't continue if there are
  3645. * modified buffers open.
  3646. */
  3647. void try_quit(void) {
  3648. for (int i = 0; i < buffers_len; i++ ) {
  3649. buffer_t * _env = buffers[i];
  3650. if (_env->modified) {
  3651. if (_env->file_name) {
  3652. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  3653. } else {
  3654. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  3655. }
  3656. return;
  3657. }
  3658. }
  3659. /* Close all buffers */
  3660. while (buffers_len) {
  3661. buffer_close(buffers[0]);
  3662. }
  3663. quit(NULL);
  3664. }
  3665. /**
  3666. * Switch to the previous buffer
  3667. */
  3668. BIM_ACTION(previous_tab, 0,
  3669. "Switch the previoius tab"
  3670. )(void) {
  3671. buffer_t * last = NULL;
  3672. for (int i = 0; i < buffers_len; i++) {
  3673. buffer_t * _env = buffers[i];
  3674. if (_env == env) {
  3675. if (last) {
  3676. /* Wrap around */
  3677. env = last;
  3678. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3679. redraw_all();
  3680. update_title();
  3681. return;
  3682. } else {
  3683. env = buffers[buffers_len-1];
  3684. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3685. redraw_all();
  3686. update_title();
  3687. return;
  3688. }
  3689. }
  3690. last = _env;
  3691. }
  3692. }
  3693. /**
  3694. * Switch to the next buffer
  3695. */
  3696. BIM_ACTION(next_tab, 0,
  3697. "Switch to the next tab"
  3698. )(void) {
  3699. for (int i = 0; i < buffers_len; i++) {
  3700. buffer_t * _env = buffers[i];
  3701. if (_env == env) {
  3702. if (i != buffers_len - 1) {
  3703. env = buffers[i+1];
  3704. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3705. redraw_all();
  3706. update_title();
  3707. return;
  3708. } else {
  3709. /* Wrap around */
  3710. env = buffers[0];
  3711. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3712. redraw_all();
  3713. update_title();
  3714. return;
  3715. }
  3716. }
  3717. }
  3718. }
  3719. /**
  3720. * Check for modified lines in a file by examining `git diff` output.
  3721. * This can be enabled globally in bimrc or per environment with the 'git' option.
  3722. */
  3723. int git_examine(char * filename) {
  3724. if (env->modified) return 1;
  3725. int fds[2];
  3726. pipe(fds);
  3727. int child = fork();
  3728. if (child == 0) {
  3729. FILE * dev_null = fopen("/dev/null","w");
  3730. close(fds[0]);
  3731. dup2(fds[1], STDOUT_FILENO);
  3732. dup2(fileno(dev_null), STDERR_FILENO);
  3733. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  3734. exit(execvp("git",args));
  3735. } else if (child < 0) {
  3736. return 1;
  3737. }
  3738. close(fds[1]);
  3739. FILE * f = fdopen(fds[0],"r");
  3740. int line_offset = 0;
  3741. while (!feof(f)) {
  3742. int c = fgetc(f);
  3743. if (c < 0) break;
  3744. if (c == '@' && line_offset == 0) {
  3745. /* Read line offset, count */
  3746. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  3747. /* This algorithm is borrowed from Kakoune and only requires us to parse the @@ line */
  3748. int from_line = 0;
  3749. int from_count = 0;
  3750. int to_line = 0;
  3751. int to_count = 0;
  3752. fscanf(f,"%d",&from_line);
  3753. if (fgetc(f) == ',') {
  3754. fscanf(f,"%d",&from_count);
  3755. } else {
  3756. from_count = 1;
  3757. }
  3758. fscanf(f,"%d",&to_line);
  3759. if (fgetc(f) == ',') {
  3760. fscanf(f,"%d",&to_count);
  3761. } else {
  3762. to_count = 1;
  3763. }
  3764. if (to_line > env->line_count) continue;
  3765. if (from_count == 0 && to_count > 0) {
  3766. /* No -, all + means all of to_count is green */
  3767. for (int i = 0; i < to_count; ++i) {
  3768. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3769. }
  3770. } else if (from_count > 0 && to_count == 0) {
  3771. /*
  3772. * No +, all - means we have a deletion. We mark the next line such that it has a red bar at the top
  3773. * Note that to_line is one lower than the affacted line, so we don't need to mes with indexes.
  3774. */
  3775. if (to_line >= env->line_count) continue;
  3776. env->lines[to_line]->rev_status = 4; /* Red */
  3777. } else if (from_count > 0 && from_count == to_count) {
  3778. /* from = to, all modified */
  3779. for (int i = 0; i < to_count; ++i) {
  3780. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3781. }
  3782. } else if (from_count > 0 && from_count < to_count) {
  3783. /* from < to, some modified, some added */
  3784. for (int i = 0; i < from_count; ++i) {
  3785. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3786. }
  3787. for (int i = from_count; i < to_count; ++i) {
  3788. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3789. }
  3790. } else if (to_count > 0 && from_count > to_count) {
  3791. /* from > to, we deleted but also modified some lines */
  3792. env->lines[to_line-1]->rev_status = 5; /* Red + Blue */
  3793. for (int i = 1; i < to_count; ++i) {
  3794. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3795. }
  3796. }
  3797. }
  3798. }
  3799. if (c == '\n') {
  3800. line_offset = 0;
  3801. continue;
  3802. }
  3803. line_offset++;
  3804. }
  3805. fclose(f);
  3806. return 0;
  3807. }
  3808. /**
  3809. * Write file contents to FILE
  3810. */
  3811. void output_file(buffer_t * env, FILE * f) {
  3812. int i, j;
  3813. for (i = 0; i < env->line_count; ++i) {
  3814. line_t * line = env->lines[i];
  3815. line->rev_status = 0;
  3816. for (j = 0; j < line->actual; j++) {
  3817. char_t c = line->text[j];
  3818. if (c.codepoint == 0) {
  3819. char buf[1] = {0};
  3820. fwrite(buf, 1, 1, f);
  3821. } else {
  3822. char tmp[8] = {0};
  3823. int i = to_eight(c.codepoint, tmp);
  3824. fwrite(tmp, i, 1, f);
  3825. }
  3826. }
  3827. if (env->crnl) fputc('\r', f);
  3828. fputc('\n', f);
  3829. }
  3830. }
  3831. /**
  3832. * Write active buffer to file
  3833. */
  3834. void write_file(char * file) {
  3835. if (!file) {
  3836. render_error("Need a file to write to.");
  3837. return;
  3838. }
  3839. FILE * f = fopen(file, "w+");
  3840. if (!f) {
  3841. render_error("Failed to open file for writing.");
  3842. return;
  3843. }
  3844. /* Go through each line and convert it back to UTF-8 */
  3845. output_file(env, f);
  3846. fclose(f);
  3847. /* Mark it no longer modified */
  3848. env->modified = 0;
  3849. env->last_save_history = env->history;
  3850. /* If there was no file name set, set one */
  3851. if (!env->file_name) {
  3852. env->file_name = malloc(strlen(file) + 1);
  3853. memcpy(env->file_name, file, strlen(file) + 1);
  3854. }
  3855. if (env->checkgitstatusonwrite) {
  3856. git_examine(file);
  3857. }
  3858. update_title();
  3859. redraw_all();
  3860. }
  3861. /**
  3862. * Close the active buffer
  3863. */
  3864. void close_buffer(void) {
  3865. buffer_t * previous_env = env;
  3866. buffer_t * new_env = buffer_close(env);
  3867. if (new_env == previous_env) {
  3868. /* ?? Failed to close buffer */
  3869. render_error("lolwat");
  3870. }
  3871. if (left_buffer && env == left_buffer) {
  3872. left_buffer = NULL;
  3873. right_buffer->left = 0;
  3874. right_buffer->width = global_config.term_width;
  3875. right_buffer = NULL;
  3876. } else if (left_buffer && env == right_buffer) {
  3877. right_buffer = NULL;
  3878. left_buffer->left = 0;
  3879. left_buffer->width = global_config.term_width;
  3880. left_buffer = NULL;
  3881. }
  3882. /* No more buffers, exit */
  3883. if (!new_env) {
  3884. quit(NULL);
  3885. }
  3886. /* Set the new active buffer */
  3887. env = new_env;
  3888. /* Redraw the screen */
  3889. redraw_all();
  3890. update_title();
  3891. }
  3892. /**
  3893. * Set the visual column the cursor should attempt to keep
  3894. * when moving up and down based on where the cursor currently is.
  3895. * This should happen whenever the user intentionally changes
  3896. * the cursor's horizontal positioning, such as with left/right
  3897. * arrow keys, word-move, search, mouse, etc.
  3898. */
  3899. void set_preferred_column(void) {
  3900. int c = 0;
  3901. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  3902. c += env->lines[env->line_no-1]->text[i].display_width;
  3903. }
  3904. env->preferred_column = c;
  3905. }
  3906. BIM_ACTION(cursor_down, 0,
  3907. "Move the cursor one line down."
  3908. )(void) {
  3909. /* If this isn't already the last line... */
  3910. if (env->line_no < env->line_count) {
  3911. /* Move the cursor down */
  3912. env->line_no += 1;
  3913. /* Try to place the cursor horizontally at the preferred column */
  3914. int _x = 0;
  3915. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3916. char_t * c = &env->lines[env->line_no-1]->text[i];
  3917. _x += c->display_width;
  3918. env->col_no = i+1;
  3919. if (_x > env->preferred_column) {
  3920. break;
  3921. }
  3922. }
  3923. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3924. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3925. }
  3926. /*
  3927. * If the horizontal cursor position exceeds the width the new line,
  3928. * then move the cursor left to the extent of the new line.
  3929. *
  3930. * If we're in insert mode, we can go one cell beyond the end of the line
  3931. */
  3932. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3933. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3934. if (env->col_no == 0) env->col_no = 1;
  3935. }
  3936. if (env->loading) return;
  3937. /*
  3938. * If the screen was scrolled horizontally, unscroll it;
  3939. * if it will be scrolled on this line as well, that will
  3940. * be handled by place_cursor_actual
  3941. */
  3942. int redraw = 0;
  3943. if (env->coffset != 0) {
  3944. env->coffset = 0;
  3945. redraw = 1;
  3946. }
  3947. /* If we've scrolled past the bottom of the screen, scroll the screen */
  3948. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  3949. env->offset += 1;
  3950. /* Tell terminal to scroll */
  3951. if (global_config.can_scroll && !left_buffer) {
  3952. shift_up(1);
  3953. /* A new line appears on screen at the bottom, draw it */
  3954. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  3955. if (env->offset + l < env->line_count + 1) {
  3956. redraw_line(env->offset + l-1);
  3957. } else {
  3958. draw_excess_line(l - 1);
  3959. }
  3960. } else {
  3961. redraw_text();
  3962. }
  3963. redraw_tabbar();
  3964. redraw_statusbar();
  3965. redraw_commandline();
  3966. place_cursor_actual();
  3967. return;
  3968. } else if (redraw) {
  3969. /* Otherwise, if we need to redraw because of coffset change, do that */
  3970. redraw_text();
  3971. }
  3972. set_history_break();
  3973. /* Update the status bar */
  3974. redraw_statusbar();
  3975. /* Place the terminal cursor again */
  3976. place_cursor_actual();
  3977. }
  3978. }
  3979. BIM_ACTION(cursor_up, 0,
  3980. "Move the cursor up one line."
  3981. )(void) {
  3982. /* If this isn't the first line already */
  3983. if (env->line_no > 1) {
  3984. /* Move the cursor down */
  3985. env->line_no -= 1;
  3986. /* Try to place the cursor horizontally at the preferred column */
  3987. int _x = 0;
  3988. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3989. char_t * c = &env->lines[env->line_no-1]->text[i];
  3990. _x += c->display_width;
  3991. env->col_no = i+1;
  3992. if (_x > env->preferred_column) {
  3993. break;
  3994. }
  3995. }
  3996. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3997. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3998. }
  3999. /*
  4000. * If the horizontal cursor position exceeds the width the new line,
  4001. * then move the cursor left to the extent of the new line.
  4002. *
  4003. * If we're in insert mode, we can go one cell beyond the end of the line
  4004. */
  4005. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4006. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4007. if (env->col_no == 0) env->col_no = 1;
  4008. }
  4009. if (env->loading) return;
  4010. /*
  4011. * If the screen was scrolled horizontally, unscroll it;
  4012. * if it will be scrolled on this line as well, that will
  4013. * be handled by place_cursor_actual
  4014. */
  4015. int redraw = 0;
  4016. if (env->coffset != 0) {
  4017. env->coffset = 0;
  4018. redraw = 1;
  4019. }
  4020. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  4021. if (env->line_no <= e) {
  4022. env->offset -= 1;
  4023. /* Tell terminal to scroll */
  4024. if (global_config.can_scroll && !left_buffer) {
  4025. shift_down(1);
  4026. /*
  4027. * The line at the top of the screen should always be real
  4028. * so we can just call redraw_line here
  4029. */
  4030. redraw_line(env->offset);
  4031. } else {
  4032. redraw_text();
  4033. }
  4034. redraw_tabbar();
  4035. redraw_statusbar();
  4036. redraw_commandline();
  4037. place_cursor_actual();
  4038. return;
  4039. } else if (redraw) {
  4040. /* Otherwise, if we need to redraw because of coffset change, do that */
  4041. redraw_text();
  4042. }
  4043. set_history_break();
  4044. /* Update the status bar */
  4045. redraw_statusbar();
  4046. /* Place the terminal cursor again */
  4047. place_cursor_actual();
  4048. }
  4049. }
  4050. BIM_ACTION(cursor_left, 0,
  4051. "Move the cursor one character to the left."
  4052. )(void) {
  4053. if (env->col_no > 1) {
  4054. env->col_no -= 1;
  4055. /* Update the status bar */
  4056. redraw_statusbar();
  4057. /* Place the terminal cursor again */
  4058. place_cursor_actual();
  4059. }
  4060. set_history_break();
  4061. set_preferred_column();
  4062. }
  4063. BIM_ACTION(cursor_right, 0,
  4064. "Move the cursor one character to the right."
  4065. )(void) {
  4066. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  4067. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  4068. env->col_no += 1;
  4069. /* Update the status bar */
  4070. redraw_statusbar();
  4071. /* Place the terminal cursor again */
  4072. place_cursor_actual();
  4073. }
  4074. set_history_break();
  4075. set_preferred_column();
  4076. }
  4077. BIM_ACTION(cursor_home, 0,
  4078. "Move the cursor to the beginning of the line."
  4079. )(void) {
  4080. env->col_no = 1;
  4081. set_history_break();
  4082. set_preferred_column();
  4083. /* Update the status bar */
  4084. redraw_statusbar();
  4085. /* Place the terminal cursor again */
  4086. place_cursor_actual();
  4087. }
  4088. BIM_ACTION(cursor_end, 0,
  4089. "Move the cursor to the end of the line, or past the end in insert mode."
  4090. )(void) {
  4091. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  4092. set_history_break();
  4093. set_preferred_column();
  4094. /* Update the status bar */
  4095. redraw_statusbar();
  4096. /* Place the terminal cursor again */
  4097. place_cursor_actual();
  4098. }
  4099. BIM_ACTION(leave_insert, 0,
  4100. "Leave insert modes and return to normal mode."
  4101. )(void) {
  4102. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4103. env->col_no = env->lines[env->line_no-1]->actual;
  4104. if (env->col_no == 0) env->col_no = 1;
  4105. set_preferred_column();
  4106. }
  4107. set_history_break();
  4108. env->mode = MODE_NORMAL;
  4109. redraw_commandline();
  4110. }
  4111. /**
  4112. * Helper for handling smart case sensitivity.
  4113. */
  4114. int search_matches(uint32_t a, uint32_t b, int mode) {
  4115. if (mode == 0) {
  4116. return a == b;
  4117. } else if (mode == 1) {
  4118. return tolower(a) == tolower(b);
  4119. }
  4120. return 0;
  4121. }
  4122. int subsearch_matches(line_t * line, int j, uint32_t * needle, int ignorecase, int *len) {
  4123. int k = j;
  4124. uint32_t * match = needle;
  4125. if (*match == '^') {
  4126. if (j != 0) return 0;
  4127. match++;
  4128. }
  4129. while (k < line->actual + 1) {
  4130. if (*match == '\0') {
  4131. if (len) *len = k - j;
  4132. return 1;
  4133. }
  4134. if (*match == '$') {
  4135. if (k != line->actual) return 0;
  4136. match++;
  4137. continue;
  4138. }
  4139. if (*match == '.') {
  4140. if (match[1] == '*') {
  4141. int greedy = !(match[2] == '?');
  4142. /* Short-circuit chained .*'s */
  4143. if (match[greedy ? 2 : 3] == '.' && match[greedy ? 3 : 4] == '*') {
  4144. int _len;
  4145. if (subsearch_matches(line, k, &match[greedy ? 2 : 3], ignorecase, &_len)) {
  4146. if (len) *len = _len + k - j;
  4147. return 1;
  4148. }
  4149. return 0;
  4150. }
  4151. int _j = greedy ? line->actual : k;
  4152. int _break = -1;
  4153. int _len = -1;
  4154. if (!match[greedy ? 2 : 3]) {
  4155. _len = greedy ? (line->actual - _j) : 0;
  4156. _break = _j;
  4157. } else {
  4158. while (_j < line->actual + 1 && _j >= k) {
  4159. int len;
  4160. if (subsearch_matches(line, _j, &match[greedy ? 2 : 3], ignorecase, &len)) {
  4161. _break = _j;
  4162. _len = len;
  4163. break;
  4164. }
  4165. _j += (greedy ? -1 : 1);
  4166. }
  4167. }
  4168. if (_break != -1) {
  4169. if (len) *len = (_break - j) + _len;
  4170. return 1;
  4171. }
  4172. return 0;
  4173. } else {
  4174. if (k >= line->actual) return 0;
  4175. match++;
  4176. k++;
  4177. continue;
  4178. }
  4179. }
  4180. if (*match == '\\' && (match[1] == '$' || match[1] == '^' || match[1] == '/' || match[1] == '\\' || match[1] == '.')) {
  4181. match++;
  4182. } else if (*match == '\\' && match[1] == 't') {
  4183. if (line->text[k].codepoint != '\t') break;
  4184. match += 2;
  4185. k++;
  4186. continue;
  4187. }
  4188. if (k == line->actual) break;
  4189. if (!search_matches(*match, line->text[k].codepoint, ignorecase)) break;
  4190. match++;
  4191. k++;
  4192. }
  4193. return 0;
  4194. }
  4195. /**
  4196. * Replace text on a given line with other text.
  4197. */
  4198. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col) {
  4199. line_t * line = env->lines[line_no-1];
  4200. int j = col;
  4201. while (j < line->actual + 1) {
  4202. int match_len;
  4203. if (subsearch_matches(line,j,needle,ignorecase,&match_len)) {
  4204. /* Perform replacement */
  4205. for (int i = 0; i < match_len; ++i) {
  4206. line_delete(line, j+1, line_no-1);
  4207. }
  4208. int t = 0;
  4209. for (uint32_t * r = replacement; *r; ++r) {
  4210. char_t _c;
  4211. _c.codepoint = *r;
  4212. _c.flags = 0;
  4213. _c.display_width = codepoint_width(*r);
  4214. line_t * nline = line_insert(line, _c, j + t, line_no -1);
  4215. if (line != nline) {
  4216. env->lines[line_no-1] = nline;
  4217. line = nline;
  4218. }
  4219. t++;
  4220. }
  4221. *out_col = j + t;
  4222. set_modified();
  4223. return;
  4224. }
  4225. j++;
  4226. }
  4227. *out_col = -1;
  4228. }
  4229. #define COMMAND_HISTORY_MAX 255
  4230. unsigned char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  4231. /**
  4232. * Add a command to the history. If that command was
  4233. * already in history, it is moved to the front of the list;
  4234. * otherwise, the whole list is shifted backwards and
  4235. * overflow is freed up.
  4236. */
  4237. void insert_command_history(char * cmd) {
  4238. /* See if this is already in the history. */
  4239. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  4240. for (int i = 0; i < COMMAND_HISTORY_MAX && command_history[i]; ++i) {
  4241. if (!strcmp((char*)command_history[i], cmd)) {
  4242. free(command_history[i]);
  4243. amount_to_shift = i;
  4244. break;
  4245. }
  4246. }
  4247. /* Remove last entry that will roll off the stack */
  4248. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  4249. if (command_history[COMMAND_HISTORY_MAX-1]) free(command_history[COMMAND_HISTORY_MAX-1]);
  4250. }
  4251. /* Roll the history */
  4252. memmove(&command_history[1], &command_history[0], sizeof(char *) * (amount_to_shift));
  4253. command_history[0] = (unsigned char*)strdup(cmd);
  4254. }
  4255. static uint32_t term_colors[] = {
  4256. 0x000000, 0xcc0000, 0x3e9a06, 0xc4a000, 0x3465a4, 0x75507b, 0x06989a, 0xeeeeec, 0x555753, 0xef2929, 0x8ae234, 0xfce94f, 0x729fcf, 0xad7fa8, 0x34e2e2,
  4257. 0xFFFFFF, 0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff, 0x008700, 0x00875f,
  4258. 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff, 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7,
  4259. 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f,
  4260. 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, 0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7,
  4261. 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff, 0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f,
  4262. 0x870087, 0x8700af, 0x8700d7, 0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, 0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7,
  4263. 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f,
  4264. 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7,
  4265. 0xaf5fff, 0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff, 0xafd700, 0xafd75f,
  4266. 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff, 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7,
  4267. 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, 0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f,
  4268. 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, 0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7,
  4269. 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff, 0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f,
  4270. 0xff8787, 0xff87af, 0xff87d7, 0xff87ff, 0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7,
  4271. 0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e,
  4272. 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2, 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4,
  4273. 0xeeeeee,
  4274. };
  4275. /**
  4276. * Convert a color setting from terminal format
  4277. * to a hexadecimal color code and add it to the current
  4278. * buffer. This is used for HTML conversion, but could
  4279. * possibly be used for other purposes.
  4280. */
  4281. static void html_convert_color(const char * color_string) {
  4282. char tmp[100];
  4283. if (!strncmp(color_string,"2;",2)) {
  4284. /* 24-bit color */
  4285. int red, green, blue;
  4286. sscanf(color_string+2,"%d;%d;%d",&red,&green,&blue);
  4287. sprintf(tmp, "#%02x%02x%02x;", red,green,blue);
  4288. } else if (!strncmp(color_string,"5;",2)) {
  4289. /* 256 colors; needs lookup table */
  4290. int index;
  4291. sscanf(color_string+2,"%d",&index);
  4292. sprintf(tmp,"#%06x;", (unsigned int)term_colors[(index >= 0 && index <= 255) ? index : 0]);
  4293. } else {
  4294. /* 16 colors; needs lookup table */
  4295. int index;
  4296. uint32_t color;
  4297. sscanf(color_string+1,"%d",&index);
  4298. if (index >= 10) {
  4299. index -= 10;
  4300. color = term_colors[index+8];
  4301. } else if (index == 9) {
  4302. color = term_colors[0];
  4303. } else {
  4304. color = term_colors[index];
  4305. }
  4306. sprintf(tmp,"#%06x;", (unsigned int)color);
  4307. }
  4308. add_string(tmp);
  4309. char * italic = strstr(color_string,";3");
  4310. if (italic && italic[2] == '\0') {
  4311. add_string(" font-style: oblique;");
  4312. }
  4313. char * bold = strstr(color_string,";1");
  4314. if (bold && bold[2] == '\0') {
  4315. add_string(" font-weight: bold;");
  4316. }
  4317. char * underline = strstr(color_string,";4");
  4318. if (underline && underline[2] == '\0') {
  4319. add_string(" font-decoration: underline;");
  4320. }
  4321. }
  4322. int convert_to_html(void) {
  4323. buffer_t * old = env;
  4324. env = buffer_new();
  4325. setup_buffer(env);
  4326. env->loading = 1;
  4327. add_string("<!doctype html>\n");
  4328. add_string("<html>\n");
  4329. add_string(" <head>\n");
  4330. add_string(" <meta charset=\"UTF-8\">\n");
  4331. if (old->file_name) {
  4332. add_string(" <title>");
  4333. add_string(file_basename(old->file_name));
  4334. add_string("</title>\n");
  4335. }
  4336. add_string(" <style>\n");
  4337. add_string(" body {\n");
  4338. add_string(" margin: 0;\n");
  4339. add_string(" -webkit-text-size-adjust: none;\n");
  4340. add_string(" counter-reset: line-no;\n");
  4341. add_string(" background-color: ");
  4342. /* Convert color */
  4343. html_convert_color(COLOR_BG);
  4344. add_string("\n");
  4345. add_string(" }\n");
  4346. for (int i = 0; i < 15; ++i) {
  4347. /* For each of the relevant flags... */
  4348. char tmp[20];
  4349. sprintf(tmp," .s%d { color: ", i);
  4350. add_string(tmp);
  4351. /* These are special */
  4352. if (i == FLAG_NOTICE) {
  4353. html_convert_color(COLOR_SEARCH_FG);
  4354. add_string(" background-color: ");
  4355. html_convert_color(COLOR_SEARCH_BG);
  4356. } else if (i == FLAG_ERROR) {
  4357. html_convert_color(COLOR_ERROR_FG);
  4358. add_string(" background-color: ");
  4359. html_convert_color(COLOR_ERROR_BG);
  4360. } else {
  4361. html_convert_color(flag_to_color(i));
  4362. }
  4363. add_string("}\n");
  4364. }
  4365. add_string(" pre {\n");
  4366. add_string(" margin: 0;\n");
  4367. add_string(" white-space: pre-wrap;\n");
  4368. add_string(" font-family: \"DejaVu Sans Mono\", Courier, monospace;\n");
  4369. add_string(" font-size: 10pt;\n");
  4370. add_string(" }\n");
  4371. add_string(" pre>span {\n");
  4372. add_string(" display: inline-block;\n");
  4373. add_string(" width: 100%;\n");
  4374. add_string(" }\n");
  4375. add_string(" pre>span>a::before {\n");
  4376. add_string(" counter-increment: line-no;\n");
  4377. add_string(" content: counter(line-no);\n");
  4378. add_string(" padding-right: 1em;\n");
  4379. add_string(" width: 3em;\n");
  4380. add_string(" display: inline-block;\n");
  4381. add_string(" text-align: right;\n");
  4382. add_string(" background-color: ");
  4383. html_convert_color(COLOR_NUMBER_BG);
  4384. add_string("\n");
  4385. add_string(" color: ");
  4386. html_convert_color(COLOR_NUMBER_FG);
  4387. add_string("\n");
  4388. add_string(" }\n");
  4389. add_string(" pre>span:target {\n");
  4390. add_string(" background-color: ");
  4391. html_convert_color(COLOR_ALT_BG);
  4392. add_string("\n");
  4393. add_string(" }\n");
  4394. add_string(" pre>span:target>a::before {\n");
  4395. add_string(" background-color: ");
  4396. html_convert_color(COLOR_NUMBER_FG);
  4397. add_string("\n");
  4398. add_string(" color: ");
  4399. html_convert_color(COLOR_NUMBER_BG);
  4400. add_string("\n");
  4401. add_string(" }\n");
  4402. for (int i = 1; i <= env->tabstop; ++i) {
  4403. char tmp[10];
  4404. sprintf(tmp, ".tab%d", i);
  4405. add_string(" ");
  4406. add_string(tmp);
  4407. add_string(">span {\n");
  4408. add_string(" display: inline-block;\n");
  4409. add_string(" overflow: hidden;\n");
  4410. add_string(" width: 0;\n");
  4411. add_string(" height: 0;\n");
  4412. add_string(" }\n");
  4413. add_string(" ");
  4414. add_string(tmp);
  4415. add_string("::after {\n");
  4416. add_string(" content: '»");
  4417. for (int j = 1; j < i; ++j) {
  4418. add_string("·");
  4419. }
  4420. add_string("';\n");
  4421. add_string(" background-color: ");
  4422. html_convert_color(COLOR_ALT_BG);
  4423. add_string("\n");
  4424. add_string(" color: ");
  4425. html_convert_color(COLOR_ALT_FG);
  4426. add_string("\n");
  4427. add_string(" }\n");
  4428. }
  4429. add_string(" .space {\n");
  4430. add_string(" border-left: 1px solid ");
  4431. html_convert_color(COLOR_ALT_FG);
  4432. add_string("\n");
  4433. add_string(" margin-left: -1px;\n");
  4434. add_string(" }\n");
  4435. add_string(" </style>\n");
  4436. add_string(" </head>\n");
  4437. add_string(" <body><pre>\n");
  4438. for (int i = 0; i < old->line_count; ++i) {
  4439. char tmp[100];
  4440. sprintf(tmp, "<span id=\"L%d\"><a href=\"#L%d\"></a>", i+1, i+1);
  4441. add_string(tmp);
  4442. int last_flag = -1;
  4443. int opened = 0;
  4444. int all_spaces = 1;
  4445. for (int j = 0; j < old->lines[i]->actual; ++j) {
  4446. char_t c = old->lines[i]->text[j];
  4447. if (c.codepoint != ' ') all_spaces = 0;
  4448. if (last_flag == -1 || last_flag != (c.flags & 0x1F)) {
  4449. if (opened) add_string("</span>");
  4450. opened = 1;
  4451. char tmp[100];
  4452. sprintf(tmp, "<span class=\"s%d\">", c.flags & 0x1F);
  4453. add_string(tmp);
  4454. last_flag = (c.flags & 0x1F);
  4455. }
  4456. if (c.codepoint == '<') {
  4457. add_string("&lt;");
  4458. } else if (c.codepoint == '>') {
  4459. add_string("&gt;");
  4460. } else if (c.codepoint == '&') {
  4461. add_string("&amp;");
  4462. } else if (c.codepoint == '\t') {
  4463. char tmp[100];
  4464. sprintf(tmp, "<span class=\"tab%d\"><span> </span></span>",c.display_width);
  4465. add_string(tmp);
  4466. } else if (j > 0 && c.codepoint == ' ' && all_spaces && !(j % old->tabstop)) {
  4467. add_string("<span class=\"space\"> </span>");
  4468. } else {
  4469. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  4470. to_eight(c.codepoint, tmp);
  4471. add_string(tmp);
  4472. }
  4473. }
  4474. if (opened) {
  4475. add_string("</span>");
  4476. } else {
  4477. add_string("<wbr>");
  4478. }
  4479. add_string("</span>\n");
  4480. }
  4481. add_string("</pre></body>\n");
  4482. add_string("</html>\n");
  4483. env->loading = 0;
  4484. env->modified = 1;
  4485. if (old->file_name) {
  4486. char * base = file_basename(old->file_name);
  4487. char * tmp = malloc(strlen(base) + 5);
  4488. *tmp = '\0';
  4489. strcat(tmp, base);
  4490. strcat(tmp, ".htm");
  4491. env->file_name = tmp;
  4492. }
  4493. for (int i = 0; i < env->line_count; ++i) {
  4494. recalculate_tabs(env->lines[i]);
  4495. }
  4496. env->syntax = match_syntax(".htm");
  4497. for (int i = 0; i < env->line_count; ++i) {
  4498. recalculate_syntax(env->lines[i],i);
  4499. }
  4500. return 0;
  4501. }
  4502. /**
  4503. * Based on vim's :TOhtml
  4504. * Convert syntax-highlighted buffer contents to HTML.
  4505. */
  4506. BIM_COMMAND(tohtml,"tohtml","Convert the document to an HTML representation with syntax highlighting.") {
  4507. convert_to_html();
  4508. redraw_all();
  4509. return 0;
  4510. }
  4511. BIM_ALIAS("TOhtml",tohtml,tohtml)
  4512. int _prefix_command_run_script(char * cmd) {
  4513. if (env->mode == MODE_LINE_SELECTION) {
  4514. int range_top, range_bot;
  4515. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4516. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4517. int in[2];
  4518. pipe(in);
  4519. int out[2];
  4520. pipe(out);
  4521. int child = fork();
  4522. /* Open child process and set up pipes */
  4523. if (child == 0) {
  4524. FILE * dev_null = fopen("/dev/null","w"); /* for stderr */
  4525. close(out[0]);
  4526. close(in[1]);
  4527. dup2(out[1], STDOUT_FILENO);
  4528. dup2(in[0], STDIN_FILENO);
  4529. dup2(fileno(dev_null), STDERR_FILENO);
  4530. if (*cmd == '!') {
  4531. system(&cmd[1]); /* Yes we can just do this */
  4532. } else {
  4533. char * const args[] = {"python3","-c",&cmd[1],NULL};
  4534. execvp("python3",args);
  4535. }
  4536. exit(1);
  4537. } else if (child < 0) {
  4538. render_error("Failed to fork");
  4539. return 1;
  4540. }
  4541. close(out[1]);
  4542. close(in[0]);
  4543. /* Write lines to child process */
  4544. FILE * f = fdopen(in[1],"w");
  4545. for (int i = range_top; i <= range_bot; ++i) {
  4546. line_t * line = env->lines[i-1];
  4547. for (int j = 0; j < line->actual; j++) {
  4548. char_t c = line->text[j];
  4549. if (c.codepoint == 0) {
  4550. char buf[1] = {0};
  4551. fwrite(buf, 1, 1, f);
  4552. } else {
  4553. char tmp[8] = {0};
  4554. int i = to_eight(c.codepoint, tmp);
  4555. fwrite(tmp, i, 1, f);
  4556. }
  4557. }
  4558. fputc('\n', f);
  4559. }
  4560. fclose(f);
  4561. close(in[1]);
  4562. /* Read results from child process into a new buffer */
  4563. FILE * result = fdopen(out[0],"r");
  4564. buffer_t * old = env;
  4565. env = buffer_new();
  4566. setup_buffer(env);
  4567. env->loading = 1;
  4568. uint8_t buf[BLOCK_SIZE];
  4569. state = 0;
  4570. while (!feof(result) && !ferror(result)) {
  4571. size_t r = fread(buf, 1, BLOCK_SIZE, result);
  4572. add_buffer(buf, r);
  4573. }
  4574. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  4575. env->lines = remove_line(env->lines, env->line_no-1);
  4576. }
  4577. fclose(result);
  4578. env->loading = 0;
  4579. /* Return to the original buffer and replace the selected lines with the output */
  4580. buffer_t * new = env;
  4581. env = old;
  4582. for (int i = range_top; i <= range_bot; ++i) {
  4583. /* Remove the existing lines */
  4584. env->lines = remove_line(env->lines, range_top-1);
  4585. }
  4586. for (int i = 0; i < new->line_count; ++i) {
  4587. /* Add the new lines */
  4588. env->lines = add_line(env->lines, range_top + i - 1);
  4589. replace_line(env->lines, range_top + i - 1, new->lines[i]);
  4590. recalculate_tabs(env->lines[range_top+i-1]);
  4591. }
  4592. env->modified = 1;
  4593. /* Close the temporary buffer */
  4594. buffer_close(new);
  4595. } else {
  4596. /* Reset and draw some line feeds */
  4597. reset();
  4598. printf("\n\n");
  4599. /* Set buffered for shell application */
  4600. set_buffered();
  4601. /* Call the shell and wait for completion */
  4602. if (*cmd == '!') {
  4603. system(&cmd[1]);
  4604. } else {
  4605. setenv("PYCMD",&cmd[1],1);
  4606. system("python3 -c \"$PYCMD\"");
  4607. }
  4608. /* Return to the editor, wait for user to press enter. */
  4609. set_unbuffered();
  4610. printf("\n\nPress ENTER to continue.");
  4611. int c;
  4612. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4613. /* Redraw the screen */
  4614. redraw_all();
  4615. }
  4616. /* Done processing command */
  4617. return 0;
  4618. }
  4619. BIM_PREFIX_COMMAND(bang,"!","Executes shell commands.") {
  4620. (void)argc, (void)argv;
  4621. return _prefix_command_run_script(cmd);
  4622. }
  4623. BIM_PREFIX_COMMAND(tick,"`","Executes Python commands.") {
  4624. (void)argc, (void)argv;
  4625. return _prefix_command_run_script(cmd);
  4626. }
  4627. int replace_text(int range_top, int range_bot, char divider, char * needle) {
  4628. char * c = needle;
  4629. char * replacement = NULL;
  4630. char * options = "";
  4631. while (*c) {
  4632. if (*c == divider) {
  4633. *c = '\0';
  4634. replacement = c + 1;
  4635. break;
  4636. }
  4637. c++;
  4638. }
  4639. if (!replacement) {
  4640. render_error("nothing to replace with");
  4641. return 1;
  4642. }
  4643. c = replacement;
  4644. while (*c) {
  4645. if (*c == divider) {
  4646. *c = '\0';
  4647. options = c + 1;
  4648. break;
  4649. }
  4650. c++;
  4651. }
  4652. int global = 0;
  4653. int case_insensitive = 0;
  4654. /* Parse options */
  4655. while (*options) {
  4656. switch (*options) {
  4657. case 'g':
  4658. global = 1;
  4659. break;
  4660. case 'i':
  4661. case_insensitive = 1;
  4662. break;
  4663. }
  4664. options++;
  4665. }
  4666. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4667. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4668. {
  4669. int i = 0;
  4670. uint32_t c, state = 0;
  4671. for (char * cin = needle; *cin; cin++) {
  4672. if (!decode(&state, &c, *cin)) {
  4673. needle_c[i] = c;
  4674. i++;
  4675. } else if (state == UTF8_REJECT) {
  4676. state = 0;
  4677. }
  4678. }
  4679. needle_c[i] = 0;
  4680. i = 0;
  4681. c = 0;
  4682. state = 0;
  4683. for (char * cin = replacement; *cin; cin++) {
  4684. if (!decode(&state, &c, *cin)) {
  4685. replacement_c[i] = c;
  4686. i++;
  4687. } else if (state == UTF8_REJECT) {
  4688. state = 0;
  4689. }
  4690. }
  4691. replacement_c[i] = 0;
  4692. }
  4693. int replacements = 0;
  4694. for (int line = range_top; line <= range_bot; ++line) {
  4695. int col = 0;
  4696. while (col != -1) {
  4697. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col);
  4698. if (col != -1) replacements++;
  4699. if (!global) break;
  4700. }
  4701. }
  4702. free(needle_c);
  4703. free(replacement_c);
  4704. if (replacements) {
  4705. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4706. set_history_break();
  4707. redraw_text();
  4708. } else {
  4709. render_error("Pattern not found: %s", needle);
  4710. }
  4711. return 0;
  4712. }
  4713. BIM_PREFIX_COMMAND(repsome,"s","Perform a replacement over selected lines") {
  4714. int range_top, range_bot;
  4715. if (env->mode == MODE_LINE_SELECTION) {
  4716. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4717. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4718. } else {
  4719. range_top = env->line_no;
  4720. range_bot = env->line_no;
  4721. }
  4722. return replace_text(range_top, range_bot, cmd[1], &cmd[2]);
  4723. }
  4724. BIM_PREFIX_COMMAND(repall,"%s","Perform a replacement over the entire file.") {
  4725. return replace_text(1, env->line_count, cmd[2], &cmd[3]);
  4726. }
  4727. BIM_COMMAND(e,"e","Open a file") {
  4728. if (argc > 1) {
  4729. /* This actually opens a new tab */
  4730. open_file(argv[1]);
  4731. update_title();
  4732. } else {
  4733. if (env->modified) {
  4734. render_error("File is modified, can not reload.");
  4735. return 1;
  4736. }
  4737. buffer_t * old_env = env;
  4738. open_file(env->file_name);
  4739. buffer_t * new_env = env;
  4740. env = old_env;
  4741. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4742. SWAP(line_t **, env->lines, new_env->lines);
  4743. SWAP(int, env->line_count, new_env->line_count);
  4744. SWAP(int, env->line_avail, new_env->line_avail);
  4745. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4746. redraw_all();
  4747. }
  4748. return 0;
  4749. }
  4750. BIM_COMMAND(tabnew,"tabnew","Open a new tab") {
  4751. if (argc > 1) {
  4752. open_file(argv[1]);
  4753. update_title();
  4754. } else {
  4755. env = buffer_new();
  4756. setup_buffer(env);
  4757. redraw_all();
  4758. update_title();
  4759. }
  4760. return 0;
  4761. }
  4762. BIM_COMMAND(w,"w","Write a file") {
  4763. /* w: write file */
  4764. if (argc > 1) {
  4765. write_file(argv[1]);
  4766. } else {
  4767. write_file(env->file_name);
  4768. }
  4769. return 0;
  4770. }
  4771. BIM_COMMAND(wq,"wq","Write and close buffer") {
  4772. write_file(env->file_name);
  4773. close_buffer();
  4774. return 0;
  4775. }
  4776. BIM_COMMAND(history,"history","Display command history") {
  4777. render_commandline_message(""); /* To clear command line */
  4778. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4779. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4780. }
  4781. render_commandline_message("\n");
  4782. redraw_tabbar();
  4783. redraw_commandline();
  4784. pause_for_key();
  4785. return 0;
  4786. }
  4787. BIM_COMMAND(q,"q","Close buffer") {
  4788. if (left_buffer && left_buffer == right_buffer) {
  4789. unsplit();
  4790. return 0;
  4791. }
  4792. if (env->modified) {
  4793. render_error("No write since last change. Use :q! to force exit.");
  4794. } else {
  4795. close_buffer();
  4796. }
  4797. update_title();
  4798. return 0;
  4799. }
  4800. BIM_COMMAND(qbang,"q!","Force close buffer") {
  4801. close_buffer();
  4802. update_title();
  4803. return 0;
  4804. }
  4805. BIM_COMMAND(qa,"qa","Try to close all buffers") {
  4806. try_quit();
  4807. return 0;
  4808. }
  4809. BIM_ALIAS("qall",qall,qa)
  4810. BIM_COMMAND(qabang,"qa!","Force exit") {
  4811. /* Forcefully exit editor */
  4812. while (buffers_len) {
  4813. buffer_close(buffers[0]);
  4814. }
  4815. quit(NULL);
  4816. return 1; /* doesn't return */
  4817. }
  4818. BIM_COMMAND(tabp,"tabp","Previous tab") {
  4819. previous_tab();
  4820. update_title();
  4821. return 0;
  4822. }
  4823. BIM_COMMAND(tabn,"tabn","Next tab") {
  4824. next_tab();
  4825. update_title();
  4826. return 0;
  4827. }
  4828. BIM_COMMAND(tabindicator,"tabindicator","Set the tab indicator") {
  4829. if (argc < 2) {
  4830. render_status_message("tabindicator=%s", global_config.tab_indicator);
  4831. return 0;
  4832. }
  4833. if (display_width_of_string(argv[1]) != 1) {
  4834. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4835. return 1;
  4836. }
  4837. if (global_config.tab_indicator) free(global_config.tab_indicator);
  4838. global_config.tab_indicator = strdup(argv[1]);
  4839. return 0;
  4840. }
  4841. BIM_COMMAND(spaceindicator,"spaceindicator","Set the space indicator") {
  4842. if (argc < 2) {
  4843. render_status_message("spaceindicator=%s", global_config.space_indicator);
  4844. return 0;
  4845. }
  4846. if (display_width_of_string(argv[1]) != 1) {
  4847. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4848. return 1;
  4849. }
  4850. if (global_config.space_indicator) free(global_config.space_indicator);
  4851. global_config.space_indicator = strdup(argv[1]);
  4852. return 0;
  4853. }
  4854. BIM_COMMAND(global_git,"global.git","Show or change the default status of git integration") {
  4855. if (argc < 2) {
  4856. render_status_message("global.git=%d", global_config.check_git);
  4857. } else {
  4858. global_config.check_git = !!atoi(argv[1]);
  4859. }
  4860. return 0;
  4861. }
  4862. BIM_COMMAND(git,"git","Show or change status of git integration") {
  4863. if (!env) {
  4864. render_error("requires environment (did you mean global.git?)");
  4865. return 1;
  4866. }
  4867. if (argc < 2) {
  4868. render_status_message("git=%d", env->checkgitstatusonwrite);
  4869. } else {
  4870. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4871. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4872. git_examine(env->file_name);
  4873. redraw_text();
  4874. }
  4875. }
  4876. return 0;
  4877. }
  4878. BIM_COMMAND(colorgutter,"colorgutter","Show or change status of gutter colorization for unsaved modifications") {
  4879. if (argc < 2) {
  4880. render_status_message("colorgutter=%d", global_config.color_gutter);
  4881. } else {
  4882. global_config.color_gutter = !!atoi(argv[1]);
  4883. redraw_text();
  4884. }
  4885. return 0;
  4886. }
  4887. BIM_COMMAND(indent,"indent","Enable smart indentation") {
  4888. env->indent = 1;
  4889. redraw_statusbar();
  4890. return 0;
  4891. }
  4892. BIM_COMMAND(noindent,"noindent","Disable smrat indentation") {
  4893. env->indent = 0;
  4894. redraw_statusbar();
  4895. return 0;
  4896. }
  4897. /* TODO: global.maxcolumn */
  4898. BIM_COMMAND(maxcolumn,"maxcolumn","Highlight past the given column to indicate maximum desired line length") {
  4899. if (argc < 2) {
  4900. render_status_message("maxcolumn=%d",env->maxcolumn);
  4901. return 0;
  4902. }
  4903. env->maxcolumn = atoi(argv[1]);
  4904. redraw_text();
  4905. return 0;
  4906. }
  4907. BIM_COMMAND(cursorcolumn,"cursorcolumn","Show the visual column offset of the cursor.") {
  4908. render_status_message("cursorcolumn=%d", env->preferred_column);
  4909. return 0;
  4910. }
  4911. BIM_COMMAND(noh,"noh","Clear search term") {
  4912. if (global_config.search) {
  4913. free(global_config.search);
  4914. global_config.search = NULL;
  4915. for (int i = 0; i < env->line_count; ++i) {
  4916. recalculate_syntax(env->lines[i],i);
  4917. }
  4918. redraw_text();
  4919. }
  4920. return 0;
  4921. }
  4922. BIM_COMMAND(help,"help","Show help text.") {
  4923. if (argc < 2) {
  4924. render_commandline_message(""); /* To clear command line */
  4925. render_commandline_message("\n");
  4926. render_commandline_message(" \033[1mbim - a text editor \033[22m\n");
  4927. render_commandline_message("\n");
  4928. render_commandline_message(" Available commands:\n");
  4929. 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");
  4930. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  4931. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  4932. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  4933. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  4934. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  4935. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  4936. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  4937. render_commandline_message("\n");
  4938. render_commandline_message(" Bim %s%s\n", BIM_VERSION, BIM_BUILD_DATE);
  4939. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  4940. render_commandline_message("\n");
  4941. } else {
  4942. int found = 0;
  4943. for (struct command_def * c = regular_commands; !found && regular_commands && c->name; ++c) {
  4944. if (!strcmp(c->name, argv[1])) {
  4945. render_commandline_message(""); /* To clear command line */
  4946. render_commandline_message("Help description for `%s`:\n", c->name);
  4947. render_commandline_message(" %s\n", c->description);
  4948. found = 1;
  4949. break;
  4950. }
  4951. }
  4952. for (struct command_def * c = prefix_commands; !found && prefix_commands && c->name; ++c) {
  4953. if (!strcmp(c->name, argv[1])) {
  4954. render_commandline_message(""); /* To clear command line */
  4955. render_commandline_message("Help description for `%s`:\n", c->name);
  4956. render_commandline_message(" %s\n", c->description);
  4957. found = 1;
  4958. break;
  4959. }
  4960. }
  4961. if (!found) {
  4962. render_error("Unknown command: %s", argv[1]);
  4963. return 1;
  4964. }
  4965. }
  4966. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  4967. redraw_tabbar();
  4968. redraw_commandline();
  4969. /* Wait for a character so we can redraw the screen before continuing */
  4970. pause_for_key();
  4971. return 0;
  4972. }
  4973. BIM_COMMAND(version,"version","Show version information.") {
  4974. render_status_message("Bim %s%s", BIM_VERSION, BIM_BUILD_DATE);
  4975. return 0;
  4976. }
  4977. void load_colorscheme_script(const char * name) {
  4978. static char name_copy[512];
  4979. char tmp[1024];
  4980. snprintf(tmp, 1023, "theme:%s", name);
  4981. if (!run_function(tmp)) {
  4982. sprintf(name_copy, "%s", name);
  4983. current_theme = name_copy;
  4984. }
  4985. }
  4986. BIM_COMMAND(theme,"theme","Set color theme") {
  4987. if (argc < 2) {
  4988. render_status_message("theme=%s", current_theme);
  4989. } else {
  4990. for (struct theme_def * d = themes; themes && d->name; ++d) {
  4991. if (!strcmp(argv[1], d->name)) {
  4992. d->load(d->name);
  4993. redraw_all();
  4994. return 0;
  4995. }
  4996. }
  4997. }
  4998. return 0;
  4999. }
  5000. BIM_ALIAS("colorscheme",colorscheme,theme)
  5001. BIM_COMMAND(splitpercent,"splitpercent","Display or change view split") {
  5002. if (argc < 2) {
  5003. render_status_message("splitpercent=%d", global_config.split_percent);
  5004. return 0;
  5005. } else {
  5006. global_config.split_percent = atoi(argv[1]);
  5007. if (left_buffer) {
  5008. update_split_size();
  5009. redraw_all();
  5010. }
  5011. }
  5012. return 0;
  5013. }
  5014. BIM_COMMAND(split,"split","Split the current view.") {
  5015. buffer_t * original = env;
  5016. if (argc > 1) {
  5017. int is_not_number = 0;
  5018. for (char * c = argv[1]; *c; ++c) is_not_number |= !isdigit(*c);
  5019. if (is_not_number) {
  5020. /* Open a file for the new split */
  5021. open_file(argv[1]);
  5022. right_buffer = buffers[buffers_len-1];
  5023. } else {
  5024. /* Use an existing buffer for the new split */
  5025. int other = atoi(argv[1]);
  5026. if (other >= buffers_len || other < 0) {
  5027. render_error("Invalid buffer number: %d", other);
  5028. return 1;
  5029. }
  5030. right_buffer = buffers[other];
  5031. }
  5032. } else {
  5033. /* Use the current buffer for the new split */
  5034. right_buffer = original;
  5035. }
  5036. left_buffer = original;
  5037. update_split_size();
  5038. redraw_all();
  5039. return 0;
  5040. }
  5041. BIM_COMMAND(unsplit,"unsplit","Show only one buffer on screen") {
  5042. unsplit();
  5043. return 0;
  5044. }
  5045. BIM_COMMAND(horizontalscrolling,"horizontalscrolling","Set the horizontal scrolling mode") {
  5046. if (argc < 2) {
  5047. render_status_message("horizontalscrolling=%d", global_config.horizontal_shift_scrolling);
  5048. return 0;
  5049. } else {
  5050. global_config.horizontal_shift_scrolling = !!atoi(argv[1]);
  5051. redraw_all();
  5052. }
  5053. return 0;
  5054. }
  5055. BIM_COMMAND(syntax,"syntax","Show or set the active syntax highlighter") {
  5056. if (argc < 2) {
  5057. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  5058. } else {
  5059. set_syntax_by_name(argv[1]);
  5060. }
  5061. return 0;
  5062. }
  5063. BIM_COMMAND(recalc,"recalc","Recalculate syntax for the entire file.") {
  5064. for (int i = 0; i < env->line_count; ++i) {
  5065. env->lines[i]->istate = -1;
  5066. }
  5067. env->loading = 1;
  5068. for (int i = 0; i < env->line_count; ++i) {
  5069. recalculate_syntax(env->lines[i],i);
  5070. }
  5071. env->loading = 0;
  5072. redraw_all();
  5073. return 0;
  5074. }
  5075. BIM_COMMAND(tabs,"tabs","Use tabs for indentation") {
  5076. env->tabs = 1;
  5077. redraw_statusbar();
  5078. return 0;
  5079. }
  5080. BIM_COMMAND(spaces,"spaces","Use spaces for indentation") {
  5081. env->tabs = 0;
  5082. redraw_statusbar();
  5083. return 0;
  5084. }
  5085. BIM_COMMAND(tabstop,"tabstop","Show or set the tabstop (width of an indentation unit)") {
  5086. if (argc < 2) {
  5087. render_status_message("tabstop=%d", env->tabstop);
  5088. } else {
  5089. int t = atoi(argv[1]);
  5090. if (t > 0 && t < 32) {
  5091. env->tabstop = t;
  5092. for (int i = 0; i < env->line_count; ++i) {
  5093. recalculate_tabs(env->lines[i]);
  5094. }
  5095. redraw_all();
  5096. } else {
  5097. render_error("Invalid tabstop: %s", argv[1]);
  5098. }
  5099. }
  5100. return 0;
  5101. }
  5102. BIM_COMMAND(clearyear,"clearyank","Clear the yank buffer") {
  5103. if (global_config.yanks) {
  5104. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5105. free(global_config.yanks[i]);
  5106. }
  5107. free(global_config.yanks);
  5108. global_config.yanks = NULL;
  5109. global_config.yank_count = 0;
  5110. redraw_statusbar();
  5111. }
  5112. return 0;
  5113. }
  5114. BIM_COMMAND(padding,"padding","Show or set cursor padding when scrolling vertically") {
  5115. if (argc < 2) {
  5116. render_status_message("padding=%d", global_config.cursor_padding);
  5117. } else {
  5118. global_config.cursor_padding = atoi(argv[1]);
  5119. if (env) {
  5120. place_cursor_actual();
  5121. }
  5122. }
  5123. return 0;
  5124. }
  5125. BIM_COMMAND(smartcase,"smartcase","Show or set the status of the smartcase search option") {
  5126. if (argc < 2) {
  5127. render_status_message("smartcase=%d", global_config.smart_case);
  5128. } else {
  5129. global_config.smart_case = atoi(argv[1]);
  5130. if (env) place_cursor_actual();
  5131. }
  5132. return 0;
  5133. }
  5134. BIM_COMMAND(hlparen,"hlparen","Show or set the configuration option to highlight matching braces") {
  5135. if (argc < 2) {
  5136. render_status_message("hlparen=%d", global_config.highlight_parens);
  5137. } else {
  5138. global_config.highlight_parens = atoi(argv[1]);
  5139. if (env) {
  5140. for (int i = 0; i < env->line_count; ++i) {
  5141. recalculate_syntax(env->lines[i],i);
  5142. }
  5143. redraw_text();
  5144. place_cursor_actual();
  5145. }
  5146. }
  5147. return 0;
  5148. }
  5149. BIM_COMMAND(hlcurrent,"hlcurrent","Show or set the configuration option to highlight the current line") {
  5150. if (argc < 2) {
  5151. render_status_message("hlcurrent=%d", global_config.highlight_current_line);
  5152. } else {
  5153. global_config.highlight_current_line = atoi(argv[1]);
  5154. if (env) {
  5155. if (!global_config.highlight_current_line) {
  5156. for (int i = 0; i < env->line_count; ++i) {
  5157. env->lines[i]->is_current = 0;
  5158. }
  5159. }
  5160. redraw_text();
  5161. place_cursor_actual();
  5162. }
  5163. }
  5164. return 0;
  5165. }
  5166. BIM_COMMAND(crnl,"crnl","Show or set the line ending mode") {
  5167. if (argc < 2) {
  5168. render_status_message("crnl=%d", env->crnl);
  5169. } else {
  5170. env->crnl = !!atoi(argv[1]);
  5171. redraw_statusbar();
  5172. }
  5173. return 0;
  5174. }
  5175. BIM_COMMAND(global_numbers,"global.numbers","Set whether numbers are displayed by default") {
  5176. if (argc < 2) {
  5177. render_status_message("global.numbers=%d", global_config.numbers);
  5178. } else {
  5179. global_config.numbers = !!atoi(argv[1]);
  5180. redraw_all();
  5181. }
  5182. return 0;
  5183. }
  5184. BIM_COMMAND(global_statusbar,"global.statusbar","Show or set whether to display the statusbar") {
  5185. if (argc < 2) {
  5186. render_status_message("global.statusbar=%d",!global_config.hide_statusbar);
  5187. } else {
  5188. global_config.hide_statusbar = !atoi(argv[1]);
  5189. global_config.bottom_size = global_config.hide_statusbar ? 1 : 2;
  5190. redraw_all();
  5191. }
  5192. return 0;
  5193. }
  5194. BIM_COMMAND(smartcomplete,"smartcomplete","Enable autocompletion while typing") {
  5195. if (argc < 2) {
  5196. render_status_message("smartcomplete=%d",global_config.smart_complete);
  5197. } else {
  5198. global_config.smart_complete = !!atoi(argv[1]);
  5199. }
  5200. return 0;
  5201. }
  5202. BIM_COMMAND(global_autohide_tabs,"global.autohidetabs","Whether to show the tab bar when there is only one tab") {
  5203. if (argc < 2) {
  5204. render_status_message("global.autohidetabs=%d", global_config.autohide_tabs);
  5205. } else {
  5206. global_config.autohide_tabs = !!atoi(argv[1]);
  5207. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  5208. redraw_all();
  5209. }
  5210. return 0;
  5211. }
  5212. BIM_COMMAND(numbers,"numbers","Show or set the display of line numbers") {
  5213. if (argc < 2) {
  5214. render_status_message("numbers=%d", env->numbers);
  5215. } else {
  5216. env->numbers = !!atoi(argv[1]);
  5217. redraw_all();
  5218. }
  5219. return 0;
  5220. }
  5221. BIM_COMMAND(relativenumbers,"relativenumbers","Show or set the display of relative line numbers") {
  5222. if (argc < 2) {
  5223. render_status_message("relativenumber=%d", global_config.relative_lines);
  5224. } else {
  5225. global_config.relative_lines = atoi(argv[1]);
  5226. if (env) {
  5227. if (!global_config.relative_lines) {
  5228. for (int i = 0; i < env->line_count; ++i) {
  5229. env->lines[i]->is_current = 0;
  5230. }
  5231. }
  5232. redraw_text();
  5233. place_cursor_actual();
  5234. }
  5235. }
  5236. return 0;
  5237. }
  5238. BIM_COMMAND(buffers,"buffers","Show the open buffers") {
  5239. for (int i = 0; i < buffers_len; ++i) {
  5240. render_commandline_message("%d: %s\n", i, buffers[i]->file_name ? buffers[i]->file_name : "(no name)");
  5241. }
  5242. redraw_tabbar();
  5243. redraw_commandline();
  5244. pause_for_key();
  5245. return 0;
  5246. }
  5247. BIM_COMMAND(keyname,"keyname","Press and key and get its name.") {
  5248. int c;
  5249. render_commandline_message("(press a key)");
  5250. while ((c = bim_getkey(200)) == KEY_TIMEOUT);
  5251. render_commandline_message("%d = %s", c, name_from_key(c));
  5252. return 0;
  5253. }
  5254. /**
  5255. * Process a user command.
  5256. */
  5257. int process_command(char * cmd) {
  5258. if (*cmd == '#') return 0;
  5259. /* First, check prefix commands */
  5260. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5261. if (strstr(cmd, c->name) == cmd &&
  5262. (!isalpha(cmd[strlen(c->name)]) || !isalpha(cmd[0]))) {
  5263. return c->command(cmd, 0, NULL);
  5264. }
  5265. }
  5266. char * argv[3] = {NULL, NULL, NULL};
  5267. int argc = !!(*cmd);
  5268. char cmd_name[512] = {0};
  5269. for (char * c = cmd; *c; ++c) {
  5270. if (c-cmd == 511) break;
  5271. if (*c == ' ') {
  5272. cmd_name[c-cmd] = '\0';
  5273. argv[1] = c+1;
  5274. if (*argv[1]) argc++;
  5275. break;
  5276. }
  5277. cmd_name[c-cmd] = *c;
  5278. }
  5279. argv[0] = cmd_name;
  5280. argv[argc] = NULL;
  5281. if (argc < 1) {
  5282. /* no op */
  5283. return 0;
  5284. }
  5285. /* Now check regular commands */
  5286. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5287. if (!strcmp(argv[0], c->name)) {
  5288. return c->command(cmd, argc, argv);
  5289. }
  5290. }
  5291. global_config.break_from_selection = 1;
  5292. if (argv[0][0] == '-' && isdigit(argv[0][1])) {
  5293. goto_line(env->line_no-atoi(&argv[0][1]));
  5294. return 0;
  5295. } else if (argv[0][0] == '+' && isdigit(argv[0][1])) {
  5296. goto_line(env->line_no+atoi(&argv[0][1]));
  5297. return 0;
  5298. } else if (isdigit(*argv[0])) {
  5299. goto_line(atoi(argv[0]));
  5300. return 0;
  5301. } else {
  5302. render_error("Not an editor command: %s", argv[0]);
  5303. return 1;
  5304. }
  5305. }
  5306. /**
  5307. * Wrap strcmp for use with qsort.
  5308. */
  5309. int compare_str(const void * a, const void * b) {
  5310. return strcmp(*(const char **)a, *(const char **)b);
  5311. }
  5312. /**
  5313. * List of file extensions to ignore when tab completing.
  5314. */
  5315. const char * tab_complete_ignore[] = {".o",NULL};
  5316. /**
  5317. * Tab completion for command mode.
  5318. */
  5319. void command_tab_complete(char * buffer) {
  5320. /* Figure out which argument this is and where it starts */
  5321. int arg = 0;
  5322. char * buf = strdup(buffer);
  5323. char * b = buf;
  5324. char * args[32];
  5325. int candidate_count= 0;
  5326. int candidate_space = 4;
  5327. char ** candidates = malloc(sizeof(char*)*candidate_space);
  5328. /* Accept whitespace before first argument */
  5329. while (*b == ' ') b++;
  5330. char * start = b;
  5331. args[0] = start;
  5332. while (*b && *b != ' ') b++;
  5333. while (*b) {
  5334. while (*b == ' ') {
  5335. *b = '\0';
  5336. b++;
  5337. }
  5338. start = b;
  5339. arg++;
  5340. args[arg] = start;
  5341. break;
  5342. }
  5343. /**
  5344. * Check a possible candidate and add it to the
  5345. * candidates list, expanding as necessary,
  5346. * if it matches for the current argument.
  5347. */
  5348. #define add_candidate(candidate) \
  5349. do { \
  5350. char * _arg = args[arg]; \
  5351. int r = strncmp(_arg, candidate, strlen(_arg)); \
  5352. if (!r) { \
  5353. if (candidate_count == candidate_space) { \
  5354. candidate_space *= 2; \
  5355. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  5356. } \
  5357. candidates[candidate_count] = strdup(candidate); \
  5358. candidate_count++; \
  5359. } \
  5360. } while (0)
  5361. int _candidates_are_files = 0;
  5362. if (arg == 0 || (arg == 1 && !strcmp(args[0], "help"))) {
  5363. /* Complete command names */
  5364. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5365. add_candidate(c->name);
  5366. }
  5367. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5368. add_candidate(c->name);
  5369. }
  5370. goto _accept_candidate;
  5371. }
  5372. if (arg == 1 && !strcmp(args[0], "syntax")) {
  5373. /* Complete syntax options */
  5374. add_candidate("none");
  5375. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  5376. add_candidate(s->name);
  5377. }
  5378. goto _accept_candidate;
  5379. }
  5380. if (arg == 1 && (!strcmp(args[0], "theme") || !strcmp(args[0], "colorscheme"))) {
  5381. /* Complete color theme names */
  5382. for (struct theme_def * s = themes; themes && s->name; ++s) {
  5383. add_candidate(s->name);
  5384. }
  5385. goto _accept_candidate;
  5386. }
  5387. if (arg == 1 && (!strcmp(args[0], "setcolor"))) {
  5388. for (struct ColorName * c = color_names; c->name; ++c) {
  5389. add_candidate(c->name);
  5390. }
  5391. goto _accept_candidate;
  5392. }
  5393. if (arg == 1 && (!strcmp(args[0], "action"))) {
  5394. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5395. add_candidate(a->name);
  5396. }
  5397. goto _accept_candidate;
  5398. }
  5399. if (arg == 1 && (!strcmp(args[0], "call") || !strcmp(args[0], "trycall") || !strcmp(args[0], "showfunction"))) {
  5400. for (int i = 0; i < flex_user_functions_count; ++i) {
  5401. add_candidate(user_functions[i]->command);
  5402. }
  5403. goto _accept_candidate;
  5404. }
  5405. if (arg == 1 && (!strcmp(args[0], "mapkey"))) {
  5406. for (int i = 0; args[arg][i]; ++i) {
  5407. if (args[arg][i] == ' ') {
  5408. while (args[arg][i] == ' ') {
  5409. args[arg][i] = '\0';
  5410. i++;
  5411. }
  5412. start = &args[arg][i];
  5413. arg++;
  5414. args[arg] = start;
  5415. if (arg == 32) {
  5416. arg = 31;
  5417. break;
  5418. }
  5419. }
  5420. }
  5421. if (arg == 1) {
  5422. for (struct mode_names * m = mode_names; m->name; ++m) {
  5423. add_candidate(m->name);
  5424. }
  5425. } else if (arg == 2) {
  5426. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  5427. add_candidate(KeyNames[i].name);
  5428. }
  5429. }
  5430. goto _accept_candidate;
  5431. }
  5432. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") ||
  5433. !strcmp(args[0],"split") || !strcmp(args[0],"w") || !strcmp(args[0],"runscript") ||
  5434. !strcmp(args[0],"rundir") || args[0][0] == '!')) {
  5435. /* Complete file paths */
  5436. /* First, find the deepest directory match */
  5437. char * tmp = strdup(args[arg]);
  5438. char * last_slash = strrchr(tmp, '/');
  5439. DIR * dirp;
  5440. if (last_slash) {
  5441. *last_slash = '\0';
  5442. if (last_slash == tmp) {
  5443. /* Started with slash, and it was the only slash */
  5444. dirp = opendir("/");
  5445. } else {
  5446. char * home;
  5447. if (*tmp == '~' && (home = getenv("HOME"))) {
  5448. char * t = malloc(strlen(tmp) + strlen(home) + 4);
  5449. sprintf(t, "%s%s",home,tmp+1);
  5450. dirp = opendir(t);
  5451. free(t);
  5452. } else {
  5453. dirp = opendir(tmp);
  5454. }
  5455. }
  5456. } else {
  5457. /* No directory match, completing from current directory */
  5458. dirp = opendir(".");
  5459. tmp[0] = '\0';
  5460. }
  5461. if (!dirp) {
  5462. /* Directory match doesn't exist, no candidates to populate */
  5463. free(tmp);
  5464. goto done;
  5465. }
  5466. _candidates_are_files = 1;
  5467. struct dirent * ent = readdir(dirp);
  5468. while (ent != NULL) {
  5469. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  5470. struct stat statbuf;
  5471. /* Figure out if this file is a directory */
  5472. if (last_slash) {
  5473. char * x;
  5474. char * home;
  5475. if (tmp[0] == '~' && (home = getenv("HOME"))) {
  5476. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1);
  5477. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1, "%s%s/%s",home,tmp+1,ent->d_name);
  5478. } else {
  5479. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  5480. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  5481. }
  5482. stat(x, &statbuf);
  5483. free(x);
  5484. } else {
  5485. stat(ent->d_name, &statbuf);
  5486. }
  5487. /* Build the complete argument name to tab complete */
  5488. char s[1024] = {0};
  5489. if (last_slash == tmp) {
  5490. strcat(s,"/");
  5491. } else if (*tmp) {
  5492. strcat(s,tmp);
  5493. strcat(s,"/");
  5494. }
  5495. strcat(s,ent->d_name);
  5496. /*
  5497. * If it is a directory, add a / to the end so the next completion
  5498. * attempt will complete the directory's contents.
  5499. */
  5500. if (S_ISDIR(statbuf.st_mode)) {
  5501. strcat(s,"/");
  5502. }
  5503. int skip = 0;
  5504. for (const char ** c = tab_complete_ignore; *c; ++c) {
  5505. if (str_ends_with(s, *c)) {
  5506. skip = 1;
  5507. break;
  5508. }
  5509. }
  5510. if (!skip) {
  5511. add_candidate(s);
  5512. }
  5513. }
  5514. ent = readdir(dirp);
  5515. }
  5516. closedir(dirp);
  5517. free(tmp);
  5518. goto _accept_candidate;
  5519. }
  5520. _accept_candidate:
  5521. if (candidate_count == 0) {
  5522. redraw_statusbar();
  5523. goto done;
  5524. }
  5525. if (candidate_count == 1) {
  5526. /* Only one completion possibility */
  5527. redraw_statusbar();
  5528. /* Fill out the rest of the command */
  5529. char * cstart = (buffer) + (start - buf);
  5530. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  5531. *cstart = candidates[0][i];
  5532. cstart++;
  5533. }
  5534. *cstart = '\0';
  5535. } else {
  5536. /* Sort candidates */
  5537. qsort(candidates, candidate_count, sizeof(candidates[0]), compare_str);
  5538. /* Print candidates in status bar */
  5539. char * tmp = malloc(global_config.term_width+1);
  5540. memset(tmp, 0, global_config.term_width+1);
  5541. int offset = 0;
  5542. for (int i = 0; i < candidate_count; ++i) {
  5543. char * printed_candidate = candidates[i];
  5544. if (_candidates_are_files) {
  5545. for (char * c = printed_candidate; *c; ++c) {
  5546. if (c[0] == '/' && c[1] != '\0') {
  5547. printed_candidate = c+1;
  5548. }
  5549. }
  5550. }
  5551. if (offset + 1 + (signed)strlen(printed_candidate) > global_config.term_width - 5) {
  5552. strcat(tmp, "...");
  5553. break;
  5554. }
  5555. if (offset > 0) {
  5556. strcat(tmp, " ");
  5557. offset++;
  5558. }
  5559. strcat(tmp, printed_candidate);
  5560. offset += strlen(printed_candidate);
  5561. }
  5562. render_status_message("%s", tmp);
  5563. free(tmp);
  5564. /* Complete to longest common substring */
  5565. char * cstart = (buffer) + (start - buf);
  5566. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5567. for (int j = 1; j < candidate_count; ++j) {
  5568. if (candidates[0][i] != candidates[j][i]) goto _reject;
  5569. }
  5570. *cstart = candidates[0][i];
  5571. cstart++;
  5572. }
  5573. /* End of longest common substring */
  5574. _reject:
  5575. *cstart = '\0';
  5576. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5577. if (start > buf) { /* Start point needs to be something other than first byte */
  5578. char * tmp = cstart - 1;
  5579. if ((*tmp & 0xC0) == 0x80) {
  5580. /* Count back until we find the start byte and make sure we have the right number */
  5581. int count = 1;
  5582. int x = 0;
  5583. while (tmp >= start) {
  5584. x++;
  5585. tmp--;
  5586. if ((*tmp & 0xC0) == 0x80) {
  5587. count++;
  5588. } else if ((*tmp & 0xC0) == 0xC0) {
  5589. /* How many should we have? */
  5590. int i = 1;
  5591. int j = *tmp;
  5592. while (j & 0x20) {
  5593. i += 1;
  5594. j <<= 1;
  5595. }
  5596. if (count != i) {
  5597. *tmp = '\0';
  5598. break;
  5599. }
  5600. break;
  5601. } else {
  5602. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5603. tmp++;
  5604. *tmp = '\0';
  5605. break;
  5606. }
  5607. }
  5608. } else if ((*tmp & 0xC0) == 0xC0) {
  5609. *tmp = '\0';
  5610. }
  5611. }
  5612. }
  5613. /* Free candidates */
  5614. for (int i = 0; i < candidate_count; ++i) {
  5615. free(candidates[i]);
  5616. }
  5617. done:
  5618. free(candidates);
  5619. free(buf);
  5620. }
  5621. /**
  5622. * Macros for use in command mode.
  5623. */
  5624. #define _syn_command() do { env->syntax = global_config.command_syn; } while (0)
  5625. #define _syn_restore() do { env->syntax = global_config.command_syn_back; } while (0)
  5626. #define _restore_history(point) do { \
  5627. unsigned char * t = command_history[point]; \
  5628. global_config.command_col_no = 1; \
  5629. global_config.command_buffer->actual = 0; \
  5630. _syn_command(); \
  5631. uint32_t state = 0; \
  5632. uint32_t c = 0; \
  5633. while (*t) { \
  5634. if (!decode(&state, &c, *t)) { \
  5635. char_t _c = {codepoint_width(c), 0, c}; \
  5636. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1); \
  5637. global_config.command_col_no++; \
  5638. } else if (state == UTF8_REJECT) state = 0; \
  5639. t++; \
  5640. } \
  5641. _syn_restore(); \
  5642. } while (0)
  5643. /**
  5644. * Draw the command buffer and any prefix.
  5645. */
  5646. void render_command_input_buffer(void) {
  5647. if (!global_config.command_buffer) return;
  5648. /* Place the cursor at the bottom of the screen */
  5649. place_cursor(1, global_config.term_height);
  5650. paint_line(COLOR_BG);
  5651. set_colors(COLOR_ALT_FG, COLOR_BG);
  5652. /* If there's a mode name to render, draw it first */
  5653. int _left_gutter = 0;
  5654. if (env->mode == MODE_LINE_SELECTION) {
  5655. _left_gutter = printf("(LINE %d:%d)",
  5656. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5657. (env->start_line < env->line_no) ? env->line_no : env->start_line);
  5658. } else if (env->mode == MODE_COL_SELECTION) {
  5659. _left_gutter = printf("(COL %d:%d %d)",
  5660. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5661. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  5662. (env->sel_col));
  5663. } else if (env->mode == MODE_CHAR_SELECTION) {
  5664. _left_gutter = printf("(CHAR)");
  5665. }
  5666. /* Figure out the cursor position and adjust the offset if necessary */
  5667. int x = 2 + _left_gutter - global_config.command_offset;
  5668. for (int i = 0; i < global_config.command_col_no - 1; ++i) {
  5669. char_t * c = &global_config.command_buffer->text[i];
  5670. x += c->display_width;
  5671. }
  5672. if (x > global_config.term_width - 1) {
  5673. int diff = x - (global_config.term_width - 1);
  5674. global_config.command_offset += diff;
  5675. x -= diff;
  5676. }
  5677. if (x < 2 + _left_gutter) {
  5678. int diff = (2 + _left_gutter) - x;
  5679. global_config.command_offset -= diff;
  5680. x += diff;
  5681. }
  5682. /* If the input buffer is horizontally shifted because it's too long, indicate that. */
  5683. if (global_config.command_offset) {
  5684. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  5685. printf("<");
  5686. } else {
  5687. /* Otherwise indicate buffer mode (search / ?, or command :) */
  5688. set_colors(COLOR_FG, COLOR_BG);
  5689. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5690. printf(global_config.search_direction == 0 ? "?" : "/");
  5691. } else {
  5692. printf(":");
  5693. }
  5694. }
  5695. /* Render the buffer */
  5696. render_line(global_config.command_buffer, global_config.term_width-1-_left_gutter, global_config.command_offset, -1);
  5697. /* Place and display the cursor */
  5698. place_cursor(x, global_config.term_height);
  5699. show_cursor();
  5700. }
  5701. BIM_ACTION(command_discard, 0,
  5702. "Discard the input buffer and cancel command or search."
  5703. )(void) {
  5704. free(global_config.command_buffer);
  5705. global_config.command_buffer = NULL;
  5706. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5707. env->line_no = global_config.prev_line;
  5708. env->col_no = global_config.prev_col;
  5709. /* Unhighlight search matches */
  5710. for (int i = 0; i < env->line_count; ++i) {
  5711. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5712. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5713. }
  5714. rehighlight_search(env->lines[i]);
  5715. }
  5716. }
  5717. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5718. redraw_all();
  5719. /* TODO exit some other modes? */
  5720. }
  5721. BIM_ACTION(enter_command, 0,
  5722. "Enter command input mode."
  5723. )(void) {
  5724. global_config.overlay_mode = OVERLAY_MODE_COMMAND;
  5725. global_config.command_offset = 0;
  5726. global_config.command_col_no = 1;
  5727. if (global_config.command_buffer) {
  5728. free(global_config.command_buffer);
  5729. }
  5730. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  5731. global_config.command_buffer->available = 32;
  5732. global_config.command_syn_back = env->syntax;
  5733. global_config.command_syn = find_syntax_calculator("bimcmd");
  5734. global_config.history_point = -1;
  5735. render_command_input_buffer();
  5736. }
  5737. BIM_ACTION(command_accept, 0,
  5738. "Accept the command input and run the requested command."
  5739. )(void) {
  5740. /* Convert command buffer to UTF-8 char-array string */
  5741. size_t size = 0;
  5742. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5743. char tmp[8] = {0};
  5744. size += to_eight(global_config.command_buffer->text[i].codepoint, tmp);
  5745. }
  5746. char * tmp = malloc(size + 8); /* for overflow from to_eight */
  5747. char * t = tmp;
  5748. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5749. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5750. }
  5751. *t = '\0';
  5752. /* Free the original editing buffer */
  5753. free(global_config.command_buffer);
  5754. global_config.command_buffer = NULL;
  5755. /* Run the converted command */
  5756. global_config.break_from_selection = 0;
  5757. insert_command_history(tmp);
  5758. process_command(tmp);
  5759. free(tmp);
  5760. if (!global_config.break_from_selection && env->mode != MODE_DIRECTORY_BROWSE) {
  5761. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) {
  5762. recalculate_selected_lines();
  5763. }
  5764. env->mode = MODE_NORMAL;
  5765. }
  5766. /* Leave command mode */
  5767. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5768. }
  5769. BIM_ACTION(command_word_delete, 0,
  5770. "Delete the previous word from the input buffer."
  5771. )(void) {
  5772. _syn_command();
  5773. while (global_config.command_col_no > 1 &&
  5774. (global_config.command_buffer->text[global_config.command_col_no-2].codepoint == ' ' ||
  5775. global_config.command_buffer->text[global_config.command_col_no-2].codepoint == '/')) {
  5776. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5777. global_config.command_col_no--;
  5778. }
  5779. while (global_config.command_col_no > 1 &&
  5780. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != ' ' &&
  5781. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != '/') {
  5782. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5783. global_config.command_col_no--;
  5784. }
  5785. _syn_restore();
  5786. }
  5787. BIM_ACTION(command_tab_complete_buffer, 0,
  5788. "Complete command names and arguments in the input buffer."
  5789. )(void) {
  5790. /* command_tab_complete should probably just be adjusted to deal with the buffer... */
  5791. char * tmp = calloc(1024,1);
  5792. char * t = tmp;
  5793. for (int i = 0; i < global_config.command_col_no-1; ++i) {
  5794. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5795. }
  5796. *t = '\0';
  5797. _syn_command();
  5798. while (global_config.command_col_no > 1) {
  5799. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5800. global_config.command_col_no--;
  5801. }
  5802. _syn_restore();
  5803. command_tab_complete(tmp);
  5804. _syn_command();
  5805. uint32_t state = 0, c= 0;
  5806. t = tmp;
  5807. while (*t) {
  5808. if (!decode(&state, &c, *t)) {
  5809. char_t _c = {codepoint_width(c), 0, c};
  5810. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5811. global_config.command_col_no++;
  5812. }
  5813. t++;
  5814. }
  5815. _syn_restore();
  5816. free(tmp);
  5817. }
  5818. BIM_ACTION(command_backspace, 0,
  5819. "Erase the character before the cursor in the input buffer."
  5820. )(void) {
  5821. if (global_config.command_col_no <= 1) {
  5822. if (global_config.command_buffer->actual == 0) {
  5823. command_discard();
  5824. }
  5825. return;
  5826. }
  5827. _syn_command();
  5828. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5829. _syn_restore();
  5830. global_config.command_col_no--;
  5831. global_config.command_offset = 0;
  5832. }
  5833. BIM_ACTION(command_scroll_history, ARG_IS_CUSTOM,
  5834. "Scroll through command input history."
  5835. )(int direction) {
  5836. if (direction == -1) {
  5837. if (command_history[global_config.history_point+1]) {
  5838. _restore_history(global_config.history_point+1);
  5839. global_config.history_point++;
  5840. }
  5841. } else {
  5842. if (global_config.history_point > 0) {
  5843. global_config.history_point--;
  5844. _restore_history(global_config.history_point);
  5845. } else {
  5846. global_config.history_point = -1;
  5847. global_config.command_col_no = 1;
  5848. global_config.command_buffer->actual = 0;
  5849. }
  5850. }
  5851. }
  5852. BIM_ACTION(command_word_left, 0,
  5853. "Move to the start of the previous word in the input buffer."
  5854. )(void) {
  5855. if (global_config.command_col_no > 1) {
  5856. do {
  5857. global_config.command_col_no--;
  5858. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5859. if (global_config.command_col_no == 1) return;
  5860. do {
  5861. global_config.command_col_no--;
  5862. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5863. 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++;
  5864. }
  5865. }
  5866. BIM_ACTION(command_word_right, 0,
  5867. "Move to the start of the next word in the input buffer."
  5868. )(void) {
  5869. if (global_config.command_col_no < global_config.command_buffer->actual) {
  5870. do {
  5871. global_config.command_col_no++;
  5872. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5873. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5874. do {
  5875. global_config.command_col_no++;
  5876. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5877. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5878. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; }
  5879. }
  5880. }
  5881. BIM_ACTION(command_cursor_left, 0,
  5882. "Move the cursor one character left in the input buffer."
  5883. )(void) {
  5884. if (global_config.command_col_no > 1) global_config.command_col_no--;
  5885. }
  5886. BIM_ACTION(command_cursor_right, 0,
  5887. "Move the cursor one character right in the input buffer."
  5888. )(void) {
  5889. if (global_config.command_col_no < global_config.command_buffer->actual+1) global_config.command_col_no++;
  5890. }
  5891. BIM_ACTION(command_cursor_home, 0,
  5892. "Move the cursor to the start of the input buffer."
  5893. )(void) {
  5894. global_config.command_col_no = 1;
  5895. }
  5896. BIM_ACTION(command_cursor_end, 0,
  5897. "Move the cursor to the end of the input buffer."
  5898. )(void) {
  5899. global_config.command_col_no = global_config.command_buffer->actual + 1;
  5900. }
  5901. BIM_ACTION(eat_mouse, 0,
  5902. "(temporary) Read, but ignore mouse input."
  5903. )(void) {
  5904. bim_getch();
  5905. bim_getch();
  5906. bim_getch();
  5907. }
  5908. BIM_ACTION(command_insert_char, ARG_IS_INPUT,
  5909. "Insert one character into the input buffer."
  5910. )(int c) {
  5911. char_t _c = {codepoint_width(c), 0, c};
  5912. _syn_command();
  5913. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5914. _syn_restore();
  5915. global_config.command_col_no++;
  5916. }
  5917. /**
  5918. * Determine whether a string should be searched
  5919. * case-sensitive or not based on whether it contains
  5920. * any upper-case letters.
  5921. */
  5922. int smart_case(uint32_t * str) {
  5923. if (!global_config.smart_case) return 0;
  5924. for (uint32_t * s = str; *s; ++s) {
  5925. if (tolower(*s) != (int)*s) {
  5926. return 0;
  5927. }
  5928. }
  5929. return 1;
  5930. }
  5931. /**
  5932. * Search forward from the given cursor position
  5933. * to find a basic search match.
  5934. *
  5935. * This could be more complicated...
  5936. */
  5937. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str, int * matchlen) {
  5938. int col = from_col;
  5939. int ignorecase = smart_case(str);
  5940. for (int i = from_line; i <= env->line_count; ++i) {
  5941. line_t * line = env->lines[i - 1];
  5942. int j = col - 1;
  5943. while (j < line->actual + 1) {
  5944. if (subsearch_matches(line, j, str, ignorecase, matchlen)) {
  5945. *out_line = i;
  5946. *out_col = j + 1;
  5947. return;
  5948. }
  5949. j++;
  5950. }
  5951. col = 0;
  5952. }
  5953. }
  5954. /**
  5955. * Search backwards for matching string.
  5956. */
  5957. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  5958. int col = from_col;
  5959. int ignorecase = smart_case(str);
  5960. for (int i = from_line; i >= 1; --i) {
  5961. line_t * line = env->lines[i-1];
  5962. int j = col - 1;
  5963. while (j > -1) {
  5964. if (subsearch_matches(line, j, str, ignorecase, NULL)) {
  5965. *out_line = i;
  5966. *out_col = j + 1;
  5967. return;
  5968. }
  5969. j--;
  5970. }
  5971. col = (i > 1) ? (env->lines[i-2]->actual + 1) : -1;
  5972. }
  5973. }
  5974. /**
  5975. * Re-mark search matches while editing text.
  5976. * This gets called after recalculate_syntax, so it works as we're typing or
  5977. * whenever syntax calculation would redraw other lines.
  5978. * XXX There's a bunch of code duplication between the (now three) search match functions.
  5979. * and search should be improved to support regex anyway, so this needs to be fixed.
  5980. */
  5981. void rehighlight_search(line_t * line) {
  5982. if (!global_config.search) return;
  5983. int j = 0;
  5984. int ignorecase = smart_case(global_config.search);
  5985. while (j < line->actual) {
  5986. int matchlen = 0;
  5987. if (subsearch_matches(line, j, global_config.search, ignorecase, &matchlen)) {
  5988. for (int i = j; matchlen > 0; ++i, matchlen--) {
  5989. line->text[i].flags |= FLAG_SEARCH;
  5990. }
  5991. }
  5992. j++;
  5993. }
  5994. }
  5995. /**
  5996. * Draw the matched search result.
  5997. */
  5998. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  5999. for (int i = 0; i < env->line_count; ++i) {
  6000. for (int j = 0; j < env->lines[i]->actual; ++j) {
  6001. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  6002. }
  6003. }
  6004. int line = -1, col = -1, _line = 1, _col = 1;
  6005. do {
  6006. int matchlen;
  6007. find_match(_line, _col, &line, &col, buffer, &matchlen);
  6008. if (line != -1) {
  6009. line_t * l = env->lines[line-1];
  6010. for (int i = col; matchlen > 0; ++i, --matchlen) {
  6011. l->text[i-1].flags |= FLAG_SEARCH;
  6012. }
  6013. }
  6014. _line = line;
  6015. _col = col+1;
  6016. line = -1;
  6017. col = -1;
  6018. } while (_line != -1);
  6019. redraw_text();
  6020. place_cursor_actual();
  6021. redraw_statusbar();
  6022. redraw_commandline();
  6023. if (redraw_buffer != -1) {
  6024. printf(redraw_buffer == 1 ? "/" : "?");
  6025. uint32_t * c = buffer;
  6026. while (*c) {
  6027. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  6028. to_eight(*c, tmp);
  6029. printf("%s", tmp);
  6030. c++;
  6031. }
  6032. }
  6033. }
  6034. BIM_ACTION(enter_search, ARG_IS_CUSTOM,
  6035. "Enter search mode."
  6036. )(int direction) {
  6037. global_config.overlay_mode = OVERLAY_MODE_SEARCH;
  6038. global_config.command_offset = 0;
  6039. global_config.command_col_no = 1;
  6040. global_config.prev_line = env->line_no;
  6041. global_config.prev_col = env->col_no;
  6042. global_config.prev_coffset = env->coffset;
  6043. global_config.prev_offset = env->offset;
  6044. global_config.search_direction = direction;
  6045. if (global_config.command_buffer) {
  6046. free(global_config.command_buffer);
  6047. }
  6048. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6049. global_config.command_buffer->available = 32;
  6050. global_config.command_syn_back = env->syntax;
  6051. global_config.command_syn = NULL; /* Disable syntax highlighting in search; maybe use buffer's mode instead? */
  6052. render_command_input_buffer();
  6053. }
  6054. BIM_ACTION(search_accept, 0,
  6055. "Accept the search term and return to the previous mode."
  6056. )(void) {
  6057. /* Store the accepted search */
  6058. if (!global_config.command_buffer->actual) {
  6059. if (global_config.search) {
  6060. search_next();
  6061. }
  6062. goto _finish;
  6063. }
  6064. if (global_config.search) {
  6065. free(global_config.search);
  6066. }
  6067. global_config.search = malloc((global_config.command_buffer->actual + 1) * sizeof(uint32_t));
  6068. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  6069. global_config.search[i] = global_config.command_buffer->text[i].codepoint;
  6070. }
  6071. global_config.search[global_config.command_buffer->actual] = 0;
  6072. _finish:
  6073. /* Free the original editing buffer */
  6074. free(global_config.command_buffer);
  6075. global_config.command_buffer = NULL;
  6076. /* Leave command mode */
  6077. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6078. }
  6079. /**
  6080. * Find the next search result, or loop back around if at the end.
  6081. */
  6082. BIM_ACTION(search_next, 0,
  6083. "Jump to the next search match."
  6084. )(void) {
  6085. if (!global_config.search) return;
  6086. if (env->coffset) env->coffset = 0;
  6087. int line = -1, col = -1;
  6088. find_match(env->line_no, env->col_no+1, &line, &col, global_config.search, NULL);
  6089. if (line == -1) {
  6090. find_match(1,1, &line, &col, global_config.search, NULL);
  6091. if (line == -1) return;
  6092. }
  6093. env->col_no = col;
  6094. env->line_no = line;
  6095. set_preferred_column();
  6096. draw_search_match(global_config.search, -1);
  6097. }
  6098. /**
  6099. * Find the previous search result, or loop to the end of the file.
  6100. */
  6101. BIM_ACTION(search_prev, 0,
  6102. "Jump to the preceding search match."
  6103. )(void) {
  6104. if (!global_config.search) return;
  6105. if (env->coffset) env->coffset = 0;
  6106. int line = -1, col = -1;
  6107. find_match_backwards(env->line_no, env->col_no-1, &line, &col, global_config.search);
  6108. if (line == -1) {
  6109. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, global_config.search);
  6110. if (line == -1) return;
  6111. }
  6112. env->col_no = col;
  6113. env->line_no = line;
  6114. set_preferred_column();
  6115. draw_search_match(global_config.search, -1);
  6116. }
  6117. /**
  6118. * Find the matching paren for this one.
  6119. *
  6120. * This approach skips having to do its own syntax parsing
  6121. * to deal with, eg., erroneous parens in comments. It does
  6122. * this by finding the matching paren with the same flag
  6123. * value, thus parens in strings will match, parens outside
  6124. * of strings will match, but parens in strings won't
  6125. * match parens outside of strings and so on.
  6126. */
  6127. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  6128. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  6129. return; /* Invalid cursor position */
  6130. }
  6131. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  6132. int paren_match = 0;
  6133. int direction = 0;
  6134. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  6135. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0x1F;
  6136. int count = 0;
  6137. /* TODO what about unicode parens? */
  6138. for (int i = 0; paren_pairs[i]; ++i) {
  6139. if (start == paren_pairs[i]) {
  6140. direction = (i % 2 == 0) ? 1 : -1;
  6141. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  6142. break;
  6143. }
  6144. }
  6145. if (!paren_match) return;
  6146. /* Scan for match */
  6147. int line = env->line_no;
  6148. int col = env->col_no - in_col + 1;
  6149. do {
  6150. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  6151. /* Only match on same syntax */
  6152. if ((env->lines[line-1]->text[col-1].flags & 0x1F) == flags) {
  6153. /* Count up on same direction */
  6154. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  6155. /* Count down on opposite direction */
  6156. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  6157. count--;
  6158. /* When count == 0 we have a match */
  6159. if (count == 0) goto _match_found;
  6160. }
  6161. }
  6162. col += direction;
  6163. }
  6164. line += direction;
  6165. /* Reached first/last line with no match */
  6166. if (line == 0 || line == env->line_count + 1) {
  6167. return;
  6168. }
  6169. /* Reset column to start/end of line, depending on direction */
  6170. if (direction > 0) {
  6171. col = 1;
  6172. } else {
  6173. col = env->lines[line-1]->actual;
  6174. }
  6175. } while (1);
  6176. _match_found:
  6177. *out_line = line;
  6178. *out_col = col;
  6179. }
  6180. /**
  6181. * Switch to the left split view
  6182. * (Primarily to handle cases where the left and right are the same buffer)
  6183. */
  6184. BIM_ACTION(use_left_buffer, 0,
  6185. "Switch to the left split view."
  6186. )(void) {
  6187. if (left_buffer == right_buffer && env->left != 0) {
  6188. view_right_offset = env->offset;
  6189. env->width = env->left;
  6190. env->left = 0;
  6191. env->offset = view_left_offset;
  6192. }
  6193. env = left_buffer;
  6194. update_title();
  6195. }
  6196. /**
  6197. * Switch to the right split view
  6198. * (Primarily to handle cases where the left and right are the same buffer)
  6199. */
  6200. BIM_ACTION(use_right_buffer, 0,
  6201. "Switch to the right split view."
  6202. )(void) {
  6203. if (left_buffer == right_buffer && env->left == 0) {
  6204. view_left_offset = env->offset;
  6205. env->left = env->width;
  6206. env->width = global_config.term_width - env->width;
  6207. env->offset = view_right_offset;
  6208. }
  6209. env = right_buffer;
  6210. update_title();
  6211. }
  6212. /**
  6213. * Handle mouse event
  6214. */
  6215. BIM_ACTION(handle_mouse, 0,
  6216. "Process mouse actions."
  6217. )(void) {
  6218. int buttons = bim_getch() - 32;
  6219. int x = bim_getch() - 32;
  6220. int y = bim_getch() - 32;
  6221. if (buttons == 64) {
  6222. /* Scroll up */
  6223. if (global_config.shift_scrolling) {
  6224. env->loading = 1;
  6225. int shifted = 0;
  6226. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6227. if (env->offset > 0) {
  6228. env->offset--;
  6229. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  6230. cursor_up();
  6231. }
  6232. shifted++;
  6233. }
  6234. }
  6235. env->loading = 0;
  6236. if (!shifted) return;
  6237. if (global_config.can_scroll && !left_buffer) {
  6238. shift_down(shifted);
  6239. for (int i = 0; i < shifted; ++i) {
  6240. redraw_line(env->offset+i);
  6241. }
  6242. } else {
  6243. redraw_text();
  6244. }
  6245. redraw_tabbar();
  6246. redraw_statusbar();
  6247. redraw_commandline();
  6248. place_cursor_actual();
  6249. } else {
  6250. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6251. cursor_up();
  6252. }
  6253. }
  6254. return;
  6255. } else if (buttons == 65) {
  6256. /* Scroll down */
  6257. if (global_config.shift_scrolling) {
  6258. env->loading = 1;
  6259. int shifted = 0;
  6260. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6261. if (env->offset < env->line_count-1) {
  6262. env->offset++;
  6263. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  6264. if (env->line_no <= e) {
  6265. cursor_down();
  6266. }
  6267. shifted++;
  6268. }
  6269. }
  6270. env->loading = 0;
  6271. if (!shifted) return;
  6272. if (global_config.can_scroll && !left_buffer) {
  6273. shift_up(shifted);
  6274. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  6275. for (int i = 0; i < shifted; ++i) {
  6276. if (env->offset + l - i < env->line_count + 1) {
  6277. redraw_line(env->offset + l-1-i);
  6278. } else {
  6279. draw_excess_line(l - 1 - i);
  6280. }
  6281. }
  6282. } else {
  6283. redraw_text();
  6284. }
  6285. redraw_tabbar();
  6286. redraw_statusbar();
  6287. redraw_commandline();
  6288. place_cursor_actual();
  6289. } else {
  6290. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6291. cursor_down();
  6292. }
  6293. }
  6294. return;
  6295. } else if (buttons == 3) {
  6296. /* Move cursor to position */
  6297. if (x < 0) return;
  6298. if (y < 0) return;
  6299. if (y == 1 && global_config.tabs_visible) {
  6300. /* Pick from tabs */
  6301. if (env->mode != MODE_NORMAL && env->mode != MODE_INSERT) return; /* Don't let the tab be switched in other modes for now */
  6302. int _x = 0;
  6303. if (global_config.tab_offset) _x = 1;
  6304. if (global_config.tab_offset && _x >= x) {
  6305. global_config.tab_offset--;
  6306. redraw_tabbar();
  6307. return;
  6308. }
  6309. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  6310. buffer_t * _env = buffers[i];
  6311. char tmp[64];
  6312. int size = 0;
  6313. int filled = draw_tab_name(_env, tmp, global_config.term_width - _x, &size);
  6314. _x += size;
  6315. if (_x >= x) {
  6316. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  6317. env = buffers[i];
  6318. redraw_all();
  6319. update_title();
  6320. return;
  6321. }
  6322. if (filled) break;
  6323. }
  6324. if (x > _x && global_config.tab_offset < buffers_len - 1) {
  6325. global_config.tab_offset++;
  6326. redraw_tabbar();
  6327. }
  6328. return;
  6329. }
  6330. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  6331. int current_mode = env->mode;
  6332. if (x < env->left && env == right_buffer) {
  6333. use_left_buffer();
  6334. } else if (x > env->width && env == left_buffer) {
  6335. use_right_buffer();
  6336. }
  6337. env->mode = current_mode;
  6338. redraw_all();
  6339. }
  6340. if (env->left) {
  6341. x -= env->left;
  6342. }
  6343. /* Figure out y coordinate */
  6344. int line_no = y + env->offset - global_config.tabs_visible;
  6345. int col_no = -1;
  6346. if (line_no > env->line_count) {
  6347. line_no = env->line_count;
  6348. }
  6349. if (line_no != env->line_no) {
  6350. env->coffset = 0;
  6351. }
  6352. /* Account for the left hand gutter */
  6353. int num_size = num_width() + gutter_width();
  6354. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  6355. /* Determine where the cursor is physically */
  6356. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  6357. char_t * c = &env->lines[line_no-1]->text[i];
  6358. _x += c->display_width;
  6359. if (_x > x-1) {
  6360. col_no = i+1;
  6361. break;
  6362. }
  6363. }
  6364. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  6365. col_no = env->lines[line_no-1]->actual;
  6366. }
  6367. env->line_no = line_no;
  6368. env->col_no = col_no;
  6369. set_history_break();
  6370. set_preferred_column();
  6371. redraw_statusbar();
  6372. place_cursor_actual();
  6373. }
  6374. return;
  6375. }
  6376. BIM_ACTION(insert_char, ARG_IS_INPUT | ACTION_IS_RW,
  6377. "Insert one character."
  6378. )(unsigned int c) {
  6379. if (!c) {
  6380. render_error("Inserted nil byte?");
  6381. return;
  6382. }
  6383. char_t _c;
  6384. _c.codepoint = c;
  6385. _c.flags = 0;
  6386. _c.display_width = codepoint_width(c);
  6387. line_t * line = env->lines[env->line_no - 1];
  6388. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  6389. if (line != nline) {
  6390. env->lines[env->line_no - 1] = nline;
  6391. }
  6392. env->col_no += 1;
  6393. set_preferred_column();
  6394. set_modified();
  6395. }
  6396. BIM_ACTION(replace_char, ARG_IS_PROMPT | ACTION_IS_RW,
  6397. "Replace a single character."
  6398. )(unsigned int c) {
  6399. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  6400. if (c >= KEY_ESCAPE) {
  6401. render_error("Invalid key for replacement");
  6402. return;
  6403. }
  6404. char_t _c;
  6405. _c.codepoint = c;
  6406. _c.flags = 0;
  6407. _c.display_width = codepoint_width(c);
  6408. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  6409. redraw_line(env->line_no-1);
  6410. set_modified();
  6411. }
  6412. BIM_ACTION(undo_history, ACTION_IS_RW,
  6413. "Undo history until the last breakpoint."
  6414. )(void) {
  6415. if (!global_config.history_enabled) return;
  6416. env->loading = 1;
  6417. history_t * e = env->history;
  6418. if (e->type == HISTORY_SENTINEL) {
  6419. env->loading = 0;
  6420. render_commandline_message("Already at oldest change");
  6421. return;
  6422. }
  6423. int count_chars = 0;
  6424. int count_lines = 0;
  6425. do {
  6426. if (e->type == HISTORY_SENTINEL) break;
  6427. switch (e->type) {
  6428. case HISTORY_INSERT:
  6429. /* Delete */
  6430. line_delete(
  6431. env->lines[e->contents.insert_delete_replace.lineno],
  6432. e->contents.insert_delete_replace.offset+1,
  6433. e->contents.insert_delete_replace.lineno
  6434. );
  6435. count_chars++;
  6436. break;
  6437. case HISTORY_DELETE:
  6438. {
  6439. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6440. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6441. env->lines[e->contents.insert_delete_replace.lineno],
  6442. _c,
  6443. e->contents.insert_delete_replace.offset-1,
  6444. e->contents.insert_delete_replace.lineno
  6445. );
  6446. }
  6447. count_chars++;
  6448. break;
  6449. case HISTORY_REPLACE:
  6450. {
  6451. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6452. line_replace(
  6453. env->lines[e->contents.insert_delete_replace.lineno],
  6454. _o,
  6455. e->contents.insert_delete_replace.offset,
  6456. e->contents.insert_delete_replace.lineno
  6457. );
  6458. }
  6459. count_chars++;
  6460. break;
  6461. case HISTORY_REMOVE_LINE:
  6462. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6463. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6464. count_lines++;
  6465. break;
  6466. case HISTORY_ADD_LINE:
  6467. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  6468. count_lines++;
  6469. break;
  6470. case HISTORY_REPLACE_LINE:
  6471. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6472. count_lines++;
  6473. break;
  6474. case HISTORY_SPLIT_LINE:
  6475. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  6476. count_lines++;
  6477. break;
  6478. case HISTORY_MERGE_LINES:
  6479. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  6480. count_lines++;
  6481. break;
  6482. case HISTORY_BREAK:
  6483. /* Ignore break */
  6484. break;
  6485. default:
  6486. render_error("Unknown type %d!\n", e->type);
  6487. break;
  6488. }
  6489. env->line_no = env->history->line;
  6490. env->col_no = env->history->col;
  6491. env->history = e->previous;
  6492. e = env->history;
  6493. } while (e->type != HISTORY_BREAK);
  6494. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6495. if (env->line_no < 1) env->line_no = 1;
  6496. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6497. if (env->col_no < 1) env->col_no = 1;
  6498. env->modified = (env->history != env->last_save_history);
  6499. env->loading = 0;
  6500. for (int i = 0; i < env->line_count; ++i) {
  6501. env->lines[i]->istate = 0;
  6502. recalculate_tabs(env->lines[i]);
  6503. }
  6504. for (int i = 0; i < env->line_count; ++i) {
  6505. recalculate_syntax(env->lines[i],i);
  6506. }
  6507. place_cursor_actual();
  6508. update_title();
  6509. redraw_all();
  6510. render_commandline_message("%d character%s, %d line%s changed",
  6511. count_chars, (count_chars == 1) ? "" : "s",
  6512. count_lines, (count_lines == 1) ? "" : "s");
  6513. }
  6514. BIM_ACTION(redo_history, ACTION_IS_RW,
  6515. "Redo history until the next breakpoint."
  6516. )(void) {
  6517. if (!global_config.history_enabled) return;
  6518. env->loading = 1;
  6519. history_t * e = env->history->next;
  6520. if (!e) {
  6521. env->loading = 0;
  6522. render_commandline_message("Already at newest change");
  6523. return;
  6524. }
  6525. int count_chars = 0;
  6526. int count_lines = 0;
  6527. while (e) {
  6528. if (e->type == HISTORY_BREAK) {
  6529. env->history = e;
  6530. break;
  6531. }
  6532. switch (e->type) {
  6533. case HISTORY_INSERT:
  6534. {
  6535. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6536. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6537. env->lines[e->contents.insert_delete_replace.lineno],
  6538. _c,
  6539. e->contents.insert_delete_replace.offset,
  6540. e->contents.insert_delete_replace.lineno
  6541. );
  6542. }
  6543. count_chars++;
  6544. break;
  6545. case HISTORY_DELETE:
  6546. /* Delete */
  6547. line_delete(
  6548. env->lines[e->contents.insert_delete_replace.lineno],
  6549. e->contents.insert_delete_replace.offset,
  6550. e->contents.insert_delete_replace.lineno
  6551. );
  6552. count_chars++;
  6553. break;
  6554. case HISTORY_REPLACE:
  6555. {
  6556. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6557. line_replace(
  6558. env->lines[e->contents.insert_delete_replace.lineno],
  6559. _o,
  6560. e->contents.insert_delete_replace.offset,
  6561. e->contents.insert_delete_replace.lineno
  6562. );
  6563. }
  6564. count_chars++;
  6565. break;
  6566. case HISTORY_ADD_LINE:
  6567. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6568. count_lines++;
  6569. break;
  6570. case HISTORY_REMOVE_LINE:
  6571. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  6572. count_lines++;
  6573. break;
  6574. case HISTORY_REPLACE_LINE:
  6575. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  6576. count_lines++;
  6577. break;
  6578. case HISTORY_MERGE_LINES:
  6579. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  6580. count_lines++;
  6581. break;
  6582. case HISTORY_SPLIT_LINE:
  6583. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  6584. count_lines++;
  6585. break;
  6586. case HISTORY_BREAK:
  6587. /* Ignore break */
  6588. break;
  6589. default:
  6590. render_error("Unknown type %d!\n", e->type);
  6591. break;
  6592. }
  6593. env->history = e;
  6594. e = e->next;
  6595. }
  6596. env->line_no = env->history->line;
  6597. env->col_no = env->history->col;
  6598. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6599. if (env->line_no < 1) env->line_no = 1;
  6600. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6601. if (env->col_no < 1) env->col_no = 1;
  6602. env->modified = (env->history != env->last_save_history);
  6603. env->loading = 0;
  6604. for (int i = 0; i < env->line_count; ++i) {
  6605. env->lines[i]->istate = 0;
  6606. recalculate_tabs(env->lines[i]);
  6607. }
  6608. for (int i = 0; i < env->line_count; ++i) {
  6609. recalculate_syntax(env->lines[i],i);
  6610. }
  6611. place_cursor_actual();
  6612. update_title();
  6613. redraw_all();
  6614. render_commandline_message("%d character%s, %d line%s changed",
  6615. count_chars, (count_chars == 1) ? "" : "s",
  6616. count_lines, (count_lines == 1) ? "" : "s");
  6617. }
  6618. int is_whitespace(int codepoint) {
  6619. return codepoint == ' ' || codepoint == '\t';
  6620. }
  6621. int is_normal(int codepoint) {
  6622. return isalnum(codepoint) || codepoint == '_';
  6623. }
  6624. int is_special(int codepoint) {
  6625. return !is_normal(codepoint) && !is_whitespace(codepoint);
  6626. }
  6627. BIM_ACTION(word_left, 0,
  6628. "Move the cursor left to the previous word."
  6629. )(void) {
  6630. if (!env->lines[env->line_no-1]) return;
  6631. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6632. env->col_no -= 1;
  6633. }
  6634. if (env->col_no == 1) {
  6635. if (env->line_no == 1) goto _place;
  6636. env->line_no--;
  6637. env->col_no = env->lines[env->line_no-1]->actual;
  6638. goto _place;
  6639. }
  6640. int (*inverse_comparator)(int) = is_special;
  6641. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6642. inverse_comparator = is_normal;
  6643. }
  6644. do {
  6645. if (env->col_no > 1) {
  6646. env->col_no -= 1;
  6647. }
  6648. } 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));
  6649. _place:
  6650. set_preferred_column();
  6651. place_cursor_actual();
  6652. }
  6653. BIM_ACTION(big_word_left, 0,
  6654. "Move the cursor left to the previous WORD."
  6655. )(void) {
  6656. int line_no = env->line_no;
  6657. int col_no = env->col_no;
  6658. do {
  6659. col_no--;
  6660. while (col_no == 0) {
  6661. line_no--;
  6662. if (line_no == 0) {
  6663. goto_line(1);
  6664. set_preferred_column();
  6665. return;
  6666. }
  6667. col_no = env->lines[line_no-1]->actual;
  6668. }
  6669. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6670. do {
  6671. col_no--;
  6672. if (col_no == 0) {
  6673. env->col_no = 1;
  6674. env->line_no = line_no;
  6675. set_preferred_column();
  6676. redraw_statusbar();
  6677. place_cursor_actual();
  6678. return;
  6679. }
  6680. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6681. env->col_no = col_no;
  6682. env->line_no = line_no;
  6683. set_preferred_column();
  6684. cursor_right();
  6685. }
  6686. BIM_ACTION(word_right, 0,
  6687. "Move the cursor right to the start of the next word."
  6688. )(void) {
  6689. if (!env->lines[env->line_no-1]) return;
  6690. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6691. /* next line */
  6692. if (env->line_no == env->line_count) return;
  6693. env->line_no++;
  6694. env->col_no = 0;
  6695. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6696. goto _place;
  6697. }
  6698. }
  6699. 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)) {
  6700. 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)) {
  6701. env->col_no++;
  6702. }
  6703. goto _place;
  6704. }
  6705. int (*inverse_comparator)(int) = is_special;
  6706. if (is_special(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6707. inverse_comparator = is_normal;
  6708. }
  6709. 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)) {
  6710. env->col_no++;
  6711. }
  6712. 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)) {
  6713. env->col_no++;
  6714. }
  6715. _place:
  6716. set_preferred_column();
  6717. place_cursor_actual();
  6718. }
  6719. BIM_ACTION(big_word_right, 0,
  6720. "Move the cursor right to the start of the next WORD."
  6721. )(void) {
  6722. int line_no = env->line_no;
  6723. int col_no = env->col_no;
  6724. do {
  6725. col_no++;
  6726. if (col_no > env->lines[line_no-1]->actual) {
  6727. line_no++;
  6728. if (line_no > env->line_count) {
  6729. env->line_no = env->line_count;
  6730. env->col_no = env->lines[env->line_no-1]->actual;
  6731. set_preferred_column();
  6732. redraw_statusbar();
  6733. place_cursor_actual();
  6734. return;
  6735. }
  6736. col_no = 0;
  6737. break;
  6738. }
  6739. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6740. do {
  6741. col_no++;
  6742. while (col_no > env->lines[line_no-1]->actual) {
  6743. line_no++;
  6744. if (line_no >= env->line_count) {
  6745. env->col_no = env->lines[env->line_count-1]->actual;
  6746. env->line_no = env->line_count;
  6747. set_preferred_column();
  6748. redraw_statusbar();
  6749. place_cursor_actual();
  6750. return;
  6751. }
  6752. col_no = 1;
  6753. }
  6754. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6755. env->col_no = col_no;
  6756. env->line_no = line_no;
  6757. set_preferred_column();
  6758. redraw_statusbar();
  6759. place_cursor_actual();
  6760. return;
  6761. }
  6762. BIM_ACTION(delete_at_cursor, ACTION_IS_RW,
  6763. "Delete the character at the cursor, or merge with previous line."
  6764. )(void) {
  6765. if (env->col_no > 1) {
  6766. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6767. env->col_no -= 1;
  6768. if (env->coffset > 0) env->coffset--;
  6769. redraw_line(env->line_no-1);
  6770. set_modified();
  6771. redraw_statusbar();
  6772. place_cursor_actual();
  6773. } else if (env->line_no > 1) {
  6774. int tmp = env->lines[env->line_no - 2]->actual;
  6775. merge_lines(env->lines, env->line_no - 1);
  6776. env->line_no -= 1;
  6777. env->col_no = tmp+1;
  6778. set_preferred_column();
  6779. redraw_text();
  6780. set_modified();
  6781. redraw_statusbar();
  6782. place_cursor_actual();
  6783. }
  6784. }
  6785. BIM_ACTION(delete_word, ACTION_IS_RW,
  6786. "Delete the previous word."
  6787. )(void) {
  6788. if (!env->lines[env->line_no-1]) return;
  6789. if (env->col_no > 1) {
  6790. /* Start by deleting whitespace */
  6791. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6792. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6793. env->col_no -= 1;
  6794. if (env->coffset > 0) env->coffset--;
  6795. }
  6796. int (*inverse_comparator)(int) = is_special;
  6797. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6798. inverse_comparator = is_normal;
  6799. }
  6800. do {
  6801. if (env->col_no > 1) {
  6802. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6803. env->col_no -= 1;
  6804. if (env->coffset > 0) env->coffset--;
  6805. }
  6806. } 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));
  6807. set_preferred_column();
  6808. redraw_text();
  6809. set_modified();
  6810. redraw_statusbar();
  6811. place_cursor_actual();
  6812. }
  6813. }
  6814. BIM_ACTION(insert_line_feed, ACTION_IS_RW,
  6815. "Insert a line break, splitting the current line into two."
  6816. )(void) {
  6817. if (env->indent) {
  6818. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  6819. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  6820. (env->col_no > 3) &&
  6821. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  6822. delete_at_cursor();
  6823. }
  6824. }
  6825. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  6826. env->lines = add_line(env->lines, env->line_no);
  6827. } else {
  6828. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  6829. }
  6830. env->coffset = 0;
  6831. env->col_no = 1;
  6832. env->line_no += 1;
  6833. set_preferred_column();
  6834. add_indent(env->line_no-1,env->line_no-2,0);
  6835. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  6836. env->offset += 1;
  6837. }
  6838. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  6839. set_modified();
  6840. }
  6841. BIM_ACTION(yank_lines, 0,
  6842. "Copy lines into the paste buffer."
  6843. )(void) {
  6844. int start = env->start_line;
  6845. int end = env->line_no;
  6846. if (global_config.yanks) {
  6847. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6848. free(global_config.yanks[i]);
  6849. }
  6850. free(global_config.yanks);
  6851. }
  6852. int lines_to_yank;
  6853. int start_point;
  6854. if (start <= end) {
  6855. lines_to_yank = end - start + 1;
  6856. start_point = start - 1;
  6857. } else {
  6858. lines_to_yank = start - end + 1;
  6859. start_point = end - 1;
  6860. }
  6861. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6862. global_config.yank_count = lines_to_yank;
  6863. global_config.yank_is_full_lines = 1;
  6864. for (int i = 0; i < lines_to_yank; ++i) {
  6865. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6866. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6867. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6868. global_config.yanks[i]->istate = 0;
  6869. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6870. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6871. global_config.yanks[i]->text[j].flags = 0;
  6872. }
  6873. }
  6874. }
  6875. /**
  6876. * Helper to yank part of a line into a new yank line.
  6877. */
  6878. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  6879. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  6880. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  6881. global_config.yanks[yank_no]->actual = count;
  6882. global_config.yanks[yank_no]->istate = 0;
  6883. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  6884. for (int i = 0; i < count; ++i) {
  6885. global_config.yanks[yank_no]->text[i].flags = 0;
  6886. }
  6887. }
  6888. /**
  6889. * Yank text...
  6890. */
  6891. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  6892. if (global_config.yanks) {
  6893. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6894. free(global_config.yanks[i]);
  6895. }
  6896. free(global_config.yanks);
  6897. }
  6898. int lines_to_yank = end_line - start_line + 1;
  6899. int start_point = start_line - 1;
  6900. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6901. global_config.yank_count = lines_to_yank;
  6902. global_config.yank_is_full_lines = 0;
  6903. if (lines_to_yank == 1) {
  6904. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  6905. } else {
  6906. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  6907. /* Yank middle lines */
  6908. for (int i = 1; i < lines_to_yank - 1; ++i) {
  6909. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6910. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6911. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6912. global_config.yanks[i]->istate = 0;
  6913. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6914. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6915. global_config.yanks[i]->text[j].flags = 0;
  6916. }
  6917. }
  6918. /* Yank end line */
  6919. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  6920. }
  6921. }
  6922. BIM_ACTION(delete_at_column, ARG_IS_CUSTOM | ACTION_IS_RW,
  6923. "Delete from the current column backwards (`<backspace>`) or forwards (`<del>`)."
  6924. )(int direction) {
  6925. if (direction == -1 && env->sel_col <= 0) return;
  6926. int prev_width = 0;
  6927. for (int i = env->line_no; i <= env->start_line; i++) {
  6928. line_t * line = env->lines[i - 1];
  6929. int _x = 0;
  6930. int col = 1;
  6931. int j = 0;
  6932. for (; j < line->actual; ++j) {
  6933. char_t * c = &line->text[j];
  6934. _x += c->display_width;
  6935. col = j+1;
  6936. if (_x > env->sel_col) break;
  6937. prev_width = c->display_width;
  6938. }
  6939. if ((direction == -1) && (_x == env->sel_col && j == line->actual)) {
  6940. line_delete(line, line->actual, i - 1);
  6941. set_modified();
  6942. } else if (_x > env->sel_col) {
  6943. line_delete(line, col - (direction == -1 ? 1 : 0), i - 1);
  6944. set_modified();
  6945. }
  6946. }
  6947. if (direction == -1) {
  6948. env->sel_col -= prev_width;
  6949. env->col_no--;
  6950. }
  6951. redraw_text();
  6952. }
  6953. uint32_t * get_word_under_cursor(void) {
  6954. /* Figure out size */
  6955. int c_before = 0;
  6956. int c_after = 0;
  6957. int i = env->col_no;
  6958. while (i > 0) {
  6959. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6960. c_before++;
  6961. i--;
  6962. }
  6963. i = env->col_no+1;
  6964. while (i < env->lines[env->line_no-1]->actual+1) {
  6965. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6966. c_after++;
  6967. i++;
  6968. }
  6969. if (!c_before && !c_after) return NULL;
  6970. /* Populate with characters */
  6971. uint32_t * out = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  6972. int j = 0;
  6973. while (c_before) {
  6974. out[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  6975. c_before--;
  6976. j++;
  6977. }
  6978. int x = 0;
  6979. while (c_after) {
  6980. out[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  6981. j++;
  6982. x++;
  6983. c_after--;
  6984. }
  6985. out[j] = 0;
  6986. return out;
  6987. }
  6988. BIM_ACTION(search_under_cursor, 0,
  6989. "Search for the word currently under the cursor."
  6990. )(void) {
  6991. if (global_config.search) free(global_config.search);
  6992. global_config.search = get_word_under_cursor();
  6993. /* Find it */
  6994. search_next();
  6995. }
  6996. BIM_ACTION(find_character_forward, ARG_IS_PROMPT | ARG_IS_INPUT,
  6997. "Find a character forward on the current line and place the cursor on (`f`) or before (`t`) it."
  6998. )(int type, int c) {
  6999. for (int i = env->col_no+1; i <= env->lines[env->line_no-1]->actual; ++i) {
  7000. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7001. env->col_no = i - !!(type == 't');
  7002. place_cursor_actual();
  7003. set_preferred_column();
  7004. return;
  7005. }
  7006. }
  7007. }
  7008. BIM_ACTION(find_character_backward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7009. "Find a character backward on the current line and place the cursor on (`F`) or after (`T`) it."
  7010. )(int type, int c) {
  7011. for (int i = env->col_no-1; i >= 1; --i) {
  7012. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7013. env->col_no = i + !!(type == 'T');
  7014. place_cursor_actual();
  7015. set_preferred_column();
  7016. return;
  7017. }
  7018. }
  7019. }
  7020. /**
  7021. * Clear the navigation number buffer
  7022. */
  7023. void reset_nav_buffer(int c) {
  7024. if (c == KEY_TIMEOUT) return;
  7025. if (nav_buffer && (c < '0' || c > '9')) {
  7026. nav_buffer = 0;
  7027. redraw_commandline();
  7028. }
  7029. }
  7030. /**
  7031. * Determine if a column + line number are within range of the
  7032. * current character selection specified by start_line, etc.
  7033. *
  7034. * Used to determine how syntax flags should be set when redrawing
  7035. * selected text in CHAR SELECTION mode.
  7036. */
  7037. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  7038. if (start_line == end_line) {
  7039. if ( end_col < start_col) {
  7040. int tmp = end_col;
  7041. end_col = start_col;
  7042. start_col = tmp;
  7043. }
  7044. return (col >= start_col && col <= end_col);
  7045. }
  7046. if (start_line > end_line) {
  7047. int tmp = end_line;
  7048. end_line = start_line;
  7049. start_line = tmp;
  7050. tmp = end_col;
  7051. end_col = start_col;
  7052. start_col = tmp;
  7053. }
  7054. if (line < start_line || line > end_line) return 0;
  7055. if (line == start_line) {
  7056. return col >= start_col;
  7057. }
  7058. if (line == end_line) {
  7059. return col <= end_col;
  7060. }
  7061. return 1;
  7062. }
  7063. /**
  7064. * Macro for redrawing selected lines with appropriate highlighting.
  7065. */
  7066. #define _redraw_line(line, force_start_line) \
  7067. do { \
  7068. if (!(force_start_line) && (line) == env->start_line) break; \
  7069. if ((line) > env->line_count + 1) { \
  7070. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7071. draw_excess_line((line) - env->offset - 1); \
  7072. } \
  7073. break; \
  7074. } \
  7075. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7076. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7077. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7078. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7079. } else { \
  7080. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7081. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7082. } \
  7083. } \
  7084. redraw_line((line)-1); \
  7085. } while (0)
  7086. #define _redraw_line_char(line, force_start_line) \
  7087. do { \
  7088. if (!(force_start_line) && (line) == env->start_line) break; \
  7089. if ((line) > env->line_count + 1) { \
  7090. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7091. draw_excess_line((line) - env->offset - 1); \
  7092. } \
  7093. break; \
  7094. } \
  7095. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7096. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7097. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7098. /* Line is completely outside selection */ \
  7099. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7100. } else { \
  7101. if ((line) == env->start_line || (line) == env->line_no) { \
  7102. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7103. } \
  7104. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7105. if (point_in_range(env->start_line, env->line_no,env->start_col, env->col_no, (line), j+1)) { \
  7106. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7107. } \
  7108. } \
  7109. } \
  7110. redraw_line((line)-1); \
  7111. } while (0)
  7112. #define _redraw_line_col(line, force_start_line) \
  7113. do {\
  7114. if (!(force_start_line) && (line) == env->start_line) break; \
  7115. if ((line) > env->line_count + 1) { \
  7116. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7117. draw_excess_line((line) - env->offset - 1); \
  7118. } \
  7119. break; \
  7120. } \
  7121. redraw_line((line)-1); \
  7122. } while (0)
  7123. BIM_ACTION(adjust_indent, ARG_IS_CUSTOM | ACTION_IS_RW,
  7124. "Adjust the indentation on the selected lines (`<tab>` for deeper, `<shift-tab>` for shallower)."
  7125. )(int direction) {
  7126. int lines_to_cover = 0;
  7127. int start_point = 0;
  7128. if (env->start_line <= env->line_no) {
  7129. start_point = env->start_line - 1;
  7130. lines_to_cover = env->line_no - env->start_line + 1;
  7131. } else {
  7132. start_point = env->line_no - 1;
  7133. lines_to_cover = env->start_line - env->line_no + 1;
  7134. }
  7135. for (int i = 0; i < lines_to_cover; ++i) {
  7136. if (env->lines[start_point + i]->actual < 1) continue;
  7137. if (direction == -1) {
  7138. if (env->tabs) {
  7139. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  7140. line_delete(env->lines[start_point + i],1,start_point+i);
  7141. _redraw_line(start_point+i+1,1);
  7142. }
  7143. } else {
  7144. for (int j = 0; j < env->tabstop; ++j) {
  7145. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  7146. line_delete(env->lines[start_point + i],1,start_point+i);
  7147. }
  7148. }
  7149. _redraw_line(start_point+i+1,1);
  7150. }
  7151. } else if (direction == 1) {
  7152. if (env->tabs) {
  7153. char_t c;
  7154. c.codepoint = '\t';
  7155. c.display_width = env->tabstop;
  7156. c.flags = FLAG_SELECT;
  7157. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7158. } else {
  7159. for (int j = 0; j < env->tabstop; ++j) {
  7160. char_t c;
  7161. c.codepoint = ' ';
  7162. c.display_width = 1;
  7163. c.flags = FLAG_SELECT;
  7164. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7165. }
  7166. }
  7167. _redraw_line(start_point+i+1,1);
  7168. }
  7169. }
  7170. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7171. env->col_no = env->lines[env->line_no-1]->actual;
  7172. }
  7173. set_preferred_column();
  7174. set_modified();
  7175. }
  7176. void recalculate_selected_lines(void) {
  7177. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7178. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7179. if (start < 1) start = 1;
  7180. if (start > env->line_count) start = env->line_count;
  7181. if (end < 1) end = 1;
  7182. if (end > env->line_count) end = env->line_count;
  7183. for (int i = (start > 1) ? (start-1) : (start); i <= end; ++i) {
  7184. recalculate_syntax(env->lines[i-1],i-1);
  7185. }
  7186. redraw_all();
  7187. }
  7188. BIM_ACTION(enter_line_selection, 0,
  7189. "Enter line selection mode."
  7190. )(void) {
  7191. /* Set mode */
  7192. env->mode = MODE_LINE_SELECTION;
  7193. /* Store start position */
  7194. env->start_line = env->line_no;
  7195. env->prev_line = env->start_line;
  7196. env->start_col = env->col_no;
  7197. /* Redraw commandline to get -- LINE SELECTION -- text */
  7198. redraw_commandline();
  7199. unhighlight_matching_paren();
  7200. /* Set this line as selected for syntax highlighting */
  7201. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  7202. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  7203. }
  7204. /* And redraw it */
  7205. redraw_line(env->line_no-1);
  7206. }
  7207. BIM_ACTION(switch_selection_mode, ARG_IS_CUSTOM,
  7208. "Swap between LINE and CHAR selection modes."
  7209. )(int mode) {
  7210. env->mode = mode;
  7211. if (mode == MODE_LINE_SELECTION) {
  7212. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7213. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7214. for (int i = start; i <= end; ++i) {
  7215. _redraw_line(i, 1);
  7216. }
  7217. } else if (mode == MODE_CHAR_SELECTION) {
  7218. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7219. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7220. for (int i = start; i <= end; ++i) {
  7221. _redraw_line_char(i, 1);
  7222. }
  7223. }
  7224. }
  7225. BIM_ACTION(delete_and_yank_lines, 0,
  7226. "Delete and yank the selected lines."
  7227. )(void) {
  7228. yank_lines();
  7229. if (env->start_line <= env->line_no) {
  7230. int lines_to_delete = env->line_no - env->start_line + 1;
  7231. for (int i = 0; i < lines_to_delete; ++i) {
  7232. env->lines = remove_line(env->lines, env->start_line-1);
  7233. }
  7234. env->line_no = env->start_line;
  7235. } else {
  7236. int lines_to_delete = env->start_line - env->line_no + 1;
  7237. for (int i = 0; i < lines_to_delete; ++i) {
  7238. env->lines = remove_line(env->lines, env->line_no-1);
  7239. }
  7240. }
  7241. if (env->line_no > env->line_count) {
  7242. env->line_no = env->line_count;
  7243. }
  7244. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7245. env->col_no = env->lines[env->line_no-1]->actual;
  7246. }
  7247. set_preferred_column();
  7248. set_modified();
  7249. }
  7250. BIM_ACTION(enter_insert, ACTION_IS_RW,
  7251. "Enter insert mode."
  7252. )(void) {
  7253. env->mode = MODE_INSERT;
  7254. set_history_break();
  7255. }
  7256. BIM_ACTION(delete_lines_and_enter_insert, ACTION_IS_RW,
  7257. "Delete and yank the selected lines and then enter insert mode."
  7258. )(void) {
  7259. delete_and_yank_lines();
  7260. env->lines = add_line(env->lines, env->line_no-1);
  7261. redraw_text();
  7262. env->mode = MODE_INSERT;
  7263. }
  7264. BIM_ACTION(replace_chars_in_line, ARG_IS_PROMPT | ACTION_IS_RW,
  7265. "Replace characters in the selected lines."
  7266. )(int c) {
  7267. if (c >= KEY_ESCAPE) {
  7268. render_error("Invalid key for replacement");
  7269. return;
  7270. }
  7271. char_t _c = {codepoint_width(c), 0, c};
  7272. int start_point = env->start_line < env->line_no ? env->start_line : env->line_no;
  7273. int end_point = env->start_line < env->line_no ? env->line_no : env->start_line;
  7274. for (int line = start_point; line <= end_point; ++line) {
  7275. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7276. line_replace(env->lines[line-1], _c, i, line-1);
  7277. }
  7278. }
  7279. }
  7280. BIM_ACTION(leave_selection, 0,
  7281. "Leave selection modes and return to normal mode."
  7282. )(void) {
  7283. set_history_break();
  7284. env->mode = MODE_NORMAL;
  7285. recalculate_selected_lines();
  7286. }
  7287. BIM_ACTION(insert_char_at_column, ARG_IS_INPUT | ACTION_IS_RW,
  7288. "Insert a character on all lines at the current column."
  7289. )(int c) {
  7290. char_t _c;
  7291. _c.codepoint = c;
  7292. _c.flags = 0;
  7293. _c.display_width = codepoint_width(c);
  7294. int inserted_width = 0;
  7295. /* For each line */
  7296. for (int i = env->line_no; i <= env->start_line; i++) {
  7297. line_t * line = env->lines[i - 1];
  7298. int _x = 0;
  7299. int col = 1;
  7300. int j = 0;
  7301. for (; j < line->actual; ++j) {
  7302. char_t * c = &line->text[j];
  7303. _x += c->display_width;
  7304. col = j+1;
  7305. if (_x > env->sel_col) break;
  7306. }
  7307. if ((_x == env->sel_col && j == line->actual)) {
  7308. _x = env->sel_col + 1;
  7309. col = line->actual + 1;
  7310. }
  7311. if (_x > env->sel_col) {
  7312. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  7313. if (line != nline) {
  7314. env->lines[i - 1] = nline;
  7315. line = nline;
  7316. }
  7317. set_modified();
  7318. }
  7319. recalculate_tabs(line);
  7320. inserted_width = line->text[col-1].display_width;
  7321. }
  7322. env->sel_col += inserted_width;
  7323. env->col_no++;
  7324. }
  7325. BIM_ACTION(enter_col_insert, ACTION_IS_RW,
  7326. "Enter column insert mode."
  7327. )(void) {
  7328. if (env->start_line < env->line_no) {
  7329. /* swap */
  7330. int tmp = env->line_no;
  7331. env->line_no = env->start_line;
  7332. env->start_line = tmp;
  7333. }
  7334. env->mode = MODE_COL_INSERT;
  7335. }
  7336. BIM_ACTION(enter_col_insert_after, ACTION_IS_RW,
  7337. "Enter column insert mode after the selected column."
  7338. )(void) {
  7339. env->sel_col += 1;
  7340. enter_col_insert();
  7341. }
  7342. BIM_ACTION(delete_column, ACTION_IS_RW,
  7343. "(temporary) Delete the selected column."
  7344. )(void) {
  7345. /* TODO maybe a flag to do this so we can just call delete_at_column with arg = 1? */
  7346. if (env->start_line < env->line_no) {
  7347. int tmp = env->line_no;
  7348. env->line_no = env->start_line;
  7349. env->start_line = tmp;
  7350. }
  7351. delete_at_column(1);
  7352. }
  7353. BIM_ACTION(enter_col_selection, 0,
  7354. "Enter column selection mode."
  7355. )(void) {
  7356. /* Set mode */
  7357. env->mode = MODE_COL_SELECTION;
  7358. /* Store cursor */
  7359. env->start_line = env->line_no;
  7360. env->sel_col = env->preferred_column;
  7361. env->prev_line = env->start_line;
  7362. /* Redraw commandline */
  7363. redraw_commandline();
  7364. /* Nothing else to do here; rely on cursor */
  7365. }
  7366. BIM_ACTION(yank_characters, 0,
  7367. "Yank the selected characters to the paste buffer."
  7368. )(void) {
  7369. int end_line = env->line_no;
  7370. int end_col = env->col_no;
  7371. if (env->start_line == end_line) {
  7372. if (env->start_col > end_col) {
  7373. int tmp = env->start_col;
  7374. env->start_col = end_col;
  7375. end_col = tmp;
  7376. }
  7377. } else if (env->start_line > end_line) {
  7378. int tmp = env->start_line;
  7379. env->start_line = end_line;
  7380. end_line = tmp;
  7381. tmp = env->start_col;
  7382. env->start_col = end_col;
  7383. end_col = tmp;
  7384. }
  7385. yank_text(env->start_line, env->start_col, end_line, end_col);
  7386. }
  7387. BIM_ACTION(delete_and_yank_chars, ACTION_IS_RW,
  7388. "Delete and yank the selected characters."
  7389. )(void) {
  7390. int end_line = env->line_no;
  7391. int end_col = env->col_no;
  7392. if (env->start_line == end_line) {
  7393. if (env->start_col > end_col) {
  7394. int tmp = env->start_col;
  7395. env->start_col = end_col;
  7396. end_col = tmp;
  7397. }
  7398. yank_text(env->start_line, env->start_col, end_line, end_col);
  7399. for (int i = env->start_col; i <= end_col; ++i) {
  7400. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7401. }
  7402. env->col_no = env->start_col;
  7403. } else {
  7404. if (env->start_line > end_line) {
  7405. int tmp = env->start_line;
  7406. env->start_line = end_line;
  7407. end_line = tmp;
  7408. tmp = env->start_col;
  7409. env->start_col = end_col;
  7410. end_col = tmp;
  7411. }
  7412. /* Copy lines */
  7413. yank_text(env->start_line, env->start_col, end_line, end_col);
  7414. /* Delete lines */
  7415. for (int i = env->start_line+1; i < end_line; ++i) {
  7416. env->lines = remove_line(env->lines, env->start_line);
  7417. } /* end_line is no longer valid; should be start_line+1*/
  7418. /* Delete from env->start_col forward */
  7419. int tmp = env->lines[env->start_line-1]->actual;
  7420. for (int i = env->start_col; i <= tmp; ++i) {
  7421. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7422. }
  7423. for (int i = 1; i <= end_col; ++i) {
  7424. line_delete(env->lines[env->start_line], 1, env->start_line);
  7425. }
  7426. /* Merge start and end lines */
  7427. merge_lines(env->lines, env->start_line);
  7428. env->line_no = env->start_line;
  7429. env->col_no = env->start_col;
  7430. }
  7431. if (env->line_no > env->line_count) {
  7432. env->line_no = env->line_count;
  7433. }
  7434. set_preferred_column();
  7435. set_modified();
  7436. }
  7437. BIM_ACTION(delete_chars_and_enter_insert, ACTION_IS_RW,
  7438. "Delete and yank the selected characters and then enter insert mode."
  7439. )(void) {
  7440. delete_and_yank_chars();
  7441. redraw_text();
  7442. enter_insert();
  7443. }
  7444. BIM_ACTION(replace_chars, ARG_IS_PROMPT | ACTION_IS_RW,
  7445. "Replace the selected characters."
  7446. )(int c) {
  7447. if (c >= KEY_ESCAPE) {
  7448. render_error("Invalid key for replacement");
  7449. return;
  7450. }
  7451. char_t _c = {codepoint_width(c), 0, c};
  7452. /* This should probably be a function line "do_over_range" or something */
  7453. if (env->start_line == env->line_no) {
  7454. int s = (env->start_col < env->col_no) ? env->start_col : env->col_no;
  7455. int e = (env->start_col < env->col_no) ? env->col_no : env->start_col;
  7456. for (int i = s; i <= e; ++i) {
  7457. line_replace(env->lines[env->start_line-1], _c, i-1, env->start_line-1);
  7458. }
  7459. redraw_text();
  7460. } else {
  7461. if (env->start_line < env->line_no) {
  7462. for (int s = env->start_col-1; s < env->lines[env->start_line-1]->actual; ++s) {
  7463. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7464. }
  7465. for (int line = env->start_line + 1; line < env->line_no; ++line) {
  7466. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7467. line_replace(env->lines[line-1], _c, i, line-1);
  7468. }
  7469. }
  7470. for (int s = 0; s < env->col_no; ++s) {
  7471. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7472. }
  7473. } else {
  7474. for (int s = env->col_no-1; s < env->lines[env->line_no-1]->actual; ++s) {
  7475. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7476. }
  7477. for (int line = env->line_no + 1; line < env->start_line; ++line) {
  7478. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7479. line_replace(env->lines[line-1], _c, i, line-1);
  7480. }
  7481. }
  7482. for (int s = 0; s < env->start_col; ++s) {
  7483. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7484. }
  7485. }
  7486. }
  7487. }
  7488. BIM_ACTION(enter_char_selection, 0,
  7489. "Enter character selection mode."
  7490. )(void) {
  7491. /* Set mode */
  7492. env->mode = MODE_CHAR_SELECTION;
  7493. /* Set cursor positions */
  7494. env->start_line = env->line_no;
  7495. env->start_col = env->col_no;
  7496. env->prev_line = env->start_line;
  7497. /* Redraw commandline for -- CHAR SELECTION -- */
  7498. redraw_commandline();
  7499. unhighlight_matching_paren();
  7500. /* Select single character */
  7501. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  7502. redraw_line(env->line_no-1);
  7503. }
  7504. BIM_ACTION(insert_at_end_of_selection, ACTION_IS_RW,
  7505. "Move the cursor to the end of the selection and enter insert mode."
  7506. )(void) {
  7507. recalculate_selected_lines();
  7508. if (env->line_no == env->start_line) {
  7509. env->col_no = env->col_no > env->start_col ? env->col_no + 1 : env->start_col + 1;
  7510. } else if (env->line_no < env->start_line) {
  7511. env->col_no = env->start_col + 1;
  7512. env->line_no = env->start_line;
  7513. } else {
  7514. env->col_no += 1;
  7515. }
  7516. env->mode = MODE_INSERT;
  7517. }
  7518. void free_completion_match(struct completion_match * match) {
  7519. if (match->string) free(match->string);
  7520. if (match->file) free(match->file);
  7521. if (match->search) free(match->search);
  7522. }
  7523. /**
  7524. * Read ctags file to find matches for a symbol
  7525. */
  7526. int read_tags(uint32_t * comp, struct completion_match **matches, int * matches_count, int complete_match) {
  7527. int _matches_len = 4;
  7528. int *matches_len = &_matches_len;
  7529. *matches_count = 0;
  7530. *matches = malloc(sizeof(struct completion_match) * (*matches_len));
  7531. FILE * tags = fopen("tags","r");
  7532. if (tags) {
  7533. char tmp[4096]; /* max line */
  7534. while (!feof(tags) && fgets(tmp, 4096, tags)) {
  7535. if (tmp[0] == '!') continue;
  7536. int i = 0;
  7537. while (comp[i] && comp[i] == (unsigned int)tmp[i]) i++;
  7538. if (comp[i] == '\0') {
  7539. if (complete_match && tmp[i] != '\t') continue;
  7540. int j = i;
  7541. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7542. tmp[j] = '\0'; j++;
  7543. char * file = &tmp[j];
  7544. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7545. tmp[j] = '\0'; j++;
  7546. char * search = &tmp[j];
  7547. while (!(tmp[j] == '/' && tmp[j+1] == ';' && tmp[j+2] == '"' && tmp[j+3] == '\t') /* /normal searches/ */
  7548. && !(tmp[j] == ';' && tmp[j+1] == '"' && tmp[j+2] == '\t') /* Old ctags line number searches */
  7549. && (tmp[j] != '\n' && tmp[j] != '\0')) j++;
  7550. tmp[j] = '\0'; j++;
  7551. add_match(tmp,file,search);
  7552. }
  7553. }
  7554. fclose(tags);
  7555. }
  7556. /* TODO: Get these from syntax files with a dynamic callback */
  7557. if (env->syntax && env->syntax->completion_matcher) {
  7558. env->syntax->completion_matcher(comp,matches,matches_count,complete_match,matches_len);
  7559. }
  7560. return 0;
  7561. }
  7562. /**
  7563. * Draw an autocomplete popover with matches.
  7564. */
  7565. void draw_completion_matches(uint32_t * tmp, struct completion_match *matches, int matches_count, int index) {
  7566. int original_length = 0;
  7567. while (tmp[original_length]) original_length++;
  7568. int max_width = 0;
  7569. for (int i = 0; i < matches_count; ++i) {
  7570. /* TODO unicode width */
  7571. unsigned int my_width = strlen(matches[i].string) + (matches[i].file ? strlen(matches[i].file) + 1 : 0);
  7572. if (my_width > (unsigned int)max_width) {
  7573. max_width = my_width;
  7574. }
  7575. }
  7576. /* Figure out how much space we have to display the window */
  7577. int cursor_y = env->line_no - env->offset + global_config.tabs_visible;
  7578. int max_y = global_config.term_height - global_config.bottom_size - cursor_y;
  7579. /* Find a good place to put the box horizontally */
  7580. int num_size = num_width() + gutter_width();
  7581. int x = num_size + 1 - env->coffset;
  7582. /* Determine where the cursor is physically */
  7583. for (int i = 0; i < env->col_no - 1 - original_length; ++i) {
  7584. char_t * c = &env->lines[env->line_no-1]->text[i];
  7585. x += c->display_width;
  7586. }
  7587. int box_width = max_width;
  7588. int box_x = x;
  7589. int box_y = cursor_y + 1;
  7590. if (max_width > env->width - num_width() - gutter_width()) {
  7591. box_width = env->width - num_width() - gutter_width();
  7592. box_x = num_width() + gutter_width() + 1;
  7593. } else if (env->width - x < max_width) {
  7594. box_width = max_width;
  7595. box_x = env->width - max_width;
  7596. }
  7597. int max_count = (max_y < matches_count) ? max_y - 1 : matches_count;
  7598. for (int x = index; x < max_count+index; ++x) {
  7599. int i = x % matches_count;
  7600. place_cursor(box_x + env->left, box_y+x-index);
  7601. set_colors(COLOR_KEYWORD, COLOR_STATUS_BG);
  7602. /* TODO wide characters */
  7603. int match_width = strlen(matches[i].string);
  7604. int file_width = matches[i].file ? strlen(matches[i].file) : 0;
  7605. for (int j = 0; j < box_width; ++j) {
  7606. if (j == original_length) set_colors(i == index ? COLOR_NUMERAL : COLOR_STATUS_FG, COLOR_STATUS_BG);
  7607. if (j == match_width) set_colors(COLOR_TYPE, COLOR_STATUS_BG);
  7608. if (j < match_width) printf("%c", matches[i].string[j]);
  7609. else if (j > match_width && j - match_width - 1 < file_width) printf("%c", matches[i].file[j-match_width-1]);
  7610. else printf(" ");
  7611. }
  7612. }
  7613. if (max_count == 0) {
  7614. place_cursor(box_x + env->left, box_y);
  7615. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7616. printf(" (no matches) ");
  7617. } else if (max_count != matches_count) {
  7618. place_cursor(box_x + env->left, box_y+max_count);
  7619. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7620. printf(" (%d more) ", matches_count-max_count);
  7621. }
  7622. }
  7623. /**
  7624. * Autocomplete words (function/variable names, etc.) in input mode.
  7625. */
  7626. int omni_complete(int quit_quietly_on_none) {
  7627. int c;
  7628. int (*qualifier)(int c) = simple_keyword_qualifier;
  7629. if (env->syntax && env->syntax->completion_qualifier) {
  7630. qualifier = env->syntax->completion_qualifier;
  7631. }
  7632. /* Pull the word from before the cursor */
  7633. int c_before = 0;
  7634. int i = env->col_no-1;
  7635. while (i > 0) {
  7636. int c = env->lines[env->line_no-1]->text[i-1].codepoint;
  7637. if (!qualifier(c)) break;
  7638. c_before++;
  7639. i--;
  7640. }
  7641. if (!c_before && quit_quietly_on_none) return 0;
  7642. /* Populate with characters */
  7643. uint32_t * tmp = malloc(sizeof(uint32_t) * (c_before+1));
  7644. int j = 0;
  7645. while (c_before) {
  7646. tmp[j] = env->lines[env->line_no-1]->text[env->col_no-c_before-1].codepoint;
  7647. c_before--;
  7648. j++;
  7649. }
  7650. tmp[j] = 0;
  7651. /*
  7652. * TODO matches should probably be a struct with more data than just
  7653. * the matching string; maybe offset where the needle was found,
  7654. * class information, source file information - anything we can extract
  7655. * from ctags, but also other information for other sources of completion.
  7656. */
  7657. struct completion_match *matches;
  7658. int matches_count;
  7659. /* TODO just reading ctags is rather mediocre; can we do something cool here? */
  7660. if (read_tags(tmp, &matches, &matches_count, 0)) goto _completion_done;
  7661. /* Draw box with matches at cursor-width(tmp) */
  7662. if (quit_quietly_on_none && matches_count == 0) return 0;
  7663. draw_completion_matches(tmp, matches, matches_count, 0);
  7664. int retval = 0;
  7665. int index = 0;
  7666. _completion_done:
  7667. place_cursor_actual();
  7668. while (1) {
  7669. c = bim_getch();
  7670. if (c == -1) continue;
  7671. if (matches_count < 1) {
  7672. redraw_all();
  7673. break;
  7674. }
  7675. if (c == 15) {
  7676. index = (index + 1) % matches_count;
  7677. draw_completion_matches(tmp, matches, matches_count, index);
  7678. place_cursor_actual();
  7679. continue;
  7680. } else if (c == '\t') {
  7681. for (unsigned int i = j; i < strlen(matches[index].string); ++i) {
  7682. insert_char(matches[index].string[i]);
  7683. }
  7684. set_preferred_column();
  7685. redraw_text();
  7686. place_cursor_actual();
  7687. goto _finish_completion;
  7688. } else if (isgraph(c) && c != '}') {
  7689. /* insert and continue matching */
  7690. insert_char(c);
  7691. set_preferred_column();
  7692. redraw_text();
  7693. place_cursor_actual();
  7694. retval = 1;
  7695. goto _finish_completion;
  7696. } else if (c == DELETE_KEY || c == BACKSPACE_KEY) {
  7697. delete_at_cursor();
  7698. set_preferred_column();
  7699. redraw_text();
  7700. place_cursor_actual();
  7701. retval = 1;
  7702. goto _finish_completion;
  7703. }
  7704. /* TODO: Keyboard navigation of the matches list would be nice */
  7705. redraw_all();
  7706. break;
  7707. }
  7708. bim_unget(c);
  7709. _finish_completion:
  7710. for (int i = 0; i < matches_count; ++i) {
  7711. free_completion_match(&matches[i]);
  7712. }
  7713. free(matches);
  7714. free(tmp);
  7715. return retval;
  7716. }
  7717. /**
  7718. * Set the search string from a UTF-8 sequence.
  7719. * Since the search string is normally a series of codepoints, this saves
  7720. * some effort when trying to search for things we pulled from the outside world.
  7721. * (eg., ctags search terms)
  7722. */
  7723. void set_search_from_bytes(char * bytes) {
  7724. if (global_config.search) free(global_config.search);
  7725. global_config.search = malloc(sizeof(uint32_t) * (strlen(bytes) + 1));
  7726. uint32_t * s = global_config.search;
  7727. char * tmp = bytes;
  7728. uint32_t c, istate = 0;
  7729. while (*tmp) {
  7730. if (!decode(&istate, &c, *tmp)) {
  7731. *s = c;
  7732. s++;
  7733. *s = 0;
  7734. } else if (istate == UTF8_REJECT) {
  7735. istate = 0;
  7736. }
  7737. tmp++;
  7738. }
  7739. }
  7740. BIM_ACTION(goto_definition, 0,
  7741. "Jump to the definition of the word under under cursor."
  7742. )(void) {
  7743. uint32_t * word = get_word_under_cursor();
  7744. if (!word) {
  7745. render_error("No match");
  7746. return;
  7747. }
  7748. struct completion_match *matches;
  7749. int matches_count;
  7750. if (read_tags(word, &matches, &matches_count, 1)) {
  7751. render_error("No tags file");
  7752. goto _done;
  7753. }
  7754. if (!matches_count) {
  7755. render_error("No match");
  7756. goto _done;
  7757. }
  7758. #define _perform_correct_search(i) do { \
  7759. if (matches[i].search[0] == '/') { \
  7760. set_search_from_bytes(&matches[i].search[1]); \
  7761. search_next(); \
  7762. } else { \
  7763. goto_line(atoi(matches[i].search)); \
  7764. } \
  7765. } while (0)
  7766. if (env->file_name && !strcmp(matches[0].file, env->file_name)) {
  7767. _perform_correct_search(0);
  7768. } else {
  7769. /* Check if there were other matches that are in this file */
  7770. for (int i =1; env->file_name && i < matches_count; ++i) {
  7771. if (!strcmp(matches[i].file, env->file_name)) {
  7772. _perform_correct_search(i);
  7773. goto _done;
  7774. }
  7775. }
  7776. /* Check buffers */
  7777. for (int i = 0; i < buffers_len; ++i) {
  7778. if (buffers[i]->file_name && !strcmp(matches[0].file,buffers[i]->file_name)) {
  7779. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  7780. env = buffers[i];
  7781. redraw_tabbar();
  7782. _perform_correct_search(i);
  7783. goto _done;
  7784. }
  7785. }
  7786. /* Okay, let's try opening */
  7787. buffer_t * old_buf = env;
  7788. open_file(matches[0].file);
  7789. if (env != old_buf) {
  7790. _perform_correct_search(0);
  7791. } else {
  7792. render_error("Could not locate file containing definition");
  7793. }
  7794. }
  7795. _done:
  7796. for (int i = 0; i < matches_count; ++i) {
  7797. free_completion_match(&matches[i]);
  7798. }
  7799. free(matches);
  7800. free(word);
  7801. }
  7802. /**
  7803. * Read one codepoint, with verbatim support.
  7804. */
  7805. int read_one_character(char * message) {
  7806. /* Read one character and replace */
  7807. if (!global_config.overlay_mode) {
  7808. render_commandline_message(message);
  7809. place_cursor_actual();
  7810. }
  7811. int c;
  7812. while ((c = bim_getkey(200))) {
  7813. if (c == KEY_TIMEOUT) continue;
  7814. if (c == KEY_CTRL_V) {
  7815. if (!global_config.overlay_mode) {
  7816. render_commandline_message(message);
  7817. printf(" ^V");
  7818. place_cursor_actual();
  7819. }
  7820. while ((c = bim_getch()) == -1);
  7821. break;
  7822. }
  7823. break;
  7824. }
  7825. redraw_commandline();
  7826. return c;
  7827. }
  7828. int read_one_byte(char * message) {
  7829. if (!global_config.overlay_mode) {
  7830. render_commandline_message(message);
  7831. place_cursor_actual();
  7832. }
  7833. int c;
  7834. while ((c = bim_getch())) {
  7835. if (c == -1) continue;
  7836. break;
  7837. }
  7838. redraw_commandline();
  7839. return c;
  7840. }
  7841. BIM_ACTION(cursor_left_with_wrap, 0,
  7842. "Move the cursor one position left, wrapping to the previous line."
  7843. )(void) {
  7844. if (env->line_no > 1 && env->col_no == 1) {
  7845. env->line_no--;
  7846. env->col_no = env->lines[env->line_no-1]->actual;
  7847. set_preferred_column();
  7848. place_cursor_actual();
  7849. } else {
  7850. cursor_left();
  7851. }
  7852. }
  7853. BIM_ACTION(prepend_and_insert, ACTION_IS_RW,
  7854. "Insert a new line before the current line and enter insert mode."
  7855. )(void) {
  7856. set_history_break();
  7857. env->lines = add_line(env->lines, env->line_no-1);
  7858. env->col_no = 1;
  7859. add_indent(env->line_no-1,env->line_no,0);
  7860. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7861. redraw_text();
  7862. set_preferred_column();
  7863. set_modified();
  7864. place_cursor_actual();
  7865. env->mode = MODE_INSERT;
  7866. }
  7867. BIM_ACTION(append_and_insert, ACTION_IS_RW,
  7868. "Insert a new line after the current line and enter insert mode."
  7869. )(void) {
  7870. set_history_break();
  7871. env->lines = add_line(env->lines, env->line_no);
  7872. env->col_no = 1;
  7873. env->line_no += 1;
  7874. add_indent(env->line_no-1,env->line_no-2,0);
  7875. set_preferred_column();
  7876. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7877. env->offset += 1;
  7878. }
  7879. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7880. redraw_text();
  7881. set_modified();
  7882. place_cursor_actual();
  7883. env->mode = MODE_INSERT;
  7884. }
  7885. BIM_ACTION(insert_after_cursor, ACTION_IS_RW,
  7886. "Place the cursor after the selected character and enter insert mode."
  7887. )(void) {
  7888. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  7889. env->col_no += 1;
  7890. }
  7891. enter_insert();
  7892. }
  7893. BIM_ACTION(delete_forward, ACTION_IS_RW,
  7894. "Delete the character under the cursor."
  7895. )(void) {
  7896. if (env->col_no <= env->lines[env->line_no-1]->actual) {
  7897. line_delete(env->lines[env->line_no-1], env->col_no, env->line_no-1);
  7898. redraw_text();
  7899. } else if (env->col_no == env->lines[env->line_no-1]->actual + 1 && env->line_count > env->line_no) {
  7900. merge_lines(env->lines, env->line_no);
  7901. redraw_text();
  7902. }
  7903. set_modified();
  7904. redraw_statusbar();
  7905. place_cursor_actual();
  7906. }
  7907. BIM_ACTION(delete_forward_and_insert, ACTION_IS_RW,
  7908. "Delete the character under the cursor and enter insert mode."
  7909. )(void) {
  7910. set_history_break();
  7911. delete_forward();
  7912. env->mode = MODE_INSERT;
  7913. }
  7914. BIM_ACTION(paste, ARG_IS_CUSTOM | ACTION_IS_RW,
  7915. "Paste yanked text before (`P`) or after (`p`) the cursor."
  7916. )(int direction) {
  7917. if (global_config.yanks) {
  7918. if (!global_config.yank_is_full_lines) {
  7919. /* Handle P for paste before, p for past after */
  7920. int target_column = (direction == -1 ? (env->col_no) : (env->col_no+1));
  7921. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  7922. target_column = env->lines[env->line_no-1]->actual + 1;
  7923. }
  7924. if (global_config.yank_count > 1) {
  7925. /* Spit the current line at the current position */
  7926. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  7927. }
  7928. /* Insert first line at current position */
  7929. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  7930. 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);
  7931. }
  7932. if (global_config.yank_count > 1) {
  7933. /* Insert full lines */
  7934. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7935. env->lines = add_line(env->lines, env->line_no);
  7936. }
  7937. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7938. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  7939. }
  7940. /* Insert characters from last line into (what was) the next line */
  7941. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  7942. 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);
  7943. }
  7944. }
  7945. } else {
  7946. /* Insert full lines */
  7947. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7948. env->lines = add_line(env->lines, env->line_no - (direction == -1 ? 1 : 0));
  7949. }
  7950. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7951. replace_line(env->lines, env->line_no - (direction == -1 ? 1 : 0) + i, global_config.yanks[i]);
  7952. }
  7953. }
  7954. /* Recalculate whole document syntax */
  7955. for (int i = 0; i < env->line_count; ++i) {
  7956. env->lines[i]->istate = 0;
  7957. }
  7958. for (int i = 0; i < env->line_count; ++i) {
  7959. recalculate_syntax(env->lines[i],i);
  7960. }
  7961. if (direction == 1) {
  7962. if (global_config.yank_is_full_lines) {
  7963. env->line_no += 1;
  7964. } else {
  7965. if (global_config.yank_count == 1) {
  7966. env->col_no = env->col_no + global_config.yanks[0]->actual;
  7967. } else {
  7968. env->line_no = env->line_no + global_config.yank_count - 1;
  7969. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  7970. }
  7971. }
  7972. }
  7973. if (global_config.yank_is_full_lines) {
  7974. env->col_no = 1;
  7975. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  7976. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  7977. env->col_no = i + 1;
  7978. break;
  7979. }
  7980. }
  7981. }
  7982. set_history_break();
  7983. set_modified();
  7984. redraw_all();
  7985. }
  7986. }
  7987. BIM_ACTION(insert_at_end, ACTION_IS_RW,
  7988. "Move the cursor to the end of the current line and enter insert mode."
  7989. )(void) {
  7990. env->col_no = env->lines[env->line_no-1]->actual+1;
  7991. env->mode = MODE_INSERT;
  7992. set_history_break();
  7993. }
  7994. BIM_ACTION(enter_replace, ACTION_IS_RW,
  7995. "Enter replace mode."
  7996. )(void) {
  7997. env->mode = MODE_REPLACE;
  7998. set_history_break();
  7999. }
  8000. BIM_ACTION(toggle_numbers, 0,
  8001. "Toggle the display of line numbers."
  8002. )(void) {
  8003. env->numbers = !env->numbers;
  8004. redraw_all();
  8005. place_cursor_actual();
  8006. }
  8007. BIM_ACTION(toggle_gutter, 0,
  8008. "Toggle the display of the revision status gutter."
  8009. )(void) {
  8010. env->gutter = !env->gutter;
  8011. redraw_all();
  8012. place_cursor_actual();
  8013. }
  8014. BIM_ACTION(toggle_indent, 0,
  8015. "Toggle smart indentation."
  8016. )(void) {
  8017. env->indent = !env->indent;
  8018. redraw_statusbar();
  8019. place_cursor_actual();
  8020. }
  8021. BIM_ACTION(toggle_smartcomplete, 0,
  8022. "Toggle smart completion."
  8023. )(void) {
  8024. global_config.smart_complete = !global_config.smart_complete;
  8025. redraw_statusbar();
  8026. place_cursor_actual();
  8027. }
  8028. BIM_ACTION(expand_split_right, 0,
  8029. "Move the view split divider to the right."
  8030. )(void) {
  8031. global_config.split_percent += 1;
  8032. update_split_size();
  8033. redraw_all();
  8034. }
  8035. BIM_ACTION(expand_split_left, 0,
  8036. "Move the view split divider to the left."
  8037. )(void) {
  8038. global_config.split_percent -= 1;
  8039. update_split_size();
  8040. redraw_all();
  8041. }
  8042. BIM_ACTION(go_page_up, 0,
  8043. "Jump up a screenful."
  8044. )(void) {
  8045. goto_line(env->line_no - (global_config.term_height - 6));
  8046. }
  8047. BIM_ACTION(go_page_down, 0,
  8048. "Jump down a screenful."
  8049. )(void) {
  8050. goto_line(env->line_no + (global_config.term_height - 6));
  8051. }
  8052. BIM_ACTION(jump_to_matching_bracket, 0,
  8053. "Find and jump to the matching bracket for the character under the cursor."
  8054. )(void) {
  8055. recalculate_selected_lines();
  8056. int paren_line = -1, paren_col = -1;
  8057. find_matching_paren(&paren_line, &paren_col, 1);
  8058. if (paren_line != -1) {
  8059. env->line_no = paren_line;
  8060. env->col_no = paren_col;
  8061. set_preferred_column();
  8062. place_cursor_actual();
  8063. redraw_statusbar();
  8064. }
  8065. }
  8066. BIM_ACTION(jump_to_previous_blank, 0,
  8067. "Jump to the preceding blank line before the cursor."
  8068. )(void) {
  8069. env->col_no = 1;
  8070. if (env->line_no == 1) return;
  8071. do {
  8072. env->line_no--;
  8073. if (env->lines[env->line_no-1]->actual == 0) break;
  8074. } while (env->line_no > 1);
  8075. set_preferred_column();
  8076. redraw_statusbar();
  8077. }
  8078. BIM_ACTION(jump_to_next_blank, 0,
  8079. "Jump to the next blank line after the cursor."
  8080. )(void) {
  8081. env->col_no = 1;
  8082. if (env->line_no == env->line_count) return;
  8083. do {
  8084. env->line_no++;
  8085. if (env->lines[env->line_no-1]->actual == 0) break;
  8086. } while (env->line_no < env->line_count);
  8087. set_preferred_column();
  8088. redraw_statusbar();
  8089. }
  8090. BIM_ACTION(first_non_whitespace, 0,
  8091. "Jump to the first non-whitespace character in the current line."
  8092. )(void) {
  8093. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8094. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8095. env->col_no = i + 1;
  8096. break;
  8097. }
  8098. }
  8099. set_preferred_column();
  8100. redraw_statusbar();
  8101. }
  8102. BIM_ACTION(next_line_non_whitespace, 0,
  8103. "Jump to the first non-whitespace character in the next next line."
  8104. )(void) {
  8105. if (env->line_no < env->line_count) {
  8106. env->line_no++;
  8107. env->col_no = 1;
  8108. } else {
  8109. return;
  8110. }
  8111. first_non_whitespace();
  8112. }
  8113. BIM_ACTION(smart_backspace, ACTION_IS_RW,
  8114. "Delete the preceding character, with special handling for indentation."
  8115. )(void) {
  8116. if (!env->tabs && env->col_no > 1) {
  8117. int i;
  8118. for (i = 0; i < env->col_no-1; ++i) {
  8119. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) break;
  8120. }
  8121. if (i == env->col_no-1) {
  8122. /* Backspace until aligned */
  8123. delete_at_cursor();
  8124. while (env->col_no > 1 && (env->col_no-1) % env->tabstop) {
  8125. delete_at_cursor();
  8126. }
  8127. return;
  8128. }
  8129. }
  8130. delete_at_cursor();
  8131. }
  8132. BIM_ACTION(perform_omni_completion, ACTION_IS_RW,
  8133. "(temporary) Perform smart symbol competion from ctags."
  8134. )(void) {
  8135. /* This should probably be a submode */
  8136. while (omni_complete(0) == 1);
  8137. }
  8138. BIM_ACTION(smart_tab, ACTION_IS_RW,
  8139. "Insert a tab or spaces depending on indent mode. (Use ^V <tab> to guarantee a literal tab)"
  8140. )(void) {
  8141. if (env->tabs) {
  8142. insert_char('\t');
  8143. } else {
  8144. for (int i = 0; i < env->tabstop; ++i) {
  8145. insert_char(' ');
  8146. }
  8147. }
  8148. }
  8149. BIM_ACTION(smart_comment_end, ARG_IS_INPUT | ACTION_IS_RW,
  8150. "Insert a `/` ending a C-style comment."
  8151. )(int c) {
  8152. /* smart *end* of comment anyway */
  8153. if (env->indent) {
  8154. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  8155. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  8156. (env->col_no > 3) &&
  8157. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  8158. env->col_no--;
  8159. replace_char('/');
  8160. env->col_no++;
  8161. place_cursor_actual();
  8162. return;
  8163. }
  8164. }
  8165. insert_char(c);
  8166. }
  8167. BIM_ACTION(smart_brace_end, ARG_IS_INPUT | ACTION_IS_RW,
  8168. "Insert a closing brace and smartly position it if it is the first character on a line."
  8169. )(int c) {
  8170. if (env->indent) {
  8171. int was_whitespace = 1;
  8172. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8173. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  8174. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  8175. was_whitespace = 0;
  8176. break;
  8177. }
  8178. }
  8179. insert_char(c);
  8180. if (was_whitespace) {
  8181. int line = -1, col = -1;
  8182. env->col_no--;
  8183. find_matching_paren(&line,&col, 1);
  8184. if (line != -1) {
  8185. line = find_brace_line_start(line, col);
  8186. while (env->lines[env->line_no-1]->actual) {
  8187. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  8188. }
  8189. add_indent(env->line_no-1,line-1,1);
  8190. env->col_no = env->lines[env->line_no-1]->actual + 1;
  8191. insert_char(c);
  8192. }
  8193. }
  8194. set_preferred_column();
  8195. return;
  8196. }
  8197. insert_char(c);
  8198. }
  8199. BIM_ACTION(enter_line_selection_and_cursor_up, 0,
  8200. "Enter line selection and move the cursor up one line."
  8201. )(void) {
  8202. enter_line_selection();
  8203. cursor_up();
  8204. }
  8205. BIM_ACTION(enter_line_selection_and_cursor_down, 0,
  8206. "Enter line selection and move the cursor down one line."
  8207. )(void) {
  8208. enter_line_selection();
  8209. cursor_down();
  8210. }
  8211. BIM_ACTION(shift_horizontally, ARG_IS_CUSTOM,
  8212. "Shift the current line or screen view horiztonally, depending on settings."
  8213. )(int amount) {
  8214. env->coffset += amount;
  8215. if (env->coffset < 0) env->coffset = 0;
  8216. redraw_text();
  8217. }
  8218. struct action_map _NORMAL_MAP[] = {
  8219. {KEY_BACKSPACE, cursor_left_with_wrap, opt_rep, 0},
  8220. {'V', enter_line_selection, 0, 0},
  8221. {'v', enter_char_selection, 0, 0},
  8222. {KEY_CTRL_V, enter_col_selection, 0, 0},
  8223. {'O', prepend_and_insert, opt_rw, 0},
  8224. {'o', append_and_insert, opt_rw, 0},
  8225. {'a', insert_after_cursor, opt_rw, 0},
  8226. {'s', delete_forward_and_insert, opt_rw, 0},
  8227. {'x', delete_forward, opt_rep | opt_rw, 0},
  8228. {'P', paste, opt_arg | opt_rw, -1},
  8229. {'p', paste, opt_arg | opt_rw, 1},
  8230. {'r', replace_char, opt_char | opt_rw, 0},
  8231. {'A', insert_at_end, opt_rw, 0},
  8232. {'u', undo_history, opt_rw, 0},
  8233. {KEY_CTRL_R, redo_history, opt_rw, 0},
  8234. {KEY_CTRL_L, redraw_all, 0, 0},
  8235. {KEY_CTRL_G, goto_definition, 0, 0},
  8236. {'i', enter_insert, opt_rw, 0},
  8237. {'R', enter_replace, opt_rw, 0},
  8238. {KEY_SHIFT_UP, enter_line_selection_and_cursor_up, 0, 0},
  8239. {KEY_SHIFT_DOWN, enter_line_selection_and_cursor_down, 0, 0},
  8240. {KEY_ALT_UP, previous_tab, 0, 0},
  8241. {KEY_ALT_DOWN, next_tab, 0, 0},
  8242. {-1, NULL, 0, 0},
  8243. };
  8244. struct action_map _INSERT_MAP[] = {
  8245. {KEY_ESCAPE, leave_insert, 0, 0},
  8246. {KEY_DELETE, delete_forward, 0, 0},
  8247. {KEY_CTRL_C, leave_insert, 0, 0},
  8248. {KEY_BACKSPACE, smart_backspace, 0, 0},
  8249. {KEY_ENTER, insert_line_feed, 0, 0},
  8250. {KEY_CTRL_O, perform_omni_completion, 0, 0},
  8251. {KEY_CTRL_V, insert_char, opt_byte, 0},
  8252. {KEY_CTRL_W, delete_word, 0, 0},
  8253. {'\t', smart_tab, 0, 0},
  8254. {'/', smart_comment_end, opt_arg, '/'},
  8255. {'}', smart_brace_end, opt_arg, '}'},
  8256. {-1, NULL, 0, 0},
  8257. };
  8258. struct action_map _REPLACE_MAP[] = {
  8259. {KEY_ESCAPE, leave_insert, 0, 0},
  8260. {KEY_DELETE, delete_forward, 0, 0},
  8261. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8262. {KEY_ENTER, insert_line_feed, 0, 0},
  8263. {-1, NULL, 0, 0},
  8264. };
  8265. struct action_map _LINE_SELECTION_MAP[] = {
  8266. {KEY_ESCAPE, leave_selection, 0, 0},
  8267. {KEY_CTRL_C, leave_selection, 0, 0},
  8268. {'V', leave_selection, 0, 0},
  8269. {'v', switch_selection_mode, opt_arg, MODE_CHAR_SELECTION},
  8270. {'y', yank_lines, opt_norm, 0},
  8271. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8272. {'\t', adjust_indent, opt_arg | opt_rw, 1},
  8273. {KEY_SHIFT_TAB, adjust_indent, opt_arg | opt_rw, -1},
  8274. {'D', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8275. {'d', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8276. {'x', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8277. {'s', delete_lines_and_enter_insert, opt_rw, 0},
  8278. {'r', replace_chars_in_line, opt_char | opt_rw, 0},
  8279. {KEY_SHIFT_UP, cursor_up, 0, 0},
  8280. {KEY_SHIFT_DOWN, cursor_down, 0, 0},
  8281. {-1, NULL, 0, 0},
  8282. };
  8283. struct action_map _CHAR_SELECTION_MAP[] = {
  8284. {KEY_ESCAPE, leave_selection, 0, 0},
  8285. {KEY_CTRL_C, leave_selection, 0, 0},
  8286. {'v', leave_selection, 0, 0},
  8287. {'V', switch_selection_mode, opt_arg, MODE_LINE_SELECTION},
  8288. {'y', yank_characters, opt_norm, 0},
  8289. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8290. {'D', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8291. {'d', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8292. {'x', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8293. {'s', delete_chars_and_enter_insert, opt_rw, 0},
  8294. {'r', replace_chars, opt_char | opt_rw, 0},
  8295. {'A', insert_at_end_of_selection, opt_rw, 0},
  8296. {-1, NULL, 0, 0},
  8297. };
  8298. struct action_map _COL_SELECTION_MAP[] = {
  8299. {KEY_ESCAPE, leave_selection, 0, 0},
  8300. {KEY_CTRL_C, leave_selection, 0, 0},
  8301. {KEY_CTRL_V, leave_selection, 0, 0},
  8302. {'I', enter_col_insert, opt_rw, 0},
  8303. {'a', enter_col_insert_after, opt_rw, 0},
  8304. {'d', delete_column, opt_norm | opt_rw, 0},
  8305. {-1, NULL, 0, 0},
  8306. };
  8307. struct action_map _COL_INSERT_MAP[] = {
  8308. {KEY_ESCAPE, leave_selection, 0, 0},
  8309. {KEY_CTRL_C, leave_selection, 0, 0},
  8310. {KEY_BACKSPACE, delete_at_column, opt_arg, -1},
  8311. {KEY_DELETE, delete_at_column, opt_arg, 1},
  8312. {KEY_ENTER, NULL, 0, 0},
  8313. {KEY_CTRL_W, NULL, 0, 0},
  8314. {KEY_CTRL_V, insert_char_at_column, opt_char, 0},
  8315. {-1, NULL, 0, 0},
  8316. };
  8317. struct action_map _NAVIGATION_MAP[] = {
  8318. /* Common navigation */
  8319. {KEY_CTRL_B, go_page_up, opt_rep, 0},
  8320. {KEY_CTRL_F, go_page_down, opt_rep, 0},
  8321. {':', enter_command, 0, 0},
  8322. {'/', enter_search, opt_arg, 1},
  8323. {'?', enter_search, opt_arg, 0},
  8324. {'n', search_next, opt_rep, 0},
  8325. {'N', search_prev, opt_rep, 0},
  8326. {'j', cursor_down, opt_rep, 0},
  8327. {'k', cursor_up, opt_rep, 0},
  8328. {'h', cursor_left, opt_rep, 0},
  8329. {'l', cursor_right, opt_rep, 0},
  8330. {'b', word_left, opt_rep, 0},
  8331. {'w', word_right, opt_rep, 0},
  8332. {'B', big_word_left, opt_rep, 0},
  8333. {'W', big_word_right, opt_rep, 0},
  8334. {'<', shift_horizontally, opt_arg, -1},
  8335. {'>', shift_horizontally, opt_arg, 1},
  8336. {'f', find_character_forward, opt_rep | opt_arg | opt_char, 'f'},
  8337. {'F', find_character_backward, opt_rep | opt_arg | opt_char, 'F'},
  8338. {'t', find_character_forward, opt_rep | opt_arg | opt_char, 't'},
  8339. {'T', find_character_backward, opt_rep | opt_arg | opt_char, 'T'},
  8340. {'G', goto_line, opt_nav, 0},
  8341. {'*', search_under_cursor, 0, 0},
  8342. {' ', go_page_down, opt_rep, 0},
  8343. {'%', jump_to_matching_bracket, 0, 0},
  8344. {'{', jump_to_previous_blank, opt_rep, 0},
  8345. {'}', jump_to_next_blank, opt_rep, 0},
  8346. {'$', cursor_end, 0, 0},
  8347. {'|', cursor_home, 0, 0},
  8348. {KEY_ENTER, next_line_non_whitespace, opt_rep, 0},
  8349. {'^', first_non_whitespace, 0, 0},
  8350. {'0', cursor_home, 0, 0},
  8351. {-1, NULL, 0, 0},
  8352. };
  8353. struct action_map _ESCAPE_MAP[] = {
  8354. {KEY_F1, toggle_numbers, 0, 0},
  8355. {KEY_F2, toggle_indent, 0, 0},
  8356. {KEY_F3, toggle_gutter, 0, 0},
  8357. {KEY_F4, toggle_smartcomplete, 0, 0},
  8358. {KEY_MOUSE, handle_mouse, 0, 0},
  8359. {KEY_UP, cursor_up, opt_rep, 0},
  8360. {KEY_DOWN, cursor_down, opt_rep, 0},
  8361. {KEY_RIGHT, cursor_right, opt_rep, 0},
  8362. {KEY_CTRL_RIGHT, big_word_right, opt_rep, 0},
  8363. {KEY_SHIFT_RIGHT, word_right, opt_rep, 0},
  8364. {KEY_ALT_RIGHT, expand_split_right, opt_rep, 0},
  8365. {KEY_ALT_SHIFT_RIGHT, use_right_buffer, opt_rep, 0},
  8366. {KEY_LEFT, cursor_left, opt_rep, 0},
  8367. {KEY_CTRL_LEFT, big_word_left, opt_rep, 0},
  8368. {KEY_SHIFT_LEFT, word_left, opt_rep, 0},
  8369. {KEY_ALT_LEFT, expand_split_left, opt_rep, 0},
  8370. {KEY_ALT_SHIFT_LEFT, use_left_buffer, opt_rep, 0},
  8371. {KEY_HOME, cursor_home, 0, 0},
  8372. {KEY_END, cursor_end, 0, 0},
  8373. {KEY_PAGE_UP, go_page_up, opt_rep, 0},
  8374. {KEY_PAGE_DOWN, go_page_down, opt_rep, 0},
  8375. {KEY_CTRL_Z, suspend, 0, 0},
  8376. {-1, NULL, 0, 0}
  8377. };
  8378. struct action_map _COMMAND_MAP[] = {
  8379. {KEY_ENTER, command_accept, 0, 0},
  8380. {'\t', command_tab_complete_buffer, 0, 0},
  8381. {KEY_UP, command_scroll_history, opt_arg, -1}, /* back */
  8382. {KEY_DOWN, command_scroll_history, opt_arg, 1}, /* forward */
  8383. {-1, NULL, 0, 0}
  8384. };
  8385. struct action_map _SEARCH_MAP[] = {
  8386. {KEY_ENTER, search_accept, 0, 0},
  8387. {KEY_UP, NULL, 0, 0},
  8388. {KEY_DOWN, NULL, 0, 0},
  8389. {-1, NULL, 0, 0}
  8390. };
  8391. struct action_map _INPUT_BUFFER_MAP[] = {
  8392. /* These are generic and shared with search */
  8393. {KEY_ESCAPE, command_discard, 0, 0},
  8394. {KEY_CTRL_C, command_discard, 0, 0},
  8395. {KEY_BACKSPACE, command_backspace, 0, 0},
  8396. {KEY_CTRL_W, command_word_delete, 0, 0},
  8397. {KEY_MOUSE, eat_mouse, 0, 0},
  8398. {KEY_LEFT, command_cursor_left, 0, 0},
  8399. {KEY_CTRL_LEFT, command_word_left, 0, 0},
  8400. {KEY_RIGHT, command_cursor_right, 0, 0},
  8401. {KEY_CTRL_RIGHT,command_word_right, 0, 0},
  8402. {KEY_HOME, command_cursor_home, 0, 0},
  8403. {KEY_END, command_cursor_end, 0, 0},
  8404. {-1, NULL, 0, 0}
  8405. };
  8406. /* DIRECTORY_BROWSE_MAP is only to override KEY_ENTER and should not be remapped,
  8407. * so unlike the others it is not going to be redefined as a pointer. */
  8408. struct action_map DIRECTORY_BROWSE_MAP[] = {
  8409. {KEY_ENTER, open_file_from_line, 0, 0},
  8410. {-1, NULL, 0, 0}
  8411. };
  8412. struct action_map * NORMAL_MAP = NULL;
  8413. struct action_map * INSERT_MAP = NULL;
  8414. struct action_map * REPLACE_MAP = NULL;
  8415. struct action_map * LINE_SELECTION_MAP = NULL;
  8416. struct action_map * CHAR_SELECTION_MAP = NULL;
  8417. struct action_map * COL_SELECTION_MAP = NULL;
  8418. struct action_map * COL_INSERT_MAP = NULL;
  8419. struct action_map * NAVIGATION_MAP = NULL;
  8420. struct action_map * ESCAPE_MAP = NULL;
  8421. struct action_map * COMMAND_MAP = NULL;
  8422. struct action_map * SEARCH_MAP = NULL;
  8423. struct action_map * INPUT_BUFFER_MAP = NULL;
  8424. struct mode_names mode_names[] = {
  8425. {"Normal","norm",&NORMAL_MAP},
  8426. {"Insert","insert",&INSERT_MAP},
  8427. {"Replace","replace",&REPLACE_MAP},
  8428. {"Line Selection","line",&LINE_SELECTION_MAP},
  8429. {"Char Selection","char",&CHAR_SELECTION_MAP},
  8430. {"Col Selection","col",&COL_SELECTION_MAP},
  8431. {"Col Insert","colinsert",&COL_INSERT_MAP},
  8432. {"Navigation (Select)","nav",&NAVIGATION_MAP},
  8433. {"Escape (Select, Insert)","esc",&ESCAPE_MAP},
  8434. {"Command","command",&COMMAND_MAP},
  8435. {"Search","search",&SEARCH_MAP},
  8436. {"Input (Command, Search)","input",&INPUT_BUFFER_MAP},
  8437. {NULL,NULL,NULL},
  8438. };
  8439. int handle_action(struct action_map * basemap, int key) {
  8440. for (struct action_map * map = basemap; map->key != -1; map++) {
  8441. if (map->key == key) {
  8442. if (!map->method) return 1;
  8443. if ((map->options & opt_rw) && (env->readonly)) {
  8444. render_error("Buffer is read-only");
  8445. return 2;
  8446. }
  8447. /* Determine how to format this request */
  8448. int reps = (map->options & opt_rep) ? ((nav_buffer) ? atoi(nav_buf) : 1) : 1;
  8449. int c = 0;
  8450. if (map->options & opt_char) {
  8451. c = read_one_character(name_from_key(key));
  8452. }
  8453. if (map->options & opt_byte) {
  8454. c = read_one_byte(name_from_key(key));
  8455. }
  8456. for (int i = 0; i < reps; ++i) {
  8457. if (((map->options & opt_char) || (map->options & opt_byte)) && (map->options & opt_arg)) {
  8458. map->method(map->arg, c);
  8459. } else if ((map->options & opt_char) || (map->options & opt_byte)) {
  8460. map->method(c);
  8461. } else if (map->options & opt_arg) {
  8462. map->method(map->arg);
  8463. } else if (map->options & opt_nav) {
  8464. if (nav_buffer) {
  8465. map->method(atoi(nav_buf));
  8466. reset_nav_buffer(0);
  8467. } else {
  8468. map->method(-1);
  8469. }
  8470. } else {
  8471. map->method();
  8472. }
  8473. }
  8474. if (map->options & opt_norm) {
  8475. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) leave_insert();
  8476. else if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) leave_selection();
  8477. else {
  8478. env->mode = MODE_NORMAL;
  8479. redraw_all();
  8480. }
  8481. }
  8482. return 1;
  8483. }
  8484. }
  8485. return 0;
  8486. }
  8487. int handle_nav_buffer(int key) {
  8488. if ((key >= '1' && key <= '9') || (key == '0' && nav_buffer)) {
  8489. if (nav_buffer < NAV_BUFFER_MAX) {
  8490. /* Up to NAV_BUFFER_MAX=10 characters; that should be enough for most tasks */
  8491. nav_buf[nav_buffer] = key;
  8492. nav_buf[nav_buffer+1] = 0;
  8493. nav_buffer++;
  8494. /* Print the number buffer */
  8495. redraw_commandline();
  8496. }
  8497. return 0;
  8498. }
  8499. return 1;
  8500. }
  8501. /**
  8502. * NORMAL mode
  8503. *
  8504. * Default editor mode - just cursor navigation and keybinds
  8505. * to enter the other modes.
  8506. */
  8507. void normal_mode(void) {
  8508. int last_mode = MODE_NORMAL;
  8509. int refresh = 0;
  8510. while (1) {
  8511. if (global_config.overlay_mode) {
  8512. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND) {
  8513. if (refresh) {
  8514. render_command_input_buffer();
  8515. refresh = 0;
  8516. }
  8517. int key = bim_getkey(200);
  8518. if (key != KEY_TIMEOUT) {
  8519. refresh = 1;
  8520. if (!handle_action(COMMAND_MAP, key))
  8521. if (!handle_action(INPUT_BUFFER_MAP, key))
  8522. if (key < KEY_ESCAPE) command_insert_char(key);
  8523. }
  8524. continue;
  8525. } else if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8526. if (refresh) {
  8527. render_command_input_buffer();
  8528. refresh = 0;
  8529. }
  8530. int key = bim_getkey(200);
  8531. if (key != KEY_TIMEOUT) {
  8532. refresh = 1;
  8533. if (!handle_action(SEARCH_MAP, key)) {
  8534. if (!handle_action(INPUT_BUFFER_MAP, key)) {
  8535. if (key < KEY_ESCAPE) command_insert_char(key);
  8536. }
  8537. }
  8538. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8539. /* Find the next search match */
  8540. uint32_t * buffer = malloc(sizeof(uint32_t) * (global_config.command_buffer->actual+1));
  8541. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  8542. buffer[i] = global_config.command_buffer->text[i].codepoint;
  8543. }
  8544. buffer[global_config.command_buffer->actual] = 0;
  8545. int line = -1, col = -1;
  8546. if (global_config.search_direction == 1) {
  8547. find_match(global_config.prev_line, global_config.prev_col, &line, &col, buffer, NULL);
  8548. if (line == -1) {
  8549. find_match(1, global_config.prev_col, &line, &col, buffer, NULL);
  8550. }
  8551. } else {
  8552. find_match_backwards(global_config.prev_line, global_config.prev_col, &line, &col, buffer);
  8553. if (line == -1) {
  8554. find_match_backwards(env->line_count, global_config.prev_col, &line, &col, buffer);
  8555. }
  8556. }
  8557. if (line != -1) {
  8558. env->col_no = col;
  8559. env->line_no = line;
  8560. set_preferred_column();
  8561. } else {
  8562. env->coffset = global_config.prev_coffset;
  8563. env->offset = global_config.prev_offset;
  8564. env->col_no = global_config.prev_col;
  8565. set_preferred_column();
  8566. env->line_no = global_config.prev_line;
  8567. }
  8568. draw_search_match(buffer, 0);
  8569. free(buffer);
  8570. }
  8571. }
  8572. continue;
  8573. }
  8574. }
  8575. if (env->mode != last_mode) {
  8576. redraw_statusbar();
  8577. redraw_commandline();
  8578. last_mode = env->mode;
  8579. }
  8580. if (env->mode == MODE_NORMAL) {
  8581. place_cursor_actual();
  8582. int key = bim_getkey(200);
  8583. if (handle_nav_buffer(key)) {
  8584. if (!handle_action(NORMAL_MAP, key))
  8585. if (!handle_action(NAVIGATION_MAP, key))
  8586. handle_action(ESCAPE_MAP, key);
  8587. }
  8588. reset_nav_buffer(key);
  8589. } else if (env->mode == MODE_INSERT) {
  8590. place_cursor_actual();
  8591. int key = bim_getkey(refresh ? 10 : 200);
  8592. if (key == KEY_TIMEOUT) {
  8593. if (refresh > 1) {
  8594. redraw_text();
  8595. } else if (refresh) {
  8596. redraw_line(env->line_no-1);
  8597. }
  8598. refresh = 0;
  8599. } else if (handle_action(INSERT_MAP, key)) {
  8600. refresh = 2;
  8601. } else if (handle_action(ESCAPE_MAP, key)) {
  8602. /* Do nothing */
  8603. } else if (key < KEY_ESCAPE) {
  8604. insert_char(key);
  8605. if (global_config.smart_complete) {
  8606. redraw_line(env->line_no-1);
  8607. while (omni_complete(1) == 1);
  8608. }
  8609. refresh |= 1;
  8610. }
  8611. } else if (env->mode == MODE_REPLACE) {
  8612. place_cursor_actual();
  8613. int key = bim_getkey(200);
  8614. if (key != KEY_TIMEOUT) {
  8615. if (handle_action(REPLACE_MAP, key)) {
  8616. redraw_text();
  8617. } else if (!handle_action(ESCAPE_MAP, key)) {
  8618. /* Perform replacement */
  8619. if (key < KEY_ESCAPE) {
  8620. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  8621. replace_char(key);
  8622. env->col_no += 1;
  8623. } else {
  8624. insert_char(key);
  8625. redraw_line(env->line_no-1);
  8626. }
  8627. set_preferred_column();
  8628. }
  8629. }
  8630. }
  8631. } else if (env->mode == MODE_LINE_SELECTION) {
  8632. place_cursor_actual();
  8633. int key = bim_getkey(200);
  8634. if (key == KEY_TIMEOUT) continue;
  8635. if (handle_nav_buffer(key)) {
  8636. if (!handle_action(LINE_SELECTION_MAP, key))
  8637. if (!handle_action(NAVIGATION_MAP, key))
  8638. handle_action(ESCAPE_MAP, key);
  8639. }
  8640. reset_nav_buffer(key);
  8641. if (env->mode == MODE_LINE_SELECTION) {
  8642. /* Mark current line */
  8643. _redraw_line(env->line_no,0);
  8644. _redraw_line(env->start_line,1);
  8645. /* Properly mark everything in the span we just moved through */
  8646. if (env->prev_line < env->line_no) {
  8647. for (int i = env->prev_line; i < env->line_no; ++i) {
  8648. _redraw_line(i,0);
  8649. }
  8650. env->prev_line = env->line_no;
  8651. } else if (env->prev_line > env->line_no) {
  8652. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8653. _redraw_line(i,0);
  8654. }
  8655. env->prev_line = env->line_no;
  8656. }
  8657. redraw_commandline();
  8658. }
  8659. } else if (env->mode == MODE_CHAR_SELECTION) {
  8660. place_cursor_actual();
  8661. int key = bim_getkey(200);
  8662. if (key == KEY_TIMEOUT) continue;
  8663. if (handle_nav_buffer(key)) {
  8664. if (!handle_action(CHAR_SELECTION_MAP, key))
  8665. if (!handle_action(NAVIGATION_MAP, key))
  8666. handle_action(ESCAPE_MAP, key);
  8667. }
  8668. reset_nav_buffer(key);
  8669. if (env->mode == MODE_CHAR_SELECTION) {
  8670. /* Mark current line */
  8671. _redraw_line_char(env->line_no,1);
  8672. /* Properly mark everything in the span we just moved through */
  8673. if (env->prev_line < env->line_no) {
  8674. for (int i = env->prev_line; i < env->line_no; ++i) {
  8675. _redraw_line_char(i,1);
  8676. }
  8677. env->prev_line = env->line_no;
  8678. } else if (env->prev_line > env->line_no) {
  8679. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8680. _redraw_line_char(i,1);
  8681. }
  8682. env->prev_line = env->line_no;
  8683. }
  8684. }
  8685. } else if (env->mode == MODE_COL_SELECTION) {
  8686. place_cursor_actual();
  8687. int key = bim_getkey(200);
  8688. if (key == KEY_TIMEOUT) continue;
  8689. if (handle_nav_buffer(key)) {
  8690. if (!handle_action(COL_SELECTION_MAP, key))
  8691. if (!handle_action(NAVIGATION_MAP, key))
  8692. handle_action(ESCAPE_MAP, key);
  8693. }
  8694. reset_nav_buffer(key);
  8695. if (env->mode == MODE_COL_SELECTION) {
  8696. _redraw_line_col(env->line_no, 0);
  8697. /* Properly mark everything in the span we just moved through */
  8698. if (env->prev_line < env->line_no) {
  8699. for (int i = env->prev_line; i < env->line_no; ++i) {
  8700. _redraw_line_col(i,0);
  8701. }
  8702. env->prev_line = env->line_no;
  8703. } else if (env->prev_line > env->line_no) {
  8704. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8705. _redraw_line_col(i,0);
  8706. }
  8707. env->prev_line = env->line_no;
  8708. }
  8709. redraw_commandline();
  8710. }
  8711. } else if (env->mode == MODE_COL_INSERT) {
  8712. int key = bim_getkey(refresh ? 10 : 200);
  8713. if (key == KEY_TIMEOUT) {
  8714. if (refresh) {
  8715. redraw_commandline();
  8716. redraw_text();
  8717. }
  8718. refresh = 0;
  8719. } else if (handle_action(COL_INSERT_MAP, key)) {
  8720. /* pass */
  8721. } else if (key < KEY_ESCAPE) {
  8722. insert_char_at_column(key);
  8723. refresh = 1;
  8724. }
  8725. } if (env->mode == MODE_DIRECTORY_BROWSE) {
  8726. place_cursor_actual();
  8727. int key = bim_getkey(200);
  8728. if (handle_nav_buffer(key)) {
  8729. if (!handle_action(DIRECTORY_BROWSE_MAP, key))
  8730. if (!handle_action(NAVIGATION_MAP, key))
  8731. handle_action(ESCAPE_MAP, key);
  8732. }
  8733. reset_nav_buffer(key);
  8734. }
  8735. }
  8736. }
  8737. /**
  8738. * Show help text for -?
  8739. */
  8740. static void show_usage(char * argv[]) {
  8741. #define _s "\033[3m"
  8742. #define _e "\033[0m\n"
  8743. printf(
  8744. "bim - Text editor\n"
  8745. "\n"
  8746. "usage: %s [options] [file]\n"
  8747. " %s [options] -- -\n"
  8748. "\n"
  8749. " -R " _s "open initial buffer read-only" _e
  8750. " -O " _s "set various options:" _e
  8751. " noscroll " _s "disable terminal scrolling" _e
  8752. " noaltscreen " _s "disable alternate screen buffer" _e
  8753. " nomouse " _s "disable mouse support" _e
  8754. " nounicode " _s "disable unicode display" _e
  8755. " nobright " _s "disable bright next" _e
  8756. " nohideshow " _s "disable togglging cursor visibility" _e
  8757. " nosyntax " _s "disable syntax highlighting on load" _e
  8758. " notitle " _s "disable title-setting escapes" _e
  8759. " history " _s "enable experimental undo/redo" _e
  8760. " -c,-C " _s "print file to stdout with syntax highlighting" _e
  8761. " " _s "-C includes line numbers, -c does not" _e
  8762. " -u " _s "override bimrc file" _e
  8763. " -? " _s "show this help text" _e
  8764. "\n"
  8765. "Long options:\n"
  8766. " --help " _s "show this help text" _e
  8767. " --version " _s "show version information and available plugins" _e
  8768. " --dump-mappings " _s "dump markdown description of key mappings" _e
  8769. " --dump-commands " _s "dump markdown description of all commands" _e
  8770. " --dump-config " _s "dump key mappings as a bimscript" _e
  8771. " --html FILE " _s "convert FILE to syntax-highlighted HTML" _e
  8772. "\n", argv[0], argv[0]);
  8773. #undef _e
  8774. #undef _s
  8775. }
  8776. void free_function(struct bim_function * func) {
  8777. do {
  8778. struct bim_function * next = func->next;
  8779. free(func->command);
  8780. free(func);
  8781. func = next;
  8782. } while (func);
  8783. }
  8784. int run_function(char * name) {
  8785. for (int i = 0; i < flex_user_functions_count; ++i) {
  8786. if (user_functions[i] && !strcmp(user_functions[i]->command, name)) {
  8787. /* Execute function */
  8788. struct bim_function * this = user_functions[i]->next;
  8789. while (this) {
  8790. char * tmp = strdup(this->command);
  8791. int result = process_command(tmp);
  8792. free(tmp);
  8793. if (result != 0) {
  8794. return result;
  8795. }
  8796. this = this->next;
  8797. }
  8798. return 0;
  8799. }
  8800. }
  8801. return -1;
  8802. }
  8803. int has_function(char * name) {
  8804. for (int i = 0; i < flex_user_functions_count; ++i) {
  8805. if (user_functions[i] && !strcmp(user_functions[i]->command, name)) {
  8806. return 1;
  8807. }
  8808. }
  8809. return 0;
  8810. }
  8811. BIM_COMMAND(call,"call","Call a function") {
  8812. if (argc < 2) {
  8813. render_error("Expected function name");
  8814. return 1;
  8815. }
  8816. int result = run_function(argv[1]);
  8817. if (result == -1) {
  8818. render_error("Undefined function: %s", argv[1]);
  8819. return 1;
  8820. }
  8821. return result;
  8822. }
  8823. BIM_COMMAND(try_call,"trycall","Call a function but return quietly if it fails") {
  8824. if (argc < 2) return 0;
  8825. run_function(argv[1]);
  8826. return 0;
  8827. }
  8828. BIM_COMMAND(list_functions,"listfunctions","List functions") {
  8829. render_commandline_message("");
  8830. for (int i = 0; i < flex_user_functions_count; ++i) {
  8831. render_commandline_message("%s\n", user_functions[i]->command);
  8832. }
  8833. pause_for_key();
  8834. return 0;
  8835. }
  8836. BIM_COMMAND(show_function,"showfunction","Show the commands in a function") {
  8837. if (argc < 2) return 1;
  8838. struct bim_function * this = NULL;
  8839. for (int i = 0; i < flex_user_functions_count; ++i) {
  8840. if (user_functions[i] && !strcmp(user_functions[i]->command, argv[1])) {
  8841. this = user_functions[i];
  8842. break;
  8843. }
  8844. }
  8845. if (!this) {
  8846. render_error("Not a function: %s", argv[1]);
  8847. return 1;
  8848. }
  8849. /* We really should rewrite this so syntax highlighting takes a highlighter */
  8850. struct syntax_definition * old_syntax = env->syntax;
  8851. env->syntax = find_syntax_calculator("bimcmd");
  8852. int i = 0;
  8853. while (this) {
  8854. /* Turn command into line */
  8855. line_t * tmp = calloc(sizeof(line_t) + sizeof(char_t) * strlen(this->command),1);
  8856. tmp->available = strlen(this->command);
  8857. unsigned char * t = (unsigned char *)this->command;
  8858. uint32_t state = 0;
  8859. uint32_t c = 0;
  8860. int col = 1;
  8861. while (*t) {
  8862. if (!decode(&state, &c, *t)) {
  8863. char_t _c = {codepoint_width(c), 0, c};
  8864. tmp = line_insert(tmp, _c, col - 1, -1);
  8865. col++;
  8866. }
  8867. t++;
  8868. }
  8869. render_commandline_message("");
  8870. render_line(tmp, global_config.term_width - 1, 0, -1);
  8871. printf("\n");
  8872. this = this->next;
  8873. i++;
  8874. if (this && i == global_config.term_height - 3) {
  8875. printf("(function continues)");
  8876. while (bim_getkey(200) == KEY_TIMEOUT);
  8877. }
  8878. }
  8879. /* Restore previous syntax */
  8880. env->syntax = old_syntax;
  8881. pause_for_key();
  8882. return 0;
  8883. }
  8884. BIM_COMMAND(runscript,"runscript","Run a script file") {
  8885. if (argc < 2) {
  8886. render_error("Expected a script to run");
  8887. return 1;
  8888. }
  8889. /* Run commands */
  8890. FILE * f;
  8891. char * home;
  8892. if (argv[1][0] == '~' && (home = getenv("HOME"))) {
  8893. char * tmp = malloc(strlen(argv[1]) + strlen(home) + 4);
  8894. sprintf(tmp,"%s%s", home, argv[1]+1);
  8895. f = fopen(tmp,"r");
  8896. free(tmp);
  8897. } else {
  8898. f = fopen(argv[1],"r");
  8899. }
  8900. if (!f) {
  8901. render_error("Failed to open script");
  8902. return 1;
  8903. }
  8904. int retval = 0;
  8905. char linebuf[4096];
  8906. int line = 1;
  8907. int was_collecting_function = 0;
  8908. char * function_name = NULL;
  8909. struct bim_function * new_function = NULL;
  8910. struct bim_function * last_function = NULL;
  8911. while (!feof(f)) {
  8912. memset(linebuf, 0, 4096);
  8913. fgets(linebuf, 4095, f);
  8914. /* Remove linefeed */
  8915. char * s = strstr(linebuf, "\n");
  8916. if (s) *s = '\0';
  8917. /* See if this is a special syntax element */
  8918. if (!strncmp(linebuf, "function ", 9)) {
  8919. /* Confirm we have a function name */
  8920. if (was_collecting_function) {
  8921. free_function(new_function);
  8922. render_error("Syntax error on line %d: attempt nest function while already defining function '%s'", line, function_name);
  8923. retval = 1;
  8924. break;
  8925. }
  8926. if (!strlen(linebuf+9)) {
  8927. render_error("Syntax error on line %d: function needs a name", line);
  8928. retval = 1;
  8929. break;
  8930. }
  8931. function_name = strdup(linebuf+9);
  8932. was_collecting_function = 1;
  8933. new_function = malloc(sizeof(struct bim_function));
  8934. new_function->command = strdup(function_name);
  8935. new_function->next = NULL;
  8936. last_function = new_function;
  8937. /* Set up function */
  8938. } else if (!strcmp(linebuf,"end")) {
  8939. if (!was_collecting_function) {
  8940. render_error("Syntax error on line %d: unexpected 'end'", line);
  8941. retval = 1;
  8942. break;
  8943. }
  8944. was_collecting_function = 0;
  8945. /* See if a function with this name is already defined */
  8946. int this = -1;
  8947. for (int i = 0; i < flex_user_functions_count; ++i) {
  8948. if (user_functions[i] && !strcmp(user_functions[i]->command, function_name)) {
  8949. this = i;
  8950. break;
  8951. }
  8952. }
  8953. if (this > -1) {
  8954. free_function(user_functions[this]);
  8955. user_functions[this] = new_function;
  8956. } else {
  8957. add_user_function(new_function);
  8958. if (strstr(function_name,"theme:") == function_name) {
  8959. add_colorscheme((struct theme_def){strdup(function_name+6), load_colorscheme_script});
  8960. }
  8961. }
  8962. free(function_name);
  8963. new_function = NULL;
  8964. last_function = NULL;
  8965. function_name = NULL;
  8966. } else if (was_collecting_function) {
  8967. /* Collect function */
  8968. last_function->next = malloc(sizeof(struct bim_function));
  8969. last_function = last_function->next;
  8970. char * s = linebuf;
  8971. while (*s == ' ') s++;
  8972. last_function->command = strdup(s);
  8973. last_function->next = NULL;
  8974. } else {
  8975. int result = process_command(linebuf);
  8976. if (result != 0) {
  8977. retval = result;
  8978. break;
  8979. }
  8980. }
  8981. line++;
  8982. }
  8983. if (was_collecting_function) {
  8984. free_function(new_function);
  8985. render_error("Syntax error on line %d: unexpected end of file while defining function '%s'", line, function_name);
  8986. retval = 1;
  8987. }
  8988. if (function_name) free(function_name);
  8989. fclose(f);
  8990. return retval;
  8991. }
  8992. BIM_COMMAND(rundir,"rundir","Run scripts from a directory, in unspecified order") {
  8993. if (argc < 2) return 1;
  8994. char * file = argv[1];
  8995. DIR * dirp = NULL;
  8996. if (file[0] == '~') {
  8997. char * home = getenv("HOME");
  8998. if (home) {
  8999. char * _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  9000. sprintf(_file, "%s%s", home, file+1);
  9001. dirp = opendir(_file);
  9002. free(_file);
  9003. }
  9004. } else {
  9005. dirp = opendir(file);
  9006. }
  9007. if (!dirp) {
  9008. render_error("Directory is not accessible: %s", argv[1]);
  9009. return 1;
  9010. }
  9011. struct dirent * ent = readdir(dirp);
  9012. while (ent) {
  9013. if (str_ends_with(ent->d_name,".bimscript")) {
  9014. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);
  9015. snprintf(tmp, strlen(file) + 1 + strlen(ent->d_name) + 1, "%s/%s", file, ent->d_name);
  9016. char * args[] = {"runscript",tmp,NULL};
  9017. bim_command_runscript("runscript", 2, args);
  9018. free(tmp);
  9019. }
  9020. ent = readdir(dirp);
  9021. }
  9022. return 0;
  9023. }
  9024. /**
  9025. * Load bimrc configuration file.
  9026. *
  9027. * At the moment, this a simple key=value list.
  9028. */
  9029. void load_bimrc(void) {
  9030. if (!global_config.bimrc_path) return;
  9031. /* Default is ~/.bimrc */
  9032. char * tmp = strdup(global_config.bimrc_path);
  9033. if (!*tmp) {
  9034. free(tmp);
  9035. return;
  9036. }
  9037. /* Parse ~ at the front of the path. */
  9038. if (*tmp == '~') {
  9039. char path[1024] = {0};
  9040. char * home = getenv("HOME");
  9041. if (!home) {
  9042. /* $HOME is unset? */
  9043. free(tmp);
  9044. return;
  9045. }
  9046. /* New path is $HOME/.bimrc */
  9047. snprintf(path, 1024, "%s%s", home, tmp+1);
  9048. free(tmp);
  9049. tmp = strdup(path);
  9050. }
  9051. struct stat statbuf;
  9052. if (stat(tmp, &statbuf)) return;
  9053. char * args[] = {"runscript", tmp, NULL};
  9054. if (bim_command_runscript("runscript", 2, args)) {
  9055. /* Wait */
  9056. render_error("Errors were encountered when loading bimrc. Press ENTER to continue.");
  9057. int c;
  9058. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  9059. }
  9060. }
  9061. /**
  9062. * Set some default values when certain terminals are detected.
  9063. */
  9064. void detect_weird_terminals(void) {
  9065. char * term = getenv("TERM");
  9066. if (term && !strcmp(term,"linux")) {
  9067. /* Linux VTs can't scroll. */
  9068. global_config.can_scroll = 0;
  9069. }
  9070. if (term && !strcmp(term,"cons25")) {
  9071. /* Dragonfly BSD console */
  9072. global_config.can_hideshow = 0;
  9073. global_config.can_altscreen = 0;
  9074. global_config.can_mouse = 0;
  9075. global_config.can_unicode = 0;
  9076. global_config.can_bright = 0;
  9077. }
  9078. if (term && !strcmp(term,"sortix")) {
  9079. /* sortix will spew title escapes to the screen, no good */
  9080. global_config.can_title = 0;
  9081. }
  9082. if (term && strstr(term,"tmux") == term) {
  9083. global_config.can_scroll = 0;
  9084. global_config.can_bce = 0;
  9085. }
  9086. if (term && strstr(term,"screen") == term) {
  9087. /* unfortunately */
  9088. global_config.can_24bit = 0;
  9089. global_config.can_italic = 0;
  9090. }
  9091. if (term && strstr(term,"toaru-vga") == term) {
  9092. global_config.can_24bit = 0; /* Also not strictly true */
  9093. global_config.can_256color = 0; /* Not strictly true */
  9094. }
  9095. if (!global_config.can_unicode) {
  9096. global_config.tab_indicator = strdup(">");
  9097. global_config.space_indicator = strdup("-");
  9098. } else {
  9099. global_config.tab_indicator = strdup("»");
  9100. global_config.space_indicator = strdup("·");
  9101. }
  9102. }
  9103. /**
  9104. * Run global initialization tasks
  9105. */
  9106. void initialize(void) {
  9107. /* Force empty locale */
  9108. setlocale(LC_ALL, "");
  9109. /* Set up default key mappings */
  9110. #define CLONE_MAP(map) do { \
  9111. int len = 0, i = 0; \
  9112. for (struct action_map * m = _ ## map; m->key != -1; m++, len++); \
  9113. map = malloc(sizeof(struct action_map) * (len + 1)); \
  9114. for (struct action_map * m = _ ## map; m->key != -1; m++, i++) { \
  9115. memcpy(&map[i], m, sizeof(struct action_map)); \
  9116. } \
  9117. map[i].key = -1; \
  9118. } while (0)
  9119. CLONE_MAP(NORMAL_MAP);
  9120. CLONE_MAP(INSERT_MAP);
  9121. CLONE_MAP(REPLACE_MAP);
  9122. CLONE_MAP(LINE_SELECTION_MAP);
  9123. CLONE_MAP(CHAR_SELECTION_MAP);
  9124. CLONE_MAP(COL_SELECTION_MAP);
  9125. CLONE_MAP(COL_INSERT_MAP);
  9126. CLONE_MAP(NAVIGATION_MAP);
  9127. CLONE_MAP(ESCAPE_MAP);
  9128. CLONE_MAP(COMMAND_MAP);
  9129. CLONE_MAP(SEARCH_MAP);
  9130. CLONE_MAP(INPUT_BUFFER_MAP);
  9131. #undef CLONE_MAP
  9132. /* Detect terminal quirks */
  9133. detect_weird_terminals();
  9134. /* Load bimrc */
  9135. load_bimrc();
  9136. /* Initialize space for buffers */
  9137. buffers_avail = 4;
  9138. buffers = malloc(sizeof(buffer_t *) * buffers_avail);
  9139. }
  9140. /**
  9141. * Initialize terminal for editor display.
  9142. */
  9143. void init_terminal(void) {
  9144. if (!isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9145. global_config.tty_in = STDERR_FILENO;
  9146. }
  9147. set_alternate_screen();
  9148. update_screen_size();
  9149. get_initial_termios();
  9150. set_unbuffered();
  9151. mouse_enable();
  9152. global_config.has_terminal = 1;
  9153. signal(SIGWINCH, SIGWINCH_handler);
  9154. signal(SIGCONT, SIGCONT_handler);
  9155. signal(SIGTSTP, SIGTSTP_handler);
  9156. }
  9157. struct action_def * find_action(void (*action)()) {
  9158. if (!action) return NULL;
  9159. for (int i = 0; i < flex_mappable_actions_count; ++i) {
  9160. if (action == mappable_actions[i].action) return &mappable_actions[i];
  9161. }
  9162. return NULL;
  9163. }
  9164. void dump_mapping(const char * description, struct action_map * map) {
  9165. printf("## %s\n", description);
  9166. printf("\n");
  9167. printf("| **Key** | **Actio