Syntax highlighting

使用 highlight.js 给代码片断添加语法高亮, 并设置更优雅的字体

当前为 2019-10-16 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Syntax highlighting
// @namespace    http://tampermonkey.net/
// @version      0.1.2
// @description  使用 highlight.js 给代码片断添加语法高亮, 并设置更优雅的字体
// @author       floatsyi
// @license      MIT
// @require      https://cdn.bootcss.com/highlight.js/9.15.10/highlight.min.js
// @require      https://cdn.bootcss.com/fontfaceobserver/2.1.0/fontfaceobserver.js
// @match             *://*/*
// @grant GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant unsafeWindow
// ==/UserScript==
//  https://www.bootcdn.cn/highlight.js/
// console.log(unsafeWindow.FontFaceObserver)
const envDetection = [unsafeWindow.Prism, unsafeWindow.hljs]
if (envDetection.some(item => !!item)) return false

const themes = [
  'atom-one-dark',
  'brown-paper',
  'color-brewer',
  'docco',
  'darkula'
]
let currentTheme = themes[0]
const fonts = ['BioRhyme', 'Fira Code', 'Lato']
let currentFont = fonts[1]

const backgroundColor = '#272c34'

const fetchStyleText = url =>
  fetch(url, {
    headers: {
      'Content-Type': 'text/plain'
    }
  }).then(function (response) {
    return response.text()
  })

const setStyle = () => {
  const themeStyle = GM_getValue(currentTheme)

  if (themeStyle) {
    GM_addStyle(themeStyle)
  } else {
    const themeUrl = `https://cdn.bootcss.com/highlight.js/9.15.10/styles/${currentTheme}.min.css`

    fetchStyleText(themeUrl).then(function (style) {
      GM_addStyle(style)
      GM_setValue(currentTheme, style)
    })
  }

  const fontStyle = GM_getValue(currentFont)
  if (fontStyle) {
    GM_addStyle(fontStyle)
  } else {
    const fontUrl = `https://fonts.loli.net/css?family=${currentFont}`

    fetchStyleText(fontUrl).then(function (style) {
      GM_addStyle(style)
      GM_setValue(currentFont, style)
    })
  }
}

const setFont = () => {
  const font = new window.FontFaceObserver(currentFont)
  font.load().then(
    function () {
      console.log('Font is available')
      for (const pre of Array.from(document.querySelectorAll('pre'))) {
        const code = pre.querySelector('code')
        window.hljs.highlightBlock(code)
        code.style.fontFamily = currentFont
      }
    },
    function () {
      console.log('Font is not available')
    }
  )
}

setStyle()
setFont()

console.log('highlight runing')