How to use the turndown function in turndown

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 webclipper / web-clipper / src / browser / content / index.tsx View on Github external
import * as QRCode from 'qrcode';
import * as Readability from '@web-clipper/readability';
import * as styles from './index.scss';
import AreaSelector from '@web-clipper/area-selector';
import Highlighter from '@web-clipper/highlight';
import plugins from '@web-clipper/turndown';
import TurndownService from 'turndown';
import { MessageListenerCombiner } from '@web-clipper/message-listener-combiner';
import { clickIcon, doYouAliveNow } from 'browserActions/browser';
import { removeTool, runScript, hideTool } from 'browserActions/message';
import { ContentScriptContext } from '@web-clipper/extensions';
import * as browser from '@web-clipper/chrome-promise';
import { localStorageService } from '@/common/chrome/storage';
import { LOCAL_USER_PREFERENCE_LOCALE_KEY } from '@/common/types';

const turndownService = new TurndownService({ codeBlockStyle: 'fenced' });
turndownService.use(plugins);

const listeners = new MessageListenerCombiner()
  .case(doYouAliveNow, (_payload, _sender, sendResponse) => {
    sendResponse(true);
    return true;
  })
  .case(hideTool, () => {
    $(`.${styles.toolFrame}`).hide();
  })
  .case(removeTool, () => {
    $(`.${styles.toolFrame}`).remove();
  })
  .case(clickIcon, () => {
    if ($(`.${styles.toolFrame}`).length === 0) {
      $('body').append(
github postlight / mercury-parser / src / extractors / generic / index.js View on Github external
const lead_image_url = this.lead_image_url({ ...options, content });
    const dek = this.dek({ ...options, content });
    const next_page_url = this.next_page_url(options);
    const excerpt = this.excerpt({ ...options, content });
    const word_count = this.word_count({ ...options, content });
    const direction = this.direction({ title });
    const { url, domain } = this.url_and_domain(options);

    let convertedContent;

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

    return {
      title,
      author,
      date_published: date_published || null,
      dek,
      lead_image_url,
      content: convertedContent,
      next_page_url,
      url,
      domain,
      excerpt,
      word_count,
      direction,
github appoly / mail-web / resources / js / Pages / Homepage / Index.vue View on Github external
markdown() {
            if (this.selectedEmail !== null) {
                let turndownService = new turndown();
                return turndownService.turndown(this.selectedEmail.body);
            }
            return '';
        },
        latestEmail(){

turndown

A library that converts HTML to Markdown

MIT
Latest version published 4 days ago

Package Health Score

86 / 100
Full package analysis