# Writing LaTeX from Julia

I’m trying to write LaTeX (which I’m sure most of you know involves a lot of backslashes, e.g. `\dfrac{3}{5}` to create a fraction with numerator 3 and denominator 5) to a text file. By a DuckDuckGo search I found that sed isn’t very LaTeX friendly in itself, so to insert that example piece of LaTeX to say line 19 I’d need to run:

``````sed -i "19i\\\dfrac{3}{5}" file.tex
``````

I’ve tried using `run` to run this command in Julia (i.e. I’ve run:

``````run(`sed -i "19i\\\dfrac{3}{5}" file.tex`)
``````

, and what I get is: `dfrac{3}{5}` being added to line 19 of file.tex. I’ve tried with fewer backslashes (1 backslash and 2 backslashes have been tried) and it doesn’t fix this error.

Is there a way around this issue?

2 Likes

My best guess would be that for `sed` to output a `\`, the slash needs to be escaped, with an extra ‘’, but you need to escape each of those `\`s in your julia string, for a total of 4.

I’ve looked at the usage info and I’m guessing using:

``````string = L"\\dfrac{3}{2}"
run(`sed -i "19i \$string" file.tex`)
``````

is what you had in mind. While for this case, this works as this is meant to be in an equation and doing this causes `\$\dfrac{3}{2}\$` to be added to file.tex, but not all the LaTeX I want to add will be inline equations, so it doesn’t seem like this is a general solution unless I’m wrong in my usage of it.

Tried four backslashes before `dfrac` and I get the same result.

@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

Perhaps if you provided some context, you could get a more general solution.

Usually, LaTeX and similar output is easiest to generate from Julia, instead of replacing strings in existing files. You can use a some kind of template for this, or alternatively just write out a tiny snippet like

``````\dfrac{3}{2}
``````

into a file and `\input` it in your LaTeX source.