1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# で Pygments を使ってシンタックスハイライト

Posted at

このへん から必要最小限な部分を抜き出しただけです。


NuGet で pygments-net をプロジェクトに追加する。

PM> Install-Package pygments-net

シンタックスハイライトのための python コードをプロジェクトに作成し、ファイルのプロパティで「出力ディレクトリにコピー」を「常にコピーする」にする。

pygments_helper.py
import clr
clr.AddReference("pygments")

from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

def generate_html(code, lexer_name, style_name):
  from pygments import highlight
  from pygments.lexers import get_lexer_by_name
  from pygments.styles import get_style_by_name
  from pygments.formatters import HtmlFormatter

  if not lexer_name: lexer_name = "text"
  if not style_name: style_name = "default"
  lexer = get_lexer_by_name(lexer_name)
  return highlight(code, lexer, HtmlFormatter(style=style_name))

def get_lexers():
  return get_all_lexers

def get_styles():
  return get_all_styles

Program.cs を次の通りに編集してビルド・実行する。

Program.cs
using System;
using System.Reflection;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting;

namespace ExamplePygment
{
    class Program
    {
        static void Main(string[] args)
        {
            string dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string code;

            using (var sr = new StreamReader(Path.Combine(dir, "pygments_helper.py")))
            {
                code = sr.ReadToEnd();
            }
            
            var ipy = Python.CreateRuntime();
            dynamic scope = ipy.UseFile(Path.Combine(dir, "pygments_helper.py"));
            
            var html = scope.generate_html(code, "py", null);
            Console.WriteLine(html);
        }
    }
}

タグ付けされた HTML の断片がコンソールに出力されます。

1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?