Example #1
0
module.exports = function(content, file, conf){
    hljs.configure(conf.hljs || {
        tabReplace: '    '
    });
    marked.setOptions(conf);
    return marked(content);
};
Example #2
0
	componentDidMount() {
		//hljs.initHighlightingOnLoad();

		hljs.configure({
		  tabReplace: '  '
		});
		//hljs.initHighlighting();
		$('pre code').each(function(i, block) {
		    hljs.highlightBlock(block);
		 });
		
	}
Example #3
0
  componentDidMount() {
    const { 
      params, 
      serverRender, 
      clientRender, 
      getForm } = this.props

    if (serverRender) {
      clientRender()
    } else {
      getForm('show', 'articles', params.name)
    }

    hljs.configure({
      languages: ['ruby', 'python']
    })
  }
Example #4
0
        function (err, data) {
            if (err) {
                res.send(500, {
                    error: true,
                    issue: err
                });
                return;
            }

            // highlight the text and postprocess
            highlight.configure({ tabReplace: '    ' });
            var highlighted = highlight.highlightAuto(data).value
              , content = new Postprocessor().process(highlighted);

            res.render('index', {
                name: filename,
                language: 'c++',
                content: content
            });
        });
Example #5
0
      .then(function(defaultHomeMarkdown) {
        hljs.configure({
          classPrefix: ''
        });

        marked.setOptions({
          gfm: true,
          tables: true,
          breaks: true,
          pedantic: false,
          sanitize: false,
          smartLists: true,
          smartypants: false,
          highlight: function (code) {
            return hljs.highlightAuto(code).value;
          }
        });

        return Q.promisify(marked)(defaultHomeMarkdown);
      })
Example #6
0
module.exports = function(options) {
  highlight.configure(options);

  /**
   * @param {Object} files
   * @param {Metalsmith} metalsmith
   * @param {Function} done
   */
  return function(files, metalsmith, done) {
    var file, data;
    for (file in files) {
      if (HTML_FILENAME_REGEXP.test(file)) {
        data = files[file];
        data.contents = new Buffer(
          highlightFile(data.contents.toString())
        );
      }
    }

    setImmediate(done);
  }
}
Example #7
0
const WORKERS = process.env.WEB_CONCURRENCY || 1;
const PORT = Number(process.env.PORT || 5500);
const TITLE = 'cdnjs.com'

const licenses = JSON.parse(fs.readFileSync(__dirname + '/license-list.json', 'utf8'));


// Load libraries into ram
const {LIBRARIES, LIBRARIES_MAP} = require('./utils/libraries');
logger.info('Libraries loaded into memory (to be deprecated)');

// Load templates into ram
const {templates, generatePage} = require('./utils/templates');

highlight.configure({
  tabReplace: '  '
                      // … other options aren't changed
})

// Setup express
// app.use(compress());
// Serve public folder
app.use(express.static(__dirname + '/public', {
    maxAge: 7200 * 1000
}));

app.use(function(req, res, next) {
  res.setHeader('X-Frame-Options', 'deny');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('X-XSS-Protection', '1; mode=block');
  if (process.env.NODE_ENV === 'production') {
    res.setHeader('Content-Security-Policy', "upgrade-insecure-requests; default-src 'unsafe-eval' 'self' *.carbonads.com *.getclicky.com fonts.gstatic.com www.google-analytics.com fonts.googleapis.com cdnjs.cloudflare.com 'unsafe-inline' https: data: ;");
function plugin(options){
  hljs.configure(options);
  //var theme = options.theme || "http://yandex.st/highlightjs/8.0/styles/default.min.css";
  return function(files, metalsmith, done){
    setImmediate(done);
    Object.keys(files).forEach(function(file){
      debug('checking file: %s', file);
      if (!markdown(file)) return;
      var data = files[file];
      var str = data.contents.toString();
      //Fenced block start/end
      var end = /```/;
      var typed = /```([\w\-]+)\r?\n/;
      var remainder = str;
      var pos = 0;
      var endpos = 0;
      
      var replacements = [];
      while(end.test(remainder)) {
        var match = remainder.match(end);
        var lang = null;
        var isTyped = remainder.match(typed);
        if (isTyped && match.index===isTyped.index) {
          lang = remainder.match(typed)[1];
        }
        var prev = pos;
        
        var buff = 3 + (lang ? lang.length : 0);
        
        pos = pos + match.index + buff;
        remainder = str.substring(pos);
        
        var ends = remainder.match(end);
        if (ends==null || ends[0] == null) {
          break;
        }
        
        endpos = ends.index;
        replacements.push(str.substring(prev, pos-buff));
        
        remainder = str.substring(pos+endpos+3);
        var code = str.substring(pos,pos+endpos);
        code = code.trim('(\r\n|\n)')
        pos = pos+endpos+3;
        if (lang==null) {
          replacements.push("<pre><code>"+hljs.highlightAuto(code).value+"</code></pre>");
        } else {
          try {
            if (lang==="no-highlight") {
              replacements.push("<pre><code class=\""+lang+"\">"+entities.encodeHTML(code)+"</code></pre>");
            } else {
              replacements.push("<pre><code class=\""+lang+"\">"+hljs.highlight(lang, code).value+"</code></pre>");
            }
          } catch(err) {
            replacements.push("<pre><code>"+hljs.highlightAuto(code).value+"</code></pre>");
          }
        }
      }
      if (pos < (str.length-1)) {
        replacements.push(str.substring(pos));
      }
      
      files[file].contents = replacements.join('');
      //files[file].contents = '<link rel="stylesheet" href="'+theme+'">\n'+files[file].contents;
      debug(files[file].contents);
    });
  };
}
var _ = require('lodash')
var highlight = require('highlight.js')

highlight.configure({
  'useBR': true
})

module.exports = {
  'swagger--collection-format': function (value, paramName) {
    return {
      'csv': 'comma separated (`' + paramName + '=aaa,bbb`)',
      'ssv': 'space separated (`' + paramName + '=aaa bbb`)',
      'tsv': 'tab separated (`' + paramName + '=aaa\\tbbb`)',
      'pipes': 'pipe separated (`' + paramName + '=aaa|bbb`)',
      'multi': 'multiple parameters (`' + paramName + '=aaa&' + paramName + '=bbb`)'
    }[value]
  },
  'swagger--response-code': function (code) {
    // Comments refer to the section number in rfc2616
    // If an rfc number is specified, the code is
    // documented in the specified rfc.
    return {
      '100': 'Continue', // 10.1.1
      '101': 'Switching Protocols', // 10.1.2
      '200': 'OK', // 10.2.1
      '201': 'Created', // 10.2.2
      '202': 'Accepted', // 10.2.3
      '203': 'Non-Authoritative Information', // 10.2.4
      '204': 'No Content', // 10.2.5
      '205': 'Reset Content', // 10.2.6
      '206': 'Partial Content', // 10.2.7
Example #10
0
var React = require('react');
var reactToJsx = require('react-to-jsx');
var slugify = require('slugify');
var hl = require("highlight.js");

hl.configure({
  languages: ['xml']
});

var highlightMarkup = function (markup) {
  return hl.highlightAuto(markup).value;
};

var StyleGuideItem = React.createClass({
  displayName: "StyleGuideItem",
  propTypes: {
    // Content
    title: React.PropTypes.string,
    description: React.PropTypes.string,
    descriptionIsHtml: React.PropTypes.bool,
    staticMarkup: React.PropTypes.string,

    // Behavior
    highlighter: React.PropTypes.func,
    expandingMarkup: React.PropTypes.bool,
    markupExpandedByDefault: React.PropTypes.bool,
    sectionLink: React.PropTypes.bool,
    sectionId: React.PropTypes.string,

    // Classes and Markup
    headingTag: React.PropTypes.string,
Example #11
0
    chalk     = require('chalk'),
    Highlight = require('highlight.js'),
    reportGen = require('./reportGenerator'),
    stringify = require('json-stringify-safe'),
    conf      = require('./config'),
    templates = require('./templates.js'),
    opener    = require('opener');
    shields = require('shields-lightweight');

var Base = mocha.reporters.Base,
    generateReport = reportGen.generateReport,
    saveToFile = reportGen.saveToFile,
    totalTestsRegistered;

Highlight.configure({
  useBR: true,
  languages: ['javascript']
});

module.exports = Mochawesome;

/**
 * Initialize a new reporter.
 *
 * @param {Runner} runner
 * @api public
 */

function Mochawesome (runner, options) {
  // Reset total tests counter
  totalTestsRegistered = 0;
Example #12
0
function plugin(options) {
    'use strict';
    hljs.configure(options);
    return function (files, metalsmith, done) {
        setImmediate(done);
        Object.keys(files).forEach(function (file) {
            debug('checking file: %s', file);
            if (!markdown(file)) { return; }
            var data = files[file],
                str = data.contents.toString(),
                end = /^(\s*)```(.*)/m,
                remainder = str,
                pos = 0,
                endpos = 0,
                replacements = [];

            while (end.test(remainder)) {
                var match = end.exec(remainder),
                    candidate = match[2] && match[2].trim(),
                    lang = (candidate && candidate.length) > 0 ? candidate : null,
                    prev = pos,
                    buff = match[0].length,
                    leadingSpaceLength = match[1] ? match[1].length : 0;

                pos = pos + match.index + buff;
                remainder = str.substring(pos);

                var ends = end.exec(remainder);
                if (ends === null) {
                    break;
                }

                endpos = ends.index;
                replacements.push(str.substring(prev, pos - buff + leadingSpaceLength));

                var fencePrefixLength = (ends[1] ? ends[1].length : 0) + 3;
                var nextPos = pos + endpos + fencePrefixLength;
                remainder = str.substring(nextPos);
                var code = str.substring(pos, pos + endpos);
                code = code.trim('(\r\n|\n)');
                pos = nextPos;
                if (lang === null) {
                    replacements.push('<pre><code class="hljs">' + hljs.highlightAuto(code).value + '</code></pre>');
                } else {
                    try {
                        if (lang === 'no-highlight') {
                            replacements.push('<pre><code class="hljs ' + lang + '">' + entities.encodeHTML(code) + '</code></pre>');
                        } else {
                            replacements.push('<pre><code class="hljs ' + lang + '">' + hljs.highlight(lang, code).value + '</code></pre>');
                        }
                    } catch (err) {
                        replacements.push('<pre><code>' + hljs.highlightAuto(code).value + '</code></pre>');
                    }
                }
            }
            if (pos < (str.length - 1)) {
                replacements.push(str.substring(pos));
            }

            files[file].contents = new Buffer(replacements.join(''));
            debug(files[file].contents.toString());
        });
    };
}
Example #13
0
import MyLayout from '../../components/MyLayout'
//其他
import { getDetailUrl, getCommentsUrl, getLastIdUrl, getNextIdUrl, getBlogUrl, addZanUrl } from '../../config'
import { COMMON_TITLE, MY_BLOG, POST_READING_STATEMENT } from '../../config/constantsData'
import { markdownConfig } from '../../config/markdown'
import { getHtml, OldTime, throttle, NewCdnTime, changeCdnUrl } from '../../until'
import './index.less'
import './pop-tips.less'
import  './viewer.min.less'
import { addZan, getHotArticleList, getHotRecommendList } from '../../store/actions'
import { REQ_ACTION } from '../admin/req-action'
//定义
const { Content } = Layout
let timer
const { options, config } = markdownConfig
hljs.configure(config)
marked.setOptions({
  highlight: (code) => hljs.highlightAuto(code).value,
  ...options
})
class Detail extends Component {
  constructor (props) {
    super(props)
    this.state = {
      articleID: '',
      articleLike: 0,
      fn: null,
      isShowEditIcon: false,
      topWidth: 0
    }
  }
Example #14
0
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var yaml = require("js-yaml");
var hljs = require("highlight.js");
var yamlHeaderRegExp = /^([\s\S]*?)\n\s*\-+\s*\n/;
var pkg = require("../package.json");

hljs.configure({
    classPrefix: ""
});

exports.highlight = function(content, language) {
    if (language) {
        return hljs.highlight(language, content).value;
    } else {
        return content;
    }
};

exports.preCompile = function(src, context) {
    context.title = "";
    context.page = "";
    var match = yamlHeaderRegExp.exec(src);
    if (match) {
highlight.configure( { classPrefix: '', languages : [
  "apache",
  "applescript",
  "css",
  "bash",
  "clojure-repl",
  "clojure",
  "javascript",
  "coffeescript",
  "cpp",
  "cs",
  "d",
  "dart",
  "delphi",
  "diff",
  "django",
  "dockerfile",
  "dos",
  "elixir",
  "erb",
  "erlang-repl",
  "erlang",
  "fortran",
  "fsharp",
  "gcode",
  "gherkin",
  "go",
  "gradle",
  "groovy",
  "haml",
  "handlebars",
  "haskell",
  "http",
  "ini",
  "java",
  "json",
  "kotlin",
  "less",
  "lisp",
  "livescript",
  "lua",
  "makefile",
  "markdown",
  "mathematica",
  "matlab",
  "nginx",
  "objectivec",
  "perl",
  "php",
  "powershell",
  "prolog",
  "puppet",
  "python",
  "q",
  "r",
  "rib",
  "rsl",
  "ruby",
  "rust",
  "scala",
  "scheme",
  "scilab",
  "scss",
  "smali",
  "smalltalk",
  "sml",
  "sql",
  "stylus",
  "swift",
  "tcl",
  "tex",
  "typescript",
  "vbnet",
  "vbscript-html",
  "vbscript",
  "vim",
  "x86asm",
  "xml"
]});
Example #16
0
 componentDidMount() {
   hljs.configure({ classPrefix: '' });
   hljs.initHighlighting();
   document.querySelectorAll('pre.hl code').forEach(block => hljs.highlightBlock(block));
 }
Example #17
0
import marked from 'marked';
import hljs from 'highlight.js';
hljs.configure({
  tabReplace: '  '
});
marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false,
  highlight: code => hljs.highlightAuto(code).value
});

/* eslint no-undef: 0 */
onmessage = ({ data }) => {
  const parsed = marked(data);
  postMessage(parsed);
};

Example #18
0
module.exports = function (comments, options, callback) {

  var linkerStack = createLinkerStack(options)
    .namespaceResolver(comments, function (namespace) {
      var slugger = new GithubSlugger();
      return '#' + slugger.slug(namespace);
    });

  var formatters = createFormatters(linkerStack.link);

  hljs.configure(options.hljs || {});

  var sharedImports = {
    imports: {
      slug: function (str) {
        var slugger = new GithubSlugger();
        return slugger.slug(str);
      },
      shortSignature: function (section) {
        var prefix = '';
        if (section.kind === 'class') {
          prefix = 'new ';
        } else if (section.kind !== 'function') {
          return section.name;
        }
        return prefix + section.name + formatters.parameters(section, true);
      },
      signature: function (section) {
        var returns = '';
        var prefix = '';
        if (section.kind === 'class') {
          prefix = 'new ';
        } else if (section.kind !== 'function') {
          return section.name;
        }
        if (section.returns) {
          returns = ': ' +
            formatters.type(section.returns[0].type);
        }
        return prefix + section.name + formatters.parameters(section) + returns;
      },
      md: function (ast, inline) {
        if (inline && ast && ast.children.length && ast.children[0].type === 'paragraph') {
          ast = {
            type: 'root',
            children: ast.children[0].children.concat(ast.children.slice(1))
          };
        }
        return formatters.markdown(ast);
      },
      formatType: formatters.type,
      autolink: formatters.autolink,
      highlight: function (example) {
        if (options.hljs && options.hljs.highlightAuto) {
          return hljs.highlightAuto(example).value;
        }
        return hljs.highlight('js', example).value;
      }
    }
  };
  
  sharedImports.imports.renderSectionList =  _.template(fs.readFileSync(path.join(__dirname, 'section_list._'), 'utf8'), sharedImports);
  sharedImports.imports.renderSection = _.template(fs.readFileSync(path.join(__dirname, 'section._'), 'utf8'), sharedImports);
  sharedImports.imports.renderNote = _.template(fs.readFileSync(path.join(__dirname, 'note._'), 'utf8'), sharedImports);

  var pageTemplate = _.template(fs.readFileSync(path.join(__dirname, 'index._'), 'utf8'),  sharedImports);

  // push assets into the pipeline as well.
  vfs.src([__dirname + '/assets/**'], { base: __dirname })
    .pipe(concat(function (files) {
      callback(null, files.concat(new File({
        path: 'index.html',
        contents: new Buffer(pageTemplate({
          docs: comments,
          options: options
        }), 'utf8')
      })));
    }));
};
Example #19
0
'use strict';

var _ = require('lodash');
var uuid = require('node-uuid');
var beautify = require('js-beautify').js_beautify;
var Highlight = require('highlight.js');
var Base = require('mocha/lib/reporters/base');

Highlight.configure({'useBR': true, 'languages': ['javascript']});

/**
 * Allows listening to events from the mocha reporter
 * @param {*} runner mocha runner.
 */
module.exports = function (runner) {
  Base.call(this, runner);

  // emit events from mocha passing along relevent arguments
  runner.on('start', function () {
    process.send({'message': 'mocha-start', 'data': this.stats});
  });

  runner.on('suite', function (suite) {
    if (suite.root) { return; }
    suite = cleanSuite(suite, true);
    process.send({'message': 'mocha-suite', 'data': suite});
    process.send({'message': 'mocha-stats', 'data': this.stats});
  });

  runner.on('suite end', function (suite) {
    if (suite.root) { return; }
/**
 * Given a hierarchy-nested set of `comments`, generate an remark-compatible
 * Abstract Syntax Tree usable for generating Markdown output
 *
 * @param {Array<Object>} comments nested comment
 * @param {Object} opts currently none accepted
 * @param {Function} callback called with AST
 * @returns {undefined}
 * @public
 */
function commentsToAST(comments, opts, callback) {
    var hljsOptions = (opts || {}).hljs || {},
        language = !hljsOptions.highlightAuto ? "javascript" : undefined;

    hljs.configure(hljsOptions);

    /**
     * Generate an AST chunk for a comment at a given depth: this is
     * split from the main function to handle hierarchially nested comments
     *
     * @param {number} depth nesting of the comment, starting at 1
     * @param {Object} comment a single comment
     * @returns {Object} remark-compatible AST
     */
    function generate(depth, comment) {
        function descriptionAsMarkdown(description, prefix) {
            if (!description) {
                return [];
            }
            if (description.children && description.children.length === 0) {
                return [];
            }
            if (prefix) {
                return [u('text', prefix)].concat(description.children)
            }
            return description.children;
        }

        var contain$destructuringParam = function(param) {
            // $0, $1
            return /^\$\d+$/.test(param.name) && param.type.name === "Object";
        };

        /**
         * create normal params
         * @param {Array} params
         * @returns {*|Array.<T>|Array}
         */
        var withoutDestructuringParam = function(params) {
            return params.filter(param => {
                return !contain$destructuringParam(param);
            });
        };
        var replacedDestructuringParamWithNormal = function($params, normalParams) {
            // replace $param with normal
            $params.forEach($param => {
                $param.properties = $param.properties.map($paramItem => {
                    var matchParam = normalParams.find(param => {
                        return `${$param.name}.${param.name}` === $paramItem.name;
                    });
                    if (matchParam) {
                        return matchParam;
                    } else {
                        return $paramItem;
                    }
                });
            });
            return $params;
        };

        /**
         * destructuring $0
         */
        function $paramList(params) {
            var normalParams = withoutDestructuringParam(params);
            return paramList(normalParams);
        }

        function paramList(params) {
            if (params.some(contain$destructuringParam)) {
                return $paramList(params);
            }
            return u("list", {ordered: false}, params.map(function(param) {
                var description = param.description ? descriptionAsMarkdown(param.description, " - ") : [];
                var defaultParameters = param.default ? [
                    u("paragraph", [
                        u("text", " (optional, default "),
                        u("inlineCode", param.default),
                        u("text", ")")
                    ])
                ] : [];
                var typeNodes = param.type ? [
                    u("text", ": "),
                    u("strong", formatType(param.type))
                ] : [];
                var inParagraph = [
                    u("inlineCode", param.name)
                ].concat(
                    typeNodes,
                    description,
                    defaultParameters).filter(isNotUndefined);
                var properties = param.properties ? paramList(param.properties) : undefined;
                var listItems = [
                    u("paragraph", inParagraph)
                ].concat(properties).filter(isNotUndefined);
                return u("listItem", listItems);
            }));
        }

        function paramSection(comment) {
            return !!comment.params && [
                    u("strong", [u("text", "Parameters")]),
                    paramList(comment.params)
                ];
        }

        function propertySection(comment) {
            return !!comment.properties && [
                    u("strong", [u("text", "Properties")]),
                    propertyList(comment.properties)
                ];
        }

        function propertyList(properties) {
            return u("list", {ordered: false},
                properties.map(function(property) {
                    var description = property.description ? descriptionAsMarkdown(property.description) : [];
                    return u("listItem", [
                        u("paragraph", [
                            u("inlineCode", property.name),
                            u("text", " "),
                            u("strong", formatType(property.type)),
                            u("text", " ")
                        ]
                            .concat(description)
                            .filter(isNotUndefined)),
                        property.properties && propertyList(property.properties)
                    ].filter(isNotUndefined));
                }));
        }

        function examplesSection(comment) {
            return !!comment.examples && [u("strong", [u("text", "Examples")])]
                    .concat(comment.examples.reduce(function(memo, example) {
                        language = hljsOptions.highlightAuto ?
                                   hljs.highlightAuto(example.description).language : "javascript";
                        return memo.concat(example.caption ?
                            [u("paragraph", [u("emphasis", example.caption)])] :
                            []).concat([u("code", {lang: language}, example.description)]);
                    }, []));
        }

        function returnsSection(comment) {
            return !!comment.returns && comment.returns.map(function(returns) {
                    var description = returns.description
                        ? descriptionAsMarkdown(returns.description, " - ")
                        : [];
                    var returnType = returns.type ? [
                        u("text", ": "),
                        u("strong", formatType(returns.type))
                    ] : [];
                    // if no return value, hidden
                    if (returnType.length === 0) {
                        return false;
                    }
                    return u("paragraph", [
                        u("text", "Returns")
                    ].concat(returnType, description).filter(isNotUndefined));
                });
        }

        function throwsSection(comment) {
            return !!comment.throws &&
                u("list", {ordered: false},
                    comment.throws.map(function(returns) {
                        var description = returns.description ? descriptionAsMarkdown(returns.description) : [];
                        return u("listItem", [
                            u("paragraph", [
                                u("text", "Throws "),
                                u("strong", formatType(returns.type)),
                                u("text", " ")
                            ].concat(description))
                        ]);
                    }));
        }

        function augmentsLink(comment) {
            return comment.augments && u("paragraph", [
                    u("strong", [
                        u("text", "Extends "),
                        u("text", comment.augments.map(function(tag) {
                            return tag.name;
                        }).join(", "))
                    ])
                ]);
        }

        function githubLink(comment) {
            return comment.context.github && u("paragraph", [
                    u("link", {
                        title: "Source code on GitHub",
                        url: comment.context.github
                    }, [
                        u("text", comment.context.path + ":" +
                            comment.context.loc.start.line + "-" +
                            comment.context.loc.end.line)
                    ])
                ]);
        }

        function metaSection(comment) {
            var meta = ["version", "since", "copyright", "author", "license"]
                .reduce(function(memo, tag) {
                    if (comment[tag]) {
                        memo.push({tag: tag, value: comment[tag]});
                    }
                    return memo;
                }, []);
            return !!meta.length && [u("strong", [u("text", "Meta")])].concat(
                    u("list", {ordered: false},
                        meta.map(function(item) {
                            return u("listItem", [
                                u("paragraph", [
                                    u("strong", [u("text", item.tag)]),
                                    u("text", ": " + item.value)
                                ])
                            ]);
                        })));
        }

        function stringifyNodes(children) {
            return children.map(function(node) {
                if (node.children) {
                    return stringifyNodes(node.children);
                } else {
                    return unescapeHTML(node.value);
                }
            }).join("");
        }

        // type node
        function stringifyType(type) {
            var typeNodeList = formatType(type);
            return stringifyNodes(typeNodeList);
        }

        // (param1: Type, param: Type)
        // return TextNode
        function paramPairString(params) {
            if (!Array.isArray(params)) {
                return "";
            }
            // When contain $, create { param } string
            if (params.some(contain$destructuringParam)) {
                const $paramList = params.filter(contain$destructuringParam);
                const normalParams = withoutDestructuringParam(params);
                const replacedDestructuringParams = replacedDestructuringParamWithNormal($paramList, normalParams);
                return replacedDestructuringParams.sort((a, b) => {
                    return a.name > b.name;
                }).map(function($param) {
                    // { foo, bar }
                    const paramNames = $param.properties.map(param => param.name);
                    return `{ ${paramNames.join(", ")} }`;
                }).join(", ");
            }
            var paramsStrings = params.map(function(param) {
                var name = param.name ? param.name : "";
                if (param.type) {
                    return name + ": " + stringifyType(param.type);
                } else {
                    return name;
                }
            });
            return paramsStrings.join(", ");
        }

        function returnTypeString(returns) {
            if (returns === undefined) {
                return "";
            }
            return returns.map(function(ret) {
                return stringifyType(ret.type);
            }).join(",");
        }

        function heading(comment) {
            var params = comment.params ? paramPairString(comment.params) : "";
            var returnType = returnTypeString(comment.returns);
            var headName = comment.name || "";
            // function( param ) : returnType
            if (comment.kind === 'function') {
                if (params.length > 0) {
                    headName += "(" + params + ")";
                } else {
                    headName += "()";
                }
                if (returnType.length > 0) {
                    headName += ": " + returnType;
                }
            }
            return u("heading", {depth: depth}, [u("inlineCode", headName)])
        }

        return []
            .concat(heading(comment))
            .concat(githubLink(comment))
            .concat(augmentsLink(comment))
            .concat(comment.description ? descriptionAsMarkdown(comment.description) : [])
            .concat(paramSection(comment))
            .concat(propertySection(comment))
            .concat(examplesSection(comment))
            .concat(throwsSection(comment))
            .concat(returnsSection(comment))
            .concat(metaSection(comment))
            .concat(!!comment.members.instance.length &&
                comment.members.instance.reduce(function(memo, child) {
                    return memo.concat(generate(depth + 1, child));
                }, []))
            .concat(!!comment.members.static.length &&
                comment.members.static.reduce(function(memo, child) {
                    return memo.concat(generate(depth + 1, child));
                }, []))
            .filter(isNotUndefined);
    }

    return callback(null, u("root", comments.reduce(function(memo, comment) {
        return memo.concat(generate(1, comment));
    }, [])));
}
Example #21
0
#!/usr/bin/env node

var hljs = require('highlight.js'); hljs.configure({classPrefix: ''});
var cheerio = require('cheerio');

var logger = require('../logger');
var textUtil = require('../textUtil');

function highlight (text, language) {
  if (language === false) return [];

  var highlighted;
  if (language) {
    try { highlighted = hljs.highlight(language, text, true); } catch (e) {}
  }
  if (!highlighted) highlighted = hljs.highlightAuto(text);

  var $ = cheerio.load(highlighted.value);
  var ranges = [];
  do {
    var lastElCount = elCount;
    var elCount = $('*:not(:has(*))').replaceWith(function () {
      var $el = $(this);
      var text = '';
      [this].concat($el.parents().get(), [$.root()]).reverse().reduce(function (parent, el) {
        $(parent).contents().each(function () {
          var $sibling = $(this);
          if ($sibling.is(el)) return false;
          text += $sibling.text();
        });
        return el;
Example #22
0
/**
 * Given a hierarchy-nested set of comments, generate an remark-compatible
 * Abstract Syntax Tree usable for generating Markdown output
 *
 * @param {Array<Object>} comments nested comment
 * @param {Object} opts currently none accepted
 * @param {Function} callback called with AST
 * @returns {undefined} calls callback
 */
function commentsToAST(comments, opts, callback) {
  var hljsOptions = (opts || {}).hljs || {},
    language = !hljsOptions.highlightAuto ? 'javascript' : undefined;

  hljs.configure(hljsOptions);

  /**
   * Generate an AST chunk for a comment at a given depth: this is
   * split from the main function to handle hierarchially nested comments
   *
   * @param {number} depth nesting of the comment, starting at 1
   * @param {Object} comment a single comment
   * @returns {Object} remark-compatible AST
   */
  function generate(depth, comment) {

    function paramList(params) {
      return u('list', { ordered: false }, params.map(function (param) {
        return u('listItem', [
          u('paragraph', [
            u('inlineCode', param.name),
            u('text', ' '),
            !!param.type && u('strong', formatType(param.type)),
            u('text', ' ')
          ].concat(remark.parse(formatInlineTags(param.description)).children)
          .concat([
            !!param.default && u('paragraph', [
              u('text', ' (optional, default '),
              u('inlineCode', param.default),
              u('text', ')')
            ])
          ]).filter(Boolean))
        ].concat(param.properties && paramList(param.properties))
        .filter(Boolean));
      }));
    }

    function paramSection(comment) {
      return !!comment.params && [
        u('strong', [u('text', 'Parameters')]),
        paramList(comment.params)
      ];
    }

    function propertySection(comment) {
      return !!comment.properties && [
        u('strong', [u('text', 'Properties')]),
        propertyList(comment.properties)
      ];
    }

    function propertyList(properties) {
      return u('list', { ordered: false },
        properties.map(function (property) {
          return u('listItem', [
            u('paragraph', [
              u('inlineCode', property.name),
              u('text', ' '),
              u('strong', formatType(property.type)),
              u('text', ' ')
            ]
            .concat(remark.parse(formatInlineTags(property.description)).children)
            .filter(Boolean)),
            property.properties && propertyList(property.properties)
          ].filter(Boolean));
        }));
    }

    function examplesSection(comment) {
      return !!comment.examples && [u('strong', [u('text', 'Examples')])]
        .concat(comment.examples.reduce(function (memo, example) {
          language = hljsOptions.highlightAuto ?
            hljs.highlightAuto(example.description).language : 'javascript';
          return memo.concat(example.caption ?
            [u('paragraph', [u('emphasis', [u('text', example.caption)])])] :
            []).concat([u('code', { lang: language }, example.description)]);
        }, []));
    }

    function returnsSection(comment) {
      return !!comment.returns && comment.returns.map(function (returns) {
        return u('paragraph', [
          u('text', 'Returns '),
          u('strong', formatType(returns.type)),
          u('text', ' ')
        ].concat(remark.parse(formatInlineTags(returns.description)).children));
      });
    }

    function throwsSection(comment) {
      return !!comment.throws &&
        u('list', { ordered: false },
        comment.throws.map(function (returns) {
          return u('listItem', [
            u('paragraph', [
              u('text', 'Throws '),
              u('strong', formatType(returns.type)),
              u('text', ' ')
            ].concat(remark.parse(formatInlineTags(returns.description)).children))
          ]);
        }));
    }

    function augmentsLink(comment) {
      return comment.augments && u('paragraph', [
        u('strong', [
          u('text', 'Extends '),
          u('text', comment.augments.map(function (tag) {
            return tag.name;
          }).join(', '))
        ])
      ]);
    }

    function githubLink(comment) {
      return comment.context.github && u('paragraph', [
        u('link', {
          title: 'Source code on GitHub',
          url: comment.context.github
        }, [u('text', comment.context.path + ':' +
          comment.context.loc.start.line + '-' +
          comment.context.loc.end.line)])
      ]);
    }

    function metaSection(comment) {
      var meta = ['version', 'since', 'copyright', 'author', 'license']
        .reduce(function (memo, tag) {
          if (comment[tag]) {
            memo.push({ tag: tag, value: comment[tag] });
          }
          return memo;
        }, []);
      return !!meta.length && [u('strong', [u('text', 'Meta')])].concat(
        u('list', { ordered: false },
          meta.map(function (item) {
            return u('listItem', [
              u('paragraph', [
                u('strong', [u('text', item.tag)]),
                u('text', ': ' + item.value)
              ])
            ]);
          })));
    }

    return [u('heading', { depth: depth }, [u('text', comment.name || '')])]
    .concat(githubLink(comment))
    .concat(augmentsLink(comment))
    .concat(remark.parse(formatInlineTags(comment.description)).children)
    .concat(paramSection(comment))
    .concat(propertySection(comment))
    .concat(examplesSection(comment))
    .concat(throwsSection(comment))
    .concat(returnsSection(comment))
    .concat(metaSection(comment))
    .concat(!!comment.members.instance.length &&
      comment.members.instance.reduce(function (memo, child) {
        return memo.concat(generate(depth + 1, child));
      }, []))
    .concat(!!comment.members.static.length &&
      comment.members.static.reduce(function (memo, child) {
        return memo.concat(generate(depth + 1, child));
      }, []))
    .filter(Boolean);
  }

  return callback(null, u('root', comments.reduce(function (memo, comment) {
    return memo.concat(generate(1, comment));
  }, [])));
}
Example #23
0
/*

    This script runs on Node v5.1.0 for Windows.
    It uses cheerio for HTML parsing and highlight.js for the highlighter.

*/

var fs = require('fs'),
    cheerio = require('cheerio'),
    hljs = require('highlight.js');

var bookpath = 'build/book.html';

hljs.configure({
    tabReplace: '    ', // 4 spaces
    classPrefix: ''     // don't append class prefix
});

fs.readFile(bookpath, function(err, data) {

    $ = cheerio.load(data, {});

    var pl = $('.programlisting').toArray();

    pl.forEach(function (v, k) {
        var rawtext = v.children[0].data;
        var result = hljs.highlight('haxe',rawtext).value;
        v.children = $.parseHTML(result);
    });

    var result = $.html();
Example #24
0
/**
 * Syntax highlighting using highlight.js - https://highlightjs.org/
 */

const hljs = require('highlight.js');
hljs.configure({
	languages: [
		'javascript',
		'xml',
		'json',
		'scss',
		'css',
		'ruby',
		'diff',
		'makefile',
		'markdown',
		'php',
		'python',
		'java',
		'sql',
		'bash',
		'handlebars',
		'nginx',
		'perl',
		'scala'
	]
});

module.exports = hljs.initHighlighting;


// TODO: This really ought to be restricted to elements within a techdocs component,
var highlightjs = require('highlight.js');
var through2 = require('through2');

highlightjs.configure({
  classPrefix: ''
});

var hljsJavascript = highlightjs.getLanguage('javascript');
// highlight Packery
hljsJavascript.keywords.isotope_keyword = 'Isotope';
// highlight packery variables
hljsJavascript.keywords.isotope_var = 'iso';

hljsJavascript.contains.push({
  className: 'jquery_var',
  begin: /\$grid/
});

// FIXME, this doesn't work
// hljsJavascript.contains.push({
//   className: 'isotope',
//   begin: /isotope/
// });

var reFirstLine = /.*\n/;

function replaceCodeBlock( match, leadingWhiteSpace, block ) {
  var langMatch = block.match( reFirstLine );
  var language = langMatch && langMatch[0];
  // remove first line
  block = block.replace( reFirstLine, '' );
Example #26
0
var hljs = require('highlight.js'),
  _ = require('lodash');

hljs.configure({
  classPrefix: ''
});

var alias = {
  js: 'javascript',
  jscript: 'javascript',
  html: 'xml',
  htm: 'xml',
  coffee: 'coffeescript',
  'coffee-script': 'coffeescript',
  yml: 'yaml',
  pl: 'perl',
  ru: 'ruby',
  rb: 'ruby',
  csharp: 'cs'
};

var keys = Object.keys(alias);

/**
* Highlights a code block.
*
* See [highlight.js](http://highlightjs.org/)
*
* @method highlight
* @param {String} str
* @param {Object} [options]
Example #27
0
var hljs = require('highlight.js');
hljs.configure({
    classPrefix: 'lang-',
    useBR: false,
});

module.exports = exports = function(text, language) {
    try {
        console.log(language, text);
        return hljs.highlight(language, text, true).value;
    }
    catch (err) {
        throw new Error(err);
    }
};