Skip to content

Commit

Permalink
Returns markdown formatted hovers.
Browse files Browse the repository at this point in the history
Fixed issue with confusion between html and already markdown documentation. Wrote unit tests

Fixes eclipse#245

Signed-off-by: Nikolas Komonen <[email protected]>
  • Loading branch information
fbricon authored and NikolasKomonen committed Jun 20, 2019
1 parent 140a8c7 commit 088bf80
Show file tree
Hide file tree
Showing 9 changed files with 269 additions and 19 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
"editor.detectIndentation": false,
"editor.tabSize": 4,
"editor.insertSpaces": false,
"java.test.defaultConfig": "default",
}
10 changes: 10 additions & 0 deletions org.eclipse.lsp4xml/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,16 @@
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>com.kotcrab.remark</groupId>
<artifactId>remark</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>xml-resolver</groupId>
<artifactId>xml-resolver</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,6 @@ public class Constants {

public static final Pattern DOCTYPE_NAME = Pattern.compile("^[_:\\w][_:\\w-.\\d]*");

public static final Pattern DOCUMENTATION_CONTENT = Pattern.compile(".*<[\\S]+:?documentation[^\\>]*>(.*)<\\/[\\S]+:?documentation[\\s]*>.*");

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.eclipse.lsp4xml.services.extensions.HoverParticipantAdapter;
import org.eclipse.lsp4xml.services.extensions.IHoverRequest;
import org.eclipse.lsp4xml.uriresolver.CacheResourceDownloadingException;
import org.eclipse.lsp4xml.utils.MarkdownConverter;

/**
* Extension to support XML hover based on content model (XML Schema completion,
Expand All @@ -38,9 +39,10 @@ public Hover onTag(IHoverRequest hoverRequest) throws Exception {
if (cmElement != null) {
String doc = cmElement.getDocumentation();
if (doc != null && doc.length() > 0) {
String markdown = MarkdownConverter.convert(doc);
MarkupContent content = new MarkupContent();
content.setKind(MarkupKind.PLAINTEXT);
content.setValue(doc);
content.setKind(MarkupKind.MARKDOWN);
content.setValue(markdown);
return new Hover(content, hoverRequest.getTagRange());
}
}
Expand Down Expand Up @@ -100,9 +102,10 @@ public Hover onAttributeValue(IHoverRequest hoverRequest) throws Exception {
if (cmAttribute != null) {
String doc = cmAttribute.getValueDocumentation(attributeValue);
if (doc != null && doc.length() > 0) {
String markdown = MarkdownConverter.convert(doc);
MarkupContent content = new MarkupContent();
content.setKind(MarkupKind.PLAINTEXT);
content.setValue(doc);
content.setKind(MarkupKind.MARKDOWN);
content.setValue(markdown);
return new Hover(content);
}
}
Expand All @@ -116,7 +119,7 @@ public Hover onAttributeValue(IHoverRequest hoverRequest) throws Exception {
private Hover getCacheWarningHover(CacheResourceDownloadingException e) {
// Here cache is enabled and some XML Schema, DTD, etc are loading
MarkupContent content = new MarkupContent();
content.setKind(MarkupKind.PLAINTEXT);
content.setKind(MarkupKind.MARKDOWN);
content.setValue("Cannot process " + (e.isDTD() ? "DTD" : "XML Schema") + " hover: " + e.getMessage());
return new Hover(content);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@
*/
package org.eclipse.lsp4xml.extensions.xsd.contentmodel;

import static org.eclipse.lsp4xml.dom.parser.Constants.DOCUMENTATION_CONTENT;
import static org.eclipse.lsp4xml.utils.StringUtils.isEmpty;
import static org.eclipse.lsp4xml.utils.StringUtils.normalizeSpace;

import java.io.StringReader;
import java.util.regex.Matcher;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
Expand Down Expand Up @@ -60,33 +63,37 @@ public static String getDocumentation(XSObjectList annotations, String value) {
StringBuilder doc = new StringBuilder();
for (Object object : annotations) {
XSAnnotation annotation = null;
if(object instanceof XSMultiValueFacet && value != null) {
if (object instanceof XSMultiValueFacet && value != null) {
XSMultiValueFacet multiValueFacet = (XSMultiValueFacet) object;
ObjectList enumerationValues = multiValueFacet.getEnumerationValues();
XSObjectList annotationValues = multiValueFacet.getAnnotations();
for (int i = 0; i < enumerationValues.getLength(); i++) {
Object enumValue = enumerationValues.get(i);

//Assuming always ValidatedInfo
// Assuming always ValidatedInfo
String enumString = ((ValidatedInfo) enumValue).stringValue();
if(value.equals(enumString)) {

if (value.equals(enumString)) {
annotation = (XSAnnotation) annotationValues.get(i);
break;
}
}
}
else if(object instanceof XSAnnotation) {
} else if (object instanceof XSAnnotation) {
annotation = (XSAnnotation) object;
}

XSDAnnotationModel annotationModel = XSDAnnotationModel.load(annotation);
if (annotationModel != null) {
if (annotationModel.getAppInfo() != null) {
doc.append(annotationModel.getAppInfo());
}
if (annotationModel.getDocumentation() != null) {
doc.append(annotationModel.getDocumentation());
} else {
String annotationString = annotation.getAnnotationString();
if (!isEmpty(annotationString)) {
doc.append(getDocumentation(annotationString));
}
}
}
}
Expand Down Expand Up @@ -122,8 +129,7 @@ public XSDAnnotationModel getModel() {
}

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (qName.endsWith(DOCUMENTATION_ELEMENT) || qName.endsWith(APPINFO_ELEMENT)) {
current = new StringBuilder();
Expand Down Expand Up @@ -153,4 +159,12 @@ public void characters(char[] ch, int start, int length) throws SAXException {

}

public static String getDocumentation(String xml) {
Matcher m = DOCUMENTATION_CONTENT.matcher(xml);
if(m.find()) {
return m.group(1);
}
return null;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*******************************************************************************
* Copyright (c) 2016-2017 Red Hat Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.lsp4xml.utils;

import static org.apache.commons.lang3.StringEscapeUtils.unescapeJava;
import static org.apache.commons.lang3.StringEscapeUtils.unescapeXml;

import java.lang.reflect.Field;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import com.overzealous.remark.Options;
import com.overzealous.remark.Options.FencedCodeBlocks;
import com.overzealous.remark.Options.Tables;
import com.overzealous.remark.Remark;

import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;

/**
* Converts HTML content into Markdown equivalent.
*
* @author Fred Bricon
*/
public class MarkdownConverter {

private static final Logger LOGGER = Logger.getLogger(MarkdownConverter.class.getName());

private static Remark remark;

//Pattern looking for any form of tag eg: <head>
private static final Pattern markdownPattern = Pattern.compile("`[^`]*<[a-z][\\s\\S]*>[^`]*`");

private MarkdownConverter(){
//no public instanciation
}

static {
Options options = new Options();
options.tables = Tables.CONVERT_TO_CODE_BLOCK;
options.hardwraps = true;
options.inlineLinks = true;
options.autoLinks = true;
options.reverseHtmlSmartPunctuation = true;
options.fencedCodeBlocks = FencedCodeBlocks.ENABLED_BACKTICK;
remark = new Remark(options);
//Stop remark from stripping file protocol in an href
try {
Field cleanerField = Remark.class.getDeclaredField("cleaner");
cleanerField.setAccessible(true);

Cleaner c = (Cleaner) cleanerField.get(remark);

Field whitelistField = Cleaner.class.getDeclaredField("whitelist");
whitelistField.setAccessible(true);

Whitelist w = (Whitelist) whitelistField.get(c);

w.addProtocols("a", "href", "file");
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
LOGGER.severe("Unable to modify jsoup to include file protocols "+ e.getMessage());
}
}

public static String convert(String html) {
if(!StringUtils.isTagOutsideOfBackticks(html)) {
return unescapeXml(html); // is not html so it can be returned as is (aside from unescaping)
}
return unescapeJava(remark.convert(html));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -279,4 +279,54 @@ public static String cleanPathForWindows(String pathString) {
return pathString;
}

public static String escapeBackticks(String text) {
int i = text.length() - 1;
StringBuilder b = new StringBuilder(text);
while(i >= 0) {
char c = text.charAt(i);
if(c == '`') {
b.insert(i, "\\");
}
i--;
}
return b.toString();
}

public static boolean isTagOutsideOfBackticks(String text) {
int i = 0;
boolean inBacktick = false;
while(i < text.length()) {
char c = text.charAt(i);
if(c == '`') {
if(inBacktick) {
inBacktick = false;
}
else {
inBacktick = true;
}
}
else if(c == '<') {
i++;
while(i < text.length()) {
c = text.charAt(i);
if(c == '`') {
i--;
break;
}
if(c == '>') {
if(!inBacktick) {
return true;
}
break;
}
i++;
}
}

i++;
}
return false;

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*******************************************************************************
* Copyright (c) 2019 Red Hat Inc. and others.
* All rights reserved. This program and the accompanying materials
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* Red Hat Inc. - initial API and implementation
*******************************************************************************/

package org.eclipse.lsp4xml.utils;

import static org.eclipse.lsp4xml.utils.MarkdownConverter.convert;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
* MarkdownConverterTest
*/
public class MarkdownConverterTest {

@Test
public void testHTMLConversion() {
assertEquals("This is `my code`", convert("This is <code>my code</code>"));
assertEquals("This is\n**bold**", convert("This is<br><b>bold</b>"));
assertEquals("The `<project>` element is the root of the descriptor.", convert("The <code>&lt;project&gt;</code> element is the root of the descriptor."));
assertEquals("# Hey Man #", convert("<h1>Hey Man</h1>"));
assertEquals("[Placeholder](https://www.xml.com)", convert("<a href=\"https://www.xml.com\">Placeholder</a>"));

String htmlList =
"<ul>\n" +
" <li>Coffee</li>\n" +
" <li>Tea</li>\n" +
" <li>Milk</li>\n" +
"</ul>";
String expectedList =
" * Coffee\n" +
" * Tea\n" +
" * Milk";
assertEquals(expectedList, convert(htmlList));
assertEquals("ONLY_THIS_TEXT", convert("<p>ONLY_THIS_TEXT</p>"));

String multilineHTML =
"multi\n" +
"line\n" +
"<code>HTML</code>\n" +
"stuff";
assertEquals("multi line `HTML` stuff", convert(multilineHTML));

String multilineHTML2 =
"<p>multi<p>\n" +
"line\n" +
"<code>HTML</code>\n" +
"stuff";
String multilineHTML2Expected =
"multi\n" +
"\n" +
"line `HTML` stuff";
assertEquals(multilineHTML2Expected, convert(multilineHTML2));
}

@Test
public void testMarkdownConversion() {
assertEquals("This is `my code`", convert("This is `my code`"));
assertEquals("The `<thing>` element is the root of the descriptor.", convert("The `<thing>` element is the root of the descriptor."));
assertEquals("The `<project>` element is the root of the descriptor.", convert("The `&lt;project&gt;` element is the root of the descriptor."));
}

}
Loading

0 comments on commit 088bf80

Please sign in to comment.