Skip to content

Distribute and run LLMs with a single file.

Add MATLAB syntax highlighting

Justine Tunney9db5a5763d36
diff --git a/build/rules.mk b/build/rules.mk
index aeb312bd..d539d67c 100644
--- a/build/rules.mk
+++ b/build/rules.mk
@@ -22,6 +22,7 @@ o/$(MODE)/%.o: %.cpp $(COSMOCC)
$(COMPILE.cc) -o $@ $<
o/$(MODE)/%.c: %.gperf
+ @mkdir -p $(@D)
build/gperf --output-file=$@ $<
o/$(MODE)/%.a:
diff --git a/llamafile/highlight.cpp b/llamafile/highlight.cpp
index ebf45e88..eedc9697 100644
--- a/llamafile/highlight.cpp
+++ b/llamafile/highlight.cpp
@@ -89,7 +89,8 @@ Highlight *Highlight::create(const std::string_view &lang) {
return new HighlightCobol;
if (lang == "pas" || //
- lang == "pascal")
+ lang == "pascal" || //
+ lang == "delphi")
return new HighlightPascal;
if (lang == "go")
@@ -199,5 +200,8 @@ Highlight *Highlight::create(const std::string_view &lang) {
lang == "freebasic")
return new HighlightBasic;
+ if (lang == "matlab")
+ return new HighlightMatlab;
+
return nullptr;
}
diff --git a/llamafile/highlight.h b/llamafile/highlight.h
index 445be3be..b9b1dc36 100644
--- a/llamafile/highlight.h
+++ b/llamafile/highlight.h
@@ -127,6 +127,9 @@ is_keyword_f is_keyword_basic_constant;
is_keyword_f is_keyword_ld;
is_keyword_f is_keyword_ld_builtin;
is_keyword_f is_keyword_ld_warning;
+is_keyword_f is_keyword_matlab;
+is_keyword_f is_keyword_matlab_builtin;
+is_keyword_f is_keyword_matlab_constant;
}
class Highlight {
@@ -625,3 +628,15 @@ class HighlightKotlin : public Highlight {
std::string word_;
unsigned char nest_[16];
};
+
+class HighlightMatlab : public Highlight {
+ public:
+ HighlightMatlab();
+ ~HighlightMatlab() override;
+ void feed(std::string *result, std::string_view input) override;
+ void flush(std::string *result) override;
+
+ private:
+ int t_ = 0;
+ std::string word_;
+};
diff --git a/llamafile/highlight_c.cpp b/llamafile/highlight_c.cpp
index 36dce25e..a769d837 100644
--- a/llamafile/highlight_c.cpp
+++ b/llamafile/highlight_c.cpp
@@ -29,6 +29,7 @@ enum {
SLASH,
SLASH_SLASH,
SLASH_STAR,
+ SLASH_SLASH_BACKSLASH,
SLASH_STAR_STAR,
R,
R_DQUOTE,
@@ -56,6 +57,8 @@ void HighlightC::feed(std::string *r, std::string_view input) {
int c;
for (size_t i = 0; i < input.size(); ++i) {
c = input[i] & 255;
+ if (c == '\r')
+ continue;
switch (t_) {
Normal:
@@ -210,9 +213,16 @@ void HighlightC::feed(std::string *r, std::string_view input) {
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
+ } else if (c == '\\') {
+ t_ = SLASH_SLASH_BACKSLASH;
}
break;
+ case SLASH_SLASH_BACKSLASH:
+ *r += c;
+ t_ = SLASH_SLASH;
+ break;
+
case SLASH_STAR:
*r += c;
if (c == '*')
@@ -381,6 +391,7 @@ void HighlightC::flush(std::string *r) {
case DQUOTE:
case DQUOTE_BACKSLASH:
case SLASH_SLASH:
+ case SLASH_SLASH_BACKSLASH:
case SLASH_STAR:
case SLASH_STAR_STAR:
case R_DQUOTE:
diff --git a/llamafile/highlight_matlab.cpp b/llamafile/highlight_matlab.cpp
new file mode 100644
index 00000000..e0ee4ad4
--- /dev/null
+++ b/llamafile/highlight_matlab.cpp
@@ -0,0 +1,166 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// Copyright 2024 Mozilla Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "highlight.h"
+
+#include <ctype.h>
+
+enum {
+ NORMAL,
+ WORD,
+ COMMENT,
+ QUOTE,
+ QUOTE_BACKSLASH,
+ DQUOTE,
+ DQUOTE_BACKSLASH,
+};
+
+HighlightMatlab::HighlightMatlab() {
+}
+
+HighlightMatlab::~HighlightMatlab() {
+}
+
+void HighlightMatlab::feed(std::string *r, std::string_view input) {
+ int c;
+ for (size_t i = 0; i < input.size(); ++i) {
+ c = input[i] & 255;
+ switch (t_) {
+
+ Normal:
+ case NORMAL:
+ if (!isascii(c) || isalpha(c) || c == '_') {
+ t_ = WORD;
+ word_ += c;
+ } else if (c == '%') {
+ t_ = COMMENT;
+ *r += HI_COMMENT;
+ *r += '%';
+ } else if (c == '\'') {
+ t_ = QUOTE;
+ *r += HI_STRING;
+ *r += '\'';
+ } else if (c == '"') {
+ t_ = DQUOTE;
+ *r += HI_STRING;
+ *r += '"';
+ } else {
+ *r += c;
+ }
+ break;
+
+ case WORD:
+ if (!isascii(c) || isalnum(c) || c == '_') {
+ word_ += c;
+ } else {
+ if (is_keyword_matlab(word_.data(), word_.size())) {
+ *r += HI_KEYWORD;
+ *r += word_;
+ *r += HI_RESET;
+ } else if (is_keyword_matlab_builtin(word_.data(), word_.size())) {
+ *r += HI_BUILTIN;
+ *r += word_;
+ *r += HI_RESET;
+ } else if (is_keyword_matlab_constant(word_.data(), word_.size())) {
+ *r += HI_CONSTANT;
+ *r += word_;
+ *r += HI_RESET;
+ } else {
+ *r += word_;
+ }
+ word_.clear();
+ t_ = NORMAL;
+ goto Normal;
+ }
+ break;
+
+ case COMMENT:
+ *r += c;
+ if (c == '\n') {
+ *r += HI_RESET;
+ t_ = NORMAL;
+ }
+ break;
+
+ case QUOTE:
+ *r += c;
+ if (c == '\'') {
+ *r += HI_RESET;
+ t_ = NORMAL;
+ } else if (c == '\\') {
+ t_ = QUOTE_BACKSLASH;
+ }
+ break;
+
+ case QUOTE_BACKSLASH:
+ *r += c;
+ t_ = QUOTE;
+ break;
+
+ case DQUOTE:
+ *r += c;
+ if (c == '"') {
+ *r += HI_RESET;
+ t_ = NORMAL;
+ } else if (c == '\\') {
+ t_ = DQUOTE_BACKSLASH;
+ }
+ break;
+
+ case DQUOTE_BACKSLASH:
+ *r += c;
+ t_ = DQUOTE;
+ break;
+
+ default:
+ __builtin_unreachable();
+ }
+ }
+}
+
+void HighlightMatlab::flush(std::string *r) {
+ switch (t_) {
+ case WORD:
+ if (is_keyword_matlab(word_.data(), word_.size())) {
+ *r += HI_KEYWORD;
+ *r += word_;
+ *r += HI_RESET;
+ } else if (is_keyword_matlab_builtin(word_.data(), word_.size())) {
+ *r += HI_BUILTIN;
+ *r += word_;
+ *r += HI_RESET;
+ } else if (is_keyword_matlab_constant(word_.data(), word_.size())) {
+ *r += HI_CONSTANT;
+ *r += word_;
+ *r += HI_RESET;
+ } else {
+ *r += word_;
+ }
+ word_.clear();
+ break;
+ case QUOTE:
+ case QUOTE_BACKSLASH:
+ case DQUOTE:
+ case DQUOTE_BACKSLASH:
+ case COMMENT:
+ *r += HI_RESET;
+ break;
+ default:
+ break;
+ }
+ t_ = NORMAL;
+}
diff --git a/llamafile/highlight_test.cpp b/llamafile/highlight_test.cpp
index b1277307..c0197f16 100644
--- a/llamafile/highlight_test.cpp
+++ b/llamafile/highlight_test.cpp
@@ -52,6 +52,7 @@ const char *const kLanguages[] = {
"m4", //
"make", //
"markdown", //
+ "matlab", //
"pascal", //
"perl", //
"php!", //
diff --git a/llamafile/is_keyword_matlab.gperf b/llamafile/is_keyword_matlab.gperf
new file mode 100644
index 00000000..c5667a6a
--- /dev/null
+++ b/llamafile/is_keyword_matlab.gperf
@@ -0,0 +1,31 @@
+%{
+#include <string.h>
+%}
+%pic
+%compare-strncmp
+%language=ANSI-C
+%readonly-tables
+%define lookup-function-name is_keyword_matlab
+%%
+break
+case
+catch
+classdef
+continue
+else
+elseif
+end
+for
+function
+global
+if
+methods
+otherwise
+parfor
+pause
+persistent
+properties
+return
+switch
+try
+while
diff --git a/llamafile/is_keyword_matlab_builtin.gperf b/llamafile/is_keyword_matlab_builtin.gperf
new file mode 100644
index 00000000..97ec9010
--- /dev/null
+++ b/llamafile/is_keyword_matlab_builtin.gperf
@@ -0,0 +1,473 @@
+%{
+#include <string.h>
+%}
+%pic
+%compare-strncmp
+%language=ANSI-C
+%readonly-tables
+%define lookup-function-name is_keyword_matlab_builtin
+%%
+abs
+acos
+acosd
+acosh
+acot
+acotd
+acoth
+acsc
+acscd
+acsch
+addedge
+addnode
+adjacency
+airy
+allcycles
+allfinite
+allpaths
+amd
+angle
+anymissing
+anynan
+asec
+asecd
+asech
+asin
+asind
+asinh
+atan
+atan2
+atan2d
+atand
+atanh
+balance
+bandwidth
+bctree
+besselh
+besseli
+besselj
+besselk
+bessely
+beta
+betainc
+betaincinv
+betaln
+bfsearch
+bicg
+bicgstab
+bicgstabl
+biconncomp
+blkdiag
+bsxfun
+cart2pol
+cart2sph
+cat
+cdf2rdf
+ceil
+centrality
+cgs
+chol
+cholupdate
+circshift
+clip
+colamd
+colon
+colperm
+combinations
+compan
+complex
+cond
+condeig
+condensation
+condest
+conj
+conncomp
+conv
+conv2
+convn
+cos
+cosd
+cosh
+cospi
+cot
+cotd
+coth
+cplxpair
+cross
+csc
+cscd
+csch
+ctranspose
+cumprod
+cumsum
+cyclebasis
+decomposition
+deconv
+deg2rad
+degree
+det
+detrend
+dfsearch
+diag
+diff
+digraph
+disp
+dissect
+distances
+dmperm
+dot
+edgecount
+eig
+eigs
+ellipj
+ellipke
+equilibrate
+erf
+erfc
+erfcinv
+erfcx
+erfinv
+etree
+etreeplot
+eval
+exp
+expint
+expm
+expm1
+expmv
+eye
+factor
+factorial
+fft
+fft2
+fftn
+fftshift
+fftw
+fillmissing
+fillmissing2
+filloutliers
+filter
+filter2
+find
+findedge
+findnode
+fix
+flip
+flipedge
+fliplr
+flipud
+floor
+fminbnd
+fminsearch
+freqspace
+full
+funm
+fzero
+gallery
+gamma
+gammainc
+gammaincinv
+gammaln
+gcd
+gmres
+gplot
+graph
+griddata
+griddatan
+griddedInterpolant
+gsvd
+hadamard
+hankel
+hascycles
+head
+hess
+highlight
+hilb
+horzcat
+hypot
+ichol
+idivide
+ifft
+ifft2
+ifftn
+ifftshift
+ilu
+imag
+incidence
+ind2sub
+indegree
+inedges
+interp1
+interp2
+interp3
+interpft
+interpn
+inv
+invhilb
+ipermute
+isbanded
+isbetween
+ischange
+iscolumn
+isdag
+isdiag
+isempty
+isfinite
+ishermitian
+isinf
+isisomorphic
+islocalmax
+islocalmax2
+islocalmin
+islocalmin2
+ismatrix
+ismember
+ismembertol
+ismissing
+ismultigraph
+isnan
+isomorphism
+isoutlier
+isprime
+isreal
+isregular
+isrow
+isscalar
+issorted
+issortedrows
+issparse
+issymmetric
+istril
+istriu
+isuniform
+isvector
+kron
+labeledge
+labelnode
+laplacian
+layout
+layoutcoords
+lcm
+ldl
+legendre
+length
+linsolve
+linspace
+log
+log10
+log1p
+log2
+logical
+logm
+logspace
+lscov
+lsqminnorm
+lsqnonneg
+lsqr
+lu
+magic
+makima
+matchpairs
+maxflow
+meshgrid
+minres
+minspantree
+mkpp
+mldivide
+mod
+movmean
+movmedian
+movsum
+mpower
+mrdivide
+mtimes
+nchoosek
+ndgrid
+ndims
+nearest
+neighbors
+nextpow2
+nnz
+nonzeros
+norm
+normalize
+normest
+nthroot
+nufft
+nufftn
+null
+numedges
+numel
+numnodes
+nzmax
+ones
+optimget
+optimset
+ordeig
+ordqz
+ordschur
+orth
+outdegree
+outedges
+paddata
+padecoef
+pagectranspose
+pageeig
+pageinv
+pagelsqminnorm
+pagemldivide
+pagemrdivide
+pagemtimes
+pagenorm
+pagepinv
+pagesvd
+pagetranspose
+pascal
+pcg
+pchip
+perms
+permute
+pinv
+planerot
+plot
+pol2cart
+poly
+polyder
+polydiv
+polyeig
+polyfit
+polyint
+polyval
+polyvalm
+pow2
+ppval
+predecessors
+primes
+prod
+psi
+qmr
+qr
+qrdelete
+qrinsert
+qrupdate
+qz
+rad2deg
+rand
+randi
+randn
+randperm
+rank
+rat
+rats
+rcond
+real
+reallog
+realpow
+realsqrt
+rem
+reordernodes
+repelem
+repmat
+rescale
+reshape
+residue
+resize
+retime
+rmedge
+rmmissing
+rmnode
+rmoutliers
+rng
+roots
+rosser
+rot90
+round
+rows2vars
+rref
+rsf2csf
+scatteredInterpolant
+schur
+sec
+secd
+sech
+shiftdim
+shortestpath
+shortestpathtree
+sign
+simplify
+sin
+sind
+sinh
+sinpi
+size
+smoothdata
+smoothdata2
+sort
+sortrows
+spalloc
+sparse
+spaugment
+spconvert
+spdiags
+speye
+spfun
+sph2cart
+spline
+spones
+spparms
+sprand
+sprandn
+sprandsym
+sprank
+spy
+sqrt
+sqrtm
+squeeze
+ss2tf
+stack
+standardizeMissing
+sub2ind
+subgraph
+subspace
+successors
+sum
+svd
+svdappend
+svds
+svdsketch
+sylvester
+symamd
+symbfact
+symmlq
+symrcm
+table
+tail
+tan
+tand
+tanh
+tensorprod
+tfqmr
+toeplitz
+toposort
+trace
+transclosure
+transpose
+transreduction
+treelayout
+treeplot
+trenddecomp
+tril
+trimdata
+triu
+uminus
+unique
+uniquetol
+unmesh
+unmkpp
+unstack
+unwrap
+uplus
+vander
+vecnorm
+vertcat
+wilkinson
+zeros
diff --git a/llamafile/is_keyword_matlab_constant.gperf b/llamafile/is_keyword_matlab_constant.gperf
new file mode 100644
index 00000000..937eab7f
--- /dev/null
+++ b/llamafile/is_keyword_matlab_constant.gperf
@@ -0,0 +1,16 @@
+%{
+#include <string.h>
+%}
+%pic
+%compare-strncmp
+%language=ANSI-C
+%readonly-tables
+%define lookup-function-name is_keyword_matlab_constant
+%%
+Inf
+NaN
+eps
+false
+flintmax
+pi
+true