bim.c 249 KB

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