How to use turndown - 10 common examples

To help you get started, we’ve selected a few turndown examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github LessWrong2 / Lesswrong2 / packages / lesswrong / lib / collections / comments / callbacks.js View on Github external
import React from 'react';
import { Comments, Posts } from "meteor/example-forum";
import { addCallback, removeCallback, runCallbacksAsync, newMutation, editMutation } from 'meteor/vulcan:core';
import Users from "meteor/vulcan:users";
import { convertFromRaw, ContentState, convertToRaw } from 'draft-js';
import { draftToHTML } from '../../editor/utils.js';
import { preProcessLatex } from '../../editor/server/utils.js';
import { performVoteServer } from 'meteor/vulcan:voting';

import { createError } from 'apollo-errors';
import Messages from '../messages/collection.js';
import Conversations from '../conversations/collection.js';

import TurndownService from 'turndown';
const turndownService = new TurndownService()
// function commentsSoftRemoveChildrenComments(comment) {
//     const childrenComments = Comments.find({parentCommentId: comment._id}).fetch();
//     childrenComments.forEach(childComment => {
//       editMutation({
//         documentId: childComment._id,
//         set: {deleted:true},
//         unset: {}
//       }).then(()=>console.log('comment softRemoved')).catch(/* error */);
//     });
// }

const getLessWrongAccount = async () => {
  let account = Users.findOne({username: "LessWrong"});
  if (!account) {
    const userData = {
      username: "LessWrong",
github sindresorhus / refined-github / source / features / copy-markdown.js View on Github external
import TurndownService from 'turndown';
import copyToClipboard from 'copy-text-to-clipboard';

const unwrapContent = content => content;
const unshortenRegex = /^https:[/][/](www[.])?|[/]$/g;

const turndownService = new TurndownService({gfm: true});

// Drop unnecessary elements
//  is GH's emoji wrapper
// input and .handle appear in "- [ ] lists", let's not copy tasks
turndownService.addRule('unnecessaryElements', {
	filter: node => node.matches('g-emoji,.handle,input.task-list-item-checkbox'),
	replacement: unwrapContent
});
// Unwrap commit/issue autolinks
turndownService.addRule('unwrapCommitIssueAutolinks', {
	filter: node => node.matches('.commit-link,.issue-link') || // GH autolinks
		(node.href && node.href.replace(unshortenRegex, '') === node.textContent), // Some of bfred-it/shorten-repo-url
	replacement: (content, element) => element.href
});
// Unwrap images
turndownService.addRule('unwrapImages', {
github notlmn / copy-as-markdown / source / background.js View on Github external
browser.tabs.create({
		url: repoUrl
	});
});

const contexts = ['image', 'link', 'selection'];

for (const context of contexts) {
	browser.contextMenus.create({
		id: `cpy-as-md:${context}`,
		title: `Copy ${context} as Markdown`,
		contexts: [context]
	});
}

const turndownService = new TurndownService({
	headingStyle: 'atx',
	bulletListMarker: '-',
	codeBlockStyle: 'fenced'
});

turndownService.keep(['kbd']); // HTML content to retain in Markdown

browser.contextMenus.onClicked.addListener(async (info, tab) => {
	const text = info.linkText;
	const assetUrl = encodeURI(info.srcUrl);
	const linkUrl = encodeURI(info.linkUrl);

	let htmlContent = '';

	if (info.menuItemId.endsWith('image')) {
		htmlContent = `<img src="${assetUrl}" alt="${text || assetUrl}">`;
github Laverna / laverna / app / scripts / components / importExport / ImportEvernote.js View on Github external
}
            else {
                item.name       = 'a';
                item.attributes = {href: `#file:${item.attributes.hash}`};
                item.elements   = [{type: 'text', text: file.name}];
            }
        });
        /* eslint-enable */

        // Convert todo lists
        content = convert.json2xml(obj)
        .replace(//g, '[] ')
        .replace(//g, '[x] ');

        // Convert to Markdown
        const md = new Turndown();
        md.use(gfm);

        return md.turndown(content)
        .replace(/\n{2,}/g, '\n')
        .replace(/\\+\[/g, '[')
        .replace(/\\+\]/g, ']');
    }
github postlight / mercury-parser / src / extractors / root-extractor.js View on Github external
$content.wrap($('<div></div>'));
    $content = $content.parent();

    $content = transformElements($content, $, extractionOpts);
    $content = cleanBySelectors($content, $, extractionOpts);

    $content = Cleaners[type]($content, { ...opts, defaultCleaner });

    if (contentType === 'html') {
      return $.html($content);
    }
    if (contentType === 'text') {
      return $.text($content);
    }
    if (contentType === 'markdown') {
      const turndownService = new TurndownService();
      return turndownService.turndown($.html($content));
    }
  }

  let result;

  // if selector is an array (e.g., ['img', 'src']),
  // extract the attr
  if (Array.isArray(matchingSelector)) {
    const [selector, attr] = matchingSelector;
    result = $(selector)
      .attr(attr)
      .trim();
  } else {
    let $node = $(matchingSelector);
github Opteo / google-ads-api / scripts / generate_services.js View on Github external
1. Update google-ads-node in package.json
    1.1 Update badge version in readme.md + container.jsx
    2. yarn &amp;&amp; yarn build
    3. update scripts/schema.json (https://googleads.googleapis.com/$discovery/rest?version=v2)
    4. update compiled_resources.json by running `pbjs -t json googleapis/google/rpc/*.proto googleapis/google/longrunning/*.proto googleapis//google/ads/googleads/v2/common/*.proto googleapis//google/ads/googleads/v2/errors/*.proto googleapis//google/ads/googleads/v2/enums/*.proto googleapis//google/ads/googleads/v2/resources/*.proto googleapis//google/ads/googleads/v2/services/*.proto &gt; compiled_resources.json`
    5. clear the .cache folder in the root of this project to make sure you get new examples from our test account

*/
const fs = require('fs-extra')
const { template, camelCase, snakeCase, endsWith, get, maxBy } = require('lodash')

const Promise = require('bluebird')

var TurndownService = require('turndown')
TurndownService.prototype.escape = t =&gt; t
var turndownService = new TurndownService()

const showdown = require('showdown')
showdown.setOption('literalMidWordUnderscores', true)
const converter = new showdown.Converter()

const sanitiseHtml = gg =&gt; {
    gg = turndownService.turndown(gg)
    const result = converter.makeHtml(gg)

    // remove <p> tags
    return result.substring(3, result.length - 4)
}

require('dotenv').config()
const { GoogleAdsApi } = require('../build')</p>
github ckeditor / ckeditor5-markdown-gfm / src / html2markdown / html2markdown.js View on Github external
/**
 * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md.
 */

import TurndownService from 'turndown';
import { gfm } from 'turndown-plugin-gfm';

// Overrides the escape() method, enlarging it.
{
	const originalEscape = TurndownService.prototype.escape;
	TurndownService.prototype.escape = function( string ) {
		string = originalEscape( string );

		// Escape "&lt;".
		string = string.replace( /
github ckeditor / ckeditor5-markdown-gfm / src / html2markdown / html2markdown.js View on Github external
/**
 * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md.
 */

import TurndownService from 'turndown';
import { gfm } from 'turndown-plugin-gfm';

// Overrides the escape() method, enlarging it.
{
	const originalEscape = TurndownService.prototype.escape;
	TurndownService.prototype.escape = function( string ) {
		string = originalEscape( string );

		// Escape "&lt;".
		string = string.replace( /
github benweet / stackedit / src / services / editor / cledit / cleditCore.js View on Github external
evt.preventDefault();
      }
    });

    contentElt.addEventListener('cut', (evt) => {
      if (evt.clipboardData) {
        evt.clipboardData.setData('text/plain', selectionMgr.getSelectedText());
        evt.preventDefault();
        replace(selectionMgr.selectionStart, selectionMgr.selectionEnd, '');
      } else {
        undoMgr.setCurrentMode('single');
      }
      adjustCursorPosition();
    });

    turndownService = new TurndownService(store.getters['data/computedSettings'].turndown);
    turndownService.escape = str => str; // Disable escaping
  }

  contentElt.addEventListener('paste', (evt) => {
    undoMgr.setCurrentMode('single');
    evt.preventDefault();
    let data;
    let { clipboardData } = evt;
    if (clipboardData) {
      data = clipboardData.getData('text/plain');
      if (turndownService) {
        try {
          const html = clipboardData.getData('text/html');
          if (html) {
            const sanitizedHtml = htmlSanitizer.sanitizeHtml(html)
              .replace(/&#160;/g, ' '); // Replace non-breaking spaces with classic spaces
github zulip / zulip / static / js / copy_and_paste.js View on Github external
exports.paste_handler_converter = function (paste_html) {
    const turndownService = new TurndownService();
    turndownService.addRule('headings', {
        filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
        replacement: function (content) {
            return content;
        },
    });
    turndownService.addRule('emphasis', {
        filter: ['em', 'i'],
        replacement: function (content) {
            return '*' + content + '*';
        },
    });
    // Checks for raw links without custom text or title.
    turndownService.addRule('links', {
        filter: function (node) {
            return node.nodeName === "A" &&

turndown

A library that converts HTML to Markdown

MIT
Latest version published 7 months ago

Package Health Score

80 / 100
Full package analysis