LoginSignup
2
1

Kotlin製テキスト装飾ライブラリMordantを試す

Posted at

Kotlinで使える文字装飾ライブラリを探していたところ、Mordantというライブラリを見つけたので紹介します。

  • ドキュメント

  • リポジトリ

導入

build.gradle.ktsを編集します。

// build.gradle.kts
repositories {
    mavenCentral()
}

dependencies {
    implementation("com.github.ajalt.mordant:mordant:2.1.0")
}

文字を装飾する

標準出力にテキストを表示するにはprintln()ではなく、Terminal.println()を利用します。

import com.github.ajalt.mordant.rendering.TextColors.*
import com.github.ajalt.mordant.rendering.TextStyles.*
import com.github.ajalt.mordant.terminal.Terminal

fun main() {
    val t = Terminal()

    t.println("Hello, ${(blue on gray)("World!")}")

    val style = (bold + white + underline)
    t.println(style("スタイルの組み合わせを記述できる!"))
    t.println(style("作ったスタイルは使い回せる。"))
}

出力するとこうなります。whiteが白っぽくないのは、IntelliJで実行しているからです。

image.png

文字に色をつけるときは、blue on grayのように表現することができます。便利ですね。

もちろん、関数のように書くこともできます。

表(テーブル)を出力する

Mordantでは、テーブルを宣言的に作成し表示することができます。

import com.github.ajalt.mordant.table.table
import com.github.ajalt.mordant.terminal.Terminal

fun main() {
    val t = Terminal()

    t.println(table{
        header{
            row("Name", "Age")
        }
        body{
            row("John Doe", "30")
            row("山田 二郎", "32")
        }
    })
}

出力するとこうなります。

image.png

日本語で表示が崩れる問題は、等幅フォントを利用することで解決します。(HackGen Console NFを利用)

image.png

Markdown文書を出力する

なんとMarkdownで記述した文書を渡すことで適当にスタイリングして表示してくれます。

以下のようなMarkdown文書を渡してみます。

# Header 1
## Header 2
### Header 3
#### Header 4
##### Header 5
###### Header 6

- List item 1
- List item 2
- List item 3
1. Ordered list item 1
2. Ordered list item 2
3. Ordered list item 3
- [Link](https://example.com/)

```
Code Block
```

> Blockquote

ターミナルではこのように表示されます。すごい。

image.png

ソースコードはこんな感じに書くだけです。

import com.github.ajalt.mordant.markdown.Markdown
import com.github.ajalt.mordant.terminal.Terminal
import kotlin.io.path.Path
import kotlin.io.path.readText

fun main() {
    val t = Terminal()

    t.print(Markdown(Path("sample.md").readText()))
}

プログレスバーを表示する

次はプログレスバーを表示させてみます。

以下のようなコードを書いて実行します。

import com.github.ajalt.mordant.animation.progressAnimation
import com.github.ajalt.mordant.terminal.Terminal

fun main() {
    val t = Terminal()
    val progress = t.progressAnimation {
        text("Downloading...")
        percentage()
        progressBar()
        completed()
    }
    progress.start()

    Thread.sleep(100)
    progress.updateTotal(100)

    repeat(100){
        progress.advance(1)
        Thread.sleep(10)
    }
    Thread.sleep(1000)
    progress.stop()
}

実行するとこのような表示になります。

image.png

image.png

プログレスバーは、進行前・進行中・終了によって異なるアニメーションで動作します。

おわりに

とても便利なライブラリで、KotlinでちょっとしたCLI(TUI)アプリケーションを作成するときにお世話になりそうな気がします。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1