Movatterモバイル変換


[0]ホーム

URL:


Title:Markdown Parser and Renderer for R Graphics
Version:1.2.1
Description:Provides the mean to parse and render markdown text with grid along with facilities to define the styling of the text.
License:MIT + file LICENSE
URL:https://marquee.r-lib.org,https://github.com/r-lib/marquee
BugReports:https://github.com/r-lib/marquee/issues
Depends:R (≥ 4.1)
Imports:cli, glue, grDevices, grid, jpeg, lifecycle, png, rlang (≥1.1.0), S7, systemfonts (≥ 1.2.0), textshaping (≥ 1.0.0),utils, vctrs
Suggests:ggplot2, gt, gtable, knitr, patchwork, ragg, rmarkdown, rsvg,testthat (≥ 3.0.0)
LinkingTo:cpp11
VignetteBuilder:knitr
Config/build/compilation-database:true
Config/Needs/website:tidyverse/tidytemplate
Config/testthat/edition:3
Config/usethis/last-upkeep:2025-04-23
Encoding:UTF-8
RoxygenNote:7.3.2
NeedsCompilation:yes
Packaged:2025-09-15 13:31:40 UTC; thomas
Author:Thomas Lin PedersenORCID iD [aut, cre], Martin Mitáš [aut] (Author of MD4C), Posit Software, PBCROR ID [cph, fnd]
Maintainer:Thomas Lin Pedersen <thomas.pedersen@posit.co>
Repository:CRAN
Date/Publication:2025-09-15 13:50:02 UTC

marquee: Markdown Parser and Renderer for R Graphics

Description

logo

Provides the mean to parse and render markdown text with grid along with facilities to define the styling of the text.

Author(s)

Maintainer: Thomas Lin Pedersenthomas.pedersen@posit.co (ORCID)

Authors:

Other contributors:

See Also

Useful links:


Geom class for geom_marquee

Description

This is the underlying Geom class that powersgeom_marquee() layers.

Usage

GeomMarquee

Guide class for guide_marquee

Description

This is sthe underlying Guide class that powersguide_marquee legends.

Usage

GuideMarquee

Classic styling for markdown

Description

This function facilitates construction of a complete style set based on theclassic look of an HTML rendered markdown document. It contains stylespecifications for all the supported markdown elements as well as asub andsup style that can be used for subscripts and superscript respectively.These are only accessible through custom spans (e.g.⁠H{.sub 2}O⁠) asmarkdown doesn't provide a syntax for these formats.

Usage

classic_style(  base_size = 12,  body_font = "",  header_font = "",  code_font = "mono",  ...,  ltr = TRUE)

Arguments

base_size

The base font size for the text. All other sizing is basedon this

body_font

The font family to use for body text

header_font

The font family to use for headers

code_font

The font family to use for code and code block text

...

Arguments passed on tobase_style

weight

The font weight to use. Can either be a number (0,100,200,300,400,500,600,700,800, or900) or a strings("undefined","thin","ultralight","light","normal","medium","semibold","bold","ultrabold", or"heavy")

italic

Should the font be slanted

width

The font width to use. Can either be a number (“0⁠, ⁠1', '2','3', '4', '5', '6', '7', '8', or '9') or strings ('"undefined"','"ultracondensed"', '"extracondensed"', '"condensed"', '"semicondensed"','"normal"', '"semiexpanded"', '"expanded"', '"extraexpanded"', or'"ultraexpanded"')

features

Afont_feature object specifyingany OpenType font features to apply to the font

color

Is the color of the font

lineheight

The spacing between subsequent lines relative to the fontsize. Can berelative() in which case it is based on the parent lineheight.

align

The alignment within the text. One of"left","center","right","justified-left","justified-center","justified-right", or"distributed"

tracking

Additional character spacing measured in 1/1000em. Can berelative() in which case it is based on the parent tracking.

indent

The indentation of the first line in a paragraph measured inpoints. Can berelative() in which case it is based on the parent indent,em() in which case it is based on the font size in this style, orrem()in which case it is based on the font size of the body element.

hanging

The indentation of all but the first line in a paragraphmeasured in points. Can berelative() in which case it is based on theparent hanging,em() in which case it is based on the font size in thisstyle, orrem() in which case it is based on the font size of the bodyelement.

margin

The margin around the element, given as a call totrbl().Margin refers to the area outside the box that text is placed in. If theelement has a background, the margin area will not be colored.

padding

The padding around the element, given as a call totrbl().Padding refers to the distance between the text and the border of the box itwill be drawn in. If the element has a background, the padding area will becolored.

background

The color of the background fill. The background includesthe padding but not the margin. Can be a solid color or a gradient or patternmade withgrid::linearGradient()/grid::radialGradient()/grid::pattern()

border

The color of the background stroke. The background includesthe padding but not the margin

border_width

The line width of the background stroke, given as a calltotrbl()

border_type

The linetype of the background stroke, given as an anlty compatible value (See theLine Type Specification section inpar)

border_radius

The corner radius of the background, given in points

outline

The color of the outline stroke.

outline_width

The line width of the outline stroke.

outline_type

The linetype of the outline stroke, given as an anlty compatible value (See theLine Type Specification section inpar)

outline_join

The line join type for the outline. Either"round","mitre", or"bevel".

outline_mitre

The mitre limit (relative distance between inner andouter corner at a join) ifoutline_join = "mitre".

bullets

A vector of strings to use for bullets in unordered lists.marquee_bullets provides a selection

underline

Should text be underlined

strikethrough

Should text be strikethrough

baseline

The baseline shift to apply to the text

img_asp

The default aspect ratio for block level images if notprovided by the image itself

text_direction

The directional flow of the text. Either"auto" tolet it be determined by the content of the text, or"ltr"/"rtl" tohard-code it to either left-to-right or right-to-left. This setting will notchange the order of glyphs within a span of text, but rather whetherconsequtive blocks of text are laid out left-to-right or right-to-left. Italso affects to which side indentation is applied as well as the meaning of"auto", and"justified-auto" aligment.

border_size

[Deprecated] Useborder_widthinstead

ltr

Is the style intended for left-to-right text? This affects listindentation and citation border

Value

A style set object

Examples

classic_style(16, "serif", "sans")

ggplot2 theme element supporting marquee syntax

Description

This theme element is a drop-in replacement forggplot2::element_text(). Itworks by integrating the various style settings of the element into the basestyle of the provided style set. If a margin is given, it is set on the bodytag withskip_inherit(). The default width isNA meaning that it willspan as long as the given text is, doing no line wrapping. You can set it toany unit to make it fit within a specific width. However, this may not workas expected with rotated text (you may get lucky). Note that you may seesmall shifts in the visuals when going fromelement_text() toelement_marquee() as size reporting may differ between the two elements.

Usage

element_marquee(  family = NULL,  colour = NULL,  size = NULL,  hjust = NULL,  vjust = NULL,  angle = NULL,  lineheight = NULL,  color = NULL,  margin = NULL,  style = NULL,  width = NULL,  inherit.blank = FALSE)

Arguments

family

The font family of the base style

colour,color

The font colour of the base style

size

The font size of the base style

hjust

Horizontal justification (in[0, 1])

vjust

Vertical justification (in[0, 1])

angle

Angle (in[0, 360])

lineheight

The lineheight of the base style

margin

The margin for the body tag. As margins inelement_text()doesn't rotate along withangle we follow this behavior here as well sothat the right margin becomes the bottom margin when rotating the text 90degrees and so forth.

style

A style set to base the rendering on

width

The maximum width of the text. See the description for somecaveats for this

inherit.blank

Should this element inherit the existence of anelement_blank among its parents? IfTRUE the existence ofa blank element among its parents will cause this element to be blank aswell. IfFALSE any blank parent element will be ignored whencalculating final element state.

Value

Anelement_marquee object that can be used in place ofelement_text in ggplot2 theme specifications

Note

grid, which marquee, ggplot2, etc are build upon contains a bug thatmeans that the height of a grob is calculated before the grob knows it'swidth. The result of this is that if the width of anelement_marquee() isNULL (the default), the text may overflow its allocated space with anadditional line. Unfortunately there is no great fix for this, other thaneyeball the width it has available and pass that to the element (e.g.element_marquee(width = grid::unit(10, "cm")))

Examples

library(ggplot2)p <- ggplot(mtcars) +  geom_point(aes(mpg, disp)) +  labs(title = "A {.red *marquee*} title\n* Look at this bullet list\n\n* great, huh?") +  theme_gray(base_size = 6) +  theme(title = element_marquee())plot(p)ggplot(mtcars) +  geom_histogram(aes(x = mpg)) +  labs(title ="I put a plot in your title so you can plot while you title![](p)What more could you _possibly_ want?") +  theme(title = element_marquee())

Draw text formatted with marquee

Description

The geom is an extension ofgeom_text() andgeom_label() that allows youto draw richly formatted text in marquee-markdown format in your plot. Forplain text it is a near-drop-in replacement for the above geoms except somesizing might be very slightly different. However, using this geom you areable to access the much more powerful font settings available in marquee, soeven then it might make sense to opt for this geom.

Usage

geom_marquee(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  size.unit = "mm",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

size.unit

How thesize aesthetic is interpreted: as millimetres("mm", default), points ("pt"), centimetres ("cm"), inches ("in"),or picas ("pc").

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics, rather thancombining with them. This is most useful for helper functions that defineboth data and aesthetics and shouldn't inherit behaviour from the defaultplot specification

Details

Styling of the text is based on a style set with the exception that thestandard aesthetics such as family, size, colour, fill, etc. are recognizedand applied to the base tag style. The default style set (classic_style)can be changed using the style aesthetic which can take a vector of stylesets so that each text can rely on it's own style if needed. As withelement_marquee(), thefill aesthetic is treated differently and notapplied to the base tag, but to the body tag as askip_inherit() style soas to not propagate the fill.

Contrary to the standard text and label geoms,geom_marquee() takes awidth aesthetic that can be used to turn on soft wrapping of text. Thedefault value (NA) lets the text run as long as it want's (honoring hardbreaks), but setting this to something else will instruct marquee to use atmost that amount of space. You can use grid units to set it to an absoluteamount. The default means that if the label contains no text at all (e.g. itis only an image tag) then the width is zero and the content disappears. Inthat case, you must provide a width.

Value

A ggplot2 layer that can be added to a plot

Examples

library(ggplot2)# Standard usep <- ggplot(mtcars, aes(wt, mpg))p + geom_marquee(aes(label = rownames(mtcars)))# Make use of more powerful font features (note, result may depend on fonts# installed on the system)p + geom_marquee(  aes(label = rownames(mtcars)),  style = classic_style(weight = "thin", width = "condensed"))# Turn on line wrappingp + geom_marquee(aes(label = rownames(mtcars)), width = unit(2, "cm"))# Style like labellabel_style <- modify_style(  classic_style(margin = trbl(0)),  "body",  padding = skip_inherit(trbl(4)),  border = "black",  border_width = skip_inherit(trbl(1)),  border_radius = 3)p + geom_marquee(aes(label = rownames(mtcars), fill = gear), style = label_style)# Use markdown to style the textred_bold_names <- sub("(\\w+)", "{.red **\\1**}", rownames(mtcars))p + geom_marquee(aes(label = red_bold_names))

Marquee subtitle guide

Description

This legend appears similar to a subtitle and uses marquee syntax to typesetthe text and interpolate legend glyphs.

Usage

guide_marquee(  title = ggplot2::waiver(),  style = marquee::style(background = NA),  detect = FALSE,  width = NULL,  theme = NULL,  position = "top",  override.aes = list(),  order = 1)

Arguments

title

A single character string indicating the text to display. IfNULL the title is not shown. Ifwaiver()(default), the name of the scale or the name specified inlabs() is used for the tyle.

style

Either astyle_set to override style setsinherited from the theme, or astyle for styling the labelsspecifically. Forcolour orfill scales, thecolor,background andborder style properties are overridden when set asNULL, see examples.

detect

EitherFALSE to typeset entirely through syntax orTRUE toautomatically detect labels and apply.

width

The width of the textbox. IfNULL it will take up the width ofthe panel, but due to issues with grid this might lead to an erroneousheight calculation

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.Arguments that apply to a single legend are respected, most of which havethelegend-prefix. Arguments that apply to combined legends(the legend box) are ignored, includinglegend.position,⁠legend.justification.*⁠,legend.location and⁠legend.box.*⁠.

position

A character string indicating where the legend should beplaced relative to the plot panels.One of "top", "right", "bottom", "left", or "inside".

override.aes

A list specifying aesthetic parameters of the legendkeys. See details and examples in?guide_legend.

order

positive integer less than 99 that specifies the order ofthis guide among multiple guides. This controls the order in whichmultiple guides are displayed, not the contents of the guide itself.If 0 (default), the order is determined by a secret algorithm.

Value

A GuideMarquee object that can be passed to theguides() function or used as theguide argument ina scale.

Text formatting

In addition to standardmarquee syntax, there isadditional syntax to make building a guide easier. In the text below,nmarks then-th break in the scale,label represents any of the scale'slabels andfoo represents arbitrary text.

Examples

library(ggplot2)# A standard plotbase <- ggplot(mpg, aes(displ, hwy)) +  geom_point()# Using key glyphsbase + aes(shape = drv) +  scale_shape_discrete(    # Same as using <<1>>, <<2>> and <<3>>,    # or ![](1), ![](2) and ![](3)    # or ![](4), ![](f) and ![](r)    name = "Cars with four wheel <<4>>, forward <<f>> or reverse <<r>> drive.",    guide = "marquee"  )# Recolouring textbase <- base +  aes(colour = drv) +  labs(    colour = "Cars with {.4 four wheel}, {.f forward} or {.r reverse} drive."  )base + guides(colour = "marquee")# Adjust display of labelsst <- style(weight = "bold", italic = TRUE, background = NA)base + guides(colour = guide_marquee(style = st))# Using background instead of text colour by setting it to NULLst <- style(color = "black", background = NULL)base + guides(colour = guide_marquee(style = st))# Customising style of each label through style sets# Note: tag names must be universal per `vctrs::vec_as_names` and# prefixed with `lab_`.st <- classic_style()st <- modify_style(st, tag = "lab_f", background = NULL, color = "black")st <- modify_style(st, tag = "lab_r", border_width = trbl(1),                   color = "black", background = NA)base + guides(colour = guide_marquee(style = st))# Alternatively:base + guides(colour = "marquee") +  theme(plot.subtitle = element_marquee(style = st))# Splicing in labels by number (!!2) or label (!!subcompact)base + aes(colour = class) +  labs(colour = "Cars including !!2 and !!subcompact vehicles") +  guides(colour = "marquee")# Using automatic detectionbase + aes(colour = class) +  labs(colour = "Cars including suv and minivan vehicles") +  guides(colour = guide_marquee(detect = TRUE))

Make justifications relative to the ink extent of the text

Description

Marquee measures the extent of the box around text with bearings, that is, theheight of the string "mean" is the same as the height of the string "median",despite the latter having a "d" extending upwards. This makes it easier tojustification text irrespective of the glyphs used to render it. However, ifyou want alignment to be relative to the "tight" box around the text (thebounding box of where ink has been placed), you can use theink() functionto inform marquee of your intend. In general the effect is often minusculefor horizontal justifications but can have a big effect on verticaljustification depending on the presence of ascenders and descenders in therendered glyphs.

Usage

ink(x = numeric(), use_ink = TRUE)

Arguments

x

A string giving a valid justification or a numeric between 0 and 1

use_ink

Should the values be relative to the ink extend. Will berecycled to the length ofx

Value

Amarquee_ink vector

Examples

# Plot to illustrate the difference in vertical alignmentlibrary(grid)grid.newpage()grid.draw(  marquee_grob(    c("### Textbox justification (default)",      "### Bounding box justification (using `ink()`)"),    x = 0.5,    y = c(0.95, 0.45),    hjust = 0.5,    width = NA  ))# Standard justificationgrid.draw(  marquee_grob(    "mean",    x = 0.5,    y = 0.75,    hjust = "right",    vjust = 0.5,    width = NA  ))grid.draw(  marquee_grob(    "median",    x = 0.5,    y = 0.75,    hjust = "left",    vjust = 0.5,    width = NA  ))# Justification using `ink()`grid.draw(  marquee_grob(    "mean",    x = 0.5,    y = 0.25,    hjust = "right",    vjust = ink(0.5),    width = NA  ))grid.draw(  marquee_grob(    "median",    x = 0.5,    y = 0.25,    hjust = "left",    vjust = ink(0.5),    width = NA  ))

Marquee-aware string interpolation

Description

If you want to create your markdown programmatically you'd probably want touse some sort of string interpolation such asglue(). However, the customspan syntax of marquee interferes with the standard interpolation syntax ofglue. This function let's you use both together.

Usage

marquee_glue(  ...,  .sep = "",  .envir = parent.frame(),  .open = "{",  .close = "}",  .na = "NA",  .null = character(),  .comment = character(),  .literal = FALSE,  .transformer = NULL,  .trim = TRUE)marquee_glue_data(  .x,  ...,  .sep = "",  .envir = parent.frame(),  .open = "{",  .close = "}",  .na = "NA",  .null = character(),  .comment = character(),  .literal = FALSE,  .transformer = NULL,  .trim = TRUE)

Arguments

...

[expressions]
Unnamed arguments are taken to be expressionstring(s) to format. Multiple inputs are concatenated together before formatting.Named arguments are taken to be temporary variables available for substitution.

Forglue_data(), elements in... override the values in.x.

.sep

[character(1): ‘""’]
Separator used to separate elements.

.envir

[environment:parent.frame()]
Environment to evaluate each expression in. Expressions areevaluated from left to right. If.x is an environment, the expressions areevaluated in that environment and.envir is ignored. IfNULL is passed, it is equivalent toemptyenv().

.open

[character(1): ‘\{’]
The opening delimiter. Doubling thefull delimiter escapes it.

.close

[character(1): ‘\}’]
The closing delimiter. Doubling thefull delimiter escapes it.

.na

[character(1): ‘NA’]
Value to replaceNA valueswith. IfNULL missing values are propagated, that is anNA result willcauseNA output. Otherwise the value is replaced by the value of.na.

.null

[character(1): ‘character()’]
Value to replaceNULL values with. Ifcharacter() whole output ischaracter(). IfNULL all NULL values are dropped (as inpaste0()). Otherwise thevalue is replaced by the value of.null.

.comment

[character(1): ‘#’]
Value to use as the commentcharacter.

.literal

[boolean(1): ‘FALSE’]
Whether to treat single ordouble quotes, backticks, and comments as regular characters (vs. assyntactic elements), when parsing the expression string. Setting.literal = TRUE probably only makes sense in combination with a custom.transformer, as is the case withglue_col(). Regard this argument(especially, its name) as experimental.

.transformer

[function]
A function taking two arguments,textandenvir, wheretext is the unparsed string inside the glue block andenvir is the execution environment. A.transformer lets you modify aglue block before, during, or after evaluation, allowing you to create yourown customglue()-like functions. Seevignette("transformers") forexamples.

.trim

[logical(1): ‘TRUE’]
Whether to trim the inputtemplate withtrim() or not.

.x

[listish]
An environment, list, or data frame used to lookup values.

Details

If you choose a different set of delimiters than"{" and"}" for theinterpolation the functions will call the equivalent glue functions directly.However, if you keep the defaults, the functions will use a customtransformer that will make sure to keep the marquee custom span notation. Youcan both interpolate the content of the span, as well as the span class (seeexamples)

Value

A character vector

Examples

# standard usered_text <- "this text will be red"marquee_glue("This will be black and {.red {red_text}}!")# if the span is not valid it will be treated as standard glue interpolationtry(  marquee_glue("This will be black and {.red}!"))# You can interpolate the tag name as wellcol <- "green"marquee_glue("This will be black and {.{col} this text will be {col}}!")# Tag name interpolation must follow a `.` or a `#` as these identify the# bracket pair as a custom span classcol <- ".yellow"# This is not what you want probablymarquee_glue("This will be black and {{col} this text will be {col}}!")# Tag interpolation should also interpolate the full tag and be followed by# a space in order to be validpart <- "l"marquee_glue("This will be black and {.ye{part}low this text will be {col}}!")try(  marquee_glue("This will be black and {.{part}avender this text will be {col}}!"))

Construct a grob rendering one or more markdown texts

Description

This is the main function of marquee. It takes a vector of markdown strings,parses them with the provided style, and returns a grob capable of renderingthe parsed text into rich text and (possibly) images. Seemarquee_parse()for more information about how markdown is parsed and see details below forfurther information on how rendering proceeds.

Usage

marquee_grob(  text,  style = classic_style(),  ignore_html = TRUE,  force_body_margin = FALSE,  x = 0,  y = 1,  width = NULL,  default.units = "npc",  hjust = "left",  vjust = "top",  angle = 0,  vp = NULL,  name = NULL)

Arguments

text

Either a character vector or amarquee_parsed object as createdbymarquee_parse()

style

A style set such asclassic_style() that defines how the textshould be rendered

ignore_html

Should HTML code be removed from the output

force_body_margin

Should the body margin override margin collapsingcalculations. See Details.

x,y

The location of the markdown text in the graphics. If numeric itwill be converted to units usingdefault.units

width

The width of each markdown text. If numeric it will be convertedto units usingdefault.units.NULL is equivalent to the width of theparent container.NA uses the width of the text as the full width of thegrob and will thus avoid any soft breaking of lines.

default.units

A string giving the default units to apply tox,y,andwidth

hjust

The horizontal justification of the markdown with respect tox. Can either be a numeric or one of"left","left-ink","center","center-ink","right-ink", or"right"

vjust

The vertical justification of the markdown with respect toy. Can either be a numeric or one of"bottom","bottom-ink","last-line","center","center-ink","first-line","top-ink","top"

angle

The angle of rotation (in degrees) aroundx andy

vp

An optional viewport to assign to the grob

name

The name for the grob. IfNULL a unique name will be generated

Value

A grob of classmarquee

Rendering

marquee is first and foremost developed with the new 'glyph' renderingfeatures in 4.3.0 in mind. However, not all graphics devices supports this,and while some might eventually do, it is quite concievable that some neverwill. Because of this, marquee has a fallback where it will render text as amix of polygons and rasters (depending on the font in use) if the devicedoesn't report 'glyphs' capabilities. The upside is that it works (almost)everywhere, but the downside is that the fallback is much slower and withpoorer visual quality. Because of this it is advisable to use a moderngraphics device with glyphs support if at all possible.

Rendering style

The rendering more or less adheres to the styling provided bymarquee_parse(), but has some intricacies as detailed below:

Tight lists

If a list is tight, the bottom margin of eachli tag will be set so thespacing matches the lineheight. Further, the top margin will be set to 0.

Block images

In markdown, image tags are span elements so they can be placed inline.However, if an image tag is the only thing that is contained inside a p tagmarquee determines that it should be considered a block element. In thatcase, the parent p element inherits the styling from the image element sothat the image can e.g. adhere toalign properties, or provide their ownpadding.

Horizontal rulers

These elements are rendered as an empty block. The standard style sets abottom border size and no size for the other sides.

Margin collapsing

Margin calculations follows the margin collapsing rules of HTML. Read moreabout these atmdn.Margin collapsing means that elements with margin set to 0 might end up witha margin. Specifically for the body element this can be a problem if you wantto enforce a tight box around your text. Because of this theforce_body_margin argument allows you to overwrite the marginsfor the body element with the original values after collapsing has beenperformed.

Underline and strikethrough

Underlines are placed according to the font specification. Strikethrough areplaced 0.3em above the baseline. The width of the line is set according tothe fonr specification for underline width, both for underline andstrikethrough. It inherits the color of the text.

Spans with background

Consecutive spans with the same background and border settings are mergedinto a single rectangle. The padding of the span defines the size of thebackground.

Bullet position

Bullets are placed, right-aligned, 0.25em to the left of the first line inthe li element if the text direction is ltr. For rtl text it is placed,left-aligned, 0.25 em to the right of the first line.

Border with border radius

If borders are not the same on all sides they are drawn one by one. In thiscase the border radius is ignored.

Image rendering

The image tag can be used to place images. There are support for both png,jpeg, and svg images. If the path instead names a grob, ggplot, or patchworkobject then this is rendered instead. If the file cannot be read, if it doesn't exist, or if the path names an object that is not a grob, ggplot orpatchwork, a placeholder is rendered in it's place (black square with redcross).

Image sizing

There is no standard in markdown for specifying the size of images. Bydefault, block-level images fill the width of it's container and maintainit's aspect ratio. Inline images have a default width of 0.65em and a heightmatching the aspect ration.

However, if you wish to control sizing, you can instead provide the image asa grob with a viewport with fixed dimensions, in which case this will be usedas long as the width doesn't exceed the width of the container (in which caseit will get downsized). If a rastergrob is provided without absolute sizing,the aspect ratio will match the raster, otherwise the aspect ratio will betaken from the styling of the element (defaults to 1.65)

Table rendering

While marquee does not support the extended table syntax for markdown it doesallow you to include tables in the output. It does so by supporting gtobjects as valid paths in image tags in the same way as ggplots etc. Thismeeans that you can style your tables any way you wish and with the fullpower of gt, which is much more flexible than the markdown table syntax.

Textbox justification

The justification options exceeds the classic ones provided by grid. Whilenumeric values are available as always, the number of possible text valuesare larger. Horizontal justification add"left-ink","center-ink", and"right-ink" which uses the left-most and right-most positioned glyph (orhalfway between them) as anchors. Vertical justification has the equivalent"bottom-ink","center-ink", and"top-ink" anchors, but also"first-line" and"last-line" which sets the anchor at the baseline of thefirst or last line respectively.


Parse a text as marquee

Description

marquee uses an extension of CommonMark with no support for HTML code (it isrendered verbatim). The focus is to allow easy formatting of text forgraphics, rather than fully fledged typesetting. Seemarquee syntax formore about the format.

Usage

marquee_parse(text, style = classic_style(), ignore_html = TRUE)

Arguments

text

A character string. The core quality of markdown is that any textis valid markdown so there is no restrictions on the content

style

A style set such asclassic_style() that defines how the textshould be rendered

ignore_html

Should HTML code be removed from the output

Value

A data frame describing the various tokens of the text and the styleto apply to them. The output is mainly meant for programmatic consumptionsuch as inmarquee_grob()

marquee tags

marquee tokenizes the input text into blocks and spans. It recognises thefollowing tags:

Block tags

body is the parent tag of a markdown document. It never contains any textitself, only other blocks.

ul is an unordered list. It contains a number ofli children

ol is an ordered list. It contains a number ofli children

li is a list element. If the list is tight it contains text directly insideof it. If not, text are placed inside childp blocks

hr is a horizontal line, spanning the width of the parent block. Forstyling, the bottom border size is used when rendering

h1-h6 are headings at different levels

cb is a code block. Text inside code blocks are rendered verbatim, i.e. itcannot contain any children

p is a standard paragraph block. Text separated by two line-ends areseparated into separate paragraphs

qb is a quote block. It may contain children

Span tags

em is an emphasized text span. Often this means italicizing the text, butit is ultimately up to the renderer

str is strong text, often rendered with bold text

a is a link text. While marquee rendering doesn't allow for links, it canstill be rendered in a particular way

code is text rendered as code. Often this uses a monospaced font. Textinside this span is rendered verbatim

u is text that should be underlined

del is text that should have strikethrough

custom spans is a marquee specific extension to the syntax that allows youto make up tags on the fly. See the section on marquee syntax for more.

marquee syntax

marquee uses md4c which is a fully CommonMark compliant markdown parser.CommonMark is an effort to create an internally coherent markdownspecification, something that was missing from the original markdowndescription. If you are used to writing markdown, you are used to CommonMark.Below is a list of notable additions or details about the specific waymarquee handles CommonMark

Underlines and strikethrough

While not part of the basic CommonMark spec, underline and strikethrough aresupported by marquee using⁠_⁠ and~ (e.g.⁠_underline this_⁠ and⁠~this was an error~⁠).

Images

Image tags (⁠![image title](path/to/image)⁠) are supported, but the title isignored. The path is returned as the token text.

HTML

HTML tags are ignored, i.e. they are rendered verbatim. This is not thatdifferent from classic markdown rendering except that people often convertmarkdown to HTML where these tags suddenly have meaning. They do not carryany special significance when rendered with marquee

Custom tags

While markdown provides most of what is necessary for standard text markup,there are situations, especially in visualisation, where we need somethingmore. Often users reach for inline HTML spans for that, but since HTML isfully ignored in marquee this is not an option. Further, adding in HTMLdecreases readability of the unformatted text a lot.

With marquee you can create a custom span using the⁠{.tag <some text>}⁠syntax, e.g.⁠{.sm small text}⁠ to wrap "small text" in thesm tag. You canalternatively use⁠{#tag <some text>}⁠ for the same effect. The onlydifference is that in the former syntax the. is stripped from the tag name,whereas in the latter the⁠#⁠ remains part of the name. See the Stylingsection for the primal use of the latter syntax.

Styling

During parsing, each token is assigned a style based on the provided styleset. The styling is cascading, but without the intricacies of CSS. A childelement inherits the styling of it's parent for the options that are set toNULL in the style matching the child tag. Any style element that arerelative() are computed based on the value of the parent style element.em() elements are resolved based on the size element of the child style,andrem() elements are resolved using the size element of thebody style.If a style is not provided for the tag, it fully inherits the style of it'sparent.

Automatic coloringRecognizing that the primary use for custom tags may be to change the colorof some text, marquee provides a shortcut for this. If a style is not foundfor the tag in the provided style set, marquee will check if the tag matchesa valid color (i.e. a string fromgrDevices::colors(), or a valid hexstring, e.g.⁠#53f2a9⁠). If it is a valid color it will set this as the fontcolor of the style. This means that parsing"Color {.red this} red"automatically sets the color of"this" to red, even if no style is providedfor thered tag. Likewise, parsing"Color {#00FF00 me} green" willautomatically set the color of"me" to #00FF00 (fully saturated green).

Automatic sizingLike the automatic coloring described above, marquee also offers a shortcutfor changing the size of text on the fly. Any class consisting solely ofnumbers will (if the class is not explicitly defined) by considered a textsizing class. So, parsing"This {.50 text} is big" automatically sets thefont size of"text" to50.

Additional parsing information

Apart from splitting the text up into tokens,marquee_parse() also providessome additional information useful for rendering the output in the expectedway. Theid column refers the tokens back to the original input text, theblock relates tokens together into blocks. Block elements increment theblock count when they are entered, and decrement it when they are excited.Thetype column provides the type of the block. Theindentation columnprovides the node level in the tree. A child block will increase theindentation for as long as it is active.ol_index provides the numberassociated with the ordered list element.tight indicates whether the listis tight (i.e. it was provided with no empty lines between list elements).Theends column indicate until which row in the output the tag is active(i.e. the tag is closed after the row indicated by the value in this column).

Examples

marquee_parse("# Header of the example\nSome body text", classic_style())

Convert all text elements in a theme to marquee elements

Description

Whileelement_marquee() should behave similar toggplot2::element_text()when used on plain text (i.e. text without any markdown markup), the realitycan be different. This is because the text shaping engine used by marquee(textshaping::shape_text()) may differ from the one used by the graphicsdevice (which is responsible for laying out text inelement_text()).Differences can range from slight differences in letter spacing to using adifferent font altogether (this is because the font keywords"","sans","serif","mono", and"symbol" may be mapped to different fontsdepending on the shaper). One way to handle this is to provide an explicitfont name for the elements, but alternatively you can use this function toconvert all text elements in a theme toelement_marquee()

Usage

marquefy_theme(theme)

Arguments

theme

A (complete) ggplot2 theme

Value

theme with all text elements substituted for marquee elements

Examples

library(ggplot2)ggplot(mtcars) +  geom_point(aes(disp, mpg)) +  ggtitle("How about that") +  marquefy_theme(theme_gray())

Create a style specification for a single tag

Description

style() constructs amarquee_style object specifying the styling for asingle tag. The meaning ofNULL is to inherit the value from the parentelement. It follows that top parent (the body element), must have values forall it's options. Thebase_style() constructor is a convenient constructorfor a style with sensible defaults for all it's options.

Usage

style(  family = NULL,  weight = NULL,  italic = NULL,  width = NULL,  features = NULL,  size = NULL,  color = NULL,  lineheight = NULL,  align = NULL,  tracking = NULL,  indent = NULL,  hanging = NULL,  margin = NULL,  padding = NULL,  background = NULL,  border = NULL,  border_width = NULL,  border_type = NULL,  border_radius = NULL,  outline = NULL,  outline_width = NULL,  outline_type = NULL,  outline_join = NULL,  outline_mitre = NULL,  bullets = NULL,  underline = NULL,  strikethrough = NULL,  baseline = NULL,  img_asp = NULL,  text_direction = NULL,  border_size = deprecated())base_style(  family = "",  weight = "normal",  italic = FALSE,  width = "normal",  features = systemfonts::font_feature(),  size = 12,  color = "black",  lineheight = 1.6,  align = "auto",  tracking = 0,  indent = 0,  hanging = 0,  margin = trbl(0, 0, rem(1)),  padding = trbl(0),  background = NA,  border = NA,  border_width = trbl(0),  border_type = "solid",  border_radius = 0,  outline = NA,  outline_width = 1,  outline_type = "solid",  outline_join = "round",  outline_mitre = 10,  bullets = marquee_bullets,  underline = FALSE,  strikethrough = FALSE,  baseline = 0,  img_asp = 1.65,  text_direction = "auto",  border_size = deprecated())

Arguments

family

The name of the font family to use

weight

The font weight to use. Can either be a number (0,100,200,300,400,500,600,700,800, or900) or a strings("undefined","thin","ultralight","light","normal","medium","semibold","bold","ultrabold", or"heavy")

italic

Should the font be slanted

width

The font width to use. Can either be a number (“0⁠, ⁠1', '2','3', '4', '5', '6', '7', '8', or '9') or strings ('"undefined"','"ultracondensed"', '"extracondensed"', '"condensed"', '"semicondensed"','"normal"', '"semiexpanded"', '"expanded"', '"extraexpanded"', or'"ultraexpanded"')

features

Afont_feature object specifyingany OpenType font features to apply to the font

size

The size of the font in points. Can berelative() orem() inwhich case it is based on the parent font size (forsize these areequivalent) orrem() in which case it is based on the font size of the bodyelement.

color

Is the color of the font

lineheight

The spacing between subsequent lines relative to the fontsize. Can berelative() in which case it is based on the parent lineheight.

align

The alignment within the text. One of"left","center","right","justified-left","justified-center","justified-right", or"distributed"

tracking

Additional character spacing measured in 1/1000em. Can berelative() in which case it is based on the parent tracking.

indent

The indentation of the first line in a paragraph measured inpoints. Can berelative() in which case it is based on the parent indent,em() in which case it is based on the font size in this style, orrem()in which case it is based on the font size of the body element.

hanging

The indentation of all but the first line in a paragraphmeasured in points. Can berelative() in which case it is based on theparent hanging,em() in which case it is based on the font size in thisstyle, orrem() in which case it is based on the font size of the bodyelement.

margin

The margin around the element, given as a call totrbl().Margin refers to the area outside the box that text is placed in. If theelement has a background, the margin area will not be colored.

padding

The padding around the element, given as a call totrbl().Padding refers to the distance between the text and the border of the box itwill be drawn in. If the element has a background, the padding area will becolored.

background

The color of the background fill. The background includesthe padding but not the margin. Can be a solid color or a gradient or patternmade withgrid::linearGradient()/grid::radialGradient()/grid::pattern()

border

The color of the background stroke. The background includesthe padding but not the margin

border_width

The line width of the background stroke, given as a calltotrbl()

border_type

The linetype of the background stroke, given as an anlty compatible value (See theLine Type Specification section inpar)

border_radius

The corner radius of the background, given in points

outline

The color of the outline stroke.

outline_width

The line width of the outline stroke.

outline_type

The linetype of the outline stroke, given as an anlty compatible value (See theLine Type Specification section inpar)

outline_join

The line join type for the outline. Either"round","mitre", or"bevel".

outline_mitre

The mitre limit (relative distance between inner andouter corner at a join) ifoutline_join = "mitre".

bullets

A vector of strings to use for bullets in unordered lists.marquee_bullets provides a selection

underline

Should text be underlined

strikethrough

Should text be strikethrough

baseline

The baseline shift to apply to the text

img_asp

The default aspect ratio for block level images if notprovided by the image itself

text_direction

The directional flow of the text. Either"auto" tolet it be determined by the content of the text, or"ltr"/"rtl" tohard-code it to either left-to-right or right-to-left. This setting will notchange the order of glyphs within a span of text, but rather whetherconsequtive blocks of text are laid out left-to-right or right-to-left. Italso affects to which side indentation is applied as well as the meaning of"auto", and"justified-auto" aligment.

border_size

[Deprecated] Useborder_widthinstead

Value

Amarquee_style object

Examples

# A partial stylestyle(color = "red", underline = TRUE)# Full stylebase_style()

Helpers for defining styles

Description

marquee provides a small set of helpers for constructing the needed styles.relative() specifies a numeric value as relative to the value of the parentstyle by a certain factor, e.g. a font size ofrelative(0.5) would give astyle a font size half of it's parent.em() specify a numeric value asrelative to the font size of the current style. If the font size is12, andindent is set toem(2), then the indent will be equivalent to 24.rem()works likeem() but rather than using the font size of the current style ituses the font size of the root style (which is the body element).trbl()helps you construct styles that refers to sides of a rectangle (margin,padding, and border size). The function names refers to the order of thearguments (top, right, bottom, left).skip_inherit() tells the styleinheritance to ignore this value and look for the value one above in thestack.marquee_bullets is just a character vector with 6 sensible bulletglyphs for unordered lists.

Usage

relative(x)em(x)rem(x)trbl(top = NULL, right = top, bottom = top, left = right)skip_inherit(x)marquee_bullets

Arguments

x

A decimal number. If a vector is provided only the first elementwill be used

top,right,bottom,left

Values for the sides of the rectangles. Eithernumbers or modifiers (relative, em, or rem)

Format

An object of classcharacter of length 6.

Value

Objects of the relevant class

Examples

relative(0.35)em(2)rem(1.2)# Argument default means it recycles like CSS if fewer values are specifiedtrbl(6, em(1.5))skip_inherit("sans")marquee_bullets

Create or modify a style set that describes a full markdown text

Description

A style set contains information on how to style the various tags in amarkdown text. While it is not necessary to provide a style for all tags (itwill just inherit the parent if missing), it is required to provide acomplete style for the body tag so an option is avialable through inheritancefor all tags and all style options. It can often be easier to derive a newstyle set from an existing one rather than building one from scratch.

Usage

style_set(...)modify_style(x, tag, ...)remove_style(x, tag)

Arguments

...

Named arguments providing a style for the specific tags. Formodify_style() a number of style options to change. If the first argumentis a marquee style it will overwrite the tag and subsequent arguments areignored. This only holds ifx is a style set.

x

A style or style set to modify

tag

The name of the tag to modify or remove ifx is a style set. Tagsare internally all lowercase andtag will be converted to lowercase beforematching

Value

Amarquee_style_set object

Examples

# Create a styles_set <- style_set(base = base_style(), p = style(indent = em(2)))# Modify an existing tagmodify_style(s_set, "p", size = 16)# Add a new tag, supplying a full style objectmodify_style(s_set, "str", style(weight = "bold"))# Same as above, but style object created implicitlymodify_style(s_set, "str", weight = "bold")# Remove a tag styleremove_style(s_set, "p")

[8]ページ先頭

©2009-2025 Movatter.jp