StyledStrings
Styling
文字列を扱う際、書式設定やスタイル設定は二次的な関心事になりがちです。
たとえば、ターミナルに出力するときは、出力にANSI escape sequencesを散りばめたくなるかもしれません。HTML を出力する場合は、<span style="...">などのスタイル指定が同様の役割を果たします。スタイル指定をコンテンツの隣にそのまま文字列として挿入することもできますが、すぐに、ごく基本的な用途以外には適さないことがわかります。すべてのターミナルが同じ ANSI コードに対応しているわけではありません。また、すでにスタイルが適用されたコンテンツの幅を計算するには、スタイル指定を丹念に取り除く必要があります。さらに、複数の出力形式を扱うとなると、問題はそれだけではありません。
こうした厄介事を下流の利用者に広く押しつけるのではなく、専用の文字列型(AnnotatedString)を導入して正面から対処します。この文字列型は、任意のAbstractString型をラップし、領域ごとに書式情報を適用できます(たとえば、1 文字目から 7 文字目までを太字かつ赤色にするなど)。
文字列の領域にスタイルを適用するには、Face(「書体」と考えてください)を指定します。これはスタイル情報を保持する構造体です。便利なことに、shadowなど、グローバルな faces 辞書にある face は、Faceを直接指定する代わりに名前で指定できます。
こうした機能に加えて、AnnotatedStringを簡単に構築する方法も用意されています。詳しくはStyled String Literalsを参照してください。
julia> using StyledStringsjulia> styled"{yellow:hello} {blue:there}""hello there"
Annotated Strings
文字列の領域に関連するメタデータを保持できると便利な場合があります。AnnotatedStringは別の文字列をラップし、その領域にラベル付きの値(:label => value)を注釈として付与できます。一般的な文字列操作はすべて、基になる文字列に対して行われます。ただし、可能な場合はスタイル情報が保持されます。そのため、AnnotatedStringに対して部分文字列の取得、パディング、他の文字列との連結などを行っても、メタデータの注釈はそのまま引き継がれます。
この文字列型はStyledStrings stdlibの基盤となっており、:faceラベルの注釈を使ってスタイル情報を保持します。
AnnotatedStringを連結する際、文字列の注釈を保持したい場合は、stringではなくannotatedstringを使ってください。
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) # *-concatenation works
trueAnnotatedStringの注釈は、annotations関数とannotate!関数を使って取得・変更できます。
Styling via AnnotatedStrings
Faces
The Face type
Faceは、テキストに適用できる書体の詳細を指定します。さまざまな形式に広く適用できる基本属性をまとめたもので、具体的には次のとおりです。
fontheightweightslantforegroundbackgroundunderlinestrikethroughinverseinherit
各属性が取りうる具体的な形式については、Faceの docstring を参照してください。特に注目すべきなのはinheritです。これを使うと、他のFaceから属性を継承できます。
The global faces dictionary
特定のスタイルを簡単に参照できるよう、グローバルなDict{Symbol, Face}が用意されています。これにより、Faceを名前だけで参照できます。パッケージはaddface!関数を使ってこの辞書に face を追加でき、読み込まれた face は簡単にcustomizedできます。
新しい face を登録するパッケージは、パッケージ名を接頭辞として付け、mypackage_myfaceの形式に従うようにしてください。これは予測可能性を高め、名前の衝突を防ぐために重要です。
また、パッケージでは、直接的な色やスタイル(cyanなど)よりも、意味に基づく face(codeなど)を使用し、導入するようにしてください。こうすることで、使用時の意図が明確になり、組み合わせやすくなるほか、ユーザーによるカスタマイズも直感的になります。
パッケージ名を接頭辞に付けるルールには、次の 2 つの例外があります。
- faces 辞書のデフォルト値に含まれる基本 face
- Julia 自身の標準ライブラリが導入する face、すなわち
JuliaSyntaxHighlighting
Basic faces
基本 face は、幅広く適用できる一般的な概念を表すことを目的としています。
特定の属性をテキストに設定するために、bold、light、italic、underline、strikethrough、inverseの各 face が用意されています。
ターミナルの 16 色にも、それぞれ名前付き face があります。black、red、green、yellow、blue、magenta、cyan、white、bright_black/grey/gray、bright_red、bright_green、bright_blue、bright_magenta、bright_cyan、bright_whiteです。
影付きのテキスト(つまり、薄く表示されるテキスト)にはshadow face を使います。選択範囲を示すにはregion face を使います。同様に、強調とハイライトにはemphasis face とhighlight face が用意されています。また、コード風のテキストにはcodeを使います。
メッセージの重大度を視覚的に示すため、error、warning、success、info、note、tipの各 face が定義されています。
Customisation of faces (Faces.toml)
グローバルな face 辞書にある名前付き face は、カスタマイズできるのが望ましいものです。テーマや見た目を調整できるのは便利ですし、アクセシビリティの観点からも重要です。TOML ファイルを解析してFaceのリストを作成し、それを face 辞書の既存のエントリにマージできます。
Faceは、TOML では次のように表されます。
[facename]
attribute = "value"
...
[package.facename]
attribute = "value"たとえば、shadow face が読みにくい場合は、次のように明るくできます。
[shadow]
foreground = "white"初期化時に、最初の Julia depot(通常は~/.julia)にあるconfig/faces.tomlファイルが読み込まれます。
Applying faces to a AnnotatedString
慣例として、AnnotatedStringの:face属性には、現在適用されているFaceに関する情報を格納します。指定方法は複数あり、グローバルな face 辞書にあるFaceを名前で指定する単一のSymbol、Faceそのもの、またはそのいずれかを要素とするベクターを使えます。
show(::IO, ::MIME"text/plain", ::AnnotatedString)メソッドとshow(::IO, ::MIME"text/html", ::AnnotatedString)メソッドは、どちらも:face属性を参照し、全体のスタイルを決定する際にそれらをすべてマージします。
:face属性は、構築時にAnnotatedStringへ渡すことも、後からプロパティのリストに追加することもできます。また、便利なStyled String literalsも利用できます。
julia> str1 = AnnotatedString("blue text", [(1:9, :face, :blue)])"blue text"julia> str2 = styled"{blue:blue text}""blue text"julia> str1 == str2truejulia> sprint(print, str1, context = :color => true)"\e[34mblue text\e[39m"julia> sprint(show, MIME("text/html"), str1, context = :color => true)"<span style=\"color: #195eb3\">blue text</span>"
Styled String Literals
Faceを適用したAnnotatedStringを簡単に構築できるよう、styled"..."スタイル付き文字列リテラルが用意されています。独自の文法を使って、内容と属性をまとめて記述できます。
styled"..."リテラルでは、中括弧は特殊文字として扱われるため、通常の用途で使う場合はエスケープする必要があります(\{、\})。これにより、中括弧を使って(入れ子にできる){annotations...:text}構文で注釈を表現できます。
annotations...の部分は、次の 3 種類の注釈をカンマ区切りで並べたリストです。
- face 名
- インラインの
Face式(key=val,...) key=valueのペア
インラインの face キーを除き、どこでも補間を使えます。
文法の詳細については、styled"..."の docstring にある拡張ヘルプを参照してください。
例として、前述の組み込み face の一覧を次のように示せます。
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}.
Remember that all these faces (and any user or package-defined ones) can
arbitrarily nest and overlap, {region,tip:like {bold,italic:so}}.")The basic font-style attributes are bold, light, italic, underline, and strikethrough. In terms of color, we have named faces for the 16 standard terminal colors: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ Since bright_black is effectively grey, we define two aliases for it: grey and gray to allow for regional spelling differences. To flip the foreground and background colors of some text, you can use the inverse face, for example: some inverse text. The intent-based basic faces are shadow (for dim but visible text), region for selections, emphasis, and highlight. As above, code is used for code-like text. Lastly, we have the 'message severity' faces: error, warning, success, info, note, and tip. Remember that all these faces (and any user or package-defined ones) can arbitrarily nest and overlap, like so.
API reference
Styling and Faces
StyledStrings.StyledMarkup.@styled_str — Macro
@styled_str -> AnnotatedStringスタイル付き文字列を構築します。文字列内では、{<specs>:<content>} が <content> に書式を適用します。書式は、カンマ区切りの指定 <specs> のリストに従います。各指定には、フェイス名、インラインのフェイス指定、または key=value のペアを指定できます。値に ,=:{} のいずれかの文字が含まれる場合は、{...} で囲む必要があります。
$ を使った文字列補間は、通常の文字列と同様に機能しますが、引用符をエスケープする必要があります。フェイス、キー、値も $ で補間できます。
Example
styled"The {bold:{italic:quick} {(foreground=#cd853f):brown} fox} jumped over the {link={https://en.wikipedia.org/wiki/Laziness}:lazy} dog"Extended help
このマクロは、次の EBNF 文法で記述できます。
styledstring = { styled | interpolated | escaped | plain } ;
specialchar = '{' | '}' | '$' | '\"' ;
anychar = [\u0-\u1fffff] ;
plain = { anychar - specialchar } ;
escaped = '\\', specialchar ;
interpolated = '$', ? expr ? | '$(', ? expr ?, ')' ;
styled = '{', ws, annotations, ':', content, '}' ;
content = { interpolated | plain | escaped | styled } ;
annotations = annotation | annotations, ws, ',', ws, annotation ;
annotation = face | inlineface | keyvalue ;
ws = { ' ' | '\t' | '\n' } ; (* whitespace *)
face = facename | interpolated ;
facename = [A-Za-z0-9_]+ ;
inlineface = '(', ws, [ faceprop ], { ws, ',', faceprop }, ws, ')' ;
faceprop = [a-z]+, ws, '=', ws, ( [^,)]+ | interpolated) ;
keyvalue = key, ws, '=', ws, value ;
key = ( [^\0${}=,:], [^\0=,:]* ) | interpolated ;
value = simplevalue | curlybraced | interpolated ;
curlybraced = '{' { escaped | plain } '}' ;
simplevalue = [^${},:], [^,:]* ;上記の文法には含まれていない追加条件として、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.styled — Function
styled(content::AbstractString) -> AnnotatedStringスタイル付き文字列を構築します。文字列内では、{<specs>:<content>}によって、カンマ区切りの指定リスト<specs>に従い、<content>に書式が適用されます。各指定には、フェイス名、インラインのフェイス指定、またはkey=valueのペアを指定できます。値に,=:{}のいずれかの文字が含まれる場合は、{...}で囲む必要があります。
これは@styled_strマクロと機能的に同等ですが、補間機能はありません。
StyledStrings.Face — Type
Faceは、テキストを表示するためのグラフィカル属性の集合です。Faceは、ターミナルや、場合によってはその他の場所でのテキストの表示方法を制御します。
ほとんどの場合、Faceはグローバルなfaces辞書に、face名のSymbolとの一意な対応として格納されます。そのため、Faceオブジェクト自体ではなく、この名前で参照されることがほとんどです。
Attributes
すべての属性はキーワードコンストラクターで設定でき、デフォルト値はnothingです。
height(IntまたはFloat64):高さを指定します。Intの場合はデシポイント単位、Float64の場合は基本サイズに対する倍率で指定します。weight(Symbol):最も薄いものから最も濃いものまで、次のいずれかのSymbolを指定します。:thin、:extralight、:light、:semilight、:normal、:medium、:semibold、:bold、:extrabold、:black。ターミナルでは、:normalより大きいウェイトはすべて太字で表示されます。また、テキストの明るさを可変にできるターミナルでは、:normalより小さいウェイトはすべて薄く表示されます。slant(Symbol):次のいずれかのSymbolを指定します。:italic、:oblique、:normal。foreground(SimpleColor):テキストの前景色です。background(SimpleColor):テキストの背景色です。underline(テキストの下線)は、次のいずれかの形式を取ります。Bool:テキストに下線を付けるかどうかを指定します。SimpleColor:指定した色でテキストに下線を付けます。Tuple{Nothing, Symbol}:Symbolで指定したスタイルでテキストに下線を付けます。Symbolには、:straight、:double、:curly、:dotted、:dashedのいずれかを指定します。Tuple{SimpleColor, Symbol}:指定したSimpleColorと、前述のSymbolで指定したスタイルを使ってテキストに下線を付けます。
strikethrough(Bool):テキストに取り消し線を付けるかどうかを指定します。inverse(Bool):前景色と背景色を反転するかどうかを指定します。inherit(Vector{Symbol}):継承元となるfaceの名前を指定します。先に指定したfaceが優先されます。すべてのfaceは:defaultfaceを継承します。
StyledStrings.addface! — Function
addface!(name::Symbol => default::Face)nameという名前で新しいフェイスを作成します。この名前のフェイスがまだ存在しない場合、defaultがFACES.defaultと、(そのコピーが)FACESに追加され、現在の値が返されます。current
フェイスnameがすでに存在する場合は、nothingが返されます。
Examples
julia> addface!(:mypkg_myface => Face(slant=:italic, underline=true))
Face (sample)
slant: italic
underline: trueStyledStrings.withfaces — Function
withfaces(f, kv::Pair...)
withfaces(f, kvpair_itr)fを実行します。FACES.currentは、0個以上の:name => val引数kvによって一時的に変更されます。または、kvpair_itrを実行して、kv形式の値を生成します。
withfacesは通常、withfaces(kv...) do ... end構文で使用します。nothingの値を指定すると、フェイスが設定されている場合に一時的に解除できます。withfacesが戻ると、元のFACES.currentが復元されています。
Examples
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 purpleStyledStrings.SimpleColor — Type
struct SimpleColor文字列のスタイル設定に用いる、色の基本的な表現です。名前付きの色(:red など)、または RGBTuple を格納できます。後者は、r、g、b の各成分を8ビットで指定する NamedTuple です。
Constructors
SimpleColor(name::Symbol) # e.g. :red
SimpleColor(rgb::RGBTuple) # e.g. (r=1, b=2, g=3)
SimpleColor(r::Integer, b::Integer, b::Integer)
SimpleColor(rgb::UInt32) # e.g. 0x123456tryparse(SimpleColor, rgb::String) も参照してください。
Base.parse — Method
parse(::Type{SimpleColor}, rgb::String)tryparse(SimpleColor, rgb::String)(そちらを参照)に相当する関数ですが、nothingを返す代わりにエラーを発生させます。
Base.tryparse — Method
tryparse(::Type{SimpleColor}, rgb::String)rgbをSimpleColorとして解析します。rgbが#で始まり、長さが7の場合、RGBTupleを基盤とするSimpleColorに変換されます。rgbがa-zで始まる場合、rgbは色名として解釈され、Symbolを基盤とするSimpleColorに変換されます。
それ以外の場合は、nothingが返されます。
Examples
julia> tryparse(SimpleColor, "blue")
SimpleColor(blue)
julia> tryparse(SimpleColor, "#9558b2")
SimpleColor(#9558b2)
julia> tryparse(SimpleColor, "#nocolor")Base.merge — Method
merge(initial::StyledStrings.Face, others::StyledStrings.Face...)initial フェイスと others フェイスのプロパティをマージします。後に指定されたフェイスのプロパティが優先されます。
複数のフェイスのスタイルを組み合わせたり、継承を解決したりするために使用します。