Debian Codegraph @

markup/org/convert.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package org converts Emacs Org-Mode to HTML.
15 package org
16
17 import (
18 "bytes"
19 "log"
20
21 "github.com/gohugoio/hugo/identity"
22
23 "github.com/gohugoio/hugo/markup/converter"
24 "github.com/niklasfasching/go-org/org"
25 "github.com/spf13/afero"
26 )
27
28 // Provider is the package entry point.
29 var Provider converter.ProviderProvider = provide{}
30
31 type provide struct{}
32
33 func (p provide) New(cfg converter.ProviderConfig) (converter.Provider, error) {
34 return converter.NewProvider("org", func(ctx converter.DocumentContext) (converter.Converter, error) {
35 return &orgConverter{
36 ctx: ctx,
37 cfg: cfg,
38 }, nil
39 }), nil
40 }
41
42 type orgConverter struct {
43 ctx converter.DocumentContext
44 cfg converter.ProviderConfig
45 }
46
47 func (c *orgConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) {
48 logger := c.cfg.Logger
49 config := org.New()
50 config.Log = log.Default() // TODO(bep)
51 config.ReadFile = func(filename string) ([]byte, error) {
52 return afero.ReadFile(c.cfg.ContentFs, filename)
53 }
54 writer := org.NewHTMLWriter()
55 writer.HighlightCodeBlock = func(source, lang string, inline bool, params map[string]string) string {
56 highlightedSource, err := c.cfg.Highlight(source, lang, "")
57 if err != nil {
58 logger.Errorf("Could not highlight source as lang %s. Using raw source.", lang)
59 return source
60 }
61 return highlightedSource
62 }
63
64 html, err := config.Parse(bytes.NewReader(ctx.Src), c.ctx.DocumentName).Write(writer)
65 if err != nil {
66 logger.Errorf("Could not render org: %s. Using unrendered content.", err)
67 return converter.Bytes(ctx.Src), nil
68 }
69 return converter.Bytes([]byte(html)), nil
70 }
71
72 func (c *orgConverter) Supports(feature identity.Identity) bool {
73 return false
74 }