parseLinkTarget function
The destination and optional title inside a link's parentheses (or after a definition's colon).
<url with spaces> is taken whole; otherwise the URL runs to the first
whitespace. A title follows in "…", '…' or (…). Backslash escapes and
entity references are decoded in both.
With strict (definitions) anything else after the URL means there is no
definition. Without it (inline links) the whole text is the URL, exactly as
before titles were understood — [doc](My File.pdf) keeps working.
Implementation
({String url, String? title})? parseLinkTarget(
String raw, {
bool strict = false,
}) {
final s = raw.trim();
String url;
String rest;
if (s.startsWith('<')) {
final end = s.indexOf('>');
if (end == -1 || s.substring(1, end).contains('<')) {
if (strict) {
return null;
}
return (url: _decode(s), title: null);
}
url = s.substring(1, end);
rest = s.substring(end + 1);
} else {
var end = 0;
while (end < s.length && !isUnicodeWhitespace(s.codeUnitAt(end))) {
end += 1;
}
url = s.substring(0, end);
rest = s.substring(end);
}
final trimmedRest = rest.trim();
if (trimmedRest.isEmpty) {
return (url: _decode(url), title: null);
}
// A title must be separated from the URL by whitespace.
final separated = rest.isNotEmpty && isUnicodeWhitespace(rest.codeUnitAt(0));
final title = separated ? _title(trimmedRest) : null;
if (title == null) {
if (strict) {
return null;
}
return (url: _decode(s), title: null);
}
return (url: _decode(url), title: _decode(title));
}