vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

typeset.vim (8027B)


      1 vim9script
      2 
      3 # Language:           Generic TeX typesetting engine
      4 # Maintainer:         Nicola Vitacolonna <nvitacolonna@gmail.com>
      5 # Latest Revision:    2026 May 20
      6 
      7 # Constants and helpers {{{
      8 const SLASH = !exists("+shellslash") || &shellslash ? '/' : '\'
      9 
     10 def Echo(msg: string, mode: string, label: string)
     11   redraw
     12   echo "\r"
     13   execute 'echohl' mode
     14   echomsg $'[{label}] {msg}'
     15   echohl None
     16 enddef
     17 
     18 def EchoMsg(msg: string, label = gettext('Notice'))
     19   Echo(msg, 'ModeMsg', label)
     20 enddef
     21 
     22 def EchoWarn(msg: string, label = gettext('Warning'))
     23   Echo(msg, 'WarningMsg', label)
     24 enddef
     25 
     26 def EchoErr(msg: string, label = gettext('Error'))
     27   Echo(msg, 'ErrorMsg', label)
     28 enddef
     29 # }}}
     30 
     31 # Track jobs {{{
     32 var running_jobs: dict<list<job>> = {}
     33 
     34 def AddJob(label: string, j: job)
     35   if !has_key(running_jobs, label)
     36     running_jobs[label] = []
     37   endif
     38 
     39   add(running_jobs[label], j)
     40 enddef
     41 
     42 def RemoveJob(label: string, j: job)
     43   if has_key(running_jobs, label) && index(running_jobs[label], j) != -1
     44     remove(running_jobs[label], index(running_jobs[label], j))
     45   endif
     46 enddef
     47 
     48 def GetRunningJobs(label: string): list<job>
     49   return has_key(running_jobs, label) ? running_jobs[label] : []
     50 enddef
     51 # }}}
     52 
     53 # Callbacks {{{
     54 def ProcessOutput(qfid: number, wd: string, efm: string, ch: channel, msg: string)
     55   # Make sure the quickfix list still exists
     56   if getqflist({'id': qfid}).id != qfid
     57     EchoErr(gettext("Quickfix list not found, stopping the job"))
     58     job_stop(ch_getjob(ch))
     59     return
     60   endif
     61 
     62   # Make sure the working directory is correct
     63   silent execute "lcd" fnameescape(wd)
     64   setqflist([], 'a', {'id': qfid, 'lines': [msg], 'efm': efm})
     65   silent lcd -
     66 enddef
     67 
     68 def CloseCb(ch: channel)
     69   job_status(ch_getjob(ch)) # Trigger exit_cb's callback
     70 enddef
     71 
     72 def ExitCb(label: string, jobid: job, exitStatus: number)
     73   RemoveJob(label, jobid)
     74 
     75   if exitStatus == 0
     76     botright cwindow
     77     EchoMsg(gettext('Success!'), label)
     78   elseif exitStatus < 0
     79     EchoWarn(gettext('Job terminated'), label)
     80   else
     81     botright copen
     82     wincmd p
     83     EchoWarn(gettext('There are errors.'), label)
     84   endif
     85 enddef
     86 # }}}
     87 
     88 # Create a new empty quickfix list at the end of the stack and return its id {{{
     89 def NewQuickfixList(path: string): number
     90   if setqflist([], ' ', {'nr': '$', 'title': path}) == -1
     91     return -1
     92   endif
     93 
     94   return getqflist({'nr': '$', 'id': 0}).id
     95 enddef
     96 # }}}
     97 
     98 # Public interface {{{
     99 # When a TeX document is split into several source files, each source file
    100 # may contain a "magic line" specifying the "root" file, e.g.:
    101 #
    102 #   % !TEX root = main.tex
    103 #
    104 # Using this line, Vim can know which file to typeset even if the current
    105 # buffer is different from main.tex.
    106 #
    107 # This function searches for the magic line in the first ten lines of the
    108 # given buffer, and returns the full path of the root document.
    109 export def FindRootDocument(bufname: string = bufname("%")): string
    110   var docpath = fnamemodify(bufname, ":p")
    111   var bufnr = bufnr(bufname)
    112   var header: list<string>
    113   var rootpath = docpath
    114 
    115   if bufexists(bufnr)
    116     header = getbufline(bufnr, 1, 10)
    117   elseif filereadable(bufname)
    118     header = readfile(bufname, "", 10)
    119   else
    120     return simplify(rootpath)
    121   endif
    122 
    123   # Search for magic line `% !TEX root = ...` in the first ten lines
    124   var idx = match(header, '^\s*%\s\+!TEX\s\+root\s*=\s*\S')
    125 
    126   if idx > -1
    127     rootpath = matchstr(header[idx], '!TEX\s\+root\s*=\s*\zs.*$')
    128 
    129     if !isabsolutepath(rootpath) # Path is relative to the buffer's path
    130       rootpath = fnamemodify(docpath, ":h") .. SLASH .. rootpath
    131     endif
    132   endif
    133 
    134   return simplify(rootpath)
    135 enddef
    136 
    137 # ConTeXt documents may specify an output directory in a comment using the
    138 # following syntax:
    139 #
    140 # runpath=texruns:<output directory>
    141 #
    142 # This function looks for such a comment in the first ten lines of the given
    143 # buffer, and returns the full path of the output directory. If the comment is
    144 # not found then the output directory coincides with the directory of the
    145 # buffer.
    146 export def GetOutputDirectory(bufname: string = bufname("%")): string
    147   var basedir = fnamemodify(bufname, ':p:h')
    148   var bufnr = bufnr(bufname)
    149   var header: list<string>
    150   var outdir = basedir
    151 
    152   if bufexists(bufnr)
    153     header = getbufline(bufnr, 1, 10)
    154   elseif filereadable(bufname)
    155     header = readfile(bufname, "", 10)
    156   else
    157     return simplify(outdir)
    158   endif
    159 
    160   # Search for output path in the first ten lines
    161   var idx = match(header, '^\s*%.*\<runpath\s*=\s*texruns\s*:\s*\S')
    162 
    163   if idx > -1
    164     outdir = matchstr(header[idx], '\<runpath\s*=\s*texruns\s*:\s*\zs.*$')
    165 
    166     if !isabsolutepath(outdir) # Path is relative to the buffer's directory
    167       outdir = basedir .. SLASH .. outdir
    168     endif
    169   endif
    170 
    171   return simplify(outdir)
    172 enddef
    173 
    174 export def LogPath(bufname: string): string
    175   var rootdoc = FindRootDocument(bufname)
    176   var docname = fnamemodify(rootdoc, ":t:r")
    177   var outdir = GetOutputDirectory(rootdoc)
    178 
    179   if empty(docname) # Set an arbitrary name to avoid returning a dotfile (.log)
    180     docname = '[NotFound]'
    181   endif
    182 
    183   return $'{outdir}{SLASH}{docname}.log'
    184 enddef
    185 
    186 # Typeset the specified path
    187 #
    188 # Parameters:
    189 #   label: a descriptive string used in messages to identify the kind of job
    190 #   Cmd:   a function that takes the path of a document and returns the typesetting command
    191 #   path:  the path of the document to be typeset. To avoid ambiguities, pass a *full* path.
    192 #   efm:   the error format string to parse the output of the command.
    193 #   env:   environment variables for the process (passed to job_start())
    194 #
    195 # Returns:
    196 #   true if the job is started successfully;
    197 #   false otherwise.
    198 export def Typeset(
    199     label: string,
    200     Cmd:   func(string): list<string>,
    201     path:  string,
    202     efm:   string,
    203     env:   dict<string> = {}
    204     ): bool
    205   var fp   = fnamemodify(path, ':p')
    206   var name = fnamemodify(fp, ':t')
    207   var wd   = fnamemodify(fp, ':h')
    208   var qfid = NewQuickfixList(fp)
    209 
    210   if qfid == -1
    211     EchoErr(gettext('Could not create quickfix list'), label)
    212     return false
    213   endif
    214 
    215   if !filereadable(fp)
    216     var msg = gettext('File not readable:')
    217     EchoErr($'{msg} {fp}', label)
    218     return false
    219   endif
    220 
    221   # Make sure to pass only the base name of the path to Cmd as this usually
    222   # works better with TeX commands (note that the command is executed inside
    223   # the file's directory). For instance, ConTeXt writes the path in .synctex
    224   # files, and full paths break syncing from the editor to the viewer.
    225   var jobid = job_start(Cmd(name), {
    226     env: env,
    227     cwd: wd,
    228     in_io: "null",
    229     callback: (c, m) => ProcessOutput(qfid, wd, efm, c, m),
    230     close_cb: CloseCb,
    231     exit_cb: (j, e) => ExitCb(label, j, e),
    232   })
    233 
    234   if job_status(jobid) ==# "fail"
    235     EchoErr(gettext("Failed to start job"), label)
    236     return false
    237   endif
    238 
    239   AddJob(label, jobid)
    240 
    241   EchoMsg(gettext('Typesetting...'), label)
    242 
    243   return true
    244 enddef
    245 
    246 export def JobStatus(label: string)
    247   var msg = gettext('Jobs still running:')
    248   EchoMsg($'{msg} {len(GetRunningJobs(label))}', label)
    249 enddef
    250 
    251 export def StopJobs(label: string)
    252   for job in GetRunningJobs(label)
    253     job_stop(job)
    254   endfor
    255 
    256   EchoMsg(gettext('Done.'), label)
    257 enddef
    258 
    259 # Typeset the specified buffer
    260 #
    261 # Parameters:
    262 #   name:    a buffer's name. this may be empty to indicate the current buffer.
    263 #   cmd:     a function that takes the path of a document and returns the typesetting command
    264 #   label:   a descriptive string used in messages to identify the kind of job
    265 #   env:     environment variables for the process (passed to job_start())
    266 #
    267 # Returns:
    268 #   true if the job is started successfully;
    269 #   false otherwise.
    270 export def TypesetBuffer(
    271     name: string,
    272     Cmd: func(string): list<string>,
    273     env = {},
    274     label = gettext('Typeset')
    275     ): bool
    276   var bufname = bufname(name)
    277 
    278   if empty(bufname)
    279     EchoErr(gettext('Please save the buffer first.'), label)
    280     return false
    281   endif
    282 
    283   var efm = getbufvar(bufnr(bufname), "&efm")
    284   var rootpath = FindRootDocument(bufname)
    285 
    286   return Typeset('ConTeXt', Cmd, rootpath, efm, env)
    287 enddef
    288 # }}}
    289 
    290 # vim: sw=2 fdm=marker