bim.c 146 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. *
  3. * Copyright (C) 2012-2018 K. Lange
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. *
  17. * bim - Text editor
  18. *
  19. * Bim is inspired by vim, and its name is short for "Bad IMitation".
  20. *
  21. * Bim supports syntax highlighting, extensive editing, line selection
  22. * and copy-paste, undo/redo stack, forward and backward search, and can
  23. * be built for ToaruOS, Sortix, Linux, macOS, and BSDs.
  24. */
  25. #define _XOPEN_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 <sys/types.h>
  41. #include <sys/ioctl.h>
  42. #include <sys/stat.h>
  43. #define BIM_VERSION "1.0.2"
  44. #define BIM_COPYRIGHT "Copyright 2013-2018 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  45. #define BLOCK_SIZE 4096
  46. #define ENTER_KEY '\n'
  47. #define BACKSPACE_KEY 0x08
  48. #define DELETE_KEY 0x7F
  49. /**
  50. * Theming data
  51. *
  52. * This is all overridden by a load_colorscheme_ method.
  53. * The default is to load_colorscheme_ansi, but config
  54. * files can be used to set a different default theme.
  55. */
  56. const char * COLOR_FG = "@17";
  57. const char * COLOR_BG = "@0";
  58. const char * COLOR_ALT_FG = "@17";
  59. const char * COLOR_ALT_BG = "@0";
  60. const char * COLOR_NUMBER_FG = "@17";
  61. const char * COLOR_NUMBER_BG = "@0";
  62. const char * COLOR_STATUS_FG = "@17";
  63. const char * COLOR_STATUS_BG = "@0";
  64. const char * COLOR_TABBAR_BG = "@0";
  65. const char * COLOR_TAB_BG = "@0";
  66. const char * COLOR_ERROR_FG = "@17";
  67. const char * COLOR_ERROR_BG = "@0";
  68. const char * COLOR_SEARCH_FG = "@17";
  69. const char * COLOR_SEARCH_BG = "@0";
  70. const char * COLOR_KEYWORD = "@17";
  71. const char * COLOR_STRING = "@17";
  72. const char * COLOR_COMMENT = "@17";
  73. const char * COLOR_TYPE = "@17";
  74. const char * COLOR_PRAGMA = "@17";
  75. const char * COLOR_NUMERAL = "@17";
  76. const char * COLOR_SELECTFG = "@0";
  77. const char * COLOR_SELECTBG = "@17";
  78. const char * COLOR_RED = "@1";
  79. const char * COLOR_GREEN = "@2";
  80. const char * current_theme = "none";
  81. /**
  82. * Syntax highlighting flags.
  83. */
  84. #define FLAG_NONE 0
  85. #define FLAG_KEYWORD 1
  86. #define FLAG_STRING 2
  87. #define FLAG_COMMENT 3
  88. #define FLAG_TYPE 4
  89. #define FLAG_PRAGMA 5
  90. #define FLAG_NUMERAL 6
  91. #define FLAG_SELECT 7
  92. #define FLAG_STRING2 8
  93. #define FLAG_DIFFPLUS 9
  94. #define FLAG_DIFFMINUS 10
  95. #define FLAG_CONTINUES (1 << 6)
  96. /**
  97. * Convert syntax hilighting flag to color code
  98. */
  99. const char * flag_to_color(int _flag) {
  100. int flag = _flag & 0x3F;
  101. switch (flag) {
  102. case FLAG_KEYWORD:
  103. return COLOR_KEYWORD;
  104. case FLAG_STRING:
  105. case FLAG_STRING2: /* allows python to differentiate " and ' */
  106. return COLOR_STRING;
  107. case FLAG_COMMENT:
  108. return COLOR_COMMENT;
  109. case FLAG_TYPE:
  110. return COLOR_TYPE;
  111. case FLAG_NUMERAL:
  112. return COLOR_NUMERAL;
  113. case FLAG_PRAGMA:
  114. return COLOR_PRAGMA;
  115. case FLAG_DIFFPLUS:
  116. return COLOR_GREEN;
  117. case FLAG_DIFFMINUS:
  118. return COLOR_RED;
  119. case FLAG_SELECT:
  120. return COLOR_FG;
  121. default:
  122. return COLOR_FG;
  123. }
  124. }
  125. /**
  126. * Line buffer definitions
  127. *
  128. * Lines are essentially resizable vectors of char_t structs,
  129. * which represent single codepoints in the file.
  130. */
  131. typedef struct {
  132. uint32_t display_width:4;
  133. uint32_t flags:7;
  134. uint32_t codepoint:21;
  135. } __attribute__((packed)) char_t;
  136. /**
  137. * Lines have available and actual lengths, describing
  138. * how much space was allocated vs. how much is being
  139. * used at the moment.
  140. */
  141. typedef struct {
  142. int available;
  143. int actual;
  144. int istate;
  145. char_t text[0];
  146. } line_t;
  147. /**
  148. * Global configuration state
  149. */
  150. struct {
  151. /* Terminal size */
  152. int term_width, term_height;
  153. int bottom_size;
  154. /* Command-line parameters */
  155. int hilight_on_open;
  156. int initial_file_is_read_only;
  157. line_t ** yanks;
  158. size_t yank_count;
  159. int yank_is_full_lines;
  160. int tty_in;
  161. const char * bimrc_path;
  162. int can_scroll;
  163. int can_hideshow;
  164. int can_altscreen;
  165. int can_mouse;
  166. int can_unicode;
  167. int can_bright;
  168. int can_title;
  169. int can_bce;
  170. int history_enabled;
  171. int cursor_padding;
  172. } global_config = {
  173. 0, /* term_width */
  174. 0, /* term_height */
  175. 2, /* bottom_size */
  176. 1, /* hilight_on_open */
  177. 0, /* initial_file_is_read_only */
  178. NULL, /* yanks */
  179. 0, /* yank_count */
  180. 0,
  181. STDIN_FILENO, /* tty_in */
  182. "~/.bimrc", /* bimrc_path */
  183. 1,
  184. 1,
  185. 1,
  186. 1,
  187. 1,
  188. 1,
  189. 1,
  190. 1,
  191. 1,
  192. 4, /* cursor padding */
  193. };
  194. void redraw_line(int j, int x);
  195. /**
  196. * Special implementation of getch with a timeout
  197. */
  198. int _bim_unget = -1;
  199. void bim_unget(int c) {
  200. _bim_unget = c;
  201. }
  202. #define bim_getch() bim_getch_timeout(200)
  203. int bim_getch_timeout(int timeout) {
  204. if (_bim_unget != -1) {
  205. int out = _bim_unget;
  206. _bim_unget = -1;
  207. return out;
  208. }
  209. struct pollfd fds[1];
  210. fds[0].fd = global_config.tty_in;
  211. fds[0].events = POLLIN;
  212. int ret = poll(fds,1,timeout);
  213. if (ret > 0 && fds[0].revents & POLLIN) {
  214. unsigned char buf[1];
  215. read(global_config.tty_in, buf, 1);
  216. return buf[0];
  217. } else {
  218. return -1;
  219. }
  220. }
  221. #define HISTORY_SENTINEL 0
  222. #define HISTORY_INSERT 1
  223. #define HISTORY_DELETE 2
  224. #define HISTORY_REPLACE 3
  225. #define HISTORY_REMOVE_LINE 4
  226. #define HISTORY_ADD_LINE 5
  227. #define HISTORY_REPLACE_LINE 6
  228. #define HISTORY_MERGE_LINES 7
  229. #define HISTORY_SPLIT_LINE 8
  230. #define HISTORY_BREAK 10
  231. typedef struct history {
  232. struct history * previous;
  233. struct history * next;
  234. int type;
  235. union {
  236. struct {
  237. int lineno;
  238. int offset;
  239. int codepoint;
  240. int old_codepoint;
  241. } insert_delete_replace;
  242. struct {
  243. int lineno;
  244. line_t * contents;
  245. line_t * old_contents;
  246. } remove_replace_line;
  247. struct {
  248. int lineno;
  249. int split;
  250. } add_merge_split_lines;
  251. };
  252. } history_t;
  253. /**
  254. * Buffer data
  255. *
  256. * A buffer describes a file, and stores
  257. * its name as well as the editor state
  258. * (cursor offsets, etc.) and the actual
  259. * line buffers.
  260. */
  261. typedef struct _env {
  262. short loading:1;
  263. short tabs:1;
  264. short modified:1;
  265. short readonly:1;
  266. short indent:1;
  267. short mode;
  268. short tabstop;
  269. char * file_name;
  270. int offset;
  271. int coffset;
  272. int line_no;
  273. int line_count;
  274. int line_avail;
  275. int col_no;
  276. uint32_t * search;
  277. struct syntax_definition * syntax;
  278. line_t ** lines;
  279. history_t * history;
  280. history_t * last_save_history;
  281. } buffer_t;
  282. /**
  283. * Pointer to current active buffer
  284. */
  285. buffer_t * env;
  286. /**
  287. * Editor modes (like in vim)
  288. */
  289. #define MODE_NORMAL 0
  290. #define MODE_INSERT 1
  291. #define MODE_LINE_SELECTION 2
  292. #define MODE_REPLACE 3
  293. #define MODE_CHAR_SELECTION 4
  294. /**
  295. * Available buffers
  296. */
  297. int buffers_len;
  298. int buffers_avail;
  299. buffer_t ** buffers;
  300. /**
  301. * Create a new buffer
  302. */
  303. buffer_t * buffer_new(void) {
  304. if (buffers_len == buffers_avail) {
  305. /* If we are out of buffer space, expand the buffers vector */
  306. buffers_avail *= 2;
  307. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  308. }
  309. /* Allocate a new buffer */
  310. buffers[buffers_len] = malloc(sizeof(buffer_t));
  311. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  312. buffers_len++;
  313. return buffers[buffers_len-1];
  314. }
  315. /**
  316. * Close a buffer
  317. */
  318. buffer_t * buffer_close(buffer_t * buf) {
  319. int i;
  320. /* Locate the buffer in the buffer pointer vector */
  321. for (i = 0; i < buffers_len; i++) {
  322. if (buf == buffers[i])
  323. break;
  324. }
  325. /* Invalid buffer? */
  326. if (i == buffers_len) {
  327. return env; /* wtf */
  328. }
  329. /* Remove the buffer from the vector, moving others up */
  330. if (i != buffers_len - 1) {
  331. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  332. }
  333. /* There is one less buffer */
  334. buffers_len--;
  335. if (!buffers_len) {
  336. /* There are no more buffers. */
  337. return NULL;
  338. }
  339. /* If this was the last buffer, return the previous last buffer */
  340. if (i == buffers_len) {
  341. return buffers[buffers_len-1];
  342. }
  343. /* Otherwise return the new last buffer */
  344. return buffers[i];
  345. }
  346. /**
  347. * Themes
  348. */
  349. /* Based on the wombat256 theme for vim */
  350. void load_colorscheme_wombat(void) {
  351. COLOR_FG = "5;230";
  352. COLOR_BG = "5;235";
  353. COLOR_ALT_FG = "5;244";
  354. COLOR_ALT_BG = "5;236";
  355. COLOR_NUMBER_BG = "5;232";
  356. COLOR_NUMBER_FG = "5;101";
  357. COLOR_STATUS_FG = "5;230";
  358. COLOR_STATUS_BG = "5;238";
  359. COLOR_TABBAR_BG = "5;230";
  360. COLOR_TAB_BG = "5;248";
  361. COLOR_KEYWORD = "5;117";
  362. COLOR_STRING = "5;113";
  363. COLOR_COMMENT = "5;102;3";
  364. COLOR_TYPE = "5;185";
  365. COLOR_PRAGMA = "5;173";
  366. COLOR_NUMERAL = COLOR_PRAGMA;
  367. COLOR_ERROR_FG = "5;15";
  368. COLOR_ERROR_BG = "5;196";
  369. COLOR_SEARCH_FG = "5;234";
  370. COLOR_SEARCH_BG = "5;226";
  371. COLOR_SELECTFG = "5;235";
  372. COLOR_SELECTBG = "5;230";
  373. COLOR_RED = "@1";
  374. COLOR_GREEN = "@2";
  375. current_theme = "wombat";
  376. }
  377. /* "City Lights" based on citylights.xyz */
  378. void load_colorscheme_citylights(void) {
  379. COLOR_FG = "2;151;178;198";
  380. COLOR_BG = "2;29;37;44";
  381. COLOR_ALT_FG = "2;45;55;65";
  382. COLOR_ALT_BG = "2;33;42;50";
  383. COLOR_NUMBER_FG = "2;71;89;103";
  384. COLOR_NUMBER_BG = "2;37;47;56";
  385. COLOR_STATUS_FG = "2;116;144;166";
  386. COLOR_STATUS_BG = "2;53;67;78";
  387. COLOR_TABBAR_BG = "2;37;47;56";
  388. COLOR_TAB_BG = "2;29;37;44";
  389. COLOR_KEYWORD = "2;94;196;255";
  390. COLOR_STRING = "2;83;154;252";
  391. COLOR_COMMENT = "2;107;133;153;3";
  392. COLOR_TYPE = "2;139;212;156";
  393. COLOR_PRAGMA = "2;0;139;148";
  394. COLOR_NUMERAL = "2;207;118;132";
  395. COLOR_ERROR_FG = "5;15";
  396. COLOR_ERROR_BG = "5;196";
  397. COLOR_SEARCH_FG = "5;234";
  398. COLOR_SEARCH_BG = "5;226";
  399. COLOR_SELECTFG = "2;29;37;44";
  400. COLOR_SELECTBG = "2;151;178;198";
  401. COLOR_RED = "2;222;53;53";
  402. COLOR_GREEN = "2;55;167;0";
  403. current_theme = "citylights";
  404. }
  405. /* Solarized Dark, popular theme */
  406. void load_colorscheme_solarized_dark(void) {
  407. COLOR_FG = "2;147;161;161";
  408. COLOR_BG = "2;0;43;54";
  409. COLOR_ALT_FG = "2;147;161;161";
  410. COLOR_ALT_BG = "2;7;54;66";
  411. COLOR_NUMBER_FG = "2;131;148;149";
  412. COLOR_NUMBER_BG = "2;7;54;66";
  413. COLOR_STATUS_FG = "2;131;148;150";
  414. COLOR_STATUS_BG = "2;7;54;66";
  415. COLOR_TABBAR_BG = "2;7;54;66";
  416. COLOR_TAB_BG = "2;131;148;150";
  417. COLOR_KEYWORD = "2;133;153;0";
  418. COLOR_STRING = "2;42;161;152";
  419. COLOR_COMMENT = "2;101;123;131";
  420. COLOR_TYPE = "2;181;137;0";
  421. COLOR_PRAGMA = "2;203;75;22";
  422. COLOR_NUMERAL = "2;220;50;47";
  423. COLOR_ERROR_FG = "5;15";
  424. COLOR_ERROR_BG = "5;196";
  425. COLOR_SEARCH_FG = "5;234";
  426. COLOR_SEARCH_BG = "5;226";
  427. COLOR_SELECTFG = "2;0;43;54";
  428. COLOR_SELECTBG = "2;147;161;161";
  429. COLOR_RED = "2;222;53;53";
  430. COLOR_GREEN = "2;55;167;0";
  431. current_theme = "solarized-dark";
  432. }
  433. /* Custom theme */
  434. void load_colorscheme_sunsmoke(void) {
  435. COLOR_FG = "2;230;230;230";
  436. COLOR_BG = "2;31;31;31";
  437. COLOR_ALT_FG = "2;122;122;122";
  438. COLOR_ALT_BG = "2;46;43;46";
  439. COLOR_NUMBER_FG = "2;150;139;57";
  440. COLOR_NUMBER_BG = "2;0;0;0";
  441. COLOR_STATUS_FG = "2;230;230;230";
  442. COLOR_STATUS_BG = "2;71;64;58";
  443. COLOR_TABBAR_BG = "2;71;64;58";
  444. COLOR_TAB_BG = "2;71;64;58";
  445. COLOR_KEYWORD = "2;51;162;230";
  446. COLOR_STRING = "2;72;176;72";
  447. COLOR_COMMENT = "2;158;153;129;3";
  448. COLOR_TYPE = "2;230;206;110";
  449. COLOR_PRAGMA = "2;194;70;54";
  450. COLOR_NUMERAL = "2;230;43;127";
  451. COLOR_ERROR_FG = "5;15";
  452. COLOR_ERROR_BG = "5;196";
  453. COLOR_SEARCH_FG = "5;234";
  454. COLOR_SEARCH_BG = "5;226";
  455. COLOR_SELECTFG = "2;0;43;54";
  456. COLOR_SELECTBG = "2;147;161;161";
  457. COLOR_RED = "2;222;53;53";
  458. COLOR_GREEN = "2;55;167;0";
  459. current_theme = "sunsmoke";
  460. }
  461. /* 16-color theme, default */
  462. void load_colorscheme_ansi(void) {
  463. COLOR_FG = global_config.can_bright ? "@17" : "@7";
  464. COLOR_BG = global_config.can_bright ? "@9" : "@0";
  465. COLOR_ALT_FG = global_config.can_bright ? "@10" : "@5";
  466. COLOR_ALT_BG = "@9";
  467. COLOR_NUMBER_FG = "@3";
  468. COLOR_NUMBER_BG = "@9";
  469. COLOR_STATUS_FG = global_config.can_bright ? "@17" : "@7";
  470. COLOR_STATUS_BG = "@4";
  471. COLOR_TABBAR_BG = "@4";
  472. COLOR_TAB_BG = "@4";
  473. COLOR_KEYWORD = global_config.can_bright ? "@14" : "@4";
  474. COLOR_STRING = "@2";
  475. COLOR_COMMENT = global_config.can_bright ? "@10" : "@5";
  476. COLOR_TYPE = "@3";
  477. COLOR_PRAGMA = "@1";
  478. COLOR_NUMERAL = "@1";
  479. COLOR_ERROR_FG = global_config.can_bright ? "@17" : "@7";
  480. COLOR_ERROR_BG = "@1";
  481. COLOR_SEARCH_FG = "@0";
  482. COLOR_SEARCH_BG = global_config.can_bright ? "@13" : "@3";
  483. COLOR_SELECTBG = global_config.can_bright ? "@17" : "@7";
  484. COLOR_SELECTFG = "@0";
  485. COLOR_RED = "@1";
  486. COLOR_GREEN = "@2";
  487. current_theme = "ansi";
  488. }
  489. struct theme_def {
  490. const char * name;
  491. void (*load)(void);
  492. } themes[] = {
  493. {"wombat", load_colorscheme_wombat},
  494. {"citylights", load_colorscheme_citylights},
  495. {"solarized-dark", load_colorscheme_solarized_dark},
  496. {"ansi", load_colorscheme_ansi},
  497. {"sunsmoke", load_colorscheme_sunsmoke},
  498. {NULL, NULL}
  499. };
  500. /**
  501. * Syntax definition for C
  502. */
  503. int syn_c_iskeywordchar(int c) {
  504. if (isalnum(c)) return 1;
  505. if (c == '_') return 1;
  506. return 0;
  507. }
  508. static char * syn_c_keywords[] = {
  509. "while","if","for","continue","return","break","switch","case","sizeof",
  510. "struct","union","typedef","do","default","else","goto",
  511. "alignas","alignof","offsetof",
  512. /* C++ stuff */
  513. "public","private","class","using","namespace",
  514. NULL
  515. };
  516. static char * syn_c_types[] = {
  517. "static","int","char","short","float","double","void","unsigned","volatile","const",
  518. "register","long","inline","restrict","enum","auto","extern","bool","complex",
  519. "uint8_t","uint16_t","uint32_t","uint64_t",
  520. "int8_t","int16_t","int32_t","int64_t","FILE",
  521. NULL
  522. };
  523. static char * syn_c_special[] = {
  524. "NULL",
  525. "stdin","stdout","stderr",
  526. "STDIN_FILENO","STDOUT_FILENO","STDERR_FILENO",
  527. NULL
  528. };
  529. static int syn_c_extended(line_t * line, int i, int c, int last, int * out_left) {
  530. if (i == 0 && c == '#') {
  531. *out_left = line->actual+1;
  532. if (line->text[line->actual-1].codepoint == '\\') {
  533. return FLAG_PRAGMA | FLAG_CONTINUES;
  534. }
  535. return FLAG_PRAGMA;
  536. }
  537. if ((!last || !syn_c_iskeywordchar(last)) && syn_c_iskeywordchar(c)) {
  538. int j = i;
  539. for (int s = 0; syn_c_special[s]; ++s) {
  540. int d = 0;
  541. while (j + d < line->actual && line->text[j+d].codepoint == syn_c_special[s][d]) d++;
  542. if (syn_c_special[s][d] == '\0' && (j+d > line->actual || !syn_c_iskeywordchar(line->text[j+d].codepoint))) {
  543. *out_left = d-1;
  544. return FLAG_NUMERAL;
  545. }
  546. }
  547. }
  548. if ((!last || !syn_c_iskeywordchar(last)) && isdigit(c)) {
  549. if (c == '0' && i < line->actual - 1 && line->text[i+1].codepoint == 'x') {
  550. int j = 2;
  551. for (; i + j < line->actual && isxdigit(line->text[i+j].codepoint); ++j);
  552. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  553. return FLAG_NONE;
  554. }
  555. *out_left = j - 1;
  556. return FLAG_NUMERAL;
  557. } else {
  558. int j = 1;
  559. while (i + j < line->actual && isdigit(line->text[i+j].codepoint)) {
  560. j++;
  561. }
  562. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  563. return FLAG_NONE;
  564. }
  565. *out_left = j - 1;
  566. return FLAG_NUMERAL;
  567. }
  568. }
  569. if (c == '/') {
  570. if (i < line->actual - 1 && line->text[i+1].codepoint == '/') {
  571. *out_left = (line->actual + 1) - i;
  572. return FLAG_COMMENT;
  573. }
  574. if (i < line->actual - 1 && line->text[i+1].codepoint == '*') {
  575. int last = 0;
  576. for (int j = i + 2; j < line->actual; ++j) {
  577. int c = line->text[j].codepoint;
  578. if (c == '/' && last == '*') {
  579. *out_left = j - i;
  580. return FLAG_COMMENT;
  581. }
  582. last = c;
  583. }
  584. /* TODO multiline - update next */
  585. *out_left = (line->actual + 1) - i;
  586. return FLAG_COMMENT | FLAG_CONTINUES;
  587. }
  588. }
  589. if (c == '\'') {
  590. if (i < line->actual - 3 && line->text[i+1].codepoint == '\\' &&
  591. line->text[i+3].codepoint == '\'') {
  592. *out_left = 3;
  593. return FLAG_NUMERAL;
  594. }
  595. if (i < line->actual - 2 && line->text[i+2].codepoint == '\'') {
  596. *out_left = 2;
  597. return FLAG_NUMERAL;
  598. }
  599. }
  600. if (c == '"') {
  601. int last = 0;
  602. for (int j = i+1; j < line->actual; ++j) {
  603. int c = line->text[j].codepoint;
  604. if (last != '\\' && c == '"') {
  605. *out_left = j - i;
  606. return FLAG_STRING;
  607. }
  608. if (last == '\\' && c == '\\') {
  609. last = 0;
  610. }
  611. last = c;
  612. }
  613. *out_left = (line->actual + 1) - i; /* unterminated string */
  614. return FLAG_STRING;
  615. }
  616. return 0;
  617. }
  618. char * syn_c_ext[] = {".c",".h",".cpp",".hpp",".c++",".h++",NULL};
  619. static int syn_c_finish(line_t * line, int * left, int state) {
  620. if (state == (FLAG_COMMENT | FLAG_CONTINUES)) {
  621. int last = 0;
  622. for (int i = 0; i < line->actual; ++i) {
  623. if (line->text[i].codepoint == '/' && last == '*') {
  624. *left = i+2;
  625. return FLAG_COMMENT;
  626. }
  627. last = line->text[i].codepoint;
  628. }
  629. return FLAG_COMMENT | FLAG_CONTINUES;
  630. }
  631. if (state == (FLAG_PRAGMA | FLAG_CONTINUES)) {
  632. *left = line->actual + 1;
  633. if (line->text[line->actual-1].codepoint == '\\') {
  634. return FLAG_PRAGMA | FLAG_CONTINUES;
  635. }
  636. return FLAG_PRAGMA;
  637. }
  638. return 0;
  639. }
  640. /**
  641. * Syntax definition for Python
  642. */
  643. static char * syn_py_keywords[] = {
  644. "class","def","return","del","if","else","elif",
  645. "for","while","continue","break","assert",
  646. "as","and","or","except","finally","from",
  647. "global","import","in","is","lambda","with",
  648. "nonlocal","not","pass","raise","try","yield",
  649. NULL
  650. };
  651. static char * syn_py_types[] = {
  652. "True","False","None",
  653. "object","set","dict","int","str","bytes",
  654. NULL
  655. };
  656. static int syn_py_extended(line_t * line, int i, int c, int last, int * out_left) {
  657. if (i == 0 && c == 'i') {
  658. /* Check for import */
  659. char * import = "import ";
  660. for (int j = 0; j < line->actual + 1; ++j) {
  661. if (import[j] == '\0') {
  662. *out_left = j - 2;
  663. return FLAG_PRAGMA;
  664. }
  665. if (line->text[j].codepoint != import[j]) break;
  666. }
  667. }
  668. if (c == '#') {
  669. *out_left = (line->actual + 1) - i;
  670. return FLAG_COMMENT;
  671. }
  672. if (c == '@') {
  673. for (int j = i+1; j < line->actual + 1; ++j) {
  674. if (!syn_c_iskeywordchar(line->text[j].codepoint)) {
  675. *out_left = j - i - 1;
  676. return FLAG_PRAGMA;
  677. }
  678. *out_left = (line->actual + 1) - i;
  679. return FLAG_PRAGMA;
  680. }
  681. }
  682. if ((!last || !syn_c_iskeywordchar(last)) && isdigit(c)) {
  683. if (c == '0' && i < line->actual - 1 && line->text[i+1].codepoint == 'x') {
  684. int j = 2;
  685. for (; i + j < line->actual && isxdigit(line->text[i+j].codepoint); ++j);
  686. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  687. return FLAG_NONE;
  688. }
  689. *out_left = j - 1;
  690. return FLAG_NUMERAL;
  691. } else {
  692. int j = 1;
  693. while (i + j < line->actual && isdigit(line->text[i+j].codepoint)) {
  694. j++;
  695. }
  696. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  697. return FLAG_NONE;
  698. }
  699. *out_left = j - 1;
  700. return FLAG_NUMERAL;
  701. }
  702. }
  703. if (line->text[i].codepoint == '\'') {
  704. if (i + 2 < line->actual && line->text[i+1].codepoint == '\'' && line->text[i+2].codepoint == '\'') {
  705. /* Begin multiline */
  706. for (int j = i + 3; j < line->actual - 2; ++j) {
  707. if (line->text[j].codepoint == '\'' &&
  708. line->text[j+1].codepoint == '\'' &&
  709. line->text[j+2].codepoint == '\'') {
  710. *out_left = (j+2) - i;
  711. return FLAG_STRING;
  712. }
  713. }
  714. return FLAG_STRING | FLAG_CONTINUES;
  715. }
  716. int last = 0;
  717. for (int j = i+1; j < line->actual; ++j) {
  718. int c = line->text[j].codepoint;
  719. if (last != '\\' && c == '\'') {
  720. *out_left = j - i;
  721. return FLAG_STRING;
  722. }
  723. if (last == '\\' && c == '\\') {
  724. last = 0;
  725. }
  726. last = c;
  727. }
  728. *out_left = (line->actual + 1) - i; /* unterminated string */
  729. return FLAG_STRING;
  730. }
  731. if (line->text[i].codepoint == '"') {
  732. if (i + 2 < line->actual && line->text[i+1].codepoint == '"' && line->text[i+2].codepoint == '"') {
  733. /* Begin multiline */
  734. for (int j = i + 3; j < line->actual - 2; ++j) {
  735. if (line->text[j].codepoint == '"' &&
  736. line->text[j+1].codepoint == '"' &&
  737. line->text[j+2].codepoint == '"') {
  738. *out_left = (j+2) - i;
  739. return FLAG_STRING;
  740. }
  741. }
  742. return FLAG_STRING2 | FLAG_CONTINUES;
  743. }
  744. int last = 0;
  745. for (int j = i+1; j < line->actual; ++j) {
  746. int c = line->text[j].codepoint;
  747. if (last != '\\' && c == '"') {
  748. *out_left = j - i;
  749. return FLAG_STRING;
  750. }
  751. if (last == '\\' && c == '\\') {
  752. last = 0;
  753. }
  754. last = c;
  755. }
  756. *out_left = (line->actual + 1) - i; /* unterminated string */
  757. return FLAG_STRING;
  758. }
  759. return 0;
  760. }
  761. static int syn_py_finish(line_t * line, int * left, int state) {
  762. /* TODO support multiline quotes */
  763. if (state == (FLAG_STRING | FLAG_CONTINUES)) {
  764. for (int j = 0; j < line->actual - 2; ++j) {
  765. if (line->text[j].codepoint == '\'' &&
  766. line->text[j+1].codepoint == '\'' &&
  767. line->text[j+2].codepoint == '\'') {
  768. *left = (j+3);
  769. return FLAG_STRING;
  770. }
  771. }
  772. return FLAG_STRING | FLAG_CONTINUES;
  773. }
  774. if (state == (FLAG_STRING2 | FLAG_CONTINUES)) {
  775. for (int j = 0; j < line->actual - 2; ++j) {
  776. if (line->text[j].codepoint == '"' &&
  777. line->text[j+1].codepoint == '"' &&
  778. line->text[j+2].codepoint == '"') {
  779. *left = (j+3);
  780. return FLAG_STRING2;
  781. }
  782. }
  783. return FLAG_STRING2 | FLAG_CONTINUES;
  784. }
  785. return 0;
  786. }
  787. char * syn_py_ext[] = {".py",NULL};
  788. /**
  789. * Syntax definition for ToaruOS shell
  790. */
  791. static char * syn_sh_keywords[] = {
  792. "cd","exit","export","help","history","if",
  793. "empty?","equals?","return","export-cmd",
  794. "source","exec","not","while","then","else",
  795. NULL,
  796. };
  797. static int variable_char(uint8_t c) {
  798. if (c >= 'A' && c <= 'Z') return 1;
  799. if (c >= 'a' && c <= 'z') return 1;
  800. if (c >= '0' && c <= '9') return 1;
  801. if (c == '_') return 1;
  802. if (c == '?') return 1;
  803. return 0;
  804. }
  805. static int syn_sh_extended(line_t * line, int i, int c, int last, int * out_left) {
  806. (void)last;
  807. if (c == '#' && last != '\\') {
  808. *out_left = (line->actual + 1) - i;
  809. return FLAG_COMMENT;
  810. }
  811. if (line->text[i].codepoint == '\'' && last != '\\') {
  812. int last = 0;
  813. for (int j = i+1; j < line->actual + 1; ++j) {
  814. int c = line->text[j].codepoint;
  815. if (last != '\\' && c == '\'') {
  816. *out_left = j - i;
  817. return FLAG_STRING;
  818. }
  819. if (last == '\\' && c == '\\') {
  820. last = 0;
  821. }
  822. last = c;
  823. }
  824. *out_left = (line->actual + 1) - i; /* unterminated string */
  825. return FLAG_STRING;
  826. }
  827. if (line->text[i].codepoint == '$' && last != '\\') {
  828. if (i < line->actual - 1 && line->text[i+1].codepoint == '{') {
  829. int j = i + 2;
  830. for (; j < line->actual+1; ++j) {
  831. if (line->text[j].codepoint == '}') break;
  832. }
  833. *out_left = (j - i);
  834. return FLAG_NUMERAL;
  835. }
  836. int j = i + 1;
  837. for (; j < line->actual + 1; ++j) {
  838. if (!variable_char(line->text[j].codepoint)) break;
  839. }
  840. *out_left = (j - i) - 1;
  841. return FLAG_NUMERAL;
  842. }
  843. if (line->text[i].codepoint == '"' && last != '\\') {
  844. int last = 0;
  845. for (int j = i+1; j < line->actual + 1; ++j) {
  846. int c = line->text[j].codepoint;
  847. if (last != '\\' && c == '"') {
  848. *out_left = j - i;
  849. return FLAG_STRING;
  850. }
  851. if (last == '\\' && c == '\\') {
  852. last = 0;
  853. }
  854. last = c;
  855. }
  856. *out_left = (line->actual + 1) - i; /* unterminated string */
  857. return FLAG_STRING;
  858. }
  859. return 0;
  860. }
  861. static int syn_sh_iskeywordchar(int c) {
  862. if (isalnum(c)) return 1;
  863. if (c == '-') return 1;
  864. if (c == '_') return 1;
  865. if (c == '?') return 1;
  866. return 0;
  867. }
  868. static char * syn_sh_ext[] = {".sh",".eshrc",".esh",NULL};
  869. static char * syn_make_ext[] = {"Makefile","makefile","GNUmakefile",".mak",NULL};
  870. static char * syn_make_commands[] = {
  871. "define","endef","undefine","ifdef","ifndef","ifeq","ifneq","else","endif",
  872. "include","sinclude","override","export","unexport","private","vpath",
  873. "-include",
  874. NULL
  875. };
  876. static char * syn_make_functions[] = {
  877. "subst","patsubst","findstring","filter","filter-out",
  878. "sort","word","words","wordlist","firstword","lastword",
  879. "dir","notdir","suffix","basename","addsuffix","addprefix",
  880. "join","wildcard","realpath","abspath","error","warning",
  881. "shell","origin","flavor","foreach","if","or","and",
  882. "call","eval","file","value",
  883. NULL
  884. };
  885. static int syn_make_extended(line_t * line, int i, int c, int last, int * out_left) {
  886. (void)last;
  887. if (c == '#') {
  888. *out_left = (line->actual + 1) - i;
  889. return FLAG_COMMENT;
  890. }
  891. if (c == '\t') {
  892. *out_left = (line->actual + 1) - i;
  893. return FLAG_NUMERAL;
  894. }
  895. if (i == 0) {
  896. int j = 0;
  897. for (; j < line->actual; ++j) {
  898. /* Handle leading spaces */
  899. if (line->text[j].codepoint != ' ') break;
  900. }
  901. for (int s = 0; syn_make_commands[s]; ++s) {
  902. int d = 0;
  903. while (j + d < line->actual && line->text[j+d].codepoint == syn_make_commands[s][d]) d++;
  904. if (syn_make_commands[s][d] == '\0') {
  905. *out_left = j+d;
  906. return FLAG_PRAGMA;
  907. }
  908. }
  909. }
  910. if (last == '(' && i > 1) {
  911. if (line->text[i-2].codepoint == '$') {
  912. int j = i;
  913. for (int s = 0; syn_make_functions[s]; ++s) {
  914. int d = 0;
  915. while (j + d < line->actual && line->text[j+d].codepoint == syn_make_functions[s][d]) d++;
  916. if (syn_make_functions[s][d] == '\0' && (j + d == line->actual
  917. || line->text[j+d].codepoint == ')' || line->text[j+d].codepoint == ' ')) {
  918. *out_left = d;
  919. return FLAG_KEYWORD;
  920. }
  921. }
  922. }
  923. }
  924. if (i == 0) {
  925. int j = 0;
  926. for (; j < line->actual; ++j) {
  927. if (line->text[j].codepoint == '=') {
  928. *out_left = j;
  929. return FLAG_TYPE;
  930. }
  931. if (line->text[j].codepoint == ':') {
  932. *out_left = j;
  933. return FLAG_TYPE;
  934. }
  935. }
  936. }
  937. return FLAG_NONE;
  938. }
  939. static char * syn_bimrc_keywords[] = {
  940. "theme",
  941. "padding",
  942. NULL,
  943. };
  944. static int syn_bimrc_extended(line_t * line, int i, int c, int last, int * out_left) {
  945. (void)last;
  946. if (i == 0 && c == '#') {
  947. *out_left = line->actual+1;
  948. return FLAG_COMMENT;
  949. }
  950. return FLAG_NONE;
  951. }
  952. static char * syn_bimrc_ext[] = {".bimrc",NULL};
  953. static int syn_gitcommit_extended(line_t * line, int i, int c, int last, int * out_left) {
  954. (void)last;
  955. if (c == '#') {
  956. *out_left = (line->actual + 1) - i;
  957. return FLAG_COMMENT;
  958. }
  959. return FLAG_NONE;
  960. }
  961. static char * syn_gitcommit_ext[] = {"COMMIT_EDITMSG",NULL};
  962. static char * syn_gitrebase_commands[] = {
  963. "p ","r ","e ","s ","f ","x "," d",
  964. "pick ","reword ","edit ","squash ","fixup ",
  965. "exec ","drop ",
  966. NULL
  967. };
  968. static int syn_gitrebase_extended(line_t * line, int i, int c, int last, int * out_left) {
  969. (void)last;
  970. if (c == '#') {
  971. *out_left = (line->actual + 1) - i;
  972. return FLAG_COMMENT;
  973. }
  974. if (i == 0) {
  975. int j = i;
  976. for (int s = 0; syn_gitrebase_commands[s]; ++s) {
  977. int d = 0;
  978. while (j + d < line->actual && line->text[j+d].codepoint == syn_gitrebase_commands[s][d]) d++;
  979. if (syn_gitrebase_commands[s][d] == '\0') {
  980. *out_left = j+d-1;
  981. return FLAG_KEYWORD;
  982. }
  983. }
  984. }
  985. if (i > 0 && (line->text[i-1].flags & FLAG_KEYWORD)) {
  986. int j = i;
  987. while (isxdigit(line->text[j].codepoint)) {
  988. j++;
  989. }
  990. *out_left = j-i-1;
  991. return FLAG_NUMERAL;
  992. }
  993. return FLAG_NONE;
  994. }
  995. static char * syn_gitrebase_ext[] = {"git-rebase-todo",NULL};
  996. static int syn_diff_extended(line_t * line, int i, int c, int last, int * out_left) {
  997. (void)last;
  998. if (i == 0) {
  999. if (c == '+') {
  1000. *out_left = (line->actual + 1);
  1001. return FLAG_DIFFPLUS;
  1002. } else if (c == '-') {
  1003. *out_left = (line->actual + 1);
  1004. return FLAG_DIFFMINUS;
  1005. } else if (c == '@') {
  1006. *out_left = (line->actual + 1);
  1007. return FLAG_TYPE;
  1008. } else if (c != ' ') {
  1009. *out_left = (line->actual + 1);
  1010. return FLAG_KEYWORD;
  1011. }
  1012. }
  1013. return FLAG_NONE;
  1014. }
  1015. static char * syn_diff_ext[] = {".diff",".patch",NULL};
  1016. /**
  1017. * Syntax hilighting definition database
  1018. */
  1019. struct syntax_definition {
  1020. char * name;
  1021. char ** ext;
  1022. char ** keywords;
  1023. char ** types;
  1024. int (*extended)(line_t *, int, int, int, int *);
  1025. int (*iskwchar)(int);
  1026. int (*finishml)(line_t *, int *, int);
  1027. } syntaxes[] = {
  1028. {"c",syn_c_ext,syn_c_keywords,syn_c_types,syn_c_extended,syn_c_iskeywordchar,syn_c_finish},
  1029. {"python",syn_py_ext,syn_py_keywords,syn_py_types,syn_py_extended,syn_c_iskeywordchar,syn_py_finish},
  1030. {"esh",syn_sh_ext,syn_sh_keywords,NULL,syn_sh_extended,syn_sh_iskeywordchar,NULL},
  1031. {"make",syn_make_ext,NULL,NULL,syn_make_extended,NULL,NULL},
  1032. {"bimrc",syn_bimrc_ext,syn_bimrc_keywords,NULL,syn_bimrc_extended,syn_c_iskeywordchar,NULL},
  1033. {"gitcommit",syn_gitcommit_ext,NULL,NULL,syn_gitcommit_extended,NULL,NULL},
  1034. {"gitrebase",syn_gitrebase_ext,NULL,NULL,syn_gitrebase_extended,NULL,NULL},
  1035. {"diff",syn_diff_ext,NULL,NULL,syn_diff_extended,NULL,NULL},
  1036. {NULL}
  1037. };
  1038. /**
  1039. * Checks whether the character pointed to by `c` is the start of a match for
  1040. * keyword or type name `str`.
  1041. */
  1042. int check_line(line_t * line, int c, char * str, int last) {
  1043. if (env->syntax->iskwchar(last)) return 0;
  1044. for (int i = c; i < line->actual; ++i, ++str) {
  1045. if (*str == '\0' && !env->syntax->iskwchar(line->text[i].codepoint)) return 1;
  1046. if (line->text[i].codepoint == *str) continue;
  1047. return 0;
  1048. }
  1049. if (*str == '\0') return 1;
  1050. return 0;
  1051. }
  1052. /**
  1053. * Calculate syntax hilighting for the given line.
  1054. */
  1055. void recalculate_syntax(line_t * line, int offset) {
  1056. if (!env->syntax) {
  1057. for (int i = 0; i < line->actual; ++i) {
  1058. line->text[i].flags = 0;
  1059. }
  1060. return;
  1061. }
  1062. /* Start from the line's stored in initial state */
  1063. int state = line->istate;
  1064. int left = 0;
  1065. int last = 0;
  1066. if (state) {
  1067. /*
  1068. * If we are already highlighting coming in, then we need to check
  1069. * for a finishing sequence for the curent state.
  1070. */
  1071. state = env->syntax->finishml(line,&left,state);
  1072. if (state & FLAG_CONTINUES) {
  1073. /* The finish check said that this multiline state continues. */
  1074. for (int i = 0; i < line->actual; i++) {
  1075. /* Set the entire line to draw with this state */
  1076. line->text[i].flags = state;
  1077. }
  1078. /* Recalculate later lines if needed */
  1079. goto _multiline;
  1080. }
  1081. }
  1082. for (int i = 0; i < line->actual; last = line->text[i++].codepoint) {
  1083. if (!left) state = 0;
  1084. if (state) {
  1085. /* Currently hilighting, have `left` characters remaining with this state */
  1086. left--;
  1087. line->text[i].flags = state;
  1088. if (!left) {
  1089. /* Done hilighting this state, go back to parsing on next character */
  1090. state = 0;
  1091. }
  1092. /* If we are hilighting something, don't parse */
  1093. continue;
  1094. }
  1095. int c = line->text[i].codepoint;
  1096. line->text[i].flags = FLAG_NONE;
  1097. /* Language-specific syntax hilighting */
  1098. if (env->syntax->extended) {
  1099. int s = env->syntax->extended(line,i,c,last,&left);
  1100. if (s) {
  1101. state = s;
  1102. if (state & FLAG_CONTINUES) {
  1103. /* A multiline state was returned. Fill the rest of the line */
  1104. for (; i < line->actual; i++) {
  1105. line->text[i].flags = state;
  1106. }
  1107. /* And recalculate later lines if needed */
  1108. goto _multiline;
  1109. }
  1110. goto _continue;
  1111. }
  1112. }
  1113. /* Keywords */
  1114. if (env->syntax->keywords) {
  1115. for (char ** kw = env->syntax->keywords; *kw; kw++) {
  1116. int c = check_line(line, i, *kw, last);
  1117. if (c == 1) {
  1118. left = strlen(*kw)-1;
  1119. state = FLAG_KEYWORD;
  1120. goto _continue;
  1121. }
  1122. }
  1123. }
  1124. /* Type names */
  1125. if (env->syntax->types) {
  1126. for (char ** kw = env->syntax->types; *kw; kw++) {
  1127. int c = check_line(line, i, *kw, last);
  1128. if (c == 1) {
  1129. left = strlen(*kw)-1;
  1130. state = FLAG_TYPE;
  1131. goto _continue;
  1132. }
  1133. }
  1134. }
  1135. _continue:
  1136. line->text[i].flags = state;
  1137. }
  1138. state = 0;
  1139. _multiline:
  1140. /*
  1141. * If the next line's initial state does not match the state we ended on,
  1142. * then it needs to be recalculated (and redraw). This may lead to multiple
  1143. * recursive calls until a match is found.
  1144. */
  1145. if (offset + 1 < env->line_count && env->lines[offset+1]->istate != state) {
  1146. /* Set the next line's initial state to our ending state */
  1147. env->lines[offset+1]->istate = state;
  1148. /* Recursively recalculate */
  1149. recalculate_syntax(env->lines[offset+1],offset+1);
  1150. /*
  1151. * Determine if this is an on-screen line so we can redraw it;
  1152. * this ends up drawing from bottom to top when multiple lines
  1153. * need to be redrawn by a recursive call.
  1154. */
  1155. if (offset+1 >= env->offset && offset+1 < env->offset + global_config.term_height - global_config.bottom_size - 1) {
  1156. redraw_line(offset + 1 - env->offset,offset+1);
  1157. }
  1158. }
  1159. }
  1160. /**
  1161. * Recalculate tab widths.
  1162. */
  1163. void recalculate_tabs(line_t * line) {
  1164. if (env->loading) return;
  1165. int j = 0;
  1166. for (int i = 0; i < line->actual; ++i) {
  1167. if (line->text[i].codepoint == '\t') {
  1168. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  1169. }
  1170. j += line->text[i].display_width;
  1171. }
  1172. }
  1173. /**
  1174. * TODO:
  1175. *
  1176. * The line editing functions should probably take a buffer_t *
  1177. * so that they can act on buffers other than the active one.
  1178. */
  1179. void recursive_history_free(history_t * root) {
  1180. if (!root->next) return;
  1181. history_t * n = root->next;
  1182. recursive_history_free(n);
  1183. switch (n->type) {
  1184. case HISTORY_REPLACE_LINE:
  1185. free(n->remove_replace_line.contents);
  1186. /* fall-through */
  1187. case HISTORY_REMOVE_LINE:
  1188. free(n->remove_replace_line.old_contents);
  1189. break;
  1190. default:
  1191. /* Nothing extra to free */
  1192. break;
  1193. }
  1194. free(n);
  1195. root->next = NULL;
  1196. }
  1197. #define HIST_APPEND(e) do { \
  1198. if (env->history) { \
  1199. e->previous = env->history; \
  1200. recursive_history_free(env->history); \
  1201. env->history->next = e; \
  1202. e->next = NULL; \
  1203. } \
  1204. env->history = e; \
  1205. } while (0)
  1206. /**
  1207. * Mark a point where a complete set of actions has ended.
  1208. */
  1209. void set_history_break(void) {
  1210. if (!global_config.history_enabled) return;
  1211. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1212. history_t * e = malloc(sizeof(history_t));
  1213. e->type = HISTORY_BREAK;
  1214. HIST_APPEND(e);
  1215. }
  1216. }
  1217. /**
  1218. * Insert a character into an existing line.
  1219. */
  1220. line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1221. if (!env->loading && global_config.history_enabled) {
  1222. history_t * e = malloc(sizeof(history_t));
  1223. e->type = HISTORY_INSERT;
  1224. e->insert_delete_replace.lineno = lineno;
  1225. e->insert_delete_replace.offset = offset;
  1226. e->insert_delete_replace.codepoint = c.codepoint;
  1227. HIST_APPEND(e);
  1228. }
  1229. /* If there is not enough space... */
  1230. if (line->actual == line->available) {
  1231. /* Expand the line buffer */
  1232. line->available *= 2;
  1233. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1234. }
  1235. /* If this was not the last character, then shift remaining characters forward. */
  1236. if (offset < line->actual) {
  1237. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1238. }
  1239. /* Insert the new character */
  1240. line->text[offset] = c;
  1241. /* There is one new character in the line */
  1242. line->actual += 1;
  1243. if (!env->loading) {
  1244. recalculate_tabs(line);
  1245. recalculate_syntax(line, lineno);
  1246. }
  1247. return line;
  1248. }
  1249. /**
  1250. * Delete a character from a line
  1251. */
  1252. void line_delete(line_t * line, int offset, int lineno) {
  1253. /* Can't delete character before start of line. */
  1254. if (offset == 0) return;
  1255. if (!env->loading && global_config.history_enabled) {
  1256. history_t * e = malloc(sizeof(history_t));
  1257. e->type = HISTORY_DELETE;
  1258. e->insert_delete_replace.lineno = lineno;
  1259. e->insert_delete_replace.offset = offset;
  1260. e->insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1261. HIST_APPEND(e);
  1262. }
  1263. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1264. if (offset < line->actual) {
  1265. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1266. }
  1267. /* The line is one character shorter */
  1268. line->actual -= 1;
  1269. recalculate_tabs(line);
  1270. recalculate_syntax(line, lineno);
  1271. }
  1272. /**
  1273. * Replace a character in a line
  1274. */
  1275. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1276. if (!env->loading && global_config.history_enabled) {
  1277. history_t * e = malloc(sizeof(history_t));
  1278. e->type = HISTORY_REPLACE;
  1279. e->insert_delete_replace.lineno = lineno;
  1280. e->insert_delete_replace.offset = offset;
  1281. e->insert_delete_replace.codepoint = _c.codepoint;
  1282. e->insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1283. HIST_APPEND(e);
  1284. }
  1285. line->text[offset] = _c;
  1286. if (!env->loading) {
  1287. recalculate_tabs(line);
  1288. recalculate_syntax(line, lineno);
  1289. }
  1290. }
  1291. /**
  1292. * Remove a line from the active buffer
  1293. */
  1294. line_t ** remove_line(line_t ** lines, int offset) {
  1295. /* If there is only one line, clear it instead of removing it. */
  1296. if (env->line_count == 1) {
  1297. while (lines[offset]->actual > 0) {
  1298. line_delete(lines[offset], lines[offset]->actual, offset);
  1299. }
  1300. return lines;
  1301. }
  1302. if (!env->loading && global_config.history_enabled) {
  1303. history_t * e = malloc(sizeof(history_t));
  1304. e->type = HISTORY_REMOVE_LINE;
  1305. e->remove_replace_line.lineno = offset;
  1306. e->remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1307. memcpy(e->remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1308. HIST_APPEND(e);
  1309. }
  1310. /* Otherwise, free the data used by the line */
  1311. free(lines[offset]);
  1312. /* Move other lines up */
  1313. if (offset < env->line_count) {
  1314. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1315. lines[env->line_count-1] = NULL;
  1316. }
  1317. /* There is one less line */
  1318. env->line_count -= 1;
  1319. return lines;
  1320. }
  1321. /**
  1322. * Add a new line to the active buffer.
  1323. */
  1324. line_t ** add_line(line_t ** lines, int offset) {
  1325. /* Invalid offset? */
  1326. if (offset > env->line_count) return lines;
  1327. if (!env->loading && global_config.history_enabled) {
  1328. history_t * e = malloc(sizeof(history_t));
  1329. e->type = HISTORY_ADD_LINE;
  1330. e->add_merge_split_lines.lineno = offset;
  1331. HIST_APPEND(e);
  1332. }
  1333. /* Not enough space */
  1334. if (env->line_count == env->line_avail) {
  1335. /* Allocate more space */
  1336. env->line_avail *= 2;
  1337. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1338. }
  1339. /* If this isn't the last line, move other lines down */
  1340. if (offset < env->line_count) {
  1341. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1342. }
  1343. /* Allocate the new line */
  1344. lines[offset] = malloc(sizeof(line_t) + sizeof(char_t) * 32);
  1345. lines[offset]->available = 32;
  1346. lines[offset]->actual = 0;
  1347. lines[offset]->istate = 0;
  1348. /* There is one new line */
  1349. env->line_count += 1;
  1350. env->lines = lines;
  1351. if (offset > 0 && !env->loading) {
  1352. recalculate_syntax(lines[offset-1],offset-1);
  1353. }
  1354. return lines;
  1355. }
  1356. /**
  1357. * Replace a line with data from another line (used by paste to paste yanked lines)
  1358. */
  1359. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1360. if (!env->loading && global_config.history_enabled) {
  1361. history_t * e = malloc(sizeof(history_t));
  1362. e->type = HISTORY_REPLACE_LINE;
  1363. e->remove_replace_line.lineno = offset;
  1364. e->remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1365. memcpy(e->remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1366. e->remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1367. memcpy(e->remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1368. HIST_APPEND(e);
  1369. }
  1370. if (lines[offset]->available < replacement->actual) {
  1371. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1372. lines[offset]->available = replacement->available;
  1373. }
  1374. lines[offset]->actual = replacement->actual;
  1375. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1376. if (!env->loading) {
  1377. recalculate_syntax(lines[offset],offset);
  1378. }
  1379. }
  1380. /**
  1381. * Merge two consecutive lines.
  1382. * lineb is the offset of the second line.
  1383. */
  1384. line_t ** merge_lines(line_t ** lines, int lineb) {
  1385. /* linea is the line immediately before lineb */
  1386. int linea = lineb - 1;
  1387. if (!env->loading && global_config.history_enabled) {
  1388. history_t * e = malloc(sizeof(history_t));
  1389. e->type = HISTORY_MERGE_LINES;
  1390. e->add_merge_split_lines.lineno = lineb;
  1391. e->add_merge_split_lines.split = env->lines[linea]->actual;
  1392. HIST_APPEND(e);
  1393. }
  1394. /* If there isn't enough space in linea hold both... */
  1395. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1396. /* ... allocate more space until it fits */
  1397. lines[linea]->available *= 2;
  1398. /* XXX why not just do this once after calculating appropriate size */
  1399. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1400. }
  1401. /* Copy the second line into the first line */
  1402. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1403. /* The first line is now longer */
  1404. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1405. if (!env->loading) {
  1406. recalculate_tabs(lines[linea]);
  1407. recalculate_syntax(lines[linea], linea);
  1408. }
  1409. /* Remove the second line */
  1410. free(lines[lineb]);
  1411. /* Move other lines up */
  1412. if (lineb < env->line_count) {
  1413. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1414. lines[env->line_count-1] = NULL;
  1415. }
  1416. /* There is one less line */
  1417. env->line_count -= 1;
  1418. return lines;
  1419. }
  1420. /**
  1421. * Split a line into two lines at the given column
  1422. */
  1423. line_t ** split_line(line_t ** lines, int line, int split) {
  1424. /* If we're trying to split from the start, just add a new blank line before */
  1425. if (split == 0) {
  1426. return add_line(lines, line);
  1427. }
  1428. if (!env->loading && global_config.history_enabled) {
  1429. history_t * e = malloc(sizeof(history_t));
  1430. e->type = HISTORY_SPLIT_LINE;
  1431. e->add_merge_split_lines.lineno = line;
  1432. e->add_merge_split_lines.split = split;
  1433. HIST_APPEND(e);
  1434. }
  1435. /* Allocate more space as needed */
  1436. if (env->line_count == env->line_avail) {
  1437. env->line_avail *= 2;
  1438. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1439. }
  1440. /* Shift later lines down */
  1441. if (line < env->line_count) {
  1442. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1443. }
  1444. /* I have no idea what this is doing */
  1445. int remaining = lines[line]->actual - split;
  1446. int v = remaining;
  1447. v--;
  1448. v |= v >> 1;
  1449. v |= v >> 2;
  1450. v |= v >> 4;
  1451. v |= v >> 8;
  1452. v |= v >> 16;
  1453. v++;
  1454. /* Allocate space for the new line */
  1455. lines[line+1] = malloc(sizeof(line_t) + sizeof(char_t) * v);
  1456. lines[line+1]->available = v;
  1457. lines[line+1]->actual = remaining;
  1458. lines[line+1]->istate = 0;
  1459. /* Move the data from the old line into the new line */
  1460. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1461. lines[line]->actual = split;
  1462. if (!env->loading) {
  1463. recalculate_tabs(lines[line]);
  1464. recalculate_tabs(lines[line+1]);
  1465. recalculate_syntax(lines[line], line);
  1466. recalculate_syntax(lines[line+1], line+1);
  1467. }
  1468. /* There is one new line */
  1469. env->line_count += 1;
  1470. /* We may have reallocated lines */
  1471. return lines;
  1472. }
  1473. /**
  1474. * Add indentation from the previous (temporally) line
  1475. */
  1476. void add_indent(int new_line, int old_line) {
  1477. if (env->indent) {
  1478. int changed = 0;
  1479. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1480. if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1481. env->lines[old_line]->text[i].codepoint == '\t') {
  1482. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1483. env->col_no++;
  1484. changed = 1;
  1485. } else {
  1486. break;
  1487. }
  1488. }
  1489. if (old_line < new_line &&
  1490. (env->lines[old_line]->text[env->lines[old_line]->actual-1].codepoint == '{' ||
  1491. env->lines[old_line]->text[env->lines[old_line]->actual-1].codepoint == ':')) {
  1492. if (env->tabs) {
  1493. char_t c;
  1494. c.codepoint = '\t';
  1495. c.display_width = env->tabstop;
  1496. env->lines[new_line] = line_insert(env->lines[new_line], c, env->lines[new_line]->actual, new_line);
  1497. env->col_no++;
  1498. changed = 1;
  1499. } else {
  1500. for (int j = 0; j < env->tabstop; ++j) {
  1501. char_t c;
  1502. c.codepoint = ' ';
  1503. c.display_width = 1;
  1504. c.flags = FLAG_SELECT;
  1505. env->lines[new_line] = line_insert(env->lines[new_line], c, env->lines[new_line]->actual, new_line);
  1506. env->col_no++;
  1507. }
  1508. changed = 1;
  1509. }
  1510. }
  1511. if (changed) {
  1512. recalculate_syntax(env->lines[new_line],new_line);
  1513. }
  1514. }
  1515. }
  1516. /**
  1517. * Initialize a buffer with default values
  1518. */
  1519. void setup_buffer(buffer_t * env) {
  1520. /* If this buffer was already initialized, clear out its line data */
  1521. if (env->lines) {
  1522. for (int i = 0; i < env->line_count; ++i) {
  1523. free(env->lines[i]);
  1524. }
  1525. free(env->lines);
  1526. }
  1527. /* Default state parameters */
  1528. env->line_no = 1; /* Default cursor position */
  1529. env->col_no = 1;
  1530. env->line_count = 1; /* Buffers always have at least one line */
  1531. env->modified = 0;
  1532. env->readonly = 0;
  1533. env->offset = 0;
  1534. env->line_avail = 8; /* Default line buffer capacity */
  1535. env->tabs = 1; /* Tabs by default */
  1536. env->tabstop = 4; /* Tab stop width */
  1537. env->indent = 1; /* Auto-indent by default */
  1538. env->history = malloc(sizeof(struct history));
  1539. memset(env->history, 0, sizeof(struct history));
  1540. env->last_save_history = env->history;
  1541. /* Allocate line buffer */
  1542. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1543. /* Initialize the first line */
  1544. env->lines[0] = malloc(sizeof(line_t) + sizeof(char_t) * 32);
  1545. env->lines[0]->available = 32;
  1546. env->lines[0]->actual = 0;
  1547. env->lines[0]->istate = 0;
  1548. }
  1549. /**
  1550. * Toggle buffered / unbuffered modes
  1551. */
  1552. struct termios old;
  1553. void get_initial_termios(void) {
  1554. tcgetattr(STDOUT_FILENO, &old);
  1555. }
  1556. void set_unbuffered(void) {
  1557. struct termios new = old;
  1558. new.c_lflag &= (~ICANON & ~ECHO);
  1559. new.c_cc[VINTR] = 0;
  1560. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1561. }
  1562. void set_buffered(void) {
  1563. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1564. }
  1565. /**
  1566. * Convert codepoint to utf-8 string
  1567. */
  1568. int to_eight(uint32_t codepoint, char * out) {
  1569. memset(out, 0x00, 7);
  1570. if (codepoint < 0x0080) {
  1571. out[0] = (char)codepoint;
  1572. } else if (codepoint < 0x0800) {
  1573. out[0] = 0xC0 | (codepoint >> 6);
  1574. out[1] = 0x80 | (codepoint & 0x3F);
  1575. } else if (codepoint < 0x10000) {
  1576. out[0] = 0xE0 | (codepoint >> 12);
  1577. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1578. out[2] = 0x80 | (codepoint & 0x3F);
  1579. } else if (codepoint < 0x200000) {
  1580. out[0] = 0xF0 | (codepoint >> 18);
  1581. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1582. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1583. out[3] = 0x80 | ((codepoint) & 0x3F);
  1584. } else if (codepoint < 0x4000000) {
  1585. out[0] = 0xF8 | (codepoint >> 24);
  1586. out[1] = 0x80 | (codepoint >> 18);
  1587. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1588. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1589. out[4] = 0x80 | ((codepoint) & 0x3F);
  1590. } else {
  1591. out[0] = 0xF8 | (codepoint >> 30);
  1592. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1593. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1594. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1595. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1596. out[5] = 0x80 | ((codepoint) & 0x3F);
  1597. }
  1598. return strlen(out);
  1599. }
  1600. /**
  1601. * Get the presentation width of a codepoint
  1602. */
  1603. int codepoint_width(wchar_t codepoint) {
  1604. if (codepoint == '\t') {
  1605. return 1; /* Recalculate later */
  1606. }
  1607. if (codepoint < 32) {
  1608. /* We render these as ^@ */
  1609. return 2;
  1610. }
  1611. if (codepoint == 0x7F) {
  1612. /* Renders as ^? */
  1613. return 2;
  1614. }
  1615. if (codepoint > 0x7f && codepoint < 0xa0) {
  1616. /* Upper control bytes <xx> */
  1617. return 4;
  1618. }
  1619. if (codepoint == 0xa0) {
  1620. /* Non-breaking space _ */
  1621. return 1;
  1622. }
  1623. /* Skip wcwidth for anything under 256 */
  1624. if (codepoint > 256) {
  1625. if (global_config.can_unicode) {
  1626. /* Higher codepoints may be wider (eg. Japanese) */
  1627. int out = wcwidth(codepoint);
  1628. if (out >= 1) return out;
  1629. }
  1630. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1631. return (codepoint < 0x10000) ? 8 : 10;
  1632. }
  1633. return 1;
  1634. }
  1635. /**
  1636. * Move the terminal cursor
  1637. */
  1638. void place_cursor(int x, int y) {
  1639. printf("\033[%d;%dH", y, x);
  1640. fflush(stdout);
  1641. }
  1642. /**
  1643. * Set text colors
  1644. *
  1645. * Normally, text colors are just strings, but if they
  1646. * start with @ they will be parsed as integers
  1647. * representing one of the 16 standard colors, suitable
  1648. * for terminals without support for the 256- or 24-bit
  1649. * color modes.
  1650. */
  1651. void set_colors(const char * fg, const char * bg) {
  1652. printf("\033[22;23;");
  1653. if (*bg == '@') {
  1654. int _bg = atoi(bg+1);
  1655. if (_bg < 10) {
  1656. printf("4%d;", _bg);
  1657. } else {
  1658. printf("10%d;", _bg-10);
  1659. }
  1660. } else {
  1661. printf("48;%s;", bg);
  1662. }
  1663. if (*fg == '@') {
  1664. int _fg = atoi(fg+1);
  1665. if (_fg < 10) {
  1666. printf("3%dm", _fg);
  1667. } else {
  1668. printf("9%dm", _fg-10);
  1669. }
  1670. } else {
  1671. printf("38;%sm", fg);
  1672. }
  1673. fflush(stdout);
  1674. }
  1675. /**
  1676. * Set just the foreground color
  1677. *
  1678. * (See set_colors above)
  1679. */
  1680. void set_fg_color(const char * fg) {
  1681. printf("\033[22;23;");
  1682. if (*fg == '@') {
  1683. int _fg = atoi(fg+1);
  1684. if (_fg < 10) {
  1685. printf("3%dm", _fg);
  1686. } else {
  1687. printf("9%dm", _fg-10);
  1688. }
  1689. } else {
  1690. printf("38;%sm", fg);
  1691. }
  1692. fflush(stdout);
  1693. }
  1694. /**
  1695. * Clear the rest of this line
  1696. */
  1697. void clear_to_end(void) {
  1698. if (global_config.can_bce) {
  1699. printf("\033[K");
  1700. fflush(stdout);
  1701. }
  1702. }
  1703. /**
  1704. * For terminals without bce,
  1705. * prepaint the whole line, so we don't have to track
  1706. * where the cursor is for everything. Inefficient,
  1707. * but effective.
  1708. */
  1709. void paint_line(const char * bg) {
  1710. if (!global_config.can_bce) {
  1711. set_colors(COLOR_FG, bg);
  1712. for (int i = 0; i < global_config.term_width; ++i) {
  1713. printf(" ");
  1714. }
  1715. printf("\r");
  1716. }
  1717. }
  1718. /**
  1719. * Enable bold text display
  1720. */
  1721. void set_bold(void) {
  1722. printf("\033[1m");
  1723. fflush(stdout);
  1724. }
  1725. /**
  1726. * Enable underlined text display
  1727. */
  1728. void set_underline(void) {
  1729. printf("\033[4m");
  1730. fflush(stdout);
  1731. }
  1732. /**
  1733. * Reset text display attributes
  1734. */
  1735. void reset(void) {
  1736. printf("\033[0m");
  1737. fflush(stdout);
  1738. }
  1739. /**
  1740. * Clear the entire screen
  1741. */
  1742. void clear_screen(void) {
  1743. printf("\033[H\033[2J");
  1744. fflush(stdout);
  1745. }
  1746. /**
  1747. * Hide the cursor
  1748. */
  1749. void hide_cursor(void) {
  1750. if (global_config.can_hideshow) {
  1751. printf("\033[?25l");
  1752. }
  1753. fflush(stdout);
  1754. }
  1755. /*
  1756. * Show the cursor
  1757. */
  1758. void show_cursor(void) {
  1759. if (global_config.can_hideshow) {
  1760. printf("\033[?25h");
  1761. }
  1762. fflush(stdout);
  1763. }
  1764. /**
  1765. * Request mouse events
  1766. */
  1767. void mouse_enable(void) {
  1768. if (global_config.can_mouse) {
  1769. printf("\033[?1000h");
  1770. }
  1771. fflush(stdout);
  1772. }
  1773. /**
  1774. * Stop mouse events
  1775. */
  1776. void mouse_disable(void) {
  1777. if (global_config.can_mouse) {
  1778. printf("\033[?1000l");
  1779. }
  1780. fflush(stdout);
  1781. }
  1782. /**
  1783. * Shift the screen up one line
  1784. */
  1785. void shift_up(void) {
  1786. printf("\033[1S");
  1787. }
  1788. /**
  1789. * Shift the screen down one line.
  1790. */
  1791. void shift_down(void) {
  1792. printf("\033[1T");
  1793. }
  1794. /**
  1795. * Switch to the alternate terminal screen.
  1796. */
  1797. void set_alternate_screen(void) {
  1798. if (global_config.can_altscreen) {
  1799. printf("\033[?1049h");
  1800. }
  1801. }
  1802. /**
  1803. * Restore the standard terminal screen.
  1804. */
  1805. void unset_alternate_screen(void) {
  1806. if (global_config.can_altscreen) {
  1807. printf("\033[?1049l");
  1808. }
  1809. }
  1810. /**
  1811. * Redaw the tabbar, with a tab for each buffer.
  1812. *
  1813. * The active buffer is highlighted.
  1814. */
  1815. void redraw_tabbar(void) {
  1816. /* Hide cursor while rendering UI */
  1817. hide_cursor();
  1818. /* Move to upper left */
  1819. place_cursor(1,1);
  1820. paint_line(COLOR_TABBAR_BG);
  1821. /* For each buffer... */
  1822. for (int i = 0; i < buffers_len; i++) {
  1823. buffer_t * _env = buffers[i];
  1824. if (_env == env) {
  1825. /* If this is the active buffer, hilight it */
  1826. reset();
  1827. set_colors(COLOR_FG, COLOR_BG);
  1828. set_bold();
  1829. } else {
  1830. /* Otherwise use default tab color */
  1831. reset();
  1832. set_colors(COLOR_FG, COLOR_TAB_BG);
  1833. set_underline();
  1834. }
  1835. /* If this buffer is modified, indicate that with a prepended + */
  1836. if (_env->modified) {
  1837. printf(" +");
  1838. }
  1839. /* Print the filename */
  1840. if (_env->file_name) {
  1841. printf(" %s ", _env->file_name);
  1842. } else {
  1843. printf(" [No Name] ");
  1844. }
  1845. }
  1846. /* Reset bold/underline */
  1847. reset();
  1848. /* Fill the rest of the tab bar */
  1849. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  1850. clear_to_end();
  1851. }
  1852. /**
  1853. * Braindead log10 implementation for the line numbers
  1854. */
  1855. int log_base_10(unsigned int v) {
  1856. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  1857. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  1858. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  1859. return r;
  1860. }
  1861. /**
  1862. * Render a line of text
  1863. *
  1864. * This handles rendering the actual text content. A full line of text
  1865. * also includes a line number and some padding.
  1866. *
  1867. * width: width of the text display region (term width - line number width)
  1868. * offset: how many cells into the line to start rendering at
  1869. */
  1870. void render_line(line_t * line, int width, int offset) {
  1871. int i = 0; /* Offset in char_t line data entries */
  1872. int j = 0; /* Offset in terminal cells */
  1873. const char * last_color = NULL;
  1874. int was_selecting = 0;
  1875. /* Set default text colors */
  1876. set_colors(COLOR_FG, COLOR_BG);
  1877. /*
  1878. * When we are rendering in the middle of a wide character,
  1879. * we render -'s to fill the remaining amount of the
  1880. * charater's width
  1881. */
  1882. int remainder = 0;
  1883. /* For each character in the line ... */
  1884. while (i < line->actual) {
  1885. /* If there is remaining text... */
  1886. if (remainder) {
  1887. /* If we should be drawing by now... */
  1888. if (j >= offset) {
  1889. /* Fill remainder with -'s */
  1890. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1891. printf("-");
  1892. set_colors(COLOR_FG, COLOR_BG);
  1893. }
  1894. /* One less remaining width cell to fill */
  1895. remainder--;
  1896. /* Terminal offset moves forward */
  1897. j++;
  1898. /*
  1899. * If this was the last remaining character, move to
  1900. * the next codepoint in the line
  1901. */
  1902. if (remainder == 0) {
  1903. i++;
  1904. }
  1905. continue;
  1906. }
  1907. /* Get the next character to draw */
  1908. char_t c = line->text[i];
  1909. /* If we should be drawing by now... */
  1910. if (j >= offset) {
  1911. /* If this character is going to fall off the edge of the screen... */
  1912. if (j - offset + c.display_width >= width) {
  1913. /* We draw this with special colors so it isn't ambiguous */
  1914. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1915. /* If it's wide, draw ---> as needed */
  1916. while (j - offset < width - 1) {
  1917. printf("-");
  1918. j++;
  1919. }
  1920. /* End the line with a > to show it overflows */
  1921. printf(">");
  1922. set_colors(COLOR_FG, COLOR_BG);
  1923. return;
  1924. }
  1925. /* Syntax hilighting */
  1926. const char * color = flag_to_color(c.flags);
  1927. if (c.flags == FLAG_SELECT) {
  1928. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  1929. was_selecting = 1;
  1930. } else {
  1931. if (was_selecting) {
  1932. set_colors(color, COLOR_BG);
  1933. last_color = color;
  1934. } else if (!last_color || strcmp(color, last_color)) {
  1935. set_fg_color(color);
  1936. last_color = color;
  1937. }
  1938. }
  1939. #define _set_colors(fg,bg) if (c.flags != FLAG_SELECT) { set_colors(fg,bg); }
  1940. /* Render special characters */
  1941. if (c.codepoint == '\t') {
  1942. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1943. if (global_config.can_unicode) {
  1944. printf("»");
  1945. for (int i = 1; i < c.display_width; ++i) {
  1946. printf("·");
  1947. }
  1948. } else {
  1949. printf(">");
  1950. for (int i = 1; i < c.display_width; ++i) {
  1951. printf("-");
  1952. }
  1953. }
  1954. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  1955. } else if (c.codepoint < 32) {
  1956. /* Codepoints under 32 to get converted to ^@ escapes */
  1957. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1958. printf("^%c", '@' + c.codepoint);
  1959. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  1960. } else if (c.codepoint == 0x7f) {
  1961. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1962. printf("^?");
  1963. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  1964. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  1965. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1966. printf("<%2x>", c.codepoint);
  1967. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  1968. } else if (c.codepoint == 0xa0) {
  1969. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1970. printf("_");
  1971. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  1972. } else if (c.display_width == 8) {
  1973. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1974. printf("[U+%04x]", c.codepoint);
  1975. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  1976. } else if (c.display_width == 10) {
  1977. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1978. printf("[U+%06x]", c.codepoint);
  1979. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  1980. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  1981. /* Special case: space at end of line */
  1982. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  1983. printf("·");
  1984. _set_colors(COLOR_FG, COLOR_BG);
  1985. } else {
  1986. /* Normal characters get output */
  1987. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  1988. to_eight(c.codepoint, tmp);
  1989. printf("%s", tmp);
  1990. }
  1991. /* Advance the terminal cell offset by the render width of this character */
  1992. j += c.display_width;
  1993. /* Advance to the next character */
  1994. i++;
  1995. } else if (c.display_width > 1) {
  1996. /*
  1997. * If this is a wide character but we aren't ready to render yet,
  1998. * we may need to draw some filler text for the remainder of its
  1999. * width to ensure we don't jump around when horizontally scrolling
  2000. * past wide characters.
  2001. */
  2002. remainder = c.display_width - 1;
  2003. j++;
  2004. } else {
  2005. /* Regular character, not ready to draw, advance without doing anything */
  2006. j++;
  2007. i++;
  2008. }
  2009. }
  2010. if (env->mode == MODE_CHAR_SELECTION) {
  2011. set_colors(COLOR_FG, COLOR_BG);
  2012. }
  2013. if (!global_config.can_bce) {
  2014. /* Paint the rest of the line */
  2015. for (; j < global_config.term_width; ++j) {
  2016. printf(" ");
  2017. }
  2018. }
  2019. /* Clear the rest of the line */
  2020. clear_to_end();
  2021. }
  2022. /**
  2023. * Get the width of the line number region
  2024. */
  2025. int num_width(void) {
  2026. int w = log_base_10(env->line_count) + 1;
  2027. if (w < 2) return 2;
  2028. return w;
  2029. }
  2030. /**
  2031. * Draw the gutter and line numbers.
  2032. */
  2033. void draw_line_number(int x) {
  2034. /* Draw the line number */
  2035. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2036. int num_size = num_width();
  2037. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2038. printf(" ");
  2039. }
  2040. printf("%d%c", x + 1, (x+1 == env->line_no && env->coffset > 0) ? '<' : ' ');
  2041. }
  2042. /**
  2043. * Redraw line.
  2044. *
  2045. * This draws the line number as well as the actual text.
  2046. * j = screen-relative line offset.
  2047. */
  2048. void redraw_line(int j, int x) {
  2049. if (env->loading) return;
  2050. /* Hide cursor when drawing */
  2051. hide_cursor();
  2052. /* Move cursor to upper left most cell of this line */
  2053. place_cursor(1,2 + j);
  2054. /* Draw a gutter on the left.
  2055. * TODO: The gutter can be used to show single-character
  2056. * line annotations, such as collapse state, or
  2057. * whether a search result was found on this line.
  2058. */
  2059. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2060. printf(" ");
  2061. draw_line_number(x);
  2062. /*
  2063. * Draw the line text
  2064. * If this is the active line, the current character cell offset should be used.
  2065. * (Non-active lines are not shifted and always render from the start of the line)
  2066. */
  2067. render_line(env->lines[x], global_config.term_width - 3 - num_width(), (x + 1 == env->line_no) ? env->coffset : 0);
  2068. }
  2069. /**
  2070. * Draw a ~ line where there is no buffer text.
  2071. */
  2072. void draw_excess_line(int j) {
  2073. place_cursor(1,2 + j);
  2074. paint_line(COLOR_ALT_BG);
  2075. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2076. printf("~");
  2077. clear_to_end();
  2078. }
  2079. /**
  2080. * Redraw the entire text area
  2081. */
  2082. void redraw_text(void) {
  2083. /* Hide cursor while rendering */
  2084. hide_cursor();
  2085. /* Figure out the available size of the text region */
  2086. int l = global_config.term_height - global_config.bottom_size - 1;
  2087. int j = 0;
  2088. /* Draw each line */
  2089. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2090. redraw_line(j,x);
  2091. j++;
  2092. }
  2093. /* Draw the rest of the text region as ~ lines */
  2094. for (; j < l; ++j) {
  2095. draw_excess_line(j);
  2096. }
  2097. }
  2098. /**
  2099. * Draw the status bar
  2100. *
  2101. * The status bar shows the name of the file, whether it has modifications,
  2102. * and (in the future) what syntax highlighting mode is enabled.
  2103. *
  2104. * The right side of the tatus bar shows the line number and column.
  2105. */
  2106. void redraw_statusbar(void) {
  2107. /* Hide cursor while rendering */
  2108. hide_cursor();
  2109. /* Move cursor to the status bar line (second from bottom */
  2110. place_cursor(1, global_config.term_height - 1);
  2111. /* Set background colors for status line */
  2112. paint_line(COLOR_STATUS_BG);
  2113. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2114. /* Print the file name */
  2115. if (env->file_name) {
  2116. printf("%s", env->file_name);
  2117. } else {
  2118. printf("[No Name]");
  2119. }
  2120. printf(" ");
  2121. if (env->syntax) {
  2122. printf("[%s]", env->syntax->name);
  2123. }
  2124. /* Print file status indicators */
  2125. if (env->modified) {
  2126. printf("[+]");
  2127. }
  2128. if (env->readonly) {
  2129. printf("[ro]");
  2130. }
  2131. printf(" ");
  2132. if (env->tabs) {
  2133. printf("[tabs]");
  2134. } else {
  2135. printf("[spaces=%d]", env->tabstop);
  2136. }
  2137. if (global_config.yanks) {
  2138. printf("[y:%ld]", global_config.yank_count);
  2139. }
  2140. if (env->indent) {
  2141. printf("[indent]");
  2142. }
  2143. /* Clear the rest of the status bar */
  2144. clear_to_end();
  2145. /* Pre-render the right hand side of the status bar */
  2146. char right_hand[1024];
  2147. snprintf(right_hand, 1024, "Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2148. /* Move the cursor appropriately to draw it */
  2149. place_cursor(global_config.term_width - strlen(right_hand), global_config.term_height - 1);
  2150. /* TODO: What if we're localized and this has wide chars? */
  2151. printf("%s",right_hand);
  2152. fflush(stdout);
  2153. }
  2154. /**
  2155. * Draw the command line
  2156. *
  2157. * The command line either has input from the user (:quit, :!make, etc.)
  2158. * or shows the INSERT (or VISUAL in the future) mode name.
  2159. */
  2160. void redraw_commandline(void) {
  2161. /* Hide cursor while rendering */
  2162. hide_cursor();
  2163. /* Move cursor to the last line */
  2164. place_cursor(1, global_config.term_height);
  2165. /* Set background color */
  2166. paint_line(COLOR_BG);
  2167. set_colors(COLOR_FG, COLOR_BG);
  2168. /* If we are in an edit mode, note that. */
  2169. if (env->mode == MODE_INSERT) {
  2170. set_bold();
  2171. printf("-- INSERT --");
  2172. clear_to_end();
  2173. reset();
  2174. } else if (env->mode == MODE_LINE_SELECTION) {
  2175. set_bold();
  2176. printf("-- LINE SELECTION --");
  2177. clear_to_end();
  2178. reset();
  2179. } else if (env->mode == MODE_REPLACE) {
  2180. set_bold();
  2181. printf("-- REPLACE --");
  2182. clear_to_end();
  2183. reset();
  2184. } else if (env->mode == MODE_CHAR_SELECTION) {
  2185. set_bold();
  2186. printf("-- CHAR SELECTION --");
  2187. clear_to_end();
  2188. reset();
  2189. } else {
  2190. clear_to_end();
  2191. }
  2192. }
  2193. /**
  2194. * Draw a message on the command line.
  2195. */
  2196. void render_commandline_message(char * message, ...) {
  2197. /* varargs setup */
  2198. va_list args;
  2199. va_start(args, message);
  2200. char buf[1024];
  2201. /* Process format string */
  2202. vsnprintf(buf, 1024, message, args);
  2203. va_end(args);
  2204. /* Hide cursor while rendering */
  2205. hide_cursor();
  2206. /* Move cursor to the last line */
  2207. place_cursor(1, global_config.term_height);
  2208. /* Set background color */
  2209. paint_line(COLOR_BG);
  2210. set_colors(COLOR_FG, COLOR_BG);
  2211. printf("%s", buf);
  2212. /* Clear the rest of the status bar */
  2213. clear_to_end();
  2214. }
  2215. /**
  2216. * Draw all screen elements
  2217. */
  2218. void redraw_all(void) {
  2219. redraw_tabbar();
  2220. redraw_text();
  2221. redraw_statusbar();
  2222. redraw_commandline();
  2223. }
  2224. /**
  2225. * Update the terminal title bar
  2226. */
  2227. void update_title(void) {
  2228. if (!global_config.can_title) return;
  2229. char cwd[1024] = {'/',0};
  2230. getcwd(cwd, 1024);
  2231. for (int i = 1; i < 3; ++i) {
  2232. printf("\033]%d;%s%s (%s) - BIM\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  2233. }
  2234. }
  2235. /**
  2236. * Mark this buffer as modified and
  2237. * redraw the status and tabbar if needed.
  2238. */
  2239. void set_modified(void) {
  2240. /* If it was already marked modified, no need to do anything */
  2241. if (env->modified) return;
  2242. /* Mark as modified */
  2243. env->modified = 1;
  2244. /* Redraw some things */
  2245. update_title();
  2246. redraw_tabbar();
  2247. redraw_statusbar();
  2248. }
  2249. /**
  2250. * Draw a message on the status line
  2251. */
  2252. void render_status_message(char * message, ...) {
  2253. /* varargs setup */
  2254. va_list args;
  2255. va_start(args, message);
  2256. char buf[1024];
  2257. /* Process format string */
  2258. vsnprintf(buf, 1024, message, args);
  2259. va_end(args);
  2260. /* Hide cursor while rendering */
  2261. hide_cursor();
  2262. /* Move cursor to the status bar line (second from bottom */
  2263. place_cursor(1, global_config.term_height - 1);
  2264. /* Set background colors for status line */
  2265. paint_line(COLOR_STATUS_BG);
  2266. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2267. printf("%s", buf);
  2268. /* Clear the rest of the status bar */
  2269. clear_to_end();
  2270. }
  2271. /**
  2272. * Draw an errormessage to the command line.
  2273. */
  2274. void render_error(char * message, ...) {
  2275. /* varargs setup */
  2276. va_list args;
  2277. va_start(args, message);
  2278. char buf[1024];
  2279. /* Process format string */
  2280. vsnprintf(buf, 1024, message, args);
  2281. va_end(args);
  2282. /* Hide cursor while rendering */
  2283. hide_cursor();
  2284. /* Move cursor to the command line */
  2285. place_cursor(1, global_config.term_height);
  2286. /* Set appropriate error message colors */
  2287. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2288. /* Draw the message */
  2289. printf("%s", buf);
  2290. fflush(stdout);
  2291. }
  2292. /**
  2293. * Move the cursor to the appropriate location based
  2294. * on where it is in the text region.
  2295. *
  2296. * This does some additional math to set the text
  2297. * region horizontal offset.
  2298. */
  2299. void place_cursor_actual(void) {
  2300. /* Invalid positions */
  2301. if (env->line_no < 1) env->line_no = 1;
  2302. if (env->col_no < 1) env->col_no = 1;
  2303. /* Account for the left hand gutter */
  2304. int num_size = num_width() + 3;
  2305. int x = num_size + 1 - env->coffset;
  2306. /* Determine where the cursor is physically */
  2307. for (int i = 0; i < env->col_no - 1; ++i) {
  2308. char_t * c = &env->lines[env->line_no-1]->text[i];
  2309. x += c->display_width;
  2310. }
  2311. /* y is a bit easier to calculate */
  2312. int y = env->line_no - env->offset + 1;
  2313. int needs_redraw = 0;
  2314. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  2315. y++;
  2316. env->offset--;
  2317. needs_redraw = 1;
  2318. }
  2319. while (y > global_config.term_height - global_config.bottom_size - global_config.cursor_padding) {
  2320. y--;
  2321. env->offset++;
  2322. needs_redraw = 1;
  2323. }
  2324. if (needs_redraw) {
  2325. redraw_text();
  2326. redraw_tabbar();
  2327. redraw_statusbar();
  2328. redraw_commandline();
  2329. }
  2330. /* If the cursor has gone off screen to the right... */
  2331. if (x > global_config.term_width - 1) {
  2332. /* Adjust the offset appropriately to scroll horizontally */
  2333. int diff = x - (global_config.term_width - 1);
  2334. env->coffset += diff;
  2335. x -= diff;
  2336. redraw_text();
  2337. }
  2338. /* Same for scrolling horizontally to the left */
  2339. if (x < num_size + 1) {
  2340. int diff = (num_size + 1) - x;
  2341. env->coffset -= diff;
  2342. x += diff;
  2343. redraw_text();
  2344. }
  2345. /* Move the actual terminal cursor */
  2346. place_cursor(x,y);
  2347. /* Show the cursor */
  2348. show_cursor();
  2349. }
  2350. /**
  2351. * Update screen size
  2352. */
  2353. void update_screen_size(void) {
  2354. struct winsize w;
  2355. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  2356. global_config.term_width = w.ws_col;
  2357. global_config.term_height = w.ws_row;
  2358. }
  2359. /**
  2360. * Handle terminal size changes
  2361. */
  2362. void SIGWINCH_handler(int sig) {
  2363. (void)sig;
  2364. update_screen_size();
  2365. redraw_all();
  2366. signal(SIGWINCH, SIGWINCH_handler);
  2367. }
  2368. /**
  2369. * Handle suspend
  2370. */
  2371. void SIGTSTP_handler(int sig) {
  2372. (void)sig;
  2373. mouse_disable();
  2374. set_buffered();
  2375. reset();
  2376. clear_screen();
  2377. show_cursor();
  2378. unset_alternate_screen();
  2379. fflush(stdout);
  2380. signal(SIGTSTP, SIG_DFL);
  2381. raise(SIGTSTP);
  2382. }
  2383. void SIGCONT_handler(int sig) {
  2384. (void)sig;
  2385. set_alternate_screen();
  2386. set_unbuffered();
  2387. mouse_enable();
  2388. redraw_all();
  2389. signal(SIGCONT, SIGCONT_handler);
  2390. signal(SIGTSTP, SIGTSTP_handler);
  2391. }
  2392. /**
  2393. * Move the cursor to a specific line.
  2394. */
  2395. void goto_line(int line) {
  2396. /* Respect file bounds */
  2397. if (line < 1) line = 1;
  2398. if (line > env->line_count) line = env->line_count;
  2399. /* Move the cursor / text region offsets */
  2400. env->coffset = 0;
  2401. env->offset = line - 1;
  2402. env->line_no = line;
  2403. env->col_no = 1;
  2404. redraw_all();
  2405. }
  2406. /**
  2407. * UTF-8 parser state
  2408. */
  2409. static uint32_t codepoint_r;
  2410. static uint32_t state = 0;
  2411. #define UTF8_ACCEPT 0
  2412. #define UTF8_REJECT 1
  2413. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  2414. static int state_table[32] = {
  2415. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  2416. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  2417. 2,2,2,2, /* 110xxxxx */
  2418. 3,3, /* 1110xxxx */
  2419. 4, /* 11110xxx */
  2420. 1 /* 11111xxx */
  2421. };
  2422. static int mask_bytes[32] = {
  2423. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  2424. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  2425. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  2426. 0x1F,0x1F,0x1F,0x1F,
  2427. 0x0F,0x0F,
  2428. 0x07,
  2429. 0x00
  2430. };
  2431. static int next[5] = {
  2432. 0,
  2433. 1,
  2434. 0,
  2435. 2,
  2436. 3
  2437. };
  2438. if (*state == UTF8_ACCEPT) {
  2439. *codep = byte & mask_bytes[byte >> 3];
  2440. *state = state_table[byte >> 3];
  2441. } else if (*state > 0) {
  2442. *codep = (byte & 0x3F) | (*codep << 6);
  2443. *state = next[*state];
  2444. }
  2445. return *state;
  2446. }
  2447. /**
  2448. * Processs (part of) a file and add it to a buffer.
  2449. */
  2450. void add_buffer(uint8_t * buf, int size) {
  2451. for (int i = 0; i < size; ++i) {
  2452. if (!decode(&state, &codepoint_r, buf[i])) {
  2453. uint32_t c = codepoint_r;
  2454. if (c == '\n') {
  2455. env->lines = add_line(env->lines, env->line_no);
  2456. env->col_no = 1;
  2457. env->line_no += 1;
  2458. } else {
  2459. char_t _c;
  2460. _c.codepoint = (uint32_t)c;
  2461. _c.flags = 0;
  2462. _c.display_width = codepoint_width((wchar_t)c);
  2463. line_t * line = env->lines[env->line_no - 1];
  2464. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  2465. if (line != nline) {
  2466. env->lines[env->line_no - 1] = nline;
  2467. }
  2468. env->col_no += 1;
  2469. }
  2470. } else if (state == UTF8_REJECT) {
  2471. state = 0;
  2472. }
  2473. }
  2474. }
  2475. struct syntax_definition * match_syntax(char * file) {
  2476. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  2477. for (char ** ext = s->ext; *ext; ++ext) {
  2478. int i = strlen(file);
  2479. int j = strlen(*ext);
  2480. do {
  2481. if (file[i] != (*ext)[j]) break;
  2482. if (j == 0) return s;
  2483. if (i == 0) break;
  2484. i--;
  2485. j--;
  2486. } while (1);
  2487. }
  2488. }
  2489. return NULL;
  2490. }
  2491. /**
  2492. * Create a new buffer from a file.
  2493. */
  2494. void open_file(char * file) {
  2495. env = buffer_new();
  2496. env->loading = 1;
  2497. setup_buffer(env);
  2498. FILE * f;
  2499. if (!strcmp(file,"-")) {
  2500. /**
  2501. * Read file from stdin. stderr provides terminal input.
  2502. */
  2503. f = stdin;
  2504. global_config.tty_in = STDERR_FILENO;
  2505. env->modified = 1;
  2506. } else {
  2507. f = fopen(file, "r");
  2508. env->file_name = strdup(file);
  2509. }
  2510. if (!f) {
  2511. if (global_config.hilight_on_open) {
  2512. env->syntax = match_syntax(file);
  2513. }
  2514. env->loading = 0;
  2515. return;
  2516. }
  2517. uint8_t buf[BLOCK_SIZE];
  2518. state = 0;
  2519. while (!feof(f) && !ferror(f)) {
  2520. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  2521. add_buffer(buf, r);
  2522. }
  2523. if (ferror(f)) {
  2524. env->loading = 0;
  2525. return;
  2526. }
  2527. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  2528. /* Remove blank line from end */
  2529. remove_line(env->lines, env->line_no-1);
  2530. }
  2531. if (global_config.hilight_on_open) {
  2532. env->syntax = match_syntax(file);
  2533. for (int i = 0; i < env->line_count; ++i) {
  2534. recalculate_syntax(env->lines[i],i);
  2535. }
  2536. }
  2537. /* Try to automatically figure out tabs vs. spaces */
  2538. int tabs = 0, spaces = 0;
  2539. for (int i = 0; i < env->line_count; ++i) {
  2540. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  2541. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  2542. if (env->lines[i]->text[0].codepoint == ' ' &&
  2543. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  2544. spaces++;
  2545. }
  2546. }
  2547. if (spaces > tabs) {
  2548. env->tabs = 0;
  2549. }
  2550. /* TODO figure out tabstop for spaces? */
  2551. env->loading = 0;
  2552. for (int i = 0; i < env->line_count; ++i) {
  2553. recalculate_tabs(env->lines[i]);
  2554. }
  2555. fclose(f);
  2556. }
  2557. /**
  2558. * Clean up the terminal and exit the editor.
  2559. */
  2560. void quit(void) {
  2561. mouse_disable();
  2562. set_buffered();
  2563. reset();
  2564. clear_screen();
  2565. show_cursor();
  2566. unset_alternate_screen();
  2567. exit(0);
  2568. }
  2569. /**
  2570. * Try to quit, but don't continue if there are
  2571. * modified buffers open.
  2572. */
  2573. void try_quit(void) {
  2574. for (int i = 0; i < buffers_len; i++ ) {
  2575. buffer_t * _env = buffers[i];
  2576. if (_env->modified) {
  2577. if (_env->file_name) {
  2578. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  2579. } else {
  2580. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  2581. }
  2582. return;
  2583. }
  2584. }
  2585. quit();
  2586. }
  2587. /**
  2588. * Switch to the previous buffer
  2589. */
  2590. void previous_tab(void) {
  2591. buffer_t * last = NULL;
  2592. for (int i = 0; i < buffers_len; i++) {
  2593. buffer_t * _env = buffers[i];
  2594. if (_env == env) {
  2595. if (last) {
  2596. /* Wrap around */
  2597. env = last;
  2598. redraw_all();
  2599. return;
  2600. } else {
  2601. env = buffers[buffers_len-1];
  2602. redraw_all();
  2603. return;
  2604. }
  2605. }
  2606. last = _env;
  2607. }
  2608. }
  2609. /**
  2610. * Switch to the next buffer
  2611. */
  2612. void next_tab(void) {
  2613. for (int i = 0; i < buffers_len; i++) {
  2614. buffer_t * _env = buffers[i];
  2615. if (_env == env) {
  2616. if (i != buffers_len - 1) {
  2617. env = buffers[i+1];
  2618. redraw_all();
  2619. return;
  2620. } else {
  2621. /* Wrap around */
  2622. env = buffers[0];
  2623. redraw_all();
  2624. return;
  2625. }
  2626. }
  2627. }
  2628. }
  2629. /**
  2630. * Write active buffer to file
  2631. */
  2632. void write_file(char * file) {
  2633. if (!file) {
  2634. render_error("Need a file to write to.");
  2635. return;
  2636. }
  2637. FILE * f = fopen(file, "w+");
  2638. if (!f) {
  2639. render_error("Failed to open file for writing.");
  2640. return;
  2641. }
  2642. /* Go through each line and convert it back to UTF-8 */
  2643. int i, j;
  2644. for (i = 0; i < env->line_count; ++i) {
  2645. line_t * line = env->lines[i];
  2646. for (j = 0; j < line->actual; j++) {
  2647. char_t c = line->text[j];
  2648. if (c.codepoint == 0) {
  2649. char buf[1] = {0};
  2650. fwrite(buf, 1, 1, f);
  2651. } else {
  2652. char tmp[8] = {0};
  2653. int i = to_eight(c.codepoint, tmp);
  2654. fwrite(tmp, i, 1, f);
  2655. }
  2656. }
  2657. fputc('\n', f);
  2658. }
  2659. fclose(f);
  2660. /* Mark it no longer modified */
  2661. env->modified = 0;
  2662. env->last_save_history = env->history;
  2663. /* If there was no file name set, set one */
  2664. if (!env->file_name) {
  2665. env->file_name = malloc(strlen(file) + 1);
  2666. memcpy(env->file_name, file, strlen(file) + 1);
  2667. }
  2668. update_title();
  2669. redraw_all();
  2670. }
  2671. /**
  2672. * Close the active buffer
  2673. */
  2674. void close_buffer(void) {
  2675. buffer_t * previous_env = env;
  2676. buffer_t * new_env = buffer_close(env);
  2677. if (new_env == previous_env) {
  2678. /* ?? Failed to close buffer */
  2679. render_error("lolwat");
  2680. }
  2681. /* No more buffers, exit */
  2682. if (!new_env) {
  2683. quit();
  2684. }
  2685. /* Clean up the old buffer */
  2686. free(previous_env);
  2687. /* Set the new active buffer */
  2688. env = new_env;
  2689. /* Redraw the screen */
  2690. redraw_all();
  2691. }
  2692. /**
  2693. * Move the cursor down one line in the text region
  2694. */
  2695. void cursor_down(void) {
  2696. /* If this isn't already the last line... */
  2697. if (env->line_no < env->line_count) {
  2698. /* Move the cursor down */
  2699. env->line_no += 1;
  2700. /*
  2701. * If the horizontal cursor position exceeds the width the new line,
  2702. * then move the cursor left to the extent of the new line.
  2703. *
  2704. * If we're in insert mode, we can go one cell beyond the end of the line
  2705. */
  2706. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  2707. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  2708. if (env->col_no == 0) env->col_no = 1;
  2709. }
  2710. /*
  2711. * If the screen was scrolled horizontally, unscroll it;
  2712. * if it will be scrolled on this line as well, that will
  2713. * be handled by place_cursor_actual
  2714. */
  2715. int redraw = 0;
  2716. if (env->coffset != 0) {
  2717. env->coffset = 0;
  2718. redraw = 1;
  2719. }
  2720. /* If we've scrolled past the bottom of the screen, scroll the screen */
  2721. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  2722. env->offset += 1;
  2723. /* Tell terminal to scroll */
  2724. if (global_config.can_scroll) {
  2725. shift_up();
  2726. /* A new line appears on screen at the bottom, draw it */
  2727. int l = global_config.term_height - global_config.bottom_size - 1;
  2728. if (env->offset + l < env->line_count + 1) {
  2729. redraw_line(l-1, env->offset + l-1);
  2730. } else {
  2731. draw_excess_line(l - 1);
  2732. }
  2733. /* Redraw elements that were moved by scrolling */
  2734. redraw_tabbar();
  2735. redraw_statusbar();
  2736. redraw_commandline();
  2737. place_cursor_actual();
  2738. } else {
  2739. redraw_all();
  2740. }
  2741. return;
  2742. } else if (redraw) {
  2743. /* Otherwise, if we need to redraw because of coffset change, do that */
  2744. redraw_text();
  2745. }
  2746. /* Update the status bar */
  2747. redraw_statusbar();
  2748. /* Place the terminal cursor again */
  2749. place_cursor_actual();
  2750. }
  2751. }
  2752. /**
  2753. * Move the cursor up one line in the text region
  2754. */
  2755. void cursor_up(void) {
  2756. /* If this isn't the first line already */
  2757. if (env->line_no > 1) {
  2758. /* Move the cursor down */
  2759. env->line_no -= 1;
  2760. /*
  2761. * If the horizontal cursor position exceeds the width the new line,
  2762. * then move the cursor left to the extent of the new line.
  2763. *
  2764. * If we're in insert mode, we can go one cell beyond the end of the line
  2765. */
  2766. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  2767. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  2768. if (env->col_no == 0) env->col_no = 1;
  2769. }
  2770. /*
  2771. * If the screen was scrolled horizontally, unscroll it;
  2772. * if it will be scrolled on this line as well, that will
  2773. * be handled by place_cursor_actual
  2774. */
  2775. int redraw = 0;
  2776. if (env->coffset != 0) {
  2777. env->coffset = 0;
  2778. redraw = 1;
  2779. }
  2780. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  2781. if (env->line_no <= e) {
  2782. env->offset -= 1;
  2783. /* Tell terminal to scroll */
  2784. if (global_config.can_scroll) {
  2785. shift_down();
  2786. /*
  2787. * The line at the top of the screen should always be real
  2788. * so we can just call redraw_line here
  2789. */
  2790. redraw_line(0,env->offset);
  2791. /* Redraw elements that were moved by scrolling */
  2792. redraw_tabbar();
  2793. redraw_statusbar();
  2794. redraw_commandline();
  2795. place_cursor_actual();
  2796. } else {
  2797. redraw_all();
  2798. }
  2799. return;
  2800. } else if (redraw) {
  2801. /* Otherwise, if we need to redraw because of coffset change, do that */
  2802. redraw_text();
  2803. }
  2804. /* Update the status bar */
  2805. redraw_statusbar();
  2806. /* Place the terminal cursor again */
  2807. place_cursor_actual();
  2808. }
  2809. }
  2810. /**
  2811. * Move the cursor one column left.
  2812. */
  2813. void cursor_left(void) {
  2814. if (env->col_no > 1) {
  2815. env->col_no -= 1;
  2816. /* Update the status bar */
  2817. redraw_statusbar();
  2818. /* Place the terminal cursor again */
  2819. place_cursor_actual();
  2820. }
  2821. }
  2822. /**
  2823. * Move the cursor one column right.
  2824. */
  2825. void cursor_right(void) {
  2826. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  2827. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  2828. env->col_no += 1;
  2829. /* Update the status bar */
  2830. redraw_statusbar();
  2831. /* Place the terminal cursor again */
  2832. place_cursor_actual();
  2833. }
  2834. }
  2835. /**
  2836. * Move the cursor to the fron the of the line
  2837. */
  2838. void cursor_home(void) {
  2839. env->col_no = 1;
  2840. /* Update the status bar */
  2841. redraw_statusbar();
  2842. /* Place the terminal cursor again */
  2843. place_cursor_actual();
  2844. }
  2845. /**
  2846. * Move the cursor to the end of the line.
  2847. *
  2848. * In INSERT mode, moves one cell right of the end of the line.
  2849. * In NORMAL mode, moves the cursor to the last occupied cell.
  2850. */
  2851. void cursor_end(void) {
  2852. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  2853. /* Update the status bar */
  2854. redraw_statusbar();
  2855. /* Place the terminal cursor again */
  2856. place_cursor_actual();
  2857. }
  2858. /**
  2859. * Leave INSERT mode
  2860. *
  2861. * If the cursor is too far right, adjust it.
  2862. * Redraw the command line.
  2863. */
  2864. void leave_insert(void) {
  2865. if (env->col_no > env->lines[env->line_no-1]->actual) {
  2866. env->col_no = env->lines[env->line_no-1]->actual;
  2867. if (env->col_no == 0) env->col_no = 1;
  2868. }
  2869. set_history_break();
  2870. env->mode = MODE_NORMAL;
  2871. redraw_commandline();
  2872. }
  2873. /**
  2874. * Process a user command.
  2875. */
  2876. void process_command(char * cmd) {
  2877. /* Special case ! to run shell commands without parsing tokens */
  2878. if (*cmd == '!') {
  2879. /* Reset and draw some line feeds */
  2880. reset();
  2881. printf("\n\n");
  2882. /* Set buffered for shell application */
  2883. set_buffered();
  2884. /* Call the shell and wait for completion */
  2885. system(&cmd[1]);
  2886. /* Return to the editor, wait for user to press enter. */
  2887. set_unbuffered();
  2888. printf("\n\nPress ENTER to continue.");
  2889. fflush(stdout);
  2890. while (bim_getch() != ENTER_KEY);
  2891. /* Redraw the screen */
  2892. redraw_all();
  2893. /* Done processing command */
  2894. return;
  2895. }
  2896. /* Tokenize argument string on spaces */
  2897. char *p, *argv[512], *last;
  2898. int argc = 0;
  2899. for ((p = strtok_r(cmd, " ", &last)); p;
  2900. (p = strtok_r(NULL, " ", &last)), argc++) {
  2901. if (argc < 511) argv[argc] = p;
  2902. }
  2903. argv[argc] = NULL;
  2904. if (argc < 1) {
  2905. /* no op */
  2906. return;
  2907. }
  2908. if (!strcmp(argv[0], "e")) {
  2909. /* e: edit file */
  2910. if (argc > 1) {
  2911. /* This actually opens a new tab */
  2912. open_file(argv[1]);
  2913. update_title();
  2914. goto_line(0);
  2915. } else {
  2916. /* TODO: Reopen file? */
  2917. render_error("Expected a file to open...");
  2918. }
  2919. } else if (!strcmp(argv[0], "tabnew")) {
  2920. if (argc > 1) {
  2921. open_file(argv[1]);
  2922. update_title();
  2923. goto_line(0);
  2924. } else {
  2925. env = buffer_new();
  2926. setup_buffer(env);
  2927. redraw_all();
  2928. update_title();
  2929. }
  2930. } else if (!strcmp(argv[0], "w")) {
  2931. /* w: write file */
  2932. if (argc > 1) {
  2933. write_file(argv[1]);
  2934. } else {
  2935. write_file(env->file_name);
  2936. }
  2937. } else if (!strcmp(argv[0], "wq")) {
  2938. /* wq: write file and close buffer; if there's no file to write to, may do weird things */
  2939. write_file(env->file_name);
  2940. close_buffer();
  2941. } else if (!strcmp(argv[0], "q")) {
  2942. /* close buffer if unmodified */
  2943. if (env->modified) {
  2944. render_error("No write since last change. Use :q! to force exit.");
  2945. } else {
  2946. close_buffer();
  2947. }
  2948. } else if (!strcmp(argv[0], "q!")) {
  2949. /* close buffer without warning if unmodified */
  2950. close_buffer();
  2951. } else if (!strcmp(argv[0], "qa") || !strcmp(argv[0], "qall")) {
  2952. /* Close all */
  2953. try_quit();
  2954. } else if (!strcmp(argv[0], "qa!")) {
  2955. /* Forcefully exit editor */
  2956. quit();
  2957. } else if (!strcmp(argv[0], "tabp")) {
  2958. /* Next tab */
  2959. previous_tab();
  2960. update_title();
  2961. } else if (!strcmp(argv[0], "tabn")) {
  2962. /* Previous tab */
  2963. next_tab();
  2964. update_title();
  2965. } else if (!strcmp(argv[0], "indent")) {
  2966. env->indent = 1;
  2967. redraw_statusbar();
  2968. } else if (!strcmp(argv[0], "noindent")) {
  2969. env->indent = 0;
  2970. redraw_statusbar();
  2971. } else if (!strcmp(argv[0], "noh")) {
  2972. if (env->search) {
  2973. free(env->search);
  2974. env->search = NULL;
  2975. redraw_text();
  2976. }
  2977. } else if (!strcmp(argv[0], "help")) {
  2978. /*
  2979. * The repeated calls to redraw_commandline here make use
  2980. * of scrolling to draw this multiline help message on
  2981. * the same background as the command line.
  2982. */
  2983. render_commandline_message(""); /* To clear command line */
  2984. render_commandline_message("\n");
  2985. render_commandline_message(" \033[1mbim - The standard ToaruOS Text Editor\033[22m\n");
  2986. render_commandline_message("\n");
  2987. render_commandline_message(" Available commands:\n");
  2988. 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");
  2989. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  2990. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  2991. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  2992. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  2993. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  2994. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  2995. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  2996. render_commandline_message("\n");
  2997. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  2998. render_commandline_message("\n");
  2999. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  3000. redraw_tabbar();
  3001. redraw_commandline();
  3002. fflush(stdout);
  3003. /* Wait for a character so we can redraw the screen before continuing */
  3004. int c;
  3005. while ((c = bim_getch())== -1);
  3006. /* Make sure that key press actually gets used */
  3007. bim_unget(c);
  3008. /*
  3009. * Redraw everything to hide the help message and get the
  3010. * upper few lines of text on screen again
  3011. */
  3012. redraw_all();
  3013. } else if (!strcmp(argv[0], "theme")) {
  3014. if (argc < 2) {
  3015. render_status_message("theme=%s", current_theme);
  3016. return;
  3017. }
  3018. for (struct theme_def * d = themes; d->name; ++d) {
  3019. if (!strcmp(argv[1], d->name)) {
  3020. d->load();
  3021. redraw_all();
  3022. return;
  3023. }
  3024. }
  3025. } else if (!strcmp(argv[0], "syntax")) {
  3026. if (argc < 2) {
  3027. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  3028. return;
  3029. }
  3030. if (!strcmp(argv[1],"none")) {
  3031. for (int i = 0; i < env->line_count; ++i) {
  3032. env->lines[i]->istate = 0;
  3033. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3034. env->lines[i]->text[j].flags = 0;
  3035. }
  3036. }
  3037. redraw_all();
  3038. return;
  3039. }
  3040. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  3041. if (!strcmp(argv[1],s->name)) {
  3042. env->syntax = s;
  3043. for (int i = 0; i < env->line_count; ++i) {
  3044. env->lines[i]->istate = 0;
  3045. }
  3046. for (int i = 0; i < env->line_count; ++i) {
  3047. recalculate_syntax(env->lines[i],i);
  3048. }
  3049. redraw_all();
  3050. return;
  3051. }
  3052. }
  3053. render_error("unrecognized syntax type");
  3054. } else if (!strcmp(argv[0], "recalc")) {
  3055. for (int i = 0; i < env->line_count; ++i) {
  3056. env->lines[i]->istate = 0;
  3057. }
  3058. for (int i = 0; i < env->line_count; ++i) {
  3059. recalculate_syntax(env->lines[i],i);
  3060. }
  3061. redraw_all();
  3062. } else if (!strcmp(argv[0], "tabs")) {
  3063. env->tabs = 1;
  3064. redraw_statusbar();
  3065. } else if (!strcmp(argv[0], "spaces")) {
  3066. env->tabs = 0;
  3067. redraw_statusbar();
  3068. } else if (!strcmp(argv[0], "tabstop")) {
  3069. if (argc < 2) {
  3070. render_status_message("tabstop=%d", env->tabstop);
  3071. } else {
  3072. int t = atoi(argv[1]);
  3073. if (t > 0 && t < 32) {
  3074. env->tabstop = t;
  3075. for (int i = 0; i < env->line_count; ++i) {
  3076. recalculate_tabs(env->lines[i]);
  3077. }
  3078. redraw_all();
  3079. } else {
  3080. render_error("Invalid tabstop: %s", argv[1]);
  3081. }
  3082. }
  3083. } else if (!strcmp(argv[0], "clearyank")) {
  3084. if (global_config.yanks) {
  3085. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  3086. free(global_config.yanks[i]);
  3087. }
  3088. free(global_config.yanks);
  3089. global_config.yanks = NULL;
  3090. global_config.yank_count = 0;
  3091. redraw_statusbar();
  3092. }
  3093. } else if (!strcmp(argv[0], "padding")) {
  3094. if (argc < 2) {
  3095. render_status_message("padding=%d", global_config.cursor_padding);
  3096. } else {
  3097. global_config.cursor_padding = atoi(argv[1]);
  3098. place_cursor_actual();
  3099. }
  3100. } else if (isdigit(*argv[0])) {
  3101. /* Go to line number */
  3102. goto_line(atoi(argv[0]));
  3103. } else {
  3104. /* Unrecognized command */
  3105. render_error("Not an editor command: %s", argv[0]);
  3106. }
  3107. }
  3108. /**
  3109. * Tab completion for command mode.
  3110. */
  3111. void command_tab_complete(char * buffer) {
  3112. /* Figure out which argument this is and where it starts */
  3113. int arg = 0;
  3114. char * buf = strdup(buffer);
  3115. char * b = buf;
  3116. char * args[32];
  3117. int candidate_count= 0;
  3118. int candidate_space = 4;
  3119. char ** candidates = malloc(sizeof(char*)*candidate_space);
  3120. /* Accept whitespace before first argument */
  3121. while (*b == ' ') b++;
  3122. char * start = b;
  3123. args[0] = start;
  3124. while (*b && *b != ' ') b++;
  3125. while (*b) {
  3126. while (*b == ' ') {
  3127. *b = '\0';
  3128. b++;
  3129. }
  3130. start = b;
  3131. arg++;
  3132. if (arg < 32) {
  3133. args[arg] = start;
  3134. }
  3135. while (*b && *b != ' ') b++;
  3136. }
  3137. /**
  3138. * Check a possible candidate and add it to the
  3139. * candidates list, expanding as necessary,
  3140. * if it matches for the current argument.
  3141. */
  3142. #define add_candidate(candidate) \
  3143. do { \
  3144. char * _arg = args[arg]; \
  3145. int r = strncmp(_arg, candidate, strlen(_arg)); \
  3146. if (!r) { \
  3147. if (candidate_count == candidate_space) { \
  3148. candidate_space *= 2; \
  3149. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  3150. } \
  3151. candidates[candidate_count] = strdup(candidate); \
  3152. candidate_count++; \
  3153. } \
  3154. } while (0)
  3155. if (arg == 0) {
  3156. /* Complete command names */
  3157. add_candidate("help");
  3158. add_candidate("recalc");
  3159. add_candidate("syntax");
  3160. add_candidate("tabn");
  3161. add_candidate("tabp");
  3162. add_candidate("tabnew");
  3163. add_candidate("theme");
  3164. add_candidate("tabs");
  3165. add_candidate("tabstop");
  3166. add_candidate("spaces");
  3167. add_candidate("noh");
  3168. add_candidate("clearyank");
  3169. add_candidate("indent");
  3170. add_candidate("noindent");
  3171. add_candidate("padding");
  3172. goto _accept_candidate;
  3173. }
  3174. if (arg == 1 && !strcmp(args[0], "syntax")) {
  3175. /* Complete syntax options */
  3176. add_candidate("none");
  3177. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  3178. add_candidate(s->name);
  3179. }
  3180. goto _accept_candidate;
  3181. }
  3182. if (arg == 1 && !strcmp(args[0], "theme")) {
  3183. /* Complete color theme names */
  3184. for (struct theme_def * s = themes; s->name; ++s) {
  3185. add_candidate(s->name);
  3186. }
  3187. goto _accept_candidate;
  3188. }
  3189. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew"))) {
  3190. /* Complete file paths */
  3191. /* First, find the deepest directory match */
  3192. char * tmp = strdup(args[arg]);
  3193. char * last_slash = strrchr(tmp, '/');
  3194. DIR * dirp;
  3195. if (last_slash) {
  3196. *last_slash = '\0';
  3197. if (last_slash == tmp) {
  3198. /* Started with slash, and it was the only slash */
  3199. dirp = opendir("/");
  3200. } else {
  3201. dirp = opendir(tmp);
  3202. }
  3203. } else {
  3204. /* No directory match, completing from current directory */
  3205. dirp = opendir(".");
  3206. tmp[0] = '\0';
  3207. }
  3208. if (!dirp) {
  3209. /* Directory match doesn't exist, no candidates to populate */
  3210. free(tmp);
  3211. goto done;
  3212. }
  3213. struct dirent * ent = readdir(dirp);
  3214. while (ent != NULL) {
  3215. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  3216. struct stat statbuf;
  3217. /* Figure out if this file is a directory */
  3218. if (last_slash) {
  3219. char * x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  3220. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  3221. stat(x, &statbuf);
  3222. free(x);
  3223. } else {
  3224. stat(ent->d_name, &statbuf);
  3225. }
  3226. /* Build the complete argument name to tab complete */
  3227. char s[1024] = {0};
  3228. if (last_slash == tmp) {
  3229. strcat(s,"/");
  3230. } else if (*tmp) {
  3231. strcat(s,tmp);
  3232. strcat(s,"/");
  3233. }
  3234. strcat(s,ent->d_name);
  3235. /*
  3236. * If it is a directory, add a / to the end so the next completion
  3237. * attempt will complete the directory's contents.
  3238. */
  3239. if (S_ISDIR(statbuf.st_mode)) {
  3240. strcat(s,"/");
  3241. }
  3242. add_candidate(s);
  3243. }
  3244. ent = readdir(dirp);
  3245. }
  3246. closedir(dirp);
  3247. free(tmp);
  3248. goto _accept_candidate;
  3249. }
  3250. _accept_candidate:
  3251. if (candidate_count == 0) {
  3252. redraw_statusbar();
  3253. goto done;
  3254. }
  3255. if (candidate_count == 1) {
  3256. /* Only one completion possibility */
  3257. redraw_statusbar();
  3258. /* Fill out the rest of the command */
  3259. char * cstart = (buffer) + (start - buf);
  3260. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  3261. *cstart = candidates[0][i];
  3262. cstart++;
  3263. }
  3264. *cstart = '\0';
  3265. } else {
  3266. /* Print candidates in status bar */
  3267. char tmp[global_config.term_width+1];
  3268. memset(tmp, 0, global_config.term_width+1);
  3269. int offset = 0;
  3270. for (int i = 0; i < candidate_count; ++i) {
  3271. if (offset + 1 + (signed)strlen(candidates[i]) > global_config.term_width - 5) {
  3272. strcat(tmp, "...");
  3273. break;
  3274. }
  3275. if (offset > 0) {
  3276. strcat(tmp, " ");
  3277. offset++;
  3278. }
  3279. strcat(tmp, candidates[i]);
  3280. offset += strlen(candidates[i]);
  3281. }
  3282. render_status_message("%s", tmp);
  3283. /* Complete to longest common substring */
  3284. char * cstart = (buffer) + (start - buf);
  3285. for (int i = 0; i < 1023 /* max length of command */; i++) {
  3286. for (int j = 1; j < candidate_count; ++j) {
  3287. if (candidates[0][i] != candidates[j][i]) goto _reject;
  3288. }
  3289. *cstart = candidates[0][i];
  3290. cstart++;
  3291. }
  3292. /* End of longest common substring */
  3293. _reject:
  3294. *cstart = '\0';
  3295. }
  3296. /* Free candidates */
  3297. for (int i = 0; i < candidate_count; ++i) {
  3298. free(candidates[i]);
  3299. }
  3300. /* Redraw command line */
  3301. done:
  3302. redraw_commandline();
  3303. printf(":%s", buffer);
  3304. free(candidates);
  3305. free(buf);
  3306. }
  3307. /**
  3308. * Command mode
  3309. *
  3310. * Accept a user command and then process it and
  3311. * return to normal mode.
  3312. *
  3313. * TODO: We only have basic line editing here; it might be
  3314. * nice to add more advanced line editing, like cursor
  3315. * movement, tab completion, etc. This is easier than
  3316. * with the shell since we have a lot more control over
  3317. * where the command input bar is rendered.
  3318. */
  3319. void command_mode(void) {
  3320. int c;
  3321. char buffer[1024] = {0};
  3322. int buffer_len = 0;
  3323. redraw_commandline();
  3324. printf(":");
  3325. show_cursor();
  3326. while ((c = bim_getch())) {
  3327. if (c == -1) {
  3328. /* Time out */
  3329. continue;
  3330. }
  3331. if (c == '\033') {
  3332. /* Escape, cancel command */
  3333. break;
  3334. } else if (c == ENTER_KEY) {
  3335. /* Enter, run command */
  3336. process_command(buffer);
  3337. break;
  3338. } else if (c == '\t') {
  3339. /* Handle tab completion */
  3340. command_tab_complete(buffer);
  3341. buffer_len = strlen(buffer);
  3342. } else if (c == BACKSPACE_KEY || c == DELETE_KEY) {
  3343. /* Backspace, delete last character in command buffer */
  3344. if (buffer_len > 0) {
  3345. buffer_len -= 1;
  3346. buffer[buffer_len] = '\0';
  3347. redraw_commandline();
  3348. printf(":%s", buffer);
  3349. } else {
  3350. /* If backspaced through entire command, cancel command mode */
  3351. redraw_commandline();
  3352. break;
  3353. }
  3354. } else {
  3355. /* Regular character */
  3356. buffer[buffer_len] = c;
  3357. buffer_len++;
  3358. printf("%c", c);
  3359. }
  3360. show_cursor();
  3361. }
  3362. }
  3363. /**
  3364. * Search forward from the given cursor position
  3365. * to find a basic search match.
  3366. *
  3367. * This could be more complicated...
  3368. */
  3369. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  3370. int col = from_col;
  3371. for (int i = from_line; i <= env->line_count; ++i) {
  3372. line_t * line = env->lines[i - 1];
  3373. int j = col - 1;
  3374. while (j < line->actual + 1) {
  3375. int k = j;
  3376. uint32_t * match = str;
  3377. while (k < line->actual + 1) {
  3378. if (*match == '\0') {
  3379. *out_line = i;
  3380. *out_col = j + 1;
  3381. return;
  3382. }
  3383. /* TODO search for UTF-8 sequences? */
  3384. if (*match != line->text[k].codepoint) break;
  3385. match++;
  3386. k++;
  3387. }
  3388. j++;
  3389. }
  3390. col = 0;
  3391. }
  3392. }
  3393. /**
  3394. * Search backwards for matching string.
  3395. */
  3396. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  3397. int col = from_col;
  3398. for (int i = from_line; i >= 1; --i) {
  3399. line_t * line = env->lines[i-1];
  3400. int j = col - 1;
  3401. while (j > -1) {
  3402. int k = j;
  3403. uint32_t * match = str;
  3404. while (k < line->actual + 1) {
  3405. if (*match == '\0') {
  3406. *out_line = i;
  3407. *out_col = j + 1;
  3408. return;
  3409. }
  3410. /* TODO search for UTF-8 sequences? */
  3411. if (*match != line->text[k].codepoint) break;
  3412. match++;
  3413. k++;
  3414. }
  3415. j--;
  3416. }
  3417. col = (i > 1) ? (env->lines[i-2]->actual) : -1;
  3418. }
  3419. }
  3420. /**
  3421. * Draw the matched search result.
  3422. */
  3423. void draw_search_match(int line, uint32_t * buffer, int redraw_buffer) {
  3424. place_cursor_actual();
  3425. redraw_text();
  3426. if (line != -1) {
  3427. /*
  3428. * TODO this should probably mark the relevant
  3429. * regions so that redraw_text can hilight it
  3430. */
  3431. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  3432. place_cursor_actual();
  3433. uint32_t * c = buffer;
  3434. while (*c) {
  3435. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  3436. to_eight(*c, tmp);
  3437. printf("%s", tmp);
  3438. c++;
  3439. }
  3440. }
  3441. redraw_statusbar();
  3442. redraw_commandline();
  3443. if (redraw_buffer != -1) {
  3444. printf(redraw_buffer == 1 ? "/" : "?");
  3445. uint32_t * c = buffer;
  3446. while (*c) {
  3447. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  3448. to_eight(*c, tmp);
  3449. printf("%s", tmp);
  3450. c++;
  3451. }
  3452. }
  3453. }
  3454. /**
  3455. * Search mode
  3456. *
  3457. * Search text for substring match.
  3458. */
  3459. void search_mode(int direction) {
  3460. uint32_t c;
  3461. uint32_t buffer[1024] = {0};
  3462. int buffer_len = 0;
  3463. /* utf-8 decoding */
  3464. /* Remember where the cursor is so we can cancel */
  3465. int prev_line = env->line_no;
  3466. int prev_col = env->col_no;
  3467. int prev_coffset = env->coffset;
  3468. int prev_offset = env->offset;
  3469. redraw_commandline();
  3470. printf(direction == 1 ? "/" : "?");
  3471. show_cursor();
  3472. uint32_t state = 0;
  3473. int cin;
  3474. while ((cin = bim_getch())) {
  3475. if (cin == -1) {
  3476. /* Time out */
  3477. continue;
  3478. }
  3479. if (!decode(&state, &c, cin)) {
  3480. if (c == '\033') {
  3481. /* Cancel search */
  3482. env->line_no = prev_line;
  3483. env->col_no = prev_col;
  3484. redraw_all();
  3485. break;
  3486. } else if (c == ENTER_KEY) {
  3487. /* Exit search */
  3488. if (env->search) {
  3489. free(env->search);
  3490. }
  3491. env->search = malloc((buffer_len + 1) * sizeof(uint32_t));
  3492. memcpy(env->search, buffer, (buffer_len + 1) * sizeof(uint32_t));
  3493. break;
  3494. } else if (c == BACKSPACE_KEY || c == DELETE_KEY) {
  3495. /* Backspace, delete last character in search buffer */
  3496. if (buffer_len > 0) {
  3497. buffer_len -= 1;
  3498. buffer[buffer_len] = '\0';
  3499. /* Search from beginning to find first match */
  3500. int line = -1, col = -1;
  3501. if (direction == 1) {
  3502. find_match(prev_line, prev_col, &line, &col, buffer);
  3503. } else {
  3504. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  3505. }
  3506. if (line != -1) {
  3507. env->col_no = col;
  3508. env->line_no = line;
  3509. }
  3510. draw_search_match(line, buffer, direction);
  3511. } else {
  3512. /* If backspaced through entire search term, cancel search */
  3513. redraw_commandline();
  3514. env->coffset = prev_coffset;
  3515. env->offset = prev_offset;
  3516. env->col_no = prev_col;
  3517. env->line_no = prev_line;
  3518. redraw_all();
  3519. break;
  3520. }
  3521. } else {
  3522. /* Regular character */
  3523. buffer[buffer_len] = c;
  3524. buffer_len++;
  3525. buffer[buffer_len] = '\0';
  3526. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  3527. to_eight(c, tmp);
  3528. printf("%s", tmp);
  3529. /* Find the next search match */
  3530. int line = -1, col = -1;
  3531. if (direction == 1) {
  3532. find_match(prev_line, prev_col, &line, &col, buffer);
  3533. } else {
  3534. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  3535. }
  3536. if (line != -1) {
  3537. env->col_no = col;
  3538. env->line_no = line;
  3539. } else {
  3540. env->coffset = prev_coffset;
  3541. env->offset = prev_offset;
  3542. env->col_no = prev_col;
  3543. env->line_no = prev_line;
  3544. }
  3545. draw_search_match(line, buffer, direction);
  3546. }
  3547. show_cursor();
  3548. } else if (state == UTF8_REJECT) {
  3549. state = 0;
  3550. }
  3551. }
  3552. }
  3553. /**
  3554. * Find the next search result, or loop back around if at the end.
  3555. */
  3556. void search_next(void) {
  3557. if (!env->search) return;
  3558. int line = -1, col = -1;
  3559. find_match(env->line_no, env->col_no+1, &line, &col, env->search);
  3560. if (line == -1) {
  3561. find_match(1,1, &line, &col, env->search);
  3562. if (line == -1) return;
  3563. }
  3564. env->col_no = col;
  3565. env->line_no = line;
  3566. draw_search_match(line, env->search, -1);
  3567. }
  3568. /**
  3569. * Find the previous search result, or loop to the end of the file.
  3570. */
  3571. void search_prev(void) {
  3572. if (!env->search) return;
  3573. int line = -1, col = -1;
  3574. find_match_backwards(env->line_no, env->col_no-1, &line, &col, env->search);
  3575. if (line == -1) {
  3576. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, env->search);
  3577. if (line == -1) return;
  3578. }
  3579. env->col_no = col;
  3580. env->line_no = line;
  3581. draw_search_match(line, env->search, -1);
  3582. }
  3583. /**
  3584. * Find the matching paren for this one.
  3585. *
  3586. * This approach skips having to do its own syntax parsing
  3587. * to deal with, eg., erroneous parens in comments. It does
  3588. * this by finding the matching paren with the same flag
  3589. * value, thus parens in strings will match, parens outside
  3590. * of strings will match, but parens in strings won't
  3591. * match parens outside of strings and so on.
  3592. */
  3593. void find_matching_paren(void) {
  3594. if (env->col_no > env->lines[env->line_no-1]->actual) {
  3595. return; /* Invalid cursor position */
  3596. }
  3597. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  3598. int paren_match = 0;
  3599. int direction = 0;
  3600. int start = env->lines[env->line_no-1]->text[env->col_no-1].codepoint;
  3601. int flags = env->lines[env->line_no-1]->text[env->col_no-1].flags;
  3602. int count = 0;
  3603. /* TODO what about unicode parens? */
  3604. char * p = "()[]{}<>";
  3605. for (int i = 0; p[i]; ++i) {
  3606. if (start == p[i]) {
  3607. direction = (i % 2 == 0) ? 1 : -1;
  3608. paren_match = p[(i % 2 == 0) ? (i+1) : (i-1)];
  3609. break;
  3610. }
  3611. }
  3612. if (!paren_match) return;
  3613. /* Scan for match */
  3614. int line = env->line_no;
  3615. int col = env->col_no;
  3616. do {
  3617. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  3618. /* Only match on same syntax */
  3619. if (env->lines[line-1]->text[col-1].flags == flags) {
  3620. /* Count up on same direction */
  3621. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  3622. /* Count down on opposite direction */
  3623. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  3624. count--;
  3625. /* When count == 0 we have a match */
  3626. if (count == 0) goto _match_found;
  3627. }
  3628. }
  3629. col += direction;
  3630. }
  3631. line += direction;
  3632. /* Reached first/last line with no match */
  3633. if (line == 0 || line == env->line_count + 1) {
  3634. return;
  3635. }
  3636. /* Reset column to start/end of line, depending on direction */
  3637. if (direction > 0) {
  3638. col = 1;
  3639. } else {
  3640. col = env->lines[line-1]->actual;
  3641. }
  3642. } while (1);
  3643. _match_found:
  3644. env->line_no = line;
  3645. env->col_no = col;
  3646. place_cursor_actual();
  3647. }
  3648. /**
  3649. * Handle mouse event
  3650. */
  3651. void handle_mouse(void) {
  3652. int buttons = bim_getch() - 32;
  3653. int x = bim_getch() - 32;
  3654. int y = bim_getch() - 32;
  3655. if (buttons == 64) {
  3656. /* Scroll up */
  3657. for (int i = 0; i < 5; ++i) {
  3658. cursor_up();
  3659. }
  3660. return;
  3661. } else if (buttons == 65) {
  3662. /* Scroll down */
  3663. for (int i = 0; i < 5; ++i) {
  3664. cursor_down();
  3665. }
  3666. return;
  3667. } else if (buttons == 3) {
  3668. /* Move cursor to position */
  3669. if (x < 0) return;
  3670. if (y < 0) return;
  3671. if (y == 1) {
  3672. /* Pick from tabs */
  3673. int _x = 0;
  3674. for (int i = 0; i < buffers_len; i++) {
  3675. buffer_t * _env = buffers[i];
  3676. if (_env->modified) {
  3677. _x += 2;
  3678. }
  3679. if (_env->file_name) {
  3680. _x += 2 + strlen(_env->file_name);
  3681. } else {
  3682. _x += strlen(" [No Name] ");
  3683. }
  3684. if (_x > x) {
  3685. env = buffers[i];
  3686. redraw_all();
  3687. return;
  3688. }
  3689. }
  3690. return;
  3691. }
  3692. /* Figure out y coordinate */
  3693. int line_no = y + env->offset - 1;
  3694. int col_no = -1;
  3695. if (line_no > env->line_count) {
  3696. line_no = env->line_count;
  3697. }
  3698. /* Account for the left hand gutter */
  3699. int num_size = num_width() + 3;
  3700. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  3701. /* Determine where the cursor is physically */
  3702. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  3703. char_t * c = &env->lines[line_no-1]->text[i];
  3704. _x += c->display_width;
  3705. if (_x > x-1) {
  3706. col_no = i+1;
  3707. break;
  3708. }
  3709. }
  3710. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  3711. col_no = env->lines[line_no-1]->actual;
  3712. }
  3713. env->line_no = line_no;
  3714. env->col_no = col_no;
  3715. place_cursor_actual();
  3716. }
  3717. return;
  3718. }
  3719. /**
  3720. * Append a character at the current cursor point.
  3721. */
  3722. void insert_char(unsigned int c) {
  3723. if (!c) {
  3724. render_error("Inserted nil byte?");
  3725. return;
  3726. }
  3727. char_t _c;
  3728. _c.codepoint = c;
  3729. _c.flags = 0;
  3730. _c.display_width = codepoint_width(c);
  3731. line_t * line = env->lines[env->line_no - 1];
  3732. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  3733. if (line != nline) {
  3734. env->lines[env->line_no - 1] = nline;
  3735. }
  3736. env->col_no += 1;
  3737. set_modified();
  3738. }
  3739. /**
  3740. * Replace a single character at the current cursor point
  3741. */
  3742. void replace_char(unsigned int c) {
  3743. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  3744. char_t _c;
  3745. _c.codepoint = c;
  3746. _c.flags = 0;
  3747. _c.display_width = codepoint_width(c);
  3748. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  3749. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  3750. set_modified();
  3751. }
  3752. /**
  3753. * Undo a history entry.
  3754. */
  3755. void undo_history(void) {
  3756. if (!global_config.history_enabled) return;
  3757. env->loading = 1;
  3758. history_t * e = env->history;
  3759. if (e->type == HISTORY_SENTINEL) {
  3760. env->loading = 0;
  3761. render_commandline_message("Already at oldest change");
  3762. return;
  3763. }
  3764. int count_chars = 0;
  3765. int count_lines = 0;
  3766. do {
  3767. if (e->type == HISTORY_SENTINEL) break;
  3768. switch (e->type) {
  3769. case HISTORY_INSERT:
  3770. /* Delete */
  3771. line_delete(
  3772. env->lines[e->insert_delete_replace.lineno],
  3773. e->insert_delete_replace.offset+1,
  3774. e->insert_delete_replace.lineno
  3775. );
  3776. env->line_no = e->insert_delete_replace.lineno + 1;
  3777. env->col_no = e->insert_delete_replace.offset + 1;
  3778. count_chars++;
  3779. break;
  3780. case HISTORY_DELETE:
  3781. {
  3782. char_t _c = {codepoint_width(e->insert_delete_replace.old_codepoint),0,e->insert_delete_replace.old_codepoint};
  3783. env->lines[e->insert_delete_replace.lineno] = line_insert(
  3784. env->lines[e->insert_delete_replace.lineno],
  3785. _c,
  3786. e->insert_delete_replace.offset-1,
  3787. e->insert_delete_replace.lineno
  3788. );
  3789. }
  3790. env->line_no = e->insert_delete_replace.lineno + 1;
  3791. env->col_no = e->insert_delete_replace.offset + 2;
  3792. count_chars++;
  3793. break;
  3794. case HISTORY_REPLACE:
  3795. {
  3796. char_t _o = {codepoint_width(e->insert_delete_replace.old_codepoint),0,e->insert_delete_replace.old_codepoint};
  3797. line_replace(
  3798. env->lines[e->insert_delete_replace.lineno],
  3799. _o,
  3800. e->insert_delete_replace.offset,
  3801. e->insert_delete_replace.lineno
  3802. );
  3803. }
  3804. env->line_no = e->insert_delete_replace.lineno + 1;
  3805. env->col_no = e->insert_delete_replace.offset + 1;
  3806. count_chars++;
  3807. break;
  3808. case HISTORY_REMOVE_LINE:
  3809. env->lines = add_line(env->lines, e->remove_replace_line.lineno);
  3810. replace_line(env->lines, e->remove_replace_line.lineno, e->remove_replace_line.old_contents);
  3811. env->line_no = e->remove_replace_line.lineno + 2;
  3812. env->col_no = 1;
  3813. count_lines++;
  3814. break;
  3815. case HISTORY_ADD_LINE:
  3816. env->lines = remove_line(env->lines, e->add_merge_split_lines.lineno);
  3817. env->line_no = e->add_merge_split_lines.lineno + 1;
  3818. env->col_no = 1;
  3819. count_lines++;
  3820. break;
  3821. case HISTORY_REPLACE_LINE:
  3822. replace_line(env->lines, e->remove_replace_line.lineno, e->remove_replace_line.old_contents);
  3823. env->line_no = e->remove_replace_line.lineno + 1;
  3824. env->col_no = 1;
  3825. count_lines++;
  3826. break;
  3827. case HISTORY_SPLIT_LINE:
  3828. env->lines = merge_lines(env->lines, e->add_merge_split_lines.lineno+1);
  3829. env->line_no = e->add_merge_split_lines.lineno + 2;
  3830. env->col_no = 1;
  3831. count_lines++;
  3832. break;
  3833. case HISTORY_MERGE_LINES:
  3834. env->lines = split_line(env->lines, e->add_merge_split_lines.lineno-1, e->add_merge_split_lines.split);
  3835. env->line_no = e->add_merge_split_lines.lineno;
  3836. env->col_no = 1;
  3837. count_lines++;
  3838. break;
  3839. case HISTORY_BREAK:
  3840. /* Ignore break */
  3841. break;
  3842. default:
  3843. render_error("Unknown type %d!\n", e->type);
  3844. break;
  3845. }
  3846. env->history = e->previous;
  3847. e = env->history;
  3848. } while (e->type != HISTORY_BREAK);
  3849. if (env->line_no > env->line_count) env->line_no = env->line_count;
  3850. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  3851. env->modified = (env->history != env->last_save_history);
  3852. env->loading = 0;
  3853. for (int i = 0; i < env->line_count; ++i) {
  3854. env->lines[i]->istate = 0;
  3855. recalculate_tabs(env->lines[i]);
  3856. }
  3857. for (int i = 0; i < env->line_count; ++i) {
  3858. recalculate_syntax(env->lines[i],i);
  3859. }
  3860. place_cursor_actual();
  3861. update_title();
  3862. redraw_all();
  3863. render_commandline_message("%d character%s, %d line%s changed",
  3864. count_chars, (count_chars == 1) ? "" : "s",
  3865. count_lines, (count_lines == 1) ? "" : "s");
  3866. }
  3867. /**
  3868. * Replay a history entry.
  3869. */
  3870. void redo_history(void) {
  3871. if (!global_config.history_enabled) return;
  3872. env->loading = 1;
  3873. history_t * e = env->history->next;
  3874. if (!e) {
  3875. env->loading = 0;
  3876. render_commandline_message("Already at newest change");
  3877. return;
  3878. }
  3879. int count_chars = 0;
  3880. int count_lines = 0;
  3881. while (e) {
  3882. if (e->type == HISTORY_BREAK) {
  3883. env->history = e;
  3884. break;
  3885. }
  3886. switch (e->type) {
  3887. case HISTORY_INSERT:
  3888. {
  3889. char_t _c = {codepoint_width(e->insert_delete_replace.codepoint),0,e->insert_delete_replace.codepoint};
  3890. env->lines[e->insert_delete_replace.lineno] = line_insert(
  3891. env->lines[e->insert_delete_replace.lineno],
  3892. _c,
  3893. e->insert_delete_replace.offset,
  3894. e->insert_delete_replace.lineno
  3895. );
  3896. }
  3897. env->line_no = e->insert_delete_replace.lineno + 1;
  3898. env->col_no = e->insert_delete_replace.offset + 2;
  3899. count_chars++;
  3900. break;
  3901. case HISTORY_DELETE:
  3902. /* Delete */
  3903. line_delete(
  3904. env->lines[e->insert_delete_replace.lineno],
  3905. e->insert_delete_replace.offset,
  3906. e->insert_delete_replace.lineno
  3907. );
  3908. env->line_no = e->insert_delete_replace.lineno + 1;
  3909. env->col_no = e->insert_delete_replace.offset + 1;
  3910. count_chars++;
  3911. break;
  3912. case HISTORY_REPLACE:
  3913. {
  3914. char_t _o = {codepoint_width(e->insert_delete_replace.codepoint),0,e->insert_delete_replace.codepoint};
  3915. line_replace(
  3916. env->lines[e->insert_delete_replace.lineno],
  3917. _o,
  3918. e->insert_delete_replace.offset,
  3919. e->insert_delete_replace.lineno
  3920. );
  3921. }
  3922. env->line_no = e->insert_delete_replace.lineno + 1;
  3923. env->col_no = e->insert_delete_replace.offset + 2;
  3924. count_chars++;
  3925. break;
  3926. case HISTORY_ADD_LINE:
  3927. env->lines = add_line(env->lines, e->remove_replace_line.lineno);
  3928. env->line_no = e->remove_replace_line.lineno + 2;
  3929. env->col_no = 1;
  3930. count_lines++;
  3931. break;
  3932. case HISTORY_REMOVE_LINE:
  3933. env->lines = remove_line(env->lines, e->remove_replace_line.lineno);
  3934. env->line_no = e->add_merge_split_lines.lineno + 1;
  3935. env->col_no = 1;
  3936. count_lines++;
  3937. break;
  3938. case HISTORY_REPLACE_LINE:
  3939. replace_line(env->lines, e->remove_replace_line.lineno, e->remove_replace_line.contents);
  3940. env->line_no = e->remove_replace_line.lineno + 2;
  3941. env->col_no = 1;
  3942. count_lines++;
  3943. break;
  3944. case HISTORY_MERGE_LINES:
  3945. env->lines = merge_lines(env->lines, e->add_merge_split_lines.lineno);
  3946. env->line_no = e->remove_replace_line.lineno + 1;
  3947. env->col_no = 1;
  3948. count_lines++;
  3949. break;
  3950. case HISTORY_SPLIT_LINE:
  3951. env->lines = split_line(env->lines, e->add_merge_split_lines.lineno, e->add_merge_split_lines.split);
  3952. env->line_no = e->remove_replace_line.lineno + 2;
  3953. env->col_no = 1;
  3954. count_lines++;
  3955. break;
  3956. case HISTORY_BREAK:
  3957. /* Ignore break */
  3958. break;
  3959. default:
  3960. render_error("Unknown type %d!\n", e->type);
  3961. break;
  3962. }
  3963. env->history = e;
  3964. e = e->next;
  3965. }
  3966. if (env->line_no > env->line_count) env->line_no = env->line_count;
  3967. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  3968. env->modified = (env->history != env->last_save_history);
  3969. env->loading = 0;
  3970. for (int i = 0; i < env->line_count; ++i) {
  3971. env->lines[i]->istate = 0;
  3972. recalculate_tabs(env->lines[i]);
  3973. }
  3974. for (int i = 0; i < env->line_count; ++i) {
  3975. recalculate_syntax(env->lines[i],i);
  3976. }
  3977. place_cursor_actual();
  3978. update_title();
  3979. redraw_all();
  3980. render_commandline_message("%d character%s, %d line%s changed",
  3981. count_chars, (count_chars == 1) ? "" : "s",
  3982. count_lines, (count_lines == 1) ? "" : "s");
  3983. }
  3984. /**
  3985. * Move the cursor the start of the previous word.
  3986. */
  3987. void word_left(void) {
  3988. int line_no = env->line_no;
  3989. int col_no = env->col_no;
  3990. do {
  3991. col_no--;
  3992. if (col_no == 0) {
  3993. line_no--;
  3994. if (line_no == 0) {
  3995. goto_line(1);
  3996. return;
  3997. }
  3998. col_no = env->lines[line_no-1]->actual + 1;
  3999. }
  4000. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4001. do {
  4002. col_no--;
  4003. if (col_no == 0) {
  4004. line_no--;
  4005. if (line_no == 0) {
  4006. goto_line(1);
  4007. return;
  4008. }
  4009. col_no = env->lines[line_no-1]->actual + 1;
  4010. }
  4011. if (col_no == 1) {
  4012. env->col_no = 1;
  4013. env->line_no = line_no;
  4014. redraw_statusbar();
  4015. place_cursor_actual();
  4016. return;
  4017. }
  4018. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4019. env->col_no = col_no;
  4020. env->line_no = line_no;
  4021. cursor_right();
  4022. }
  4023. /**
  4024. * Word right
  4025. */
  4026. void word_right(void) {
  4027. int line_no = env->line_no;
  4028. int col_no = env->col_no;
  4029. do {
  4030. col_no++;
  4031. if (col_no >= env->lines[line_no-1]->actual + 1) {
  4032. line_no++;
  4033. if (line_no >= env->line_count) {
  4034. env->col_no = env->lines[env->line_count-1]->actual;
  4035. env->line_no = env->line_count;
  4036. redraw_statusbar();
  4037. place_cursor_actual();
  4038. return;
  4039. }
  4040. col_no = 0;
  4041. break;
  4042. }
  4043. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4044. do {
  4045. col_no++;
  4046. if (col_no >= env->lines[line_no-1]->actual + 1) {
  4047. line_no++;
  4048. if (line_no >= env->line_count) {
  4049. env->col_no = env->lines[env->line_count-1]->actual;
  4050. env->line_no = env->line_count;
  4051. redraw_statusbar();
  4052. place_cursor_actual();
  4053. return;
  4054. }
  4055. col_no = 1;
  4056. break;
  4057. }
  4058. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4059. env->col_no = col_no;
  4060. env->line_no = line_no;
  4061. redraw_statusbar();
  4062. place_cursor_actual();
  4063. return;
  4064. }
  4065. /**
  4066. * Backspace from the current cursor position.
  4067. */
  4068. void delete_at_cursor(void) {
  4069. if (env->col_no > 1) {
  4070. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  4071. env->col_no -= 1;
  4072. if (env->coffset > 0) env->coffset--;
  4073. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4074. set_modified();
  4075. redraw_statusbar();
  4076. place_cursor_actual();
  4077. } else if (env->line_no > 1) {
  4078. int tmp = env->lines[env->line_no - 2]->actual;
  4079. merge_lines(env->lines, env->line_no - 1);
  4080. env->line_no -= 1;
  4081. env->col_no = tmp+1;
  4082. redraw_text();
  4083. set_modified();
  4084. redraw_statusbar();
  4085. place_cursor_actual();
  4086. }
  4087. }
  4088. void delete_word(void) {
  4089. if (!env->lines[env->line_no-1]) return;
  4090. if (env->col_no > 1) {
  4091. do {
  4092. if (env->col_no > 1) {
  4093. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  4094. env->col_no -= 1;
  4095. if (env->coffset > 0) env->coffset--;
  4096. }
  4097. } while (env->col_no > 1 && env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint != ' ');
  4098. redraw_text();
  4099. set_modified();
  4100. redraw_statusbar();
  4101. place_cursor_actual();
  4102. }
  4103. }
  4104. /**
  4105. * Break the current line in two at the current cursor position.
  4106. */
  4107. void insert_line_feed(void) {
  4108. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  4109. env->lines = add_line(env->lines, env->line_no);
  4110. } else {
  4111. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  4112. }
  4113. env->col_no = 1;
  4114. env->line_no += 1;
  4115. add_indent(env->line_no-1,env->line_no-2);
  4116. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  4117. env->offset += 1;
  4118. }
  4119. set_modified();
  4120. }
  4121. /**
  4122. * Yank lines between line start and line end (which may be in either order)
  4123. */
  4124. void yank_lines(int start, int end) {
  4125. if (global_config.yanks) {
  4126. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  4127. free(global_config.yanks[i]);
  4128. }
  4129. free(global_config.yanks);
  4130. }
  4131. int lines_to_yank;
  4132. int start_point;
  4133. if (start <= end) {
  4134. lines_to_yank = end - start + 1;
  4135. start_point = start - 1;
  4136. } else {
  4137. lines_to_yank = start - end + 1;
  4138. start_point = end - 1;
  4139. }
  4140. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  4141. global_config.yank_count = lines_to_yank;
  4142. global_config.yank_is_full_lines = 1;
  4143. for (int i = 0; i < lines_to_yank; ++i) {
  4144. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  4145. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  4146. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  4147. global_config.yanks[i]->istate = 0;
  4148. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  4149. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  4150. global_config.yanks[i]->text[j].flags = 0;
  4151. }
  4152. }
  4153. }
  4154. /**
  4155. * Helper to yank part of a line into a new yank line.
  4156. */
  4157. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  4158. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  4159. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  4160. global_config.yanks[yank_no]->actual = count;
  4161. global_config.yanks[yank_no]->istate = 0;
  4162. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  4163. for (int i = 0; i < count; ++i) {
  4164. global_config.yanks[yank_no]->text[i].flags = 0;
  4165. }
  4166. }
  4167. /**
  4168. * Yank text...
  4169. */
  4170. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  4171. if (global_config.yanks) {
  4172. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  4173. free(global_config.yanks[i]);
  4174. }
  4175. free(global_config.yanks);
  4176. }
  4177. int lines_to_yank = end_line - start_line + 1;
  4178. int start_point = start_line - 1;
  4179. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  4180. global_config.yank_count = lines_to_yank;
  4181. global_config.yank_is_full_lines = 0;
  4182. if (lines_to_yank == 1) {
  4183. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  4184. } else {
  4185. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  4186. /* Yank middle lines */
  4187. for (int i = 1; i < lines_to_yank - 1; ++i) {
  4188. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  4189. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  4190. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  4191. global_config.yanks[i]->istate = 0;
  4192. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  4193. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  4194. global_config.yanks[i]->text[j].flags = 0;
  4195. }
  4196. }
  4197. /* Yank end line */
  4198. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  4199. }
  4200. }
  4201. /**
  4202. * Handle shared escape keys (mostly navigation)
  4203. */
  4204. int handle_escape(int * this_buf, int * timeout, int c) {
  4205. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '\033') {
  4206. this_buf[*timeout] = c;
  4207. (*timeout)++;
  4208. return 1;
  4209. }
  4210. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c != '[') {
  4211. *timeout = 0;
  4212. bim_unget(c);
  4213. return 1;
  4214. }
  4215. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '[') {
  4216. *timeout = 1;
  4217. this_buf[*timeout] = c;
  4218. (*timeout)++;
  4219. return 0;
  4220. }
  4221. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  4222. (isdigit(c) || c == ';')) {
  4223. this_buf[*timeout] = c;
  4224. (*timeout)++;
  4225. return 0;
  4226. }
  4227. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  4228. switch (c) {
  4229. case 'M':
  4230. handle_mouse();
  4231. break;
  4232. case 'A': // up
  4233. cursor_up();
  4234. break;
  4235. case 'B': // down
  4236. cursor_down();
  4237. break;
  4238. case 'C': // right
  4239. if (this_buf[*timeout-1] == '5') {
  4240. word_right();
  4241. } else {
  4242. cursor_right();
  4243. }
  4244. break;
  4245. case 'D': // left
  4246. if (this_buf[*timeout-1] == '5') {
  4247. word_left();
  4248. } else {
  4249. cursor_left();
  4250. }
  4251. break;
  4252. case 'H': // home
  4253. cursor_home();
  4254. break;
  4255. case 'F': // end
  4256. cursor_end();
  4257. break;
  4258. case 'I':
  4259. goto_line(env->line_no - (global_config.term_height - 6));
  4260. break;
  4261. case 'G':
  4262. goto_line(env->line_no + global_config.term_height - 6);
  4263. break;
  4264. case 'Z':
  4265. /* Shift tab */
  4266. if (env->mode == MODE_LINE_SELECTION) {
  4267. *timeout = 0;
  4268. return 'Z';
  4269. }
  4270. break;
  4271. case '~':
  4272. switch (this_buf[*timeout-1]) {
  4273. case '1':
  4274. cursor_home();
  4275. break;
  4276. case '3':
  4277. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) {
  4278. if (env->col_no < env->lines[env->line_no - 1]->actual + 1) {
  4279. line_delete(env->lines[env->line_no - 1], env->col_no, env->line_no - 1);
  4280. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4281. set_modified();
  4282. redraw_statusbar();
  4283. place_cursor_actual();
  4284. } else if (env->line_no < env->line_count) {
  4285. merge_lines(env->lines, env->line_no);
  4286. redraw_text();
  4287. set_modified();
  4288. redraw_statusbar();
  4289. place_cursor_actual();
  4290. }
  4291. }
  4292. break;
  4293. case '4':
  4294. cursor_end();
  4295. break;
  4296. case '5':
  4297. goto_line(env->line_no - (global_config.term_height - 6));
  4298. break;
  4299. case '6':
  4300. goto_line(env->line_no + global_config.term_height - 6);
  4301. break;
  4302. }
  4303. break;
  4304. default:
  4305. render_error("Unrecognized escape sequence identifier: %c", c);
  4306. break;
  4307. }
  4308. *timeout = 0;
  4309. return 0;
  4310. }
  4311. *timeout = 0;
  4312. return 0;
  4313. }
  4314. /**
  4315. * Standard navigation shared by normal, line, and char selection.
  4316. */
  4317. void handle_navigation(int c) {
  4318. switch (c) {
  4319. case ':': /* Switch to command mode */
  4320. command_mode();
  4321. break;
  4322. case '/': /* Switch to search mode */
  4323. search_mode(1);
  4324. break;
  4325. case '?': /* Switch to search mode */
  4326. search_mode(0);
  4327. break;
  4328. case 'n': /* Jump to next search result */
  4329. search_next();
  4330. break;
  4331. case 'N': /* Jump backwards to previous search result */
  4332. search_prev();
  4333. break;
  4334. case 'j': /* Move cursor down */
  4335. cursor_down();
  4336. break;
  4337. case 'k': /* Move cursor up */
  4338. cursor_up();
  4339. break;
  4340. case 'h': /* Move cursor left */
  4341. cursor_left();
  4342. break;
  4343. case 'l': /* Move cursor right*/
  4344. cursor_right();
  4345. break;
  4346. case ' ': /* Jump forward several lines */
  4347. goto_line(env->line_no + global_config.term_height - 6);
  4348. break;
  4349. case '%': /* Jump to matching brace/bracket */
  4350. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) {
  4351. /* These modes need to recalculate syntax as find_matching_brace uses it to find appropriate match */
  4352. for (int i = 0; i < env->line_count; ++i) {
  4353. recalculate_syntax(env->lines[i],i);
  4354. }
  4355. }
  4356. find_matching_paren();
  4357. redraw_statusbar();
  4358. break;
  4359. case '{': /* Jump to previous blank line */
  4360. env->col_no = 1;
  4361. if (env->line_no == 1) break;
  4362. do {
  4363. env->line_no--;
  4364. if (env->lines[env->line_no-1]->actual == 0) break;
  4365. } while (env->line_no > 1);
  4366. redraw_statusbar();
  4367. break;
  4368. case '}': /* Jump to next blank line */
  4369. env->col_no = 1;
  4370. if (env->line_no == env->line_count) break;
  4371. do {
  4372. env->line_no++;
  4373. if (env->lines[env->line_no-1]->actual == 0) break;
  4374. } while (env->line_no < env->line_count);
  4375. redraw_statusbar();
  4376. break;
  4377. case '$': /* Move cursor to end of line */
  4378. cursor_end();
  4379. break;
  4380. case '^':
  4381. case '0': /* Move cursor to beginning of line */
  4382. cursor_home();
  4383. break;
  4384. }
  4385. }
  4386. /**
  4387. * Macro for redrawing selected lines with appropriate highlighting.
  4388. */
  4389. #define _redraw_line(line, force_start_line) \
  4390. do { \
  4391. if (!(force_start_line) && (line) == start_line) break; \
  4392. if ((line) > env->line_count + 1) { \
  4393. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  4394. draw_excess_line((line) - env->offset - 1); \
  4395. } \
  4396. break; \
  4397. } \
  4398. if ((env->line_no < start_line && ((line) < env->line_no || (line) > start_line)) || \
  4399. (env->line_no > start_line && ((line) > env->line_no || (line) < start_line)) || \
  4400. (env->line_no == start_line && (line) != start_line)) { \
  4401. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  4402. } else { \
  4403. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  4404. env->lines[(line)-1]->text[j].flags = FLAG_SELECT; \
  4405. } \
  4406. } \
  4407. if ((line) - env->offset + 1 > 1 && \
  4408. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  4409. redraw_line((line) - env->offset - 1, (line)-1); \
  4410. } \
  4411. } while (0)
  4412. /**
  4413. * Adjust indentation on selected lines.
  4414. */
  4415. void adjust_indent(int start_line, int direction) {
  4416. int lines_to_cover = 0;
  4417. int start_point = 0;
  4418. if (start_line <= env->line_no) {
  4419. start_point = start_line - 1;
  4420. lines_to_cover = env->line_no - start_line + 1;
  4421. } else {
  4422. start_point = env->line_no - 1;
  4423. lines_to_cover = start_line - env->line_no + 1;
  4424. }
  4425. for (int i = 0; i < lines_to_cover; ++i) {
  4426. if ((direction == -1) && env->lines[start_point + i]->actual < 1) continue;
  4427. if (direction == -1) {
  4428. if (env->tabs) {
  4429. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  4430. line_delete(env->lines[start_point + i],1,start_point+i);
  4431. _redraw_line(start_point+i+1,1);
  4432. }
  4433. } else {
  4434. for (int j = 0; j < env->tabstop; ++j) {
  4435. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  4436. line_delete(env->lines[start_point + i],1,start_point+i);
  4437. }
  4438. }
  4439. _redraw_line(start_point+i+1,1);
  4440. }
  4441. } else if (direction == 1) {
  4442. if (env->tabs) {
  4443. char_t c;
  4444. c.codepoint = '\t';
  4445. c.display_width = env->tabstop;
  4446. c.flags = FLAG_SELECT;
  4447. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  4448. } else {
  4449. for (int j = 0; j < env->tabstop; ++j) {
  4450. char_t c;
  4451. c.codepoint = ' ';
  4452. c.display_width = 1;
  4453. c.flags = FLAG_SELECT;
  4454. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  4455. }
  4456. }
  4457. _redraw_line(start_point+i+1,1);
  4458. }
  4459. }
  4460. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4461. env->col_no = env->lines[env->line_no-1]->actual;
  4462. }
  4463. set_modified();
  4464. }
  4465. /**
  4466. * LINE SELECTION mode
  4467. *
  4468. * Equivalent to visual line in vim; selects lines of texts.
  4469. */
  4470. void line_selection_mode(void) {
  4471. int start_line = env->line_no;
  4472. int prev_line = start_line;
  4473. env->mode = MODE_LINE_SELECTION;
  4474. redraw_commandline();
  4475. int c;
  4476. int timeout = 0;
  4477. int this_buf[20];
  4478. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  4479. env->lines[env->line_no-1]->text[j].flags = FLAG_SELECT;
  4480. }
  4481. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4482. while ((c = bim_getch())) {
  4483. if (c == -1) {
  4484. if (timeout && this_buf[timeout-1] == '\033') {
  4485. goto _leave_select_line;
  4486. }
  4487. timeout = 0;
  4488. continue;
  4489. } else {
  4490. if (timeout == 0) {
  4491. switch (c) {
  4492. case '\033':
  4493. if (timeout == 0) {
  4494. this_buf[timeout] = c;
  4495. timeout++;
  4496. }
  4497. break;
  4498. case DELETE_KEY:
  4499. case BACKSPACE_KEY:
  4500. cursor_left();
  4501. break;
  4502. case '\t':
  4503. if (env->readonly) goto _readonly;
  4504. adjust_indent(start_line, 1);
  4505. break;
  4506. case 'V':
  4507. goto _leave_select_line;
  4508. case 'y':
  4509. yank_lines(start_line, env->line_no);
  4510. goto _leave_select_line;
  4511. case 'D':
  4512. case 'd':
  4513. if (env->readonly) goto _readonly;
  4514. yank_lines(start_line, env->line_no);
  4515. if (start_line <= env->line_no) {
  4516. int lines_to_delete = env->line_no - start_line + 1;
  4517. for (int i = 0; i < lines_to_delete; ++i) {
  4518. remove_line(env->lines, start_line-1);
  4519. }
  4520. env->line_no = start_line;
  4521. } else {
  4522. int lines_to_delete = start_line - env->line_no + 1;
  4523. for (int i = 0; i < lines_to_delete; ++i) {
  4524. remove_line(env->lines, env->line_no-1);
  4525. }
  4526. }
  4527. if (env->line_no > env->line_count) {
  4528. env->line_no = env->line_count;
  4529. }
  4530. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4531. env->col_no = env->lines[env->line_no-1]->actual;
  4532. }
  4533. set_modified();
  4534. goto _leave_select_line;
  4535. default:
  4536. handle_navigation(c);
  4537. break;
  4538. }
  4539. } else {
  4540. switch (handle_escape(this_buf,&timeout,c)) {
  4541. case 1:
  4542. bim_unget(c);
  4543. goto _leave_select_line;
  4544. case 'Z':
  4545. /* Unindent */
  4546. if (env->readonly) goto _readonly;
  4547. adjust_indent(start_line, -1);
  4548. break;
  4549. }
  4550. }
  4551. /* Mark current line */
  4552. _redraw_line(env->line_no,0);
  4553. /* Properly mark everything in the span we just moved through */
  4554. if (prev_line < env->line_no) {
  4555. for (int i = prev_line; i < env->line_no; ++i) {
  4556. _redraw_line(i,0);
  4557. }
  4558. prev_line = env->line_no;
  4559. } else if (prev_line > env->line_no) {
  4560. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  4561. _redraw_line(i,0);
  4562. }
  4563. prev_line = env->line_no;
  4564. }
  4565. place_cursor_actual();
  4566. continue;
  4567. _readonly:
  4568. render_error("Buffer is read-only");
  4569. }
  4570. }
  4571. _leave_select_line:
  4572. set_history_break();
  4573. env->mode = MODE_NORMAL;
  4574. for (int i = 0; i < env->line_count; ++i) {
  4575. recalculate_syntax(env->lines[i],i);
  4576. }
  4577. redraw_all();
  4578. }
  4579. /**
  4580. * Determine if a column + line number are within range of the
  4581. * current character selection specified by start_line, etc.
  4582. *
  4583. * Used to determine how syntax flags should be set when redrawing
  4584. * selected text in CHAR SELECTION mode.
  4585. */
  4586. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  4587. if (start_line == end_line) {
  4588. if ( end_col < start_col) {
  4589. int tmp = end_col;
  4590. end_col = start_col;
  4591. start_col = tmp;
  4592. }
  4593. return (col >= start_col && col <= end_col);
  4594. }
  4595. if (start_line > end_line) {
  4596. int tmp = end_line;
  4597. end_line = start_line;
  4598. start_line = tmp;
  4599. tmp = end_col;
  4600. end_col = start_col;
  4601. start_col = tmp;
  4602. }
  4603. if (line < start_line || line > end_line) return 0;
  4604. if (line == start_line) {
  4605. return col >= start_col;
  4606. }
  4607. if (line == end_line) {
  4608. return col <= end_col;
  4609. }
  4610. return 1;
  4611. }
  4612. #define _redraw_line_char(line, force_start_line) \
  4613. do { \
  4614. if (!(force_start_line) && (line) == start_line) break; \
  4615. if ((line) > env->line_count + 1) { \
  4616. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  4617. draw_excess_line((line) - env->offset - 1); \
  4618. } \
  4619. break; \
  4620. } \
  4621. if ((env->line_no < start_line && ((line) < env->line_no || (line) > start_line)) || \
  4622. (env->line_no > start_line && ((line) > env->line_no || (line) < start_line)) || \
  4623. (env->line_no == start_line && (line) != start_line)) { \
  4624. /* Line is completely outside selection */ \
  4625. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  4626. } else { \
  4627. if ((line) == start_line || (line) == env->line_no) { \
  4628. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  4629. } \
  4630. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  4631. if (point_in_range(start_line, env->line_no,start_col, env->col_no, (line), j+1)) { \
  4632. env->lines[(line)-1]->text[j].flags = FLAG_SELECT; \
  4633. } \
  4634. } \
  4635. } \
  4636. if ((line) - env->offset + 1 > 1 && \
  4637. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  4638. redraw_line((line) - env->offset - 1, (line)-1); \
  4639. } \
  4640. } while (0)
  4641. /**
  4642. * CHAR SELECTION mode.
  4643. */
  4644. void char_selection_mode(void) {
  4645. int start_line = env->line_no;
  4646. int start_col = env->col_no;
  4647. int prev_line = start_line;
  4648. env->mode = MODE_CHAR_SELECTION;
  4649. redraw_commandline();
  4650. int c;
  4651. int timeout = 0;
  4652. int this_buf[20];
  4653. /* Select single character */
  4654. env->lines[env->line_no-1]->text[env->col_no-1].flags = FLAG_SELECT;
  4655. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4656. while ((c = bim_getch())) {
  4657. if (c == -1) {
  4658. if (timeout && this_buf[timeout-1] == '\033') {
  4659. goto _leave_select_char;
  4660. }
  4661. timeout = 0;
  4662. continue;
  4663. } else {
  4664. if (timeout == 0) {
  4665. switch (c) {
  4666. case '\033':
  4667. if (timeout == 0) {
  4668. this_buf[timeout] = c;
  4669. timeout++;
  4670. }
  4671. break;
  4672. case DELETE_KEY:
  4673. case BACKSPACE_KEY:
  4674. cursor_left();
  4675. break;
  4676. case 'v':
  4677. goto _leave_select_char;
  4678. case 'y':
  4679. {
  4680. int end_line = env->line_no;
  4681. int end_col = env->col_no;
  4682. if (start_line == end_line) {
  4683. if (start_col > end_col) {
  4684. int tmp = start_col;
  4685. start_col = end_col;
  4686. end_col = tmp;
  4687. }
  4688. } else if (start_line > end_line) {
  4689. int tmp = start_line;
  4690. start_line = end_line;
  4691. end_line = tmp;
  4692. tmp = start_col;
  4693. start_col = end_col;
  4694. end_col = tmp;
  4695. }
  4696. yank_text(start_line, start_col, end_line, end_col);
  4697. }
  4698. goto _leave_select_char;
  4699. case 'D':
  4700. case 'd':
  4701. if (env->readonly) goto _readonly;
  4702. {
  4703. int end_line = env->line_no;
  4704. int end_col = env->col_no;
  4705. if (start_line == end_line) {
  4706. if (start_col > end_col) {
  4707. int tmp = start_col;
  4708. start_col = end_col;
  4709. end_col = tmp;
  4710. }
  4711. yank_text(start_line, start_col, end_line, end_col);
  4712. for (int i = start_col; i <= end_col; ++i) {
  4713. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  4714. }
  4715. env->col_no = start_col;
  4716. } else {
  4717. if (start_line > end_line) {
  4718. int tmp = start_line;
  4719. start_line = end_line;
  4720. end_line = tmp;
  4721. tmp = start_col;
  4722. start_col = end_col;
  4723. end_col = tmp;
  4724. }
  4725. /* Copy lines */
  4726. yank_text(start_line, start_col, end_line, end_col);
  4727. /* Delete lines */
  4728. for (int i = start_line+1; i < end_line; ++i) {
  4729. remove_line(env->lines, start_line);
  4730. } /* end_line is no longer valid; should be start_line+1*/
  4731. /* Delete from start_col forward */
  4732. int tmp = env->lines[start_line-1]->actual;
  4733. for (int i = start_col; i <= tmp; ++i) {
  4734. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  4735. }
  4736. for (int i = 1; i <= end_col; ++i) {
  4737. line_delete(env->lines[start_line], 1, start_line);
  4738. }
  4739. /* Merge start and end lines */
  4740. merge_lines(env->lines, start_line);
  4741. env->line_no = start_line;
  4742. env->col_no = start_col;
  4743. }
  4744. }
  4745. if (env->line_no > env->line_count) {
  4746. env->line_no = env->line_count;
  4747. }
  4748. set_modified();
  4749. goto _leave_select_char;
  4750. default:
  4751. handle_navigation(c);
  4752. break;
  4753. }
  4754. } else {
  4755. switch (handle_escape(this_buf,&timeout,c)) {
  4756. case 1:
  4757. bim_unget(c);
  4758. goto _leave_select_char;
  4759. }
  4760. }
  4761. /* Mark current line */
  4762. _redraw_line_char(env->line_no,1);
  4763. /* Properly mark everything in the span we just moved through */
  4764. if (prev_line < env->line_no) {
  4765. for (int i = prev_line; i < env->line_no; ++i) {
  4766. _redraw_line_char(i,1);
  4767. }
  4768. prev_line = env->line_no;
  4769. } else if (prev_line > env->line_no) {
  4770. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  4771. _redraw_line_char(i,1);
  4772. }
  4773. prev_line = env->line_no;
  4774. }
  4775. place_cursor_actual();
  4776. continue;
  4777. _readonly:
  4778. render_error("Buffer is read-only");
  4779. }
  4780. }
  4781. _leave_select_char:
  4782. set_history_break();
  4783. env->mode = MODE_NORMAL;
  4784. for (int i = 0; i < env->line_count; ++i) {
  4785. recalculate_syntax(env->lines[i],i);
  4786. }
  4787. redraw_all();
  4788. }
  4789. /**
  4790. * INSERT mode
  4791. *
  4792. * Accept input into the text buffer.
  4793. */
  4794. void insert_mode(void) {
  4795. int cin;
  4796. uint32_t c;
  4797. /* Set mode line */
  4798. env->mode = MODE_INSERT;
  4799. redraw_commandline();
  4800. /* Place the cursor in the text area */
  4801. place_cursor_actual();
  4802. int timeout = 0;
  4803. int this_buf[20];
  4804. uint32_t istate = 0;
  4805. int redraw = 0;
  4806. while ((cin = bim_getch_timeout((redraw ? 10 : 200)))) {
  4807. if (cin == -1) {
  4808. if (redraw) {
  4809. if (redraw & 2) {
  4810. redraw_text();
  4811. } else {
  4812. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4813. }
  4814. redraw_statusbar();
  4815. place_cursor_actual();
  4816. redraw = 0;
  4817. }
  4818. if (timeout && this_buf[timeout-1] == '\033') {
  4819. leave_insert();
  4820. return;
  4821. }
  4822. timeout = 0;
  4823. continue;
  4824. }
  4825. if (!decode(&istate, &c, cin)) {
  4826. if (timeout == 0) {
  4827. switch (c) {
  4828. case '\033':
  4829. if (timeout == 0) {
  4830. this_buf[timeout] = c;
  4831. timeout++;
  4832. }
  4833. break;
  4834. case DELETE_KEY:
  4835. case BACKSPACE_KEY:
  4836. delete_at_cursor();
  4837. break;
  4838. case ENTER_KEY:
  4839. insert_line_feed();
  4840. redraw |= 2;
  4841. break;
  4842. case 22: /* ^V */
  4843. /* Insert next byte raw */
  4844. {
  4845. /* Indicate we're in literal mode */
  4846. render_commandline_message("^V");
  4847. /* Put the cursor back into the text field */
  4848. place_cursor_actual();
  4849. /* Get next character */
  4850. while ((cin = bim_getch()) == -1);
  4851. /* Insert literal */
  4852. insert_char(cin);
  4853. /* Redraw INSERT */
  4854. redraw_commandline();
  4855. /* Draw text */
  4856. redraw |= 1;
  4857. }
  4858. break;
  4859. case 23: /* ^W */
  4860. delete_word();
  4861. break;
  4862. case '\t':
  4863. if (env->tabs) {
  4864. insert_char('\t');
  4865. } else {
  4866. for (int i = 0; i < env->tabstop; ++i) {
  4867. insert_char(' ');
  4868. }
  4869. }
  4870. redraw |= 1;
  4871. break;
  4872. default:
  4873. insert_char(c);
  4874. redraw |= 1;
  4875. break;
  4876. }
  4877. } else {
  4878. if (handle_escape(this_buf,&timeout,c)) {
  4879. bim_unget(c);
  4880. leave_insert();
  4881. return;
  4882. }
  4883. }
  4884. } else if (istate == UTF8_REJECT) {
  4885. istate = 0;
  4886. }
  4887. }
  4888. }
  4889. /*
  4890. * REPLACE mode
  4891. *
  4892. * Like insert, but replaces characters.
  4893. */
  4894. void replace_mode(void) {
  4895. int cin;
  4896. uint32_t c;
  4897. /* Set mode line */
  4898. env->mode = MODE_REPLACE;
  4899. redraw_commandline();
  4900. /* Place the cursor in the text area */
  4901. place_cursor_actual();
  4902. int timeout = 0;
  4903. int this_buf[20];
  4904. uint32_t istate = 0;
  4905. while ((cin = bim_getch())) {
  4906. if (cin == -1) {
  4907. if (timeout && this_buf[timeout-1] == '\033') {
  4908. leave_insert();
  4909. return;
  4910. }
  4911. timeout = 0;
  4912. continue;
  4913. }
  4914. if (!decode(&istate, &c, cin)) {
  4915. if (timeout == 0) {
  4916. switch (c) {
  4917. case '\033':
  4918. if (timeout == 0) {
  4919. this_buf[timeout] = c;
  4920. timeout++;
  4921. }
  4922. break;
  4923. case DELETE_KEY:
  4924. case BACKSPACE_KEY:
  4925. if (env->line_no > 1 && env->col_no == 1) {
  4926. env->line_no--;
  4927. env->col_no = env->lines[env->line_no-1]->actual;
  4928. place_cursor_actual();
  4929. } else {
  4930. cursor_left();
  4931. }
  4932. break;
  4933. case ENTER_KEY:
  4934. insert_line_feed();
  4935. redraw_text();
  4936. set_modified();
  4937. redraw_statusbar();
  4938. place_cursor_actual();
  4939. break;
  4940. default:
  4941. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  4942. replace_char(c);
  4943. env->col_no += 1;
  4944. } else {
  4945. insert_char(c);
  4946. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4947. }
  4948. redraw_statusbar();
  4949. place_cursor_actual();
  4950. break;
  4951. }
  4952. } else {
  4953. if (handle_escape(this_buf,&timeout,c)) {
  4954. bim_unget(c);
  4955. leave_insert();
  4956. return;
  4957. }
  4958. }
  4959. } else if (istate == UTF8_REJECT) {
  4960. istate = 0;
  4961. }
  4962. }
  4963. }
  4964. /**
  4965. * NORMAL mode
  4966. *
  4967. * Default editor mode - just cursor navigation and keybinds
  4968. * to enter the other modes.
  4969. */
  4970. void normal_mode(void) {
  4971. while (1) {
  4972. place_cursor_actual();
  4973. int c;
  4974. int timeout = 0;
  4975. int this_buf[20];
  4976. while ((c = bim_getch())) {
  4977. if (c == -1) {
  4978. /* getch timed out, nothing to do in normal mode */
  4979. continue;
  4980. }
  4981. if (timeout == 0) {
  4982. switch (c) {
  4983. case '\033':
  4984. if (timeout == 0) {
  4985. this_buf[timeout] = c;
  4986. timeout++;
  4987. }
  4988. break;
  4989. case DELETE_KEY:
  4990. case BACKSPACE_KEY:
  4991. if (env->line_no > 1 && env->col_no == 1) {
  4992. env->line_no--;
  4993. env->col_no = env->lines[env->line_no-1]->actual;
  4994. place_cursor_actual();
  4995. } else {
  4996. cursor_left();
  4997. }
  4998. break;
  4999. case 'V': /* Enter LINE SELECTION mode */
  5000. line_selection_mode();
  5001. break;
  5002. case 'v': /* Enter CHAR SELECTION mode */
  5003. char_selection_mode();
  5004. break;
  5005. case 'O': /* Append line before and enter INSERT mode */
  5006. {
  5007. if (env->readonly) goto _readonly;
  5008. env->lines = add_line(env->lines, env->line_no-1);
  5009. env->col_no = 1;
  5010. add_indent(env->line_no-1,env->line_no);
  5011. redraw_text();
  5012. set_modified();
  5013. place_cursor_actual();
  5014. goto _insert;
  5015. }
  5016. case 'o': /* Append line after and enter INSERT mode */
  5017. {
  5018. if (env->readonly) goto _readonly;
  5019. env->lines = add_line(env->lines, env->line_no);
  5020. env->col_no = 1;
  5021. env->line_no += 1;
  5022. add_indent(env->line_no-1,env->line_no-2);
  5023. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  5024. env->offset += 1;
  5025. }
  5026. redraw_text();
  5027. set_modified();
  5028. place_cursor_actual();
  5029. goto _insert;
  5030. }
  5031. case 'a': /* Enter INSERT mode with cursor after current position */
  5032. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  5033. env->col_no += 1;
  5034. }
  5035. goto _insert;
  5036. case 'P': /* Paste before */
  5037. case 'p': /* Paste after */
  5038. if (env->readonly) goto _readonly;
  5039. if (global_config.yanks) {
  5040. if (!global_config.yank_is_full_lines) {
  5041. /* Handle P for paste before, p for past after */
  5042. int target_column = (c == 'P' ? (env->col_no) : (env->col_no+1));
  5043. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  5044. target_column = env->lines[env->line_no-1]->actual + 1;
  5045. }
  5046. if (global_config.yank_count > 1) {
  5047. /* Spit the current line at the current position */
  5048. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  5049. }
  5050. /* Insert first line at current position */
  5051. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  5052. 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);
  5053. }
  5054. if (global_config.yank_count > 1) {
  5055. /* Insert full lines */
  5056. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  5057. env->lines = add_line(env->lines, env->line_no);
  5058. }
  5059. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  5060. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  5061. }
  5062. /* Insert characters from last line into (what was) the next line */
  5063. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  5064. 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);
  5065. }
  5066. }
  5067. } else {
  5068. /* Insert full lines */
  5069. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5070. env->lines = add_line(env->lines, env->line_no - (c == 'P' ? 1 : 0));
  5071. }
  5072. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5073. replace_line(env->lines, env->line_no - (c == 'P' ? 1 : 0) + i, global_config.yanks[i]);
  5074. }
  5075. }
  5076. /* Recalculate whole document syntax */
  5077. for (int i = 0; i < env->line_count; ++i) {
  5078. env->lines[i]->istate = 0;
  5079. }
  5080. for (int i = 0; i < env->line_count; ++i) {
  5081. recalculate_syntax(env->lines[i],i);
  5082. }
  5083. set_history_break();
  5084. set_modified();
  5085. redraw_all();
  5086. }
  5087. break;
  5088. case 'u': /* Undo one block of history */
  5089. undo_history();
  5090. break;
  5091. case 18: /* ^R - Redo one block of history */
  5092. redo_history();
  5093. break;
  5094. case 12: /* ^L - Repaint the whole screen */
  5095. redraw_all();
  5096. break;
  5097. case 'i': /* Enter INSERT mode */
  5098. _insert:
  5099. if (env->readonly) goto _readonly;
  5100. insert_mode();
  5101. redraw_statusbar();
  5102. redraw_commandline();
  5103. timeout = 0;
  5104. break;
  5105. case 'R': /* Enter REPLACE mode */
  5106. if (env->readonly) goto _readonly;
  5107. replace_mode();
  5108. redraw_statusbar();
  5109. redraw_commandline();
  5110. timeout = 0;
  5111. break;
  5112. _readonly:
  5113. render_error("Buffer is read-only");
  5114. break;
  5115. default:
  5116. handle_navigation(c);
  5117. break;
  5118. }
  5119. } else {
  5120. handle_escape(this_buf,&timeout,c);
  5121. }
  5122. place_cursor_actual();
  5123. }
  5124. }
  5125. }
  5126. /**
  5127. * Show help text for -?
  5128. */
  5129. static void show_usage(char * argv[]) {
  5130. #define _S "\033[3m"
  5131. #define _E "\033[0m\n"
  5132. printf(
  5133. "bim - Text editor\n"
  5134. "\n"
  5135. "usage: %s [options] [file]\n"
  5136. " %s [options] -- -\n"
  5137. "\n"
  5138. " -R " _S "open initial buffer read-only" _E
  5139. " -O " _S "set various options:" _E
  5140. " noscroll " _S "disable terminal scrolling" _E
  5141. " noaltscreen " _S "disable alternate screen buffer" _E
  5142. " nomouse " _S "disable mouse support" _E
  5143. " nounicode " _S "disable unicode display" _E
  5144. " nobright " _S "disable bright next" _E
  5145. " nohideshow " _S "disable togglging cursor visibility" _E
  5146. " nosyntax " _S "disable syntax highlighting on load" _E
  5147. " notitle " _S "disable title-setting escapes" _E
  5148. " history " _S "enable experimental undo/redo" _E
  5149. " -c,-C " _S "print file to stdout with syntax hilighting" _E
  5150. " " _S "-C includes line numbers, -c does not" _E
  5151. " -u " _S "override bimrc file" _E
  5152. " -? " _S "show this help text" _E
  5153. "\n", argv[0], argv[0]);
  5154. #undef _E
  5155. #undef _S
  5156. }
  5157. /**
  5158. * Load bimrc configuration file.
  5159. *
  5160. * At the moment, this a simple key=value list.
  5161. */
  5162. void load_bimrc(void) {
  5163. if (!global_config.bimrc_path) return;
  5164. /* Default is ~/.bimrc */
  5165. char * tmp = strdup(global_config.bimrc_path);
  5166. if (!*tmp) {
  5167. free(tmp);
  5168. return;
  5169. }
  5170. /* Parse ~ at the front of the path. */
  5171. if (*tmp == '~') {
  5172. char path[1024] = {0};
  5173. char * home = getenv("HOME");
  5174. if (!home) {
  5175. /* $HOME is unset? */
  5176. free(tmp);
  5177. return;
  5178. }
  5179. /* New path is $HOME/.bimrc */
  5180. snprintf(path, 1024, "%s%s", home, tmp+1);
  5181. free(tmp);
  5182. tmp = strdup(path);
  5183. }
  5184. /* Try to open the file */
  5185. FILE * bimrc = fopen(tmp, "r");
  5186. if (!bimrc) {
  5187. /* No bimrc, or bad permissions */
  5188. free(tmp);
  5189. return;
  5190. }
  5191. /* Parse through lines */
  5192. char line[1024];
  5193. while (!feof(bimrc)) {
  5194. char * l = fgets(line, 1023, bimrc);
  5195. /* Ignore bad lines */
  5196. if (!l) break;
  5197. if (!*l) continue;
  5198. if (*l == '\n') continue;
  5199. /* Ignore comment lines */
  5200. if (*l == '#') continue;
  5201. /* Remove linefeed at the end */
  5202. char *nl = strstr(l,"\n");
  5203. if (nl) *nl = '\0';
  5204. /* Extract value from keypair, if available
  5205. * (I foresee options without values in the future) */
  5206. char *value= strstr(l,"=");
  5207. if (value) {
  5208. *value = '\0';
  5209. value++;
  5210. }
  5211. /* theme=... */
  5212. if (!strcmp(l,"theme") && value) {
  5213. /* Examine available themes for a match. */
  5214. for (struct theme_def * d = themes; d->name; ++d) {
  5215. if (!strcmp(value, d->name)) {
  5216. d->load();
  5217. break;
  5218. }
  5219. }
  5220. }
  5221. /* enable history (experimental) */
  5222. if (!strcmp(l,"history")) {
  5223. global_config.history_enabled = 1;
  5224. }
  5225. /* padding= */
  5226. if (!strcmp(l,"padding") && value) {
  5227. global_config.cursor_padding = atoi(value);
  5228. }
  5229. }
  5230. fclose(bimrc);
  5231. }
  5232. /**
  5233. * Set some default values when certain terminals are detected.
  5234. */
  5235. void detect_weird_terminals(void) {
  5236. char * term = getenv("TERM");
  5237. if (term && !strcmp(term,"linux")) {
  5238. /* Linux VTs can't scroll. */
  5239. global_config.can_scroll = 0;
  5240. }
  5241. if (term && !strcmp(term,"cons25")) {
  5242. /* Dragonfly BSD console */
  5243. global_config.can_hideshow = 0;
  5244. global_config.can_altscreen = 0;
  5245. global_config.can_mouse = 0;
  5246. global_config.can_unicode = 0;
  5247. global_config.can_bright = 0;
  5248. }
  5249. if (term && !strcmp(term,"sortix")) {
  5250. /* sortix will spew title escapes to the screen, no good */
  5251. global_config.can_title = 0;
  5252. }
  5253. if (term && strstr(term,"tmux") == term) {
  5254. global_config.can_scroll = 0;
  5255. global_config.can_bce = 0;
  5256. }
  5257. }
  5258. /**
  5259. * Run global initialization tasks
  5260. */
  5261. void initialize(void) {
  5262. setlocale(LC_ALL, "");
  5263. detect_weird_terminals();
  5264. load_colorscheme_ansi();
  5265. load_bimrc();
  5266. buffers_avail = 4;
  5267. buffers = malloc(sizeof(buffer_t *) * buffers_avail);
  5268. }
  5269. /**
  5270. * Initialize terminal for editor display.
  5271. */
  5272. void init_terminal(void) {
  5273. set_alternate_screen();
  5274. update_screen_size();
  5275. get_initial_termios();
  5276. set_unbuffered();
  5277. mouse_enable();
  5278. signal(SIGWINCH, SIGWINCH_handler);
  5279. signal(SIGCONT, SIGCONT_handler);
  5280. signal(SIGTSTP, SIGTSTP_handler);
  5281. }
  5282. int main(int argc, char * argv[]) {
  5283. int opt;
  5284. while ((opt = getopt(argc, argv, "?c:C:u:RO:-:")) != -1) {
  5285. switch (opt) {
  5286. case 'R':
  5287. global_config.initial_file_is_read_only = 1;
  5288. break;
  5289. case 'c':
  5290. case 'C':
  5291. /* Print file to stdout using our syntax highlighting and color theme */
  5292. initialize();
  5293. open_file(optarg);
  5294. for (int i = 0; i < env->line_count; ++i) {
  5295. if (opt == 'C') {
  5296. draw_line_number(i);
  5297. }
  5298. render_line(env->lines[i], 6 * (env->lines[i]->actual + 1), 0);
  5299. reset();
  5300. fprintf(stdout, "\n");
  5301. }
  5302. return 0;
  5303. case 'u':
  5304. global_config.bimrc_path = optarg;
  5305. break;
  5306. case 'O':
  5307. /* Set various display options */
  5308. if (!strcmp(optarg,"noaltscreen")) global_config.can_altscreen = 0;
  5309. else if (!strcmp(optarg,"noscroll")) global_config.can_scroll = 0;
  5310. else if (!strcmp(optarg,"nomouse")) global_config.can_mouse = 0;
  5311. else if (!strcmp(optarg,"nounicode")) global_config.can_unicode = 0;
  5312. else if (!strcmp(optarg,"nobright")) global_config.can_bright = 0;
  5313. else if (!strcmp(optarg,"nohideshow")) global_config.can_hideshow = 0;
  5314. else if (!strcmp(optarg,"nosyntax")) global_config.hilight_on_open = 0;
  5315. else if (!strcmp(optarg,"nohistory")) global_config.history_enabled = 0;
  5316. else if (!strcmp(optarg,"notitle")) global_config.can_title = 0;
  5317. else if (!strcmp(optarg,"nobce")) global_config.can_bce = 0;
  5318. else {
  5319. fprintf(stderr, "%s: unrecognized -O option: %s\n", argv[0], optarg);
  5320. return 1;
  5321. }
  5322. break;
  5323. case '-':
  5324. if (!strcmp(optarg,"version")) {
  5325. fprintf(stderr, "bim %s %s\n", BIM_VERSION, BIM_COPYRIGHT);
  5326. fprintf(stderr, " Available syntax highlighters:");
  5327. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  5328. fprintf(stderr, " %s", s->name);
  5329. }
  5330. fprintf(stderr, "\n");
  5331. fprintf(stderr, " Available color themes:");
  5332. for (struct theme_def * d = themes; d->name; ++d) {
  5333. fprintf(stderr, " %s", d->name);
  5334. }
  5335. fprintf(stderr, "\n");
  5336. return 0;
  5337. }
  5338. break;
  5339. case '?':
  5340. show_usage(argv);
  5341. return 0;
  5342. }
  5343. }
  5344. /* Set up terminal */
  5345. initialize();
  5346. init_terminal();
  5347. /* Open file */
  5348. if (argc > optind) {
  5349. open_file(argv[optind]);
  5350. update_title();
  5351. goto_line(0);
  5352. if (global_config.initial_file_is_read_only) {
  5353. env->readonly = 1;
  5354. }
  5355. } else {
  5356. env = buffer_new();
  5357. update_title();
  5358. setup_buffer(env);
  5359. }
  5360. /* Draw the screen once */
  5361. redraw_all();
  5362. /* Start accepting key commands */
  5363. normal_mode();
  5364. return 0;
  5365. }