makeup.ex (2259B)
1 defmodule Makeup do 2 @moduledoc """ 3 Syntax highlighting library for code, inspired by Pygments. 4 5 By default, it doesn't include any lexers. You must import 6 them separately (even the Elixir lexer). 7 """ 8 alias Makeup.Formatters.HTML.HTMLFormatter 9 alias Makeup.Lexers.ElixirLexer 10 alias Makeup.Styles.HTML.StyleMap 11 alias Makeup.Styles.HTML.Style 12 alias Makeup.Registry 13 require StyleMap 14 15 @doc """ 16 Highlights the given string using the given lexer and formatter. 17 18 By default it highlight the Elixir language using HTML 19 """ 20 def highlight(source, options \\ []) do 21 {lexer, lexer_options} = fetch_lexer(options) 22 23 formatter = 24 case options[:formatter] do 25 nil -> HTMLFormatter 26 module when is_atom(module) -> module 27 end 28 29 tokens = apply(lexer, :lex, [source, lexer_options]) 30 apply(formatter, :format_as_binary, [tokens]) 31 end 32 33 def highlight_inner_html(source, options \\ []) do 34 {lexer, lexer_options} = fetch_lexer(options) 35 formatter_options = Keyword.get(options, :formatter_options, []) 36 37 tokens = apply(lexer, :lex, [source, lexer_options]) 38 apply(HTMLFormatter, :format_inner_as_binary, [tokens, formatter_options]) 39 end 40 41 defp fetch_lexer(options) do 42 {lexer, lexer_options} = 43 case options[:lexer] do 44 nil -> {ElixirLexer, []} 45 module when is_atom(module) -> {module, []} 46 name -> Registry.fetch_lexer_by_name!(name) 47 end 48 49 {lexer, Keyword.merge(lexer_options, Keyword.get(options, :lexer_options, []))} 50 end 51 52 @doc """ 53 Generates a CSS stylesheet for highlighted code for the given style. 54 55 It expects a `style`, either as an atom name or as `StyleMap`, and the 56 `css_class` as the top level class for highlighted code. 57 58 Ff the `css_class` is `"highlight"` (the default), the stylesheet has 59 the form: 60 61 ```css 62 .highlight .someclass {...} 63 .highlight .anotherclass {...} 64 ``` 65 66 See `Makeup.Styles.HTML.StyleMap` for all style maps. 67 """ 68 def stylesheet(style \\ StyleMap.default_style(), css_class \\ "highlight") 69 70 def stylesheet(style, css_class) when is_atom(style) do 71 stylesheet(apply(StyleMap, style, []), css_class) 72 end 73 74 def stylesheet(style, css_class) do 75 Style.stylesheet(style, css_class) 76 end 77 end