Writing LaTeX from Julia

@simeonschaub provided me with a general solution to this problem at Write to a particular line in a file. Here’s the function I’m going to use to edit my LaTeX file and insert my LaTeX code (contained within string):

function skiplines(io::IO, n)
    i = 1
    while i <= n
       eof(io) && error("File contains less than $n lines")
       i += read(io, Char) === '\n'
    end
end

function insertLine(file::String, string::String, lineNr::Integer)
    f = open(file, "r+");
    skiplines(f, lineNr);
    skip(f, -1)
    mark(f)
    buf = IOBuffer()
    write(buf, f)
    seekstart(buf)
    reset(f)
    print(f, string);
    write(f, buf)
    close(f)
end

For the aforementioned example I’d use the code:

insertLine("file.tex", "\\dfrac{3}{2}", 19)

to call this function.

1 Like