% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/latex-grob.R
\name{latex_grob}
\alias{latex_grob}
\alias{grid.latex}
\title{Create a grid grob from a LaTeX expression}
\usage{
latex_grob(
  tex,
  x = grid::unit(0.5, "npc"),
  y = grid::unit(0.5, "npc"),
  default.units = "npc",
  hjust = 0.5,
  vjust = 0.5,
  rot = 0,
  math_font = "",
  max_width = 0,
  tex_style = "",
  input_mode = c("mixed", "math"),
  render_mode = c("typeface", "path"),
  justify = FALSE,
  line_break = c("greedy", "optimal"),
  debug = FALSE,
  name = NULL,
  gp = grid::gpar()
)

grid.latex(tex, ...)
}
\arguments{
\item{tex}{Character string of LaTeX math code.}

\item{x, y}{Position in grid coordinates.}

\item{default.units}{Units for x, y if given as numeric.}

\item{hjust, vjust}{Horizontal/vertical justification. Accepts the
usual numeric values in \verb{[0, 1]}. As a convenience, \code{hjust} also
accepts the strings \code{"left"}/\code{"bbleft"}, \code{"center"}/\code{"centre"}/
\code{"middle"}/\code{"bbcentre"}, and \code{"right"}/\code{"bbright"}; \code{vjust} accepts
\code{"bottom"}, \code{"center"}/\code{"centre"}/\code{"middle"}, \code{"top"}, and
\code{"baseline"}. \code{"baseline"} aligns the formula's math baseline with
the anchor point — handy for placing a formula in flowing text.}

\item{rot}{Rotation angle in degrees, counter-clockwise (default: 0).
Matches the \code{rot} parameter of \code{\link[grid]{textGrob}}.}

\item{math_font}{Name of the math font to use (e.g., \code{"stix"}).
Use \code{""} (default) for Lete Sans Math, which pairs with R's
default sans-serif text font.
See \code{\link{available_math_fonts}} for loaded fonts.}

\item{max_width}{Numeric maximum width in big points for automatic
line wrapping.  Use \code{0} (default) for no wrapping.}

\item{tex_style}{Character: TeX style override. One of \code{""}
(default; let the parser decide), \code{"display"}, \code{"text"},
\code{"script"}, or \code{"scriptscript"}. See
\code{\link{latex_grob}} for the semantics of each value.}

\item{input_mode}{How \code{tex} is interpreted before being parsed.
\code{"mixed"} (default) wraps the input in \code{\\text{...}} so the
string reads as ordinary text and \code{$...$} (or \code{\\(...\\)})
opens math mode, matching document-level LaTeX semantics. Useful for
labels that arrive from external sources mixing prose and math without
explicit \code{\\text{}} markers. \code{"math"} is the classic
MicroTeX behaviour --- the whole string is treated as math, so unwrapped
prose renders as spaced math italics. The default can be changed globally via
\code{\link{latex_options}(input_mode = "math")}. See \code{\link{latex_wrap}}
for details on the wrapping process.}

\item{render_mode}{Character string: \code{"typeface"} (default) renders
glyphs as native text using the math font, producing
selectable/accessible text in PDF and SVG output.
Bundled math fonts and any registered via \code{\link{load_math_font}}
are read directly from their OTF files --- no system-wide font
install is required.
Falls back to path mode automatically on devices that lack the
R \eqn{\geq} 4.3 glyph engine (e.g., the base \code{pdf()} device).
For selectable PDF output, prefer \code{\link[grDevices]{cairo_pdf}}.
\code{"path"} renders math symbols as filled vector paths (works on
all devices but text is not selectable in PDF/SVG).}

\item{justify}{Logical. When \code{TRUE}, wrapped text is stretched at
its interword spaces so every line but the last fills
\code{max_width} exactly. Requires \code{max_width}: it acts on the
lines the wrapper produces, so it does nothing on its own.
\code{FALSE} (default) leaves the right edge ragged, matching R's own
text drawing. In a narrow column, expect wide word spaces; mark the
words that may break with \code{\\-} to tighten them.}

\item{line_break}{How lines are chosen when wrapping.
\code{"greedy"} (default) fills each line as far as it will go and
never reconsiders. \code{"optimal"} chooses the breaks together so
the paragraph as a whole reads best, in the spirit of Knuth-Plass:
pulling one word down early can improve every later line, which a
greedy pass cannot see. Requires \code{max_width}, and costs a
little more layout time.}

\item{debug}{Logical; if \code{TRUE}, draws diagnostic overlays on the
grob --- the full bounding box (dashed gray), the baseline (solid
red), the depth line (dashed gray), and a small dot at each
MicroTeX draw record's origin. Useful for checking positioning and
diagnosing vertical alignment.}

\item{name}{Optional grob name.}

\item{gp}{Graphical parameters (see \code{\link[grid]{gpar}}).
Common entries: \code{col} (formula foreground), \code{fontfamily}
(text font), \code{fontsize} / \code{cex}
(formula size), and \code{lineheight} (multi-line spacing). See
\code{\link{latex_grob}} for how each of these flows through
MicroTeX.}

\item{...}{Additional arguments passed to \code{\link{latex_grob}}.}
}
\value{
A \code{grid} grob of class \code{"latexgrob"}.

Invisibly returns the grob.
}
\description{
Parses a LaTeX math expression and returns a grid grob object
that renders the formula using native grid graphics primitives.
The grob supports standard grid queries such as \code{grobWidth()},
\code{grobHeight()}, \code{grobX()}, and \code{grobY()}.

A convenience wrapper that creates a \code{\link{latex_grob}} and
immediately draws it on the current device via
\code{\link[grid]{grid.draw}}.
}
\details{
\subsection{Controlling TeX style with \code{tex_style}}{

\code{tex_style} selects the size-and-spacing regime MicroTeX applies to
the whole expression. It changes the \emph{style} (display vs. text), not
the font size --- size is always set via \code{gp$fontsize} / \code{gp$cex};
style-dependent shrinking (for \code{"script"} and \code{"scriptscript"}) is
applied on top of that size.
\itemize{
\item \code{""} (default): let the parser choose based on the delimiters in
\code{tex}. Inline delimiters (single \code{$}, or \verb{\\(...\\)}) produce
\code{"text"} style; display delimiters (double \verb{$$}, or \verb{\[...\]})
produce \code{"display"} style. If the string has no delimiters,
MicroTeX defaults to \code{"text"} style.
\item \code{"display"}: force display style. Large operators (\verb{\\sum},
\verb{\\int}, \verb{\\prod}) render at their full size, limits are placed
above/below rather than as subscripts/superscripts, and fractions
use full-size numerators and denominators. Useful when you want a
display-style equation inline in a label, legend, or
\code{element_latex()} title.
\item \code{"text"}: force text (inline) style. Big operators shrink to their
inline size and limits attach as scripts. The right choice for
formulas embedded in a line of prose.
\item \code{"script"}: force script style --- the size normally used for
first-level subscripts and superscripts. Produces a smaller,
tighter layout; mainly useful for callouts or sub-labels where a
compact equation is wanted.
\item \code{"scriptscript"}: force scriptscript style --- the smallest style,
used by TeX for doubly-nested scripts. Rarely needed on its own;
primarily for very dense annotations.
}

\code{tex_style} applies to the entire expression. To override the style
of a sub-expression from within \code{tex}, use the inline TeX commands
\verb{\\displaystyle}, \verb{\\textstyle}, \verb{\\scriptstyle}, or
\verb{\\scriptscriptstyle}.
}

\subsection{Graphical parameters (\code{gp})}{
\itemize{
\item \code{col}: default foreground color for the formula. Individual
elements can still be overridden with an inline \verb{\\textcolor}
command in the LaTeX string.
\item \code{fontfamily}: controls the font of text inside \verb{\\text} and \verb{\\mbox}
blocks. For example, \code{gpar(fontfamily = "serif")} renders \verb{\\text}
content in R's serif family. Any font available to R's graphics
system works --- base families (\code{"sans"}, \code{"serif"}, \code{"mono"}) as
well as fonts registered via \pkg{showtext} or \pkg{systemfonts}.
Math symbols always use the selected math font (see \code{math_font}).
Bold/italic text is controlled from within the LaTeX source
(\verb{\\textbf\{\}}, \verb{\\textit\{\}}, \verb{\\bf}, ...), not via \code{gp$fontface} ---
MicroTeX needs the style at layout time to size each run correctly,
so a \code{gpar()}-level face is not consulted.

\code{fontfamily} \emph{also} drives MicroTeX's layout metrics for non-math
text: the matching system font is resolved via \pkg{systemfonts},
a minimal metrics file is generated on first use and cached under
\code{tools::R_user_dir("gridmicrotex", "cache")}, so MicroTeX's
spacing of \verb{\\text} blocks stays in sync with what \pkg{grid}
actually draws. When \code{fontfamily} is unset, the R default
(\code{"sans"}) is used. No manual font loading is required for text
fonts; \code{\link[=load_math_font]{load_math_font()}} remains only for adding custom \strong{math}
fonts.
\item \code{fontsize} / \code{cex}: formula size is \code{fontsize * cex} big points
(default 20 * 1). Both math and text scale together. The effective
size is baked into the parsed layout, so downstream viewports that
inherit \code{cex} will not re-scale the grob (matching \code{textGrob}
semantics when \code{gp} is set explicitly).
\item \code{lineheight}: controls multi-line spacing (default 1.2). The
inter-line gap is \code{(lineheight - 1) * fontsize} big points.
}
}

\subsection{LaTeX document-level wrappers}{

The parser accepts raw output from \code{print.xtable()},
\code{knitr::kable()}, and similar functions that emit complete
\code{tabular} LaTeX. The following document-level constructs are
recognized and rewritten silently before the input reaches MicroTeX:

\strong{Removed (no visual effect):}
\itemize{
\item \verb{\%}-to-end-of-line comments (escaped \verb{\\\%} is preserved)
\item preamble: \verb{\\documentclass[...]\{...\}}, \verb{\\usepackage[...]\{...\}},
\verb{\\begin\{document\}} / \verb{\\end\{document\}}
\item title metadata: \verb{\\maketitle}, \verb{\\title\{...\}}, \verb{\\author\{...\}}
\item cross-reference labels: \verb{\\label\{...\}}
\item float wrappers: \verb{\\begin\{table\}} / \verb{\\end\{table\}}, \verb{\\begin\{figure\}} /
\verb{\\end\{figure\}} (and starred variants)
\item layout scopes: \verb{\\centering}, \verb{\\raggedright}, \verb{\\raggedleft},
\verb{\\flushleft}, \verb{\\flushright}
}

\strong{Rewritten:}
\itemize{
\item booktabs rules: \verb{\\toprule}, \verb{\\midrule}, \verb{\\bottomrule}, \verb{\\cmidrule}
are mapped to \verb{\\hline}. The optional column-range and trim
arguments of \verb{\\cmidrule} are discarded (MicroTeX has no concept of
partial-column rules).
\item \verb{\\caption[short]\{X\}} is extracted as \verb{\\text\{X\}\\\\} at its source
position, so a caption written after \verb{\\includegraphics} renders below
the figure and one written before a \code{tabular} renders above the table.
Full LaTeX instead positions the caption by float type regardless of
source order, and numbers it from a counter; there is no counter here.
Wrap the figure and its caption in \verb{\\begin\{array\}\{c\}...\\end\{array\}} to
centre them on each other (\verb{\\centering} is dropped --- a grob has no
page to centre against).
\item \verb{\\graphicspath\{\{dir/\}\}} and \verb{\\DeclareGraphicsExtensions\{...\}} are
consumed rather than typeset; the former's directories are searched.
}

\strong{Images:}
\itemize{
\item \verb{\\includegraphics[opts]\{file\}} draws a PNG, JPEG or SVG inline. The
starred form is accepted and behaves identically. \code{width}, \code{height}
and \code{scale} take any LaTeX length (\verb{\\textwidth} resolves against
\code{max_width}, and without one falls back to the file's own size with a
warning); \code{scale} multiplies whatever \code{width}/\code{height} settled on, and
\code{keepaspectratio} fits inside them instead of stretching to fill.
\code{angle} rotates the figure and grows the surrounding box to the rotated
bounds, as \verb{\\rotatebox} does. \code{origin}, \code{trim}, \code{clip} and \code{viewport}
are parsed but not applied, and warn once so the difference is not
silent; so does a length that cannot be read, or one that sizes the
figure to nothing.
\item The extension may be omitted, as in LaTeX: \code{{plots/fig}} finds
\code{plots/fig.svg}, then \code{.png}, \code{.jpg}, \code{.jpeg}.
\item An SVG is drawn as real vector and stays sharp at any output
resolution; a bitmap does not, and warns when it would be shown below
150 dpi. PDF and EPS are not supported --- save the figure as SVG
instead. A file that cannot be read --- missing, unsupported, or an
SVG with no \code{rsvg} installed --- warns and draws its name rather than
disappearing.
}

Anything not in this list is passed to MicroTeX unchanged. An unknown
command is not an error: MicroTeX typesets its name in red, which
makes unsupported markup easy to spot in the output.
}

\subsection{Parallelism}{

The MicroTeX engine keeps mutable C++ state for font caching and text
measurement. Rendering is safe single-threaded and under separate-process
backends such as \code{future::plan(multisession)}. It is \emph{not} safe
under forked backends (\code{parallel::mclapply()},
\code{future::plan(multicore)}) on Unix, because forked workers share that
state without synchronisation. Use a socket/multisession backend instead.
}
}
\examples{
\donttest{
  g <- latex_grob(r"($\fcolorbox{red}{yellow}{\frac{a}{b}}$)",
                  x = grid::unit(0.3, "npc"),
                  y = grid::unit(0.3, "npc"),
                  gp = grid::gpar(fontsize = 30))
  grid::grid.draw(g)
  # Red formula
  grid::grid.draw(latex_grob("$x^{2}$",
                             x = grid::unit(0.3, "npc"),
                             y = grid::unit(0.8, "npc"),
                             gp = grid::gpar(col = "red")))

                             # Rotated formula
  grid::grid.draw(latex_grob(r"($\colorbox{BurntOrange}{x^{2}} + y^{2}$)",
                             x = grid::unit(0.6, "npc"),
                             y = grid::unit(0.3, "npc"),
                             gp = grid::gpar(fontsize = 24),
                             rot = 45))

  grid.latex(r"($\textcolor{red}{x^{2}} + y^{2} = z^{2}$)",
             x = grid::unit(0.6, "npc"),
             y = grid::unit(0.8, "npc"),)
}
}
\seealso{
\code{\link{grid.latex}}, \code{\link{latex_dims}},
\code{\link{geom_latex}}, \code{\link{available_math_fonts}},
\code{\link{latex_wrap}}, \code{\link{latex_options}}
}
