[医]杂丝
应用样式
在处理字符串时,格式化和应用样式通常会退后一步。
例如,当输出到终端时,您可能需要添加https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_ (Select_Graphic_Rendition)_parameters[ANSI转义序列]在输出时,输出构造为HTML样式(`<span style="...">`等。)服务于类似的目的,等等。 您可以简单地将原始样式结构粘贴到内容本身旁边的行中,但很快就会清楚此选项仅适用于最简单的用例。 并非所有终端都支持相同的ANSI代码,并且在计算已经风格化的内容的宽度时需要费力地删除样式结构,更不用说使用多种输出格式了。
这个任务可以通过引入一个特殊的字符串类型('AnnotatedString')。 此字符串类型包含任何其他类型。 'AbstractString'并允许将格式化信息应用于区域(例如,字符1到7以粗体和红色突出显示)。
除了这些功能,我们还提供了一个方便的构建方法 `AnnotatedString',在章节中有详细描述 程式化字符串的文字。
julia> using StyledStrings
julia> styled"{yellow:hello} {blue:there}"
"hello there"
注释行
有时,能够存储与字符串区域相关的元数据是很有用的。 'AnnotatedString'包装另一个字符串,并允许您使用标记值(:label=>value
)注释其区域。 所有通用字符串操作都应用于基字符串。 然而,在可能的情况下,样式信息被保存。 这意味着你可以与 `AnnotatedString'--取子字符串,对其进行补码,将其与其他字符串组合—并附加元数据注释。
此字符串类型是[StyledStrings stdlib](StyledStrings.md#stdlib-styledstrings)的主要类型,它使用标记为`:face`的注释来存储有关样式的信息。
串联时 'AnnotatedString'尝试使用 `annotatedstring'而不是 'string',如果要保存字符串注释。
julia> str = AnnotatedString("hello there", [(1:5, :word, :greeting), (7:11, :label, 1)])
"hello there"
julia> length(str)
11
julia> lpad(str, 14)
" hello there"
julia> typeof(lpad(str, 7))
AnnotatedString{String}
julia> str2 = AnnotatedString(" julia", [(2:6, :face, :magenta)])
" julia"
julia> annotatedstring(str, str2)
"hello there julia"
julia> str * str2 == annotatedstring(str, str2) # *-конкатенация работает
true
访问注释 'AnnotatedString'和它们的修改是使用函数进行的 '注释'和 '注释!`.
使用程式化 '注释字符串'
字体
"脸"类型
'Face'定义文本可以键入的字体的详细信息。 它涵盖了一组非常适合各种格式的基本属性,即:
-
'字体`
-
'身高`
-
'重量`
-
'倾斜`
-
`前景'
-
`背景'
-
"下划线`
-
'删除线`
-
`逆'
-
`继承'
全局字体字典
为了方便引用某些样式,有一个全局字典`Dict'。{Symbol, Face}',它允许你链接到字体(`脸')只是名字。 包可以使用函数向该字典添加字体 'addface!',并且下载的字体可以很容易地 自定义。
!!! 警告"适当的人脸命名" 任何注册新字体的包都必须确保它们具有包名称形式的前缀,即符合格式`mypackage_myface`。 这对于可预测性和避免命名冲突非常重要。
此外,软件包应该使用(并引入)*语义*字体(例如"代码"),而不是直接的颜色和样式(例如"青色")。 由于各种原因,从更明显的使用意图到组合性和更直观的用户自定义,这是有用的。
数据包前缀规则有两个例外:
-
作为字体字典默认值一部分的一组基本字体;
-
Julia自己的标准库提供的字体,即’JuliaSyntaxHighlighting'。
基本字体
基本字体的设计是为了代表一个广泛适用的一般思想.
要设置具有特定属性的文本,有以下字体:"粗体","浅色","斜体","下划线","删除线"和"反向"。
还为16种终端颜色提供了命名字体:'black`,red
,green
,yellow
,blue
,magenta
,cyan
,white
,bright_black
/grey
/gray
,bright_red
,bright_green
,bright_blue',`bright_magenta
,`bright_cyan’和’bright_white'。
对于阴影文本(即,暗淡但存在),使用"阴影"字体。 有一个"区域"字体来表示选定的区域。 字体"强调"和"突出显示"被定义为表示重要性和强调。 对于类似代码的文本也有一个’代码'。
定义了"错误"、"警告"、"成功"、"信息"、"注意"和"提示"等字体,以直观地指示消息的严重性。
字体设置(')。toml')
建议全局字体字典中的命名字体是可自定义的。 设计和美学是一个很好的补充,这在辅助功能方面也很重要。 可以将TOML文件分析为规格列表。 'Face',它与字体字典中的现有条目相结合。
字体(`Face')在TOML中表示如下:
[facename]
attribute = "value"
...
[package.facename]
attribute = "value"
例如,如果字体"阴影"太难以阅读,则可以按如下方式使其更亮:
[shadow]
foreground = "white"
在初始化期间,文件’config/faces。toml’加载在第一个Julia存储库中(通常是'~/。朱莉娅`)。
将字体应用于’AnnotatedString`
传统属性`:脸` 'AnnotatedString'包含有关字体的信息('Face'),目前正在使用。 它们可以以多种形式指定:作为单个字符(`符号')命名字体(`Face')在字体的全局字典中,字体本身('Face')或它们中的任何一个的向量。
方法`show(::IO,::MIME"text/plain",::AnnotatedString)和`show(::IO,::MIME"text/html",::AnnotatedString)`检查属性
:face’并在定义公共样式时将它们组合在一起。
您可以在构造过程中为`AnnotatedString`指定属性`:face',将它们添加到属性列表中或使用方便 程式化字符串的文字。
str1 = AnnotatedString("blue text", [(1:9, :face, :blue)])
str2 = styled"{blue:blue text}"
str1 == str2
sprint(print, str1, context = :color => true)
sprint(show, MIME("text/html"), str1, context = :color => true)
程式化字符串的文字
简化创作 `AnnotatedString'与应用的字体(`Face'),程式化字符串的字面量 '风格"。.."'可以使用自定义语法轻松表达内容和属性。
文字里面 '风格"。.."'花括号被认为是特殊字符,在正常使用中必须转义(\{
, \}
). 这允许它们用于表达带有(嵌套)构造的注释`{annotations...:text}`.
'Annotations'组件。..'是由三种类型的注释组成的逗号分隔列表。
-
字体名称
-
表达式'(key=val,...)'嵌入式’脸`
-
'键=值’对
除了嵌入式字体键之外,任何地方都可以进行插值。
有关语法的更多信息,请参阅docstring的扩展帮助。 '风格"。.."`.
作为一个例子,您可以演示上面提到的嵌入字体列表,如下所示:
julia> println(styled"
The basic font-style attributes are {bold:bold}, {light:light}, {italic:italic},
{underline:underline}, and {strikethrough:strikethrough}.
In terms of color, we have named faces for the 16 standard terminal colors:
{black:■} {red:■} {green:■} {yellow:■} {blue:■} {magenta:■} {cyan:■} {white:■}
{bright_black:■} {bright_red:■} {bright_green:■} {bright_yellow:■} {bright_blue:■} {bright_magenta:■} {bright_cyan:■} {bright_white:■}
Since {code:bright_black} is effectively grey, we define two aliases for it:
{code:grey} and {code:gray} to allow for regional spelling differences.
To flip the foreground and background colors of some text, you can use the
{code:inverse} face, for example: {magenta:some {inverse:inverse} text}.
The intent-based basic faces are {shadow:shadow} (for dim but visible text),
{region:region} for selections, {emphasis:emphasis}, and {highlight:highlight}.
As above, {code:code} is used for code-like text.
Lastly, we have the 'message severity' faces: {error:error}, {warning:warning},
{success:success}, {info:info}, {note:note}, and {tip:tip}.
请记住,所有这些面(以及任何用户或包定义的面)都可以
任意嵌套和重叠, {region,tip:like {bold,italic:so}}.")
Documenter doesn't properly represent all the styling above, so I've converted it manually to HTML and LaTeX.
<pre>
The basic font-style attributes are <span style="font-weight: 700;">bold, <span style="font-weight: 300;">light, <span style="font-style: italic;">italic,
<span style="text-decoration: underline;">underline, and <span style="text-decoration: line-through">strikethrough.
In terms of color, we have named faces for the 16 standard terminal colors:
<span style="color: #1c1a23;">■ <span style="color: #a51c2c;">■ <span style="color: #25a268;">■ <span style="color: #e5a509;">■ <span style="color: #195eb3;">■ <span style="color: #803d9b;">■ <span style="color: #0097a7;">■ <span style="color: #dddcd9;">■
<span style="color: #76757a;">■ <span style="color: #ed333b;">■ <span style="color: #33d079;">■ <span style="color: #f6d22c;">■ <span style="color: #3583e4;">■ <span style="color: #bf60ca;">■ <span style="color: #26c6da;">■ <span style="color: #f6f5f4;">■
Since <span style="color: #0097a7;">bright_black является фактически серым, мы определяем для него два псевдонима:
<span style="color: #0097a7;">grey и <span style="color: #0097a7;">grey для учета различий в написании.
To flip the foreground and background colors of some text, you can use the
<span style="color: #0097a7;">inverse, например: <span style="color: #803d9b;">какой-то <span style="background-color: #803d9b;">обратный<span style="color: #803d9b;"> текст.
The intent-based basic faces are <span style="color: #76757a;">shadow (для неяркого, но видимого текста),
<span style="background-color: #3a3a3a;">region для выделений, <span style="color: #195eb3;">emphasis и <span style="background-color: #195eb3;">highlight.
As above, <span style="color: #0097a7;">code используется для текста, похожего на код.
Lastly, we have the 'message severity' faces: <span style="color: #ed333b;">error, <span style="color: #e5a509;">warning,
<span style="color: #25a268;">success, <span style="color: #26c6da;">info, <span style="color: #76757a;">note и <span style="color: #33d079;">tip.
Remember that all these faces (and any user or package-defined ones) can
arbitrarily nest and overlap, <span style="color: #33d079;background-color: #3a3a3a;">таким <span style="font-weight: 700;font-style: italic;">образом.</pre>
\begingroup
\ttfamily
\setlength{\parindent}{0pt}
\setlength{\parskip}{\baselineskip}
The basic font-style attributes are {\fontseries{b}\selectfont bold}, {\fontseries{l}\selectfont light}, {\fontshape{it}\selectfont italic},\\
\underline{underline}, and {strikethrough}.
In terms of color, we have named faces for the 16 standard terminal colors:\\
{\color[HTML]{1c1a23}\(\blacksquare\)} {\color[HTML]{a51c2c}\(\blacksquare\)} {\color[HTML]{25a268}\(\blacksquare\)}
{\color[HTML]{e5a509}\(\blacksquare\)} {\color[HTML]{195eb3}\(\blacksquare\)} {\color[HTML]{803d9b}\(\blacksquare\)}
{\color[HTML]{0097a7}\(\blacksquare\)} {\color[HTML]{dddcd9}\(\blacksquare\)} \\
{\color[HTML]{76757a}\(\blacksquare\)} {\color[HTML]{ed333b}\(\blacksquare\)} {\color[HTML]{33d079}\(\blacksquare\)} {\color[HTML]{f6d22c}\(\blacksquare\)} {\color[HTML]{3583e4}\(\blacksquare\)} {\color[HTML]{bf60ca}\(\blacksquare\)} {\color[HTML]{26c6da}\(\blacksquare\)} {\color[HTML]{f6f5f4}\(\blacksquare\)}
Since {\color[HTML]{0097a7}bright\_black} is effectively grey, we define two aliases for it:\\
{\color[HTML]{0097a7}grey} and {\color[HTML]{0097a7}gray} to allow for regional spelling differences.
To flip the foreground and background colors of some text, you can use the\\
{\color[HTML]{0097a7}inverse} face, for example: {\color[HTML]{803d9b}some \colorbox[HTML]{803d9b}{\color[HTML]{000000}inverse} text}.
The intent-based basic faces are {\color[HTML]{76757a}shadow} (for dim but visible text),\\
\colorbox[HTML]{3a3a3a}{region} for selections, {\color[HTML]{195eb3}emphasis}, and \colorbox[HTML]{195eb3}{highlight}.\\
As above, {\color[HTML]{0097a7}code} is used for code-like text.
Lastly, we have the 'message severity' faces: {\color[HTML]{ed333b}error}, {\color[HTML]{e5a509}warning},\\
{\color[HTML]{25a268}success}, {\color[HTML]{26c6da}info}, {\color[HTML]{76757a}note}, and {\color[HTML]{33d079}tip}.
请记住,所有这些面(以及任何用户或包定义的面)都可以\\
任意嵌套和重叠,\colorbox[HTML]{3a3a3a}{\color[HTML]{33d079}像
{\fontseries{b}\字体形状{it}\selectfont so}}。
\端组
API帮助
样式和字体
# ’StyledStrings。StyledMarkup.@styled_str'*-Macro
@styled_str -> AnnotatedString
创建一个风格化的字符串。 结构字符串内部 {<specs>:<content>}
根据逗号分隔的规范列表"<specs>"将格式应用于"<content>"。 每个规范可以采用字体名称,嵌入字体规范或一对`key=value’的形式。 如果值包含字符',=:{}`, оно должно быть заключено в +{…}+
.
使用`$'的字符串插值与常规字符串的工作方式相同,只是引号需要转义。 字体,键和值也可以使用`$'进行插值。
例子
styled"The {bold:{italic:quick} {(foreground=#cd853f):brown} fox} jumped over the {link={https://en.wikipedia.org/wiki/Laziness}:lazy} dog"
高级帮助
这个宏可以用下面的EBNF语法来描述:
styledstring = { styled | interpolated | escaped | plain } ;
specialchar = '{' | '}' | '$' | '\"' ;
anychar = [\u0-\u1fffff] ;
plain = { anychar - specialchar } ;
escaped = '\\', specialchar ;
插值='$',? expr? | '$(', ? expr?, ')' ;
风格='{', ws, annotations, ':', content, '}' ;
内容= { interpolated | plain | escaped | styled } ;
注解=注解/注解,ws,',',ws,注解 ;
注释=面/内联面|键值 ;
ws= { ' ' | '\t' | '\n' } ;(*空格*)
脸=面名/插值 ;
面名=[A-Za-z0-9_]+ ;
inlineface='(',ws,[faceprop], { ws, ',', faceprop },ws,')' ;
faceprop=[a-z]+,ws,'=',ws,([^,)]+/插值) ;
keyvalue=key,ws,'=',ws,value ;
钥匙= ( [^\0${}=,:], [^\0=,:]* ) | 插值,插值 ;
值=simplevalue|curlybraced/插值 ;
curlybraced='{' { escaped | plain } '}' ;
[医]单纯性= [^${},:], [^,:]* ;
在上面的语法中没有指定的附加条件是’plain’必须是有效的输入数据 'unescape_string',而’specialchar’被保存。
上面的’inlineface’语法被简化了,实际的实现有点复杂。 下面给出该行为的完整描述。
faceprop = ( 'face', ws, '=', ws, ( ? string ? | interpolated ) ) |
( 'height', ws, '=', ws, ( ? number ? | interpolated ) ) |
( 'weight', ws, '=', ws, ( symbol | interpolated ) ) |
( 'slant', ws, '=', ws, ( symbol | interpolated ) ) |
( ( 'foreground' | 'fg' | 'background' | 'bg' ),
ws, '=', ws, ( simplecolor | interpolated ) ) |
( 'underline', ws, '=', ws, ( underline | interpolated ) ) |
( 'strikethrough', ws, '=', ws, ( bool | interpolated ) ) |
( 'inverse', ws, '=', ws, ( bool | interpolated ) ) |
( 'inherit', ws, '=', ws, ( inherit | interpolated ) ) ;
nothing = 'nothing' ;
bool = 'true' | 'false' ;
symbol = [^ ,)]+ ;
hexcolor = ('#' | '0x'), [0-9a-f]{6} ;
simplecolor = hexcolor | symbol | nothing ;
underline = nothing | bool | simplecolor | underlinestyled;
underlinestyled = '(', ws, ('' | nothing | simplecolor | interpolated), ws,
',', ws, ( symbol | interpolated ), ws ')' ;
inherit = ( '[', inheritval, { ',', inheritval }, ']' ) | inheritval;
inheritval = ws, ':'?, symbol ;
# ’StyledStrings。StyledMarkup.样式'*-Function</no-翻译>
styled(content::AbstractString) -> AnnotatedString
创建一个风格化的字符串。 结构字符串内部 {<specs>:<content>}
根据逗号分隔的规范列表"<specs>"将格式应用于"<content>"。 每个规范可以采用字体名称,嵌入字体规范或一对`key=value’的形式。 如果值包含字符',=:{}`, оно должно быть заключено в +{…}+
.
这是宏的功能等价物。 '@styled_str',只有没有插值的可能性。
# ’StyledStrings。面'*-Type
'Face'是用于显示文本的图形属性的集合。 字体控制文本在终端中的显示方式,也可能控制在其他地方。
属性
所有属性都可以使用命名参数构造函数设置;默认情况下,它们被设置为’nothing'。
-
'height'(
Int’or’Float64
):小数点的高度(Int
)或作为基本大小的乘数(Float64
)。 -
weight
(符号
):其中一个符号(从最微弱到最饱和):thin
,:extralight
,:light
,:semilight
,:normal
,:medium
,:semibold
,:bold
,:extrabold`或
:black'。 在任何饱和度大于`:normal’的终端中,文本以粗体显示,在支持可变亮度文本的终端中,任何饱和度小于`:normal`的终端中,文本以暗淡字体显示。 -
'slant'(
Symbol'):字符
:斜体`,`:斜体`或':正常’之一。 -
'foreground'('SimpleColor'):文本的前景色。
-
'background'('SimpleColor'):文本的背景颜色。
-
"下划线",用以下形式之一下划线文本: 'Bool':文本是否应该加下划线。 'SimpleColor':文本应该用这种颜色加下划线。 '元组{Nothing, Symbol}`:文本必须使用字符`:straight`,
:double
,:curly
,:dotted`或
:dashed’指定的样式加下划线。 '元组{SimpleColor, Symbol}':文本必须以指定的SimpleColor颜色加下划线,并使用符号指定的样式,如前所述。 -
'删除线'('Bool`):文本是否应该被划掉。
-
'inverse'(`Bool'):前景色和背景色是否应该反转。
-
'继承'('向量{Symbol}
):应该继承的字体名称,早期字体优先。 所有字体都继承自字体
:default'。
#
'StyledStrings。脸!
*-Function</no-翻译>
addface!(name::Symbol => default::Face)
创建一个名为"名称"的新字体。 如果还没有具有该名称的字体,则会将"默认"添加到两个"面"中。默认`和(副本)'FACES'。'current',并返回当前值。
如果字体’name’已经存在,则返回’nothing`。
例子
julia> addface!(:mypkg_myface => Face(slant=:italic, underline=true))
Face (sample)
slant: italic
underline: true
# ’StyledStrings。withfaces'*-Function
withfaces(f, kv::Pair...)
withfaces(f, kvpair_itr)
用`FACES`执行`f'。当前',暂时更改为零个或多个参数':name=>val''kv`,或`kvpair_itr',它创建形式为`kv’的值。
"内"函数通常与语法"内"(kv)一起使用。..)做。.. 结束'。 使用’nothing’值,您可以暂时禁用字体(如果已设置)。 当’withfaces’函数返回控件时,原始的’FACES'。电流’被恢复。
例子
julia> withfaces(:yellow => Face(foreground=:red), :green => :blue) do
println(styled"{yellow:red} and {green:blue} mixed make {magenta:purple}")
end
red and blue mixed make purple
#
'StyledStrings。SimpleColor
*-Type
struct SimpleColor
为字符串样式设计的基本颜色表示. 它可以包含一个命名颜色(例如,:red
),或者一个对象`RGBTuple`,它是一个NamedTuple的元组,定义颜色`r`,g
,b
,深度为8位。
构造函数
SimpleColor(name::Symbol) # например, :red
SimpleColor(rgb::RGBTuple) # например, (r=1, b=2, g=3)
SimpleColor(r::Integer, b::Integer, b::Integer)
SimpleColor(rgb::UInt32) # например, 0x123456
另请参阅`tryparse(SimpleColor,rgb::String)`的描述。
# '基。解析'-Method</no-翻译>
parse(::Type{SimpleColor}, rgb::String)
Tryparse(SimpleColor,rgb::String)`的模拟,它返回错误而不是返回`nothing
。
# '基。tryparse'-Method
tryparse(::Type{SimpleColor}, rgb::String)
尝试将`rgb’分析为’SimpleColor'。 如果’rgb’值以`#'开头并且长度为7,则根据`RGBTuple`将其转换为`SimpleColor'。 如果`rgb`的值以`a`--`z’开头,则’rgb’被解释为颜色的名称,并根据`符号`转换为`SimpleColor'。
否则,'nothing’被返回。
例子
julia> tryparse(SimpleColor, "blue")
SimpleColor(blue)
julia> tryparse(SimpleColor, "#9558b2")
SimpleColor(#9558b2)
julia> tryparse(SimpleColor, "#nocolor")