link.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var uri = require('../util/enclose-uri');
  3. var title = require('../util/enclose-title');
  4. module.exports = link;
  5. /* Expression for a protocol:
  6. * http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax */
  7. var PROTOCOL = /^[a-z][a-z+.-]+:\/?/i;
  8. /* Stringify a link.
  9. *
  10. * When no title exists, the compiled `children` equal
  11. * `url`, and `url` starts with a protocol, an auto
  12. * link is created:
  13. *
  14. * <http://example.com>
  15. *
  16. * Otherwise, is smart about enclosing `url` (see
  17. * `encloseURI()`) and `title` (see `encloseTitle()`).
  18. *
  19. * [foo](<foo at bar dot com> 'An "example" e-mail')
  20. *
  21. * Supports named entities in the `url` and `title` when
  22. * in `settings.encode` mode. */
  23. function link(node) {
  24. var self = this;
  25. var content = self.encode(node.url || '', node);
  26. var exit = self.enterLink();
  27. var escaped = self.encode(self.escape(node.url || '', node));
  28. var value = self.all(node).join('');
  29. exit();
  30. if (
  31. node.title == null &&
  32. PROTOCOL.test(content) &&
  33. (escaped === value || escaped === 'mailto:' + value)
  34. ) {
  35. /* Backslash escapes do not work in autolinks,
  36. * so we do not escape. */
  37. return uri(self.encode(node.url), true);
  38. }
  39. content = uri(content);
  40. if (node.title) {
  41. content += ' ' + title(self.encode(self.escape(node.title, node), node));
  42. }
  43. return '[' + value + '](' + content + ')';
  44. }