Example #1
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) {
 replacement = function (wholeMatch, match, left, right) {
   // unescape match to prevent double escaping
   match = htmlunencode(match);
   return left + hljs.highlightAuto(match).value + right;
 };
Example #3
0
 $(program.ultimate.select).each(function () {
     $(this).html(highlight.highlight(program.ultimate.language, $(this).text()).value)
 })
Example #4
0
renderer.code = function (code, language) {
  var highlighted = language ? highlight.highlight(language, code).value
                             : highlight.highlightAuto(code).value;

  return '<pre class="highlight ' + language + '"><code>' + highlighted + '</code></pre>';
};
Example #5
0
exports.getCode = function getCode(args) {
  return hljs.highlight('javascript', args.callee.toString()).value;
}
Example #6
0
exports.newPost = function newPost(content) {
  var customRenderer = new marked.Renderer();
  var post = jsYaml.loadFront(content);
  var author = post['author'];
  var authorIndex = authors.indexOf(author);
  var authorId;

  marked.setOptions({

    /* Highlight block code */
    highlight(code, lang) {
      if (lang) {
        code = hljs.highlight(lang, code).value;
      } else {
        code = hljs.highlightAuto(code).value;
      }

      /* Make sure Handlebars in block code isn't parsed by Ember */
      return replaceHandlebars(code);
    },
  });

  /* Make sure Handlebars in inline code isn't parsed by Ember  */
  customRenderer.codespan = function(text, level) {
    var codeBlock = replaceHandlebars(text);

    return '<code>' + codeBlock + '</code>';
  }

  /* Parse post content as markdown */
  post['__content'] = marked(post['__content'], {
    renderer: customRenderer
  });

  /* Makre sure Ember parses Handlebars correctly */
  post['__content'] = replaceApostrophes(post['__content']);

  /* Rename content to body */
  post['body'] = post['__content'];
  delete post['__content'];

  /* Add urlString to model */
  post['urlString'] = dasherize(post['title']);

  /* Map out the posts and authors belongsTo relationship */
  if (authorIndex === -1) {
    authors.push(author);

    authorsFixtures.push({
      id: currentAuthorId,
      name: author,
      posts: [currentPostId],
      urlString: dasherize(author)
    });

    authorId = currentAuthorId;
    currentAuthorId++;
  } else {
    authorId = authorIndex;
    author = authorsFixtures[authorId];

    author.posts.push(currentPostId);
  }

  post['author'] = authorId;

  /* Map out the posts and categories many-to-many relationship  */
  if(post['categories']) {
    post['categories'] = post['categories'].map(function(category) {
      let categoryIndex = categories.indexOf(category);
      let categoryId;

      if (categoryIndex === -1) {

        /* Add categories that aren't already registered */
        categories.push(category);

        categoriesFixtures.push({
          id: currentCategoryId,
          name: category,
          posts: [currentPostId],
          urlString: dasherize(category)
        });

        categoryId = currentCategoryId;
        currentCategoryId++;
      } else {

        /* Add the post to already registered categories */
        categoryId = categoryIndex;
        category = categoriesFixtures[categoryId];

        category.posts.push(currentPostId);
      }

      return categoryId;
    });
  }

  /* Add posts fixture ID */
  post['id'] = currentPostId;
  currentPostId++;

  return post;
}
Example #7
0
 let highlightContent = markedContent.replace(/<pre><code\s*(?:class="lang-(\w+)")?>([\s\S]+?)<\/code><\/pre>/mg, (a, language, text) => {
   text = text.replace(/&#39;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/\&quot;/g, '"').replace(/\&amp;/g, "&");
   var result = highlight.highlightAuto(text, language ? [language] : undefined);
   return `<pre><code class="hljs lang-${result.language}">${result.value}</code></pre>`;
 });
Example #8
0
 highlightCss: function(string) {
   return hljs.highlight('css', string).value;
 },
Example #9
0
var defaultConfig = {
	highlight: true,
	highlightStyle: "github",
	path: [],
	index: PATH.join(assetPath, "md/index.md"),
	error: PATH.join(assetPath, "md/error.md"),
	customCSS: false,
	contentOnly: true
};

var slice = Array.prototype.slice;
var hasOwnProperty = Object.prototype.hasOwnProperty;

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

module.exports = function(opts) {
	var config = mix({}, defaultConfig, opts);
	return function * (next) {
		var res = this;
		var file = decodeURI(res.path);
		var raw = res.query.raw;
		var hasFile = true;
		var contentOnly = config.contentOnly;
		var ret;
		if (r_md_post.test(file)) {
			if (file === "/index.md") {
				file = config.index;
			}
Example #10
0
 let hl = (code) => highlight.highlightAuto(code).value
Example #11
0
require('jquery')
require('bootstrap')
const hljs = require('highlight.js')

hljs.initHighlightingOnLoad()
Example #12
0
 _highlightCode() {
     let node = ReactDOM.findDOMNode(this.refs.code);
     Hjs.highlightBlock(node);
 }
Example #13
0
 highlight: (code) => hljs.highlightAuto(code).value,
Example #14
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 #15
0
require('./style.less')

const hl = require('highlight.js')

hl.initHighlightingOnLoad()
Example #16
0
	Array.prototype.slice.apply(doc.getElementsByTagName('code')).forEach(function(code) {
		code.innerHTML = hljs.fixMarkup(hljs.highlightAuto(entities.decodeHTML(code.innerHTML)).value);
	});
  grunt.registerMultiTask('mini_static_blog', 'The best Grunt plugin ever.', function() {
    // Import external libraries
    var Handlebars = require('handlebars'),
      Moment = require('moment'),
      RSS = require('rss'),
      hljs = require('highlight.js'),
      MarkedMetadata = require('meta-marked'),
      _ = require('lodash'),
      parseUrl = require('url');

    // Declare variables
    var output, path;

    // Import options
    var options = this.options({
      year: new Date().getFullYear(),
      size: 5
    });
    options.domain = parseUrl.parse(options.data.url).hostname;

    // Register partials
    Handlebars.registerPartial({
      header: grunt.file.read(options.template.header),
      footer: grunt.file.read(options.template.footer)
    });

    // Get languages
    var langs = hljs.listLanguages();

    // Get Marked Metadata
    MarkedMetadata.setOptions({
      gfm: true,
      tables: true,
      smartLists: true,
      smartypants: true,
      langPrefix: 'hljs lang-',
      highlight: function (code, lang) {
        if (typeof lang !== "undefined" && langs.indexOf(lang) > 0) {
          return hljs.highlight(lang, code).value;
        } else {
          return hljs.highlightAuto(code).value;
        }
      }
    });

    // Get matching files
    var posts = grunt.file.expand(options.src.posts + '*.md', options.src.posts + '*.markdown');
    var pages = grunt.file.expand(options.src.pages + '*.md', options.src.pages + '*.markdown');

    // Get Handlebars templates
    var postTemplate = Handlebars.compile(grunt.file.read(options.template.post));
    var pageTemplate = Handlebars.compile(grunt.file.read(options.template.page));
    var indexTemplate = Handlebars.compile(grunt.file.read(options.template.index));
    var notFoundTemplate = Handlebars.compile(grunt.file.read(options.template.notfound));

    // Generate posts
    var post_items = [];
    posts.forEach(function(file) {
      // Convert it to Markdown
      var content = grunt.file.read(file);
      var md = new MarkedMetadata(content);
      var mdcontent = md.html;
      var meta = md.meta;

      // Get path
      var permalink = '/blog/' + (file.replace(options.src.posts, '').replace(/(\d{4})-(\d{2})-(\d{2})-/, '$1/$2/$3').replace('.markdown', '').replace('.md', ''));
      var path = options.www.dest + permalink;

      // Render the Handlebars template with the content
      var data = {
        year: options.year,
        data: options.data,
        domain: options.domain,
        path: permalink + '/',
        meta: {
          title: meta.title.replace(/"/g, ''),
          date: meta.date,
          formattedDate: new Moment(new Date(meta.date)).format('Do MMMM YYYY h:mm a'),
          categories: meta.categories
        },
        post: {
          content: mdcontent,
          rawcontent: content
        }
      };
      post_items.push(data);
    });

    // Sort posts
    post_items = _.sortBy(post_items, function(item) {
      return item.meta.date;
    });

    // Get recent posts
    var recent_posts = post_items.slice(Math.max(post_items.length - 5, 1)).reverse();

    // Output them
    post_items.forEach(function(data, index, list) {
      // Get next and previous
      if (index < (list.length - 1)) {
        data.next = {
          title: list[index + 1].meta.title,
          path: list[index + 1].path
        };
      }

      // Get recent posts
      data.recent_posts = recent_posts;

      // Render template
      var output = postTemplate(data);

      // Write post to destination
      grunt.file.mkdir(options.www.dest + data.path);
      grunt.file.write(options.www.dest + data.path + '/index.html', output);
    });

    /* Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      punctuation: '.',
      separator: ', '
    }); */

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).join(grunt.util.normalizelf(options.separator));

      // Handle options.
      src += options.punctuation;

      // Write the destination file.
      grunt.file.write(f.dest, src);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });
Example #18
0
 highlight: function(code, lang) {
   if (lang === 'js') {
     return highlight.highlightAuto(code).value;
   }
   return code;
 }
Example #19
0
for(var i = 0; i < pages.length; i++){
	var page = pages[i];
	var filename = "./pages/" + page['name'] + ".html";
	if(fs.existsSync(filename)){
		console.log("Building " + (page['name'] === "Home" ? "/" : "/" + page['name'] + "/"));
		var opts = page;
		if(page.title.length > 0)
			opts.title = "Dan Hlavenka - " + page.title + " - Illinois State University";
		else
			opts.title = "Dan Hlavenka - Illinois State University";
		if(page['name'] === "Home"){
			page.home = "current";
			page.links = links;
		}else
			page.home = "parent";
		page.tabs = tabs;
		for(var j = 0; j < page.tabs.length; j++)
			page.tabs[j].current = page['name'] === page.tabs[j]['name'] ? "current" : "";
		page.content = fs.readFileSync(filename) + '';
		var content = ejs.render(pageTemplate, {$: page});
		fs.writeFileSync(".." + (page['name'] === "Home" ? "" : "/" + page['name']) + "/index.html", content);
	}else
		console.log('ERROR: Unable to build "' + page['name'] + '". Could not load page content.');
}

console.log("Building /webcam/about.html");
var code = fs.readFileSync("./pages/webcam.js") + '';
code = hljs.highlight("javascript", code);
var content = ejs.render(webcamTemplate, {code: code.value});
fs.writeFileSync("../webcam/about.html", content);
 highlight: function(code, lang) {
   if (lang === undefined) lang = 'bash';
   if (lang === 'html') lang = 'xml';
   if (lang === 'js') lang = 'javascript';
   return '<div class="code-container">' + hljs.highlight(lang, code).value + '</div>';
 }
Example #21
0
  },

  ready () {
    // TODO: src, if we have src, ignore textContent
    // let text = Fs.readFileSync( this.path, {encoding: 'utf-8'} );

    this.value = this._unindent(this.textContent);

    // TODO: MutationObserver for characterData
  },

  _render () {
    let md = new Remarkable({
      html: true,
      highlight ( str, lang ) {
        if (lang && Hljs.getLanguage(lang)) {
          try {
            return Hljs.highlight(lang, str).value;
          } catch (err) {
            Console.error(`Syntax highlight failed: ${err.message}` );
          }
        }

        try {
          return Hljs.highlightAuto(str).value;
        } catch (err) {
          Console.error(`Syntax highlight failed: ${err.message}` );
        }

        return ''; // use external default escaping
      }
Example #22
0
function highlight(code, lang) {
  var val = hljs.highlight(lang, code).value

  return val
}
Example #23
0
 componentDidMount() {
   hljs.initHighlighting();
 }
Example #24
0
 sections.forEach(function(section) {
   section.codeHtml = highlight.highlight(lang.highlightLanguage || lang.language, section.code).value;
   section.docHtml = md.render(section.docs);
 });
Example #25
0
var blessed = require('blessed');
var _ = require('lazy.js');
var hljs = require('highlight.js'); hljs.configure({classPrefix: ''});
var cheerio = require('cheerio');
var entities = require('entities');
var Lexer = require('lex');

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

function markup (text, style, start, end) {
  if (!text) return text;
  start = typeof start !== 'undefined' ? markup.index(text, start) : 0;
  end = typeof end !== 'undefined' ? markup.index(text, end) : Infinity;
  if (start === end) return text;

  style = style || '';
  var middle = style + text.slice(start, end) + markup.closeTags(style);
  return text.slice(0, start) + middle + text.slice(end);
};

markup._tagRegExp = /\{(\/?)([\w\-,;!#]*)\}/g;
markup._addTag = function (openTags, tag, close, name) {
  if (!close) openTags.push(tag);
  else if (!name) openTags.splice(0, Infinity);
  else {
    var lastTagIndex = openTags.lastIndexOf('{'+name+'}');
    if (lastTagIndex !== -1) openTags.splice(lastTagIndex, 1);
  }
};
Example #26
0
 $('.clojure').each(function(i, node){
   $(node).html(hljs.highlightAuto($(node).text()).value).addClass('hljs');
 });
Example #27
0
 highlight: function (code) {
   return hljs.highlightAuto(code).value;
 }
Example #28
0
	highlight: function(code) {
		return highlight.highlightAuto(code).value
	}
Example #29
0
 highlight: function(code, lang) {
   if (lang) {
     return hljs.highlight(lang, code).value;
   }
   return code;
 }
Example #30
0
 highlight: (code, lang) => {
     return hljs.highlightAuto(code, [lang]).value;
 },