diff --git a/org/html_writer.go b/org/html_writer.go index 561067a..f2e75a0 100644 --- a/org/html_writer.go +++ b/org/html_writer.go @@ -15,8 +15,9 @@ import ( // HTMLWriter exports an org document into a html document. type HTMLWriter struct { - ExtendingWriter Writer - HighlightCodeBlock func(source, lang string, inline bool) string + ExtendingWriter Writer + HighlightCodeBlock func(source, lang string, inline bool) string + PrettyRelativeLinks bool strings.Builder document *Document @@ -342,7 +343,14 @@ func (w *HTMLWriter) WriteRegularLink(l RegularLink) { if l.Protocol == "file" { url = url[len("file:"):] } - if (l.Protocol == "file" || l.Protocol == "") && strings.HasSuffix(url, ".org") { + if isRelative := l.Protocol == "file" || l.Protocol == ""; isRelative && w.PrettyRelativeLinks { + if !strings.HasPrefix(url, "/") { + url = "../" + url + } + if strings.HasSuffix(url, ".org") { + url = strings.TrimSuffix(url, ".org") + "/" + } + } else if isRelative && strings.HasSuffix(url, ".org") { url = strings.TrimSuffix(url, ".org") + ".html" } if prefix := w.document.Links[l.Protocol]; prefix != "" { diff --git a/org/html_writer_test.go b/org/html_writer_test.go index 37f97a4..969360c 100644 --- a/org/html_writer_test.go +++ b/org/html_writer_test.go @@ -42,3 +42,30 @@ func TestExtendedHTMLWriter(t *testing.T) { t.Errorf("WriteText method of extending writer was not called: CallCount %d", extendedWriter.callCount) } } + +var prettyRelativeLinkTests = map[string]string{ + "[[/hello.org][hello]]": `

hello

`, + "[[hello.org][hello]]": `

hello

`, + "[[file:/hello.org]]": `

/hello/

`, + "[[file:hello.org]]": `

../hello/

`, + "[[http://hello.org]]": `

http://hello.org

`, + "[[/foo.png]]": `

/foo.png

`, + "[[foo.png]]": `

../foo.png

`, + "[[/foo.png][foo]]": `

foo

`, + "[[foo.png][foo]]": `

foo

`, +} + +func TestPrettyRelativeLinks(t *testing.T) { + for org, expected := range prettyRelativeLinkTests { + t.Run(org, func(t *testing.T) { + writer := NewHTMLWriter() + writer.PrettyRelativeLinks = true + actual, err := New().Silent().Parse(strings.NewReader(org), "./prettyRelativeLinkTests.org").Write(writer) + if err != nil { + t.Errorf("%s\n got error: %s", org, err) + } else if actual := strings.TrimSpace(actual); actual != expected { + t.Errorf("%s:\n%s'", org, diff(actual, expected)) + } + }) + } +}