├── Cartfile ├── Shots ├── demo1.png └── demo2.png ├── Cartfile.resolved ├── MarkRight ├── .DS_Store ├── Assets.xcassets │ ├── Contents.json │ └── AppIcon.appiconset │ │ ├── icon_16x16.png │ │ ├── icon_32x32.png │ │ ├── icon_128x128.png │ │ ├── icon_16x16@2x.png │ │ ├── icon_256x256.png │ │ ├── icon_32x32@2x.png │ │ ├── icon_512x512.png │ │ ├── icon_128x128@2x.png │ │ ├── icon_256x256@2x.png │ │ ├── icon_512x512@2x.png │ │ └── Contents.json ├── MarkRight.entitlements ├── Protocol │ └── HTMLConversionProtocol.swift ├── Model │ ├── MarkdownNode.swift │ ├── InlineNode.swift │ ├── ContainerNode.swift │ └── BlockNode.swift ├── Extension │ ├── InlineLine+HTML.swift │ ├── MarkdownNode+HTML.swift │ ├── CharacterSet+Extension.swift │ ├── InlineNode+HTML.swift │ ├── ContainerNode+HTML.swift │ └── BlockNode+HTML.swift ├── AppDelegate.swift ├── Resource │ ├── css_injector.js │ ├── Test.md │ ├── theme-solarized-dark.css │ ├── theme-light.css │ ├── theme.css │ └── highlight.js ├── Info.plist ├── MarkdownParser │ ├── MarkdownParser.swift │ ├── ListItems.swift │ ├── Inlines.swift │ ├── ContainerItems.swift │ ├── GenericStringTerms.swift │ └── LeafBlock.swift ├── HTMLEntities │ ├── ParseError.swift │ ├── Utilities.swift │ └── String+HTMLEntities.swift └── ViewController.swift ├── MarkRight.xcodeproj ├── xcuserdata │ ├── xihe.xcuserdatad │ │ ├── xcdebugger │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── xcschemes │ │ │ └── xcschememanagement.plist │ └── octree.xcuserdatad │ │ ├── xcdebugger │ │ └── Breakpoints_v2.xcbkptlist │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── project.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcuserdata │ │ └── xihe.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist └── project.pbxproj ├── MarkRightTests ├── Info.plist └── MarkRightTests.swift ├── README.md └── .gitignore /Cartfile: -------------------------------------------------------------------------------- 1 | github "Octree/ParserCombinator" -------------------------------------------------------------------------------- /Shots/demo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/Shots/demo1.png -------------------------------------------------------------------------------- /Shots/demo2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/Shots/demo2.png -------------------------------------------------------------------------------- /Cartfile.resolved: -------------------------------------------------------------------------------- 1 | github "Octree/FP" "0.4.1" 2 | github "Octree/ParserCombinator" "0.3.0" 3 | -------------------------------------------------------------------------------- /MarkRight/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/.DS_Store -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_16x16.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_32x32.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_128x128.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_256x256.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_512x512.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png -------------------------------------------------------------------------------- /MarkRight.xcodeproj/xcuserdata/xihe.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /MarkRight/MarkRight.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /MarkRight.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /MarkRight.xcodeproj/project.xcworkspace/xcuserdata/xihe.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octree/MarkRight/HEAD/MarkRight.xcodeproj/project.xcworkspace/xcuserdata/xihe.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /MarkRight.xcodeproj/xcuserdata/octree.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | -------------------------------------------------------------------------------- /MarkRight.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /MarkRight/Protocol/HTMLConversionProtocol.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MDInlineProtocol.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/11. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | protocol HTMLConversionProtocol { 12 | 13 | var htmlText: String { get } 14 | } 15 | -------------------------------------------------------------------------------- /MarkRight/Model/MarkdownNode.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MarkdownNode.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/11. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | 12 | indirect enum MarkdownNode { 13 | 14 | case container(ContainerNode) 15 | case leaf(BlockNode) 16 | } 17 | -------------------------------------------------------------------------------- /MarkRight/Extension/InlineLine+HTML.swift: -------------------------------------------------------------------------------- 1 | // 2 | // InlineLine+HTML.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | extension Array: HTMLConversionProtocol where Element: HTMLConversionProtocol { 12 | 13 | var htmlText: String { 14 | 15 | return map { $0.htmlText }.reduce("", +) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /MarkRight.xcodeproj/xcuserdata/xihe.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | MarkRight.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /MarkRight.xcodeproj/xcuserdata/octree.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | MarkRight.xcscheme_^#shared#^_ 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /MarkRight/Extension/MarkdownNode+HTML.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MarkdownNode+HTML.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | extension MarkdownNode: HTMLConversionProtocol { 12 | 13 | var htmlText: String { 14 | 15 | switch self { 16 | case .leaf(let l): 17 | return l.htmlText 18 | case .container(let c): 19 | return c.htmlText 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /MarkRight/Extension/CharacterSet+Extension.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CharacterSet+Extension.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/7. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | extension CharacterSet { 12 | 13 | func contains(_ c: Character) -> Bool { 14 | 15 | let scalars = String(c).unicodeScalars 16 | guard scalars.count == 1 else { 17 | return false 18 | } 19 | return contains(scalars.first!) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /MarkRight/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Cocoa 10 | 11 | @NSApplicationMain 12 | class AppDelegate: NSObject, NSApplicationDelegate { 13 | 14 | 15 | 16 | func applicationDidFinishLaunching(_ aNotification: Notification) { 17 | // Insert code here to initialize your application 18 | } 19 | 20 | func applicationWillTerminate(_ aNotification: Notification) { 21 | // Insert code here to tear down your application 22 | } 23 | 24 | 25 | } 26 | 27 | -------------------------------------------------------------------------------- /MarkRight/Model/InlineNode.swift: -------------------------------------------------------------------------------- 1 | // 2 | // InlineNode.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | typealias InlineLine = [InlineNode] 12 | 13 | enum InlineNode { 14 | 15 | case textualContent(String) 16 | // ![desc](url) 17 | case image(desc: String, url: String?) 18 | // `xxxxx` 19 | case codeSpan(String) 20 | // *xxx* 21 | case emphasis(String) 22 | // **xxx** 23 | case strongEmphasis(String) 24 | // [text](url) 25 | case inlineLink(text: String, url: String?) 26 | } 27 | -------------------------------------------------------------------------------- /MarkRight/Resource/css_injector.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | window.cssInjector = { 3 | 4 | inject: function inject(json) { 5 | let identifier = json["identifier"] 6 | let css = json["css"] 7 | var style = document.getElementById(identifier); 8 | if (!style) { 9 | var style = document.createElement('style'); 10 | style.type = 'text/css';style.setAttribute('id', identifier); 11 | } 12 | style.innerHTML = css; 13 | document.getElementsByTagName('head')[0].appendChild(style); 14 | }, 15 | 16 | remove: function remove(identifier) { 17 | 18 | var style = document.getElementById(identifier); 19 | if (style) { 20 | style.parentNode.removeChild(style); 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /MarkRightTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /MarkRight/Model/ContainerNode.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContainerNode.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | 12 | //typealias OrderedListItem = (ListItemLeafBlock) 13 | //typealias BulletListItem = (Character, ListItemLeafBlock) 14 | 15 | indirect enum ContainerNode { 16 | 17 | case inlineLines([InlineLine]) 18 | case listItemParagraph(main: InlineLine, sub: [ContainerNode]?) 19 | case listItemFencedCodeBlock(info: String?, lines: [String]?) 20 | case taskListItem(Bool, ContainerNode) 21 | case blockQuote([InlineLine]) 22 | // [bulletListItem] 23 | case bulletList([ContainerNode]) 24 | // [orderedListItem] 25 | case orderedList([ContainerNode]) 26 | case taskList([ContainerNode]) 27 | } 28 | -------------------------------------------------------------------------------- /MarkRight/Model/BlockNode.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BlockNode.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | enum TableDataAlignment { 12 | 13 | case left 14 | case center 15 | case right 16 | } 17 | 18 | indirect enum BlockNode { 19 | 20 | case h1(String) 21 | case h2(String) 22 | case h3(String) 23 | case h4(String) 24 | case h5(String) 25 | case h6(String) 26 | 27 | case fencedCodeBlock(info: String?, lines: [String]?) 28 | 29 | case thematicBreak 30 | case blankLines(Int) 31 | case paragraph([InlineLine]) 32 | case indentedChunk([String]) 33 | // [indentedChunk] 34 | case indentedCodeBlock([BlockNode]) 35 | case tableHeading(TableDataAlignment, [InlineNode]) 36 | case tableData(TableDataAlignment, [InlineNode]) 37 | case tableRow([BlockNode]) 38 | case table(BlockNode, [BlockNode]) 39 | } 40 | -------------------------------------------------------------------------------- /MarkRightTests/MarkRightTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MarkRightTests.swift 3 | // MarkRightTests 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import XCTest 10 | 11 | class MarkRightTests: XCTestCase { 12 | 13 | override func setUp() { 14 | super.setUp() 15 | // Put setup code here. This method is called before the invocation of each test method in the class. 16 | } 17 | 18 | override func tearDown() { 19 | // Put teardown code here. This method is called after the invocation of each test method in the class. 20 | super.tearDown() 21 | } 22 | 23 | func testExample() { 24 | // This is an example of a functional test case. 25 | // Use XCTAssert and related functions to verify your tests produce the correct results. 26 | } 27 | 28 | func testPerformanceExample() { 29 | // This is an example of a performance test case. 30 | self.measure { 31 | // Put the code you want to measure the time of here. 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /MarkRight/Extension/InlineNode+HTML.swift: -------------------------------------------------------------------------------- 1 | // 2 | // InlineNode+HTML.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | extension InlineNode: HTMLConversionProtocol { 12 | 13 | var htmlText: String { 14 | 15 | switch self { 16 | 17 | case .textualContent(let text): 18 | return text.htmlEscape() 19 | case let .image(desc, url): 20 | return """ 21 | \(desc.htmlEscape()) 22 | """ 23 | case let .codeSpan(text): 24 | 25 | return """ 26 | \(text.htmlEscape()) 27 | """ 28 | case let .emphasis(text): 29 | return """ 30 | \(text.htmlEscape()) 31 | """ 32 | case let .strongEmphasis(text): 33 | return """ 34 | \(text.htmlEscape()) 35 | """ 36 | case let .inlineLink(text, url): 37 | 38 | return """ 39 | \(text.htmlEscape()) 40 | """ 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MarkRight/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleVersion 22 | 1 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSAppTransportSecurity 26 | 27 | NSAllowsArbitraryLoads 28 | 29 | 30 | NSHumanReadableCopyright 31 | Copyright © 2018年 Octree. All rights reserved. 32 | NSMainStoryboardFile 33 | Main 34 | NSPrincipalClass 35 | NSApplication 36 | 37 | 38 | -------------------------------------------------------------------------------- /MarkRight/MarkdownParser/MarkdownParser.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MarkdownParser.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/11. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import FP 11 | import ParserCombinator 12 | 13 | /********************************************* 14 | ********** Markdown Parser *********** 15 | ********************************************/ 16 | 17 | /// block = containerBlock | leafBlock; 18 | let block = containerBlock <|> leafBlock 19 | private let markdownParser = { $0 } <^> block.many 20 | 21 | struct MarkdownParser { 22 | 23 | static func parse(_ text: String) -> Reply { 24 | return markdownParser.parse(Substring(text + "\n")) 25 | } 26 | 27 | static func toHTML(_ text: String) -> String? { 28 | 29 | let result = parse(text).map { rt -> String in 30 | let html = rt.map { $0.htmlText }.joined(separator: "\n") 31 | 32 | return """ 33 |
34 | \(html) 35 |
36 | """ 37 | } 38 | switch result { 39 | case let .done(_, html): 40 | return html 41 | default: 42 | return nil 43 | } 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MarkRight 2 | 3 | 4 | 5 | A simple Markdown Parser written in `swift`, Powered by [ParserCombinator](https://github.com/octree/ParserCombinator) 6 | 7 | 8 | 9 | ## Ugly Demo 10 | 11 | 12 | 13 | ![Demo](./Shots/demo1.png) 14 | 15 | 16 | 17 | ![Demo](./Shots/demo2.png) 18 | 19 | ## Supported grammars 20 | 21 | * Preliminaries 22 | - [x] Characters and lines 23 | - [x] Tabs 24 | - [x] Insecure characters 25 | * Blocks and inlines 26 | - [x] Precedence 27 | - [x] Container blocks and leaf blocks 28 | * Leaf blocks 29 | - [x] Thematic breaks 30 | - [x] ATX headings 31 | - [ ] Setext headings 32 | - [x] Indented code blocks 33 | - [x] Fenced code blocks 34 | - [ ] HTML blocks 35 | - [ ] Link reference definitions 36 | - [x] Paragraphs 37 | - [x] Blank lines 38 | - [x] Tables (extension) 39 | * Container blocks 40 | - [x] Block quotes 41 | - [x] List items 42 | - [x] Task list items (extension) 43 | - [x] Lists 44 | * Inlines 45 | - [x] Backslash escapes 46 | - [x] Entity and numeric character references 47 | - [x] Code spans 48 | - [x] Emphasis and strong emphasis 49 | - [ ] Strikethrough (extension) 50 | - [x] Links 51 | - [x] Images 52 | - [ ] Autolinks 53 | - [ ] Autolinks (extension) 54 | - [ ] Raw HTML 55 | - [x] Disallowed Raw HTML (extension) 56 | - [x] Hard line breaks 57 | - [x] Soft line breaks 58 | - [x] Textual content 59 | -------------------------------------------------------------------------------- /MarkRight/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "16x16", 5 | "idiom" : "mac", 6 | "filename" : "icon_16x16.png", 7 | "scale" : "1x" 8 | }, 9 | { 10 | "size" : "16x16", 11 | "idiom" : "mac", 12 | "filename" : "icon_16x16@2x.png", 13 | "scale" : "2x" 14 | }, 15 | { 16 | "size" : "32x32", 17 | "idiom" : "mac", 18 | "filename" : "icon_32x32.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "32x32", 23 | "idiom" : "mac", 24 | "filename" : "icon_32x32@2x.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "128x128", 29 | "idiom" : "mac", 30 | "filename" : "icon_128x128.png", 31 | "scale" : "1x" 32 | }, 33 | { 34 | "size" : "128x128", 35 | "idiom" : "mac", 36 | "filename" : "icon_128x128@2x.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "256x256", 41 | "idiom" : "mac", 42 | "filename" : "icon_256x256.png", 43 | "scale" : "1x" 44 | }, 45 | { 46 | "size" : "256x256", 47 | "idiom" : "mac", 48 | "filename" : "icon_256x256@2x.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "512x512", 53 | "idiom" : "mac", 54 | "filename" : "icon_512x512.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "512x512", 59 | "idiom" : "mac", 60 | "filename" : "icon_512x512@2x.png", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } -------------------------------------------------------------------------------- /MarkRight/MarkdownParser/ListItems.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ListItems.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/11. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import FP 11 | import ParserCombinator 12 | 13 | /********************************************* 14 | ********** List Items Parser *********** 15 | ********************************************/ 16 | 17 | /// listItemParagraph = inlineLine, {4 * space, inlineLine}; 18 | 19 | let listItemIndentation = space.repeat(4)// <|> string("\t") 20 | 21 | func listItemParagraph(depth: Int) -> MDParser { 22 | 23 | let indentation = listItemIndentation.repeat(depth) 24 | 25 | let transformer: (InlineLine) -> MDParser = { 26 | inline in 27 | 28 | let special = listItemFencedCodeBlock(depth: depth) <|> depthOrderedList(depth: depth + 1) <|> depthBulletList(depth: depth + 1) <|> depthTaskList(depth: depth + 1) 29 | let lines = ContainerNode.inlineLines <^> (indentation *> inlineLine).difference(special).many1 30 | let elt = blankLine.optional *> (special <|> lines) 31 | return curry(ContainerNode.listItemParagraph)(inline) <^> elt.many1.optional 32 | } 33 | 34 | return inlineLine >>- transformer 35 | } 36 | 37 | /// listItemFencedCodeBlock = "```", [infoString], lineEnding, 38 | /// {4 * space, line}, 39 | /// 4 * space, "```", lineEnding; 40 | func listItemFencedCodeBlock(depth: Int) -> MDParser { 41 | 42 | let indentation = listItemIndentation.repeat(depth) 43 | 44 | return curry(ContainerNode.listItemFencedCodeBlock) <^> (indentation *> string("```") *> textualContent.optional <* lineEnding) <*> 45 | (indentation *> line).difference(indentation *> string("```")).many <* indentation <* string("```") <* lineEnding 46 | } 47 | 48 | -------------------------------------------------------------------------------- /MarkRight/Resource/Test.md: -------------------------------------------------------------------------------- 1 | # 微小的工作 2 | 3 | - [三件小事](#三件小事) 4 | - [一点成绩](#一点成绩) 5 | - [人生的经验](#人生的经验) 6 | - [没香港记者跑得快的 Swift](#没香港记者跑得快的Swift) 7 | - [并不 Naive 的香港记者](#并不Naive的香港记者) 8 | - [嵌套](#嵌套) 9 | - [Task List](#TaskList) 10 | - [Table](#Table) 11 | 12 | 13 | ## 三件小事 14 | 15 | 1. 一个,确立了*社会主义市场经济* 16 | 2. 把 [邓小平的理论](https://zh.wikipedia.org/wiki/%E9%82%93%E5%B0%8F%E5%B9%B3%E7%90%86%E8%AE%BA) 列入了党章 17 | 3. 第三个,就是我们知道的`三个代表` 18 | 19 | 20 | ## 一点成绩 21 | 22 | * 军队一律不得经商 23 | + 九八年的抗洪也是很重要地 24 | 25 | 26 | ## 人生的经验 27 | 28 | > 我今天是作为一个长者给你们讲的。 29 | > 我不是新闻工作者,但是我见得太多了。 30 | > 我……我有这个必要好告诉你们一点,人生的经验。 31 | 32 | 33 | ## 没香港记者跑得快的 Swift 34 | 35 | ```swift 36 | struct Parser { 37 | 38 | typealias Stream = Substring 39 | let parse: (Stream) -> (Result, Stream)? 40 | } 41 | 42 | /// atxHeading1 = "#", space, textualContent, atxClosingSequence; 43 | let atxHeading1 = BlockNode.h1 <^> (string("#") *> space *> textualContent <* space.many.optional <* lineEnding) 44 | 45 | ``` 46 | 47 | 48 | ## 并不 Naive 的香港记者 49 | 50 | ![真正的粉丝](https://2-im.guokr.com/sFp7eZ-PiCYjlJ7nNtnu7nusCu2psuY_BKrelYER7SL0AQAAAQIAAEdJ.gif) 51 | 52 | 53 | ## 嵌套 54 | 55 | 1. 小明的`爷爷` 56 | * 小明的`爸爸` 57 | + 这是`小明` 58 | 59 | ```javascript 60 | // 小明是傻逼,只会 JS 61 | console.log("Javascript === Shit") 62 | ``` 63 | 2. `创世`节点,没有爸爸 64 | 3. 学 `PHP` 并不能救中国 65 | ```php 66 | echo "PHP 是世界上最好的语言" 67 | ``` 68 | 69 | 70 | ## Task List 71 | 72 | 73 | - [x] Parser Combinator 74 | - [x] Generic String Parser 75 | - [x] Inline Parser 76 | - [ ] Block Parser 77 | - [ ] Container Parser 78 | 79 | 80 | 81 | ## Table 82 | 83 | ------ 84 | 85 | | Programming Language | Ratings | Change | 86 | | -------------- |:-------------:| -----:| 87 | | Swift | 1.534 % | 1.34% | 88 | | Kotlin | 0.32% | 1.45% | 89 | | Scala | 2.1234% | 0.233333% | 90 | | Haskell | 0.233333333% | 0.123% | 91 | | Objective-C | 3.25% | -1.02% | 92 | 93 | 94 | -------------------------------------------------------------------------------- /MarkRight/Extension/ContainerNode+HTML.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContainerNode+HTML.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | 12 | extension ContainerNode: HTMLConversionProtocol { 13 | 14 | var htmlText: String { 15 | switch self { 16 | 17 | case let .inlineLines(lines): 18 | return """ 19 |

\(lines.htmlText)

20 | """ 21 | case let .blockQuote(lines): 22 | return """ 23 |

\(lines.map { $0.htmlText }.joined(separator: "
"))

24 | """ 25 | case let .bulletList(items): 26 | return """ 27 |
    28 | \(items.htmlText) 29 |
30 | """ 31 | case let .orderedList(item): 32 | return """ 33 |
    34 | \(item.htmlText) 35 |
36 | """ 37 | case let .listItemParagraph(main, nodes): 38 | 39 | let son = nodes.map { 40 | return """ 41 | \($0.htmlText) 42 | """ 43 | } 44 | 45 | return """ 46 |
  • \(main.htmlText)
  • 47 | \(son ?? "") 48 | """ 49 | case let .listItemFencedCodeBlock(info, lines): 50 | let code = (lines ?? []).map { $0.htmlEscape() }.joined(separator: "\n") 51 | 52 | return """ 53 |
    \(code)
    54 | """ 55 | case let .taskListItem(checked, node): 56 | 57 | guard case let .listItemParagraph(main, sons) = node else { 58 | return "" 59 | } 60 | let son = sons.map { 61 | return """ 62 | \($0.htmlText) 63 | """ 64 | } 65 | return """ 66 |
  • 67 | 68 | 69 | \(main.htmlText) 70 |
  • 71 | \(son ?? "") 72 | """ 73 | case let .taskList(nodes): 74 | return """ 75 |
      76 | \(nodes.htmlText) 77 |
    78 | """ 79 | } 80 | 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /MarkRight/HTMLEntities/ParseError.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright IBM Corporation 2016, 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /// Enums used to delineate the different kinds of parse errors 18 | /// that may be encountered during HTML unescaping. See 19 | /// https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 20 | /// for an explanation of the different parse errors. 21 | public enum ParseError: Error { 22 | /// "If that number is one of the numbers in the first column of the following 23 | /// table, then this is a parse error." 24 | case DeprecatedNumericReference(String) 25 | 26 | /// "[I]f the number is in the range 0x0001 to 0x0008, 0x000D to 0x001F, 0x007F 27 | /// to 0x009F, 0xFDD0 to 0xFDEF, or is one of 0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 28 | /// 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 29 | /// 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 30 | /// 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 31 | /// 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, or 0x10FFFF, then 32 | /// this is a parse error." 33 | case DisallowedNumericReference(String) 34 | 35 | /// This should NEVER be hit in code execution. If this error is thrown, then 36 | /// decoder has faulty logic 37 | case IllegalArgument(String) 38 | 39 | /// "[I]f the characters after the U+0026 AMPERSAND character (&) consist of 40 | /// a sequence of one or more alphanumeric ASCII characters followed by a 41 | /// U+003B SEMICOLON character (;), then this is a parse error." 42 | case InvalidNamedReference(String) 43 | 44 | /// "If no characters match the range, then don't consume any characters 45 | /// (and unconsume the U+0023 NUMBER SIGN character and, if appropriate, 46 | /// the X character). This is a parse error; nothing is returned." 47 | case MalformedNumericReference(String) 48 | 49 | /// "[I]f the next character is a U+003B SEMICOLON, consume that too. 50 | /// If it isn't, there is a parse error." 51 | case MissingSemicolon(String) 52 | 53 | /// "[I]f the number is in the range 0xD800 to 0xDFFF or is greater 54 | /// than 0x10FFFF, then this is a parse error." 55 | case OutsideValidUnicodeRange(String) 56 | } 57 | -------------------------------------------------------------------------------- /MarkRight/Resource/theme-solarized-dark.css: -------------------------------------------------------------------------------- 1 | 2 | html, body, * { 3 | font-size: 16px; 4 | color: #B6C2D3; 5 | margin: 0; 6 | padding: 0; 7 | font-family: 'Open Sans', sans-serif; 8 | } 9 | html, body { 10 | background: #1D202B; 11 | } 12 | 13 | *, *:before, *:after { 14 | box-sizing: border-box; 15 | } 16 | 17 | html { 18 | padding: 1em; 19 | } 20 | 21 | /* highlight: #3FC6B4 */ 22 | /* code backg: #052128 */ 23 | 24 | h1 { 25 | font-size: 1.6em; 26 | } 27 | 28 | h2 { 29 | font-size: 1.4em; 30 | border-bottom: solid 1px #66818A; 31 | } 32 | 33 | h3 { 34 | font-size: 1.3em; 35 | } 36 | 37 | h4 { 38 | font-size: 1.25em; 39 | } 40 | 41 | h5 { 42 | font-size: 1.17em; 43 | } 44 | 45 | h6 { 46 | font-size: 1.1em; 47 | } 48 | 49 | h1, h2, h3, h4, h5, h6 { 50 | color: #FFFFFB; 51 | } 52 | 53 | hr { 54 | display: block; 55 | height: 1px; 56 | border: 0; 57 | border-top: 1px solid #66818A; 58 | margin: 1em 0; 59 | padding: 0; 60 | } 61 | 62 | pre, ul, ol, blockquote, p { 63 | 64 | margin-top: 0.5em; 65 | margin-bottom: 0.5em; 66 | } 67 | 68 | li { 69 | margin-bottom: 0.3em; 70 | } 71 | 72 | pre { 73 | background-color: #052128; 74 | padding: 10px 18px; 75 | border-radius: 4px; 76 | } 77 | 78 | code { 79 | background-color: #052128; 80 | padding: 2px 4px; 81 | border-radius: 2px; 82 | } 83 | 84 | strong { 85 | font-weight: bold; 86 | } 87 | 88 | em { 89 | font-weight: normal; 90 | font-style:italic; 91 | } 92 | 93 | 94 | ul { 95 | list-style-position: inside; 96 | } 97 | 98 | ol { 99 | list-style-position: inside; 100 | } 101 | 102 | 103 | a { 104 | color: #3FC6B4; 105 | } 106 | 107 | div.oct-sub { 108 | margin-left: 1.2em; 109 | } 110 | 111 | blockquote { 112 | margin: 0; 113 | display: block; 114 | border-left: solid 2px #3FC6B4; 115 | padding: 8px 10px; 116 | } 117 | 118 | table { 119 | display: table; 120 | width: 100%; 121 | border-collapse: collapse; 122 | border-spacing: 0; 123 | overflow: auto; 124 | line-height: 1.5; 125 | word-wrap: break-word; 126 | border-color: solid 1px #66818A; 127 | /* background-color: #586D75; */ 128 | } 129 | 130 | thead { 131 | display: table-header-group; 132 | vertical-align: middle; 133 | border-color: inherit; 134 | } 135 | 136 | tbody { 137 | display: table-row-group; 138 | vertical-align: middle; 139 | border-color: inherit; 140 | } 141 | 142 | th { 143 | font-weight: bold; 144 | padding: 6px 12px; 145 | border: 1px solid #66818A; 146 | } 147 | 148 | td { 149 | padding: 6px 12px; 150 | border: 1px solid #66818A; 151 | } 152 | 153 | tr:nth-child(2n) { 154 | /* background-color: #839496; */ 155 | } 156 | 157 | -------------------------------------------------------------------------------- /MarkRight/MarkdownParser/Inlines.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Inlines.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/11. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import FP 11 | import ParserCombinator 12 | 13 | /********************************************* 14 | ********** Inlines *********** 15 | ********************************************/ 16 | 17 | 18 | /// textualContent = characterWithoutLinebreak, {characterWithoutLinebreak}; 19 | let textualContent = { String($0) } <^> characterWithoutLinebreak.many1 20 | 21 | /// softLineBreak = "\n"; 22 | let softLineBreak = String.init <^> character { $0 == "\n" } 23 | 24 | /// hardLineBreak = (" " | "\\"), "\n"; 25 | let hardLineBreak = curry({ $0 + $1 }) <^> (string(" ") <|> string("\\")) <*> string("\n") 26 | 27 | /// lineBreak = hardLineBreak | softLineBreak; 28 | let lineBreak = hardLineBreak <|> softLineBreak 29 | 30 | 31 | /// codeSpan = "`", textualContent, "`"; 32 | let codeSpan = InlineNode.codeSpan <^> (string("`") *> stringExcept(["\n", "\r", "`"]) <* string("`")) 33 | 34 | /// emphasis = "*", textualContent, "*"; 35 | let emphasis = InlineNode.emphasis <^> (string("*") *> stringExcept(["\n", "\r", "*"]) <* string("*")) 36 | 37 | /// strongEmphasis = "**", textualContent, "**"; 38 | let strongEmphasis = InlineNode.strongEmphasis <^> (string("**") *> stringExcept(["\n", "\r", "*"]) <* string("**")) 39 | 40 | /// linkText = "[", textualContent, "]"; 41 | let linkText = string("[") *> stringExcept(["\n", "\r", "]"]) <* string("]") 42 | 43 | /// linkLabel = "[", nonWhitespaceCharacter, 998 * [nonWhitespaceCharacter], "]" 44 | 45 | /// (*Second Option*) 46 | //linkDestination = "<", nonWhitespaceCharacter, {nonWhitespaceCharacter}, ">"; 47 | let linkDestination = { String($0) } <^> nonWhitespaceCharacter.difference(string(")")).many1 48 | 49 | /// inlineLink = linkText, "(", [whitespace], [linkDestination], [whitespace, linkTitle], [whitespace], ")"; 50 | let inlineLink = curry(InlineNode.inlineLink) <^> linkText <*> ( string("(") *> linkDestination.optional <* string(")")) 51 | 52 | /// imageDescription = "![", textualContent, "]"; 53 | 54 | let imageDescription = string("![") *> stringExcept(["\n", "\r", "]"]).otherwise("") <* string("]") 55 | 56 | /// image = imageDescription, "(", [linkDestination], ")"; 57 | let image = curry(InlineNode.image) <^> imageDescription <*> (string("(") *> linkDestination.optional <* string(")")) 58 | 59 | /// inlineWithoutLineBreak = codeSpan | emphasis | strongEmphasis | inlineLink | fullReferenceLink | image | textualContent; 60 | 61 | 62 | let correctTextualContent = { InlineNode.textualContent(String($0)) } <^> (characterWithoutLinebreak.difference(codeSpan <|> strongEmphasis <|> emphasis <|> inlineLink <|> image)).many1 63 | let inlineWithoutLineBreak = codeSpan <|> strongEmphasis <|> emphasis <|> inlineLink <|> image <|> correctTextualContent 64 | 65 | /// inlineLine = inlineWithoutLineBreak, {inlineWithoutLineBreak}, lineBreak; 66 | let inlineLine = inlineWithoutLineBreak.many1 <* lineBreak 67 | 68 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/xcode,macos,swift,carthage,cocoapods,swiftpackagemanager 3 | 4 | ### Carthage ### 5 | # Carthage 6 | # 7 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 8 | Carthage/Checkouts 9 | 10 | Carthage/Build 11 | 12 | ### CocoaPods ### 13 | ## CocoaPods GitIgnore Template 14 | 15 | # CocoaPods - Only use to conserve bandwidth / Save time on Pushing 16 | # - Also handy if you have a large number of dependant pods 17 | # - AS PER https://guides.cocoapods.org/using/using-cocoapods.html NEVER IGNORE THE LOCK FILE 18 | Pods/ 19 | 20 | ### macOS ### 21 | *.DS_Store 22 | .AppleDouble 23 | .LSOverride 24 | 25 | # Icon must end with two \r 26 | Icon 27 | 28 | # Thumbnails 29 | ._* 30 | 31 | # Files that might appear in the root of a volume 32 | .DocumentRevisions-V100 33 | .fseventsd 34 | .Spotlight-V100 35 | .TemporaryItems 36 | .Trashes 37 | .VolumeIcon.icns 38 | .com.apple.timemachine.donotpresent 39 | 40 | # Directories potentially created on remote AFP share 41 | .AppleDB 42 | .AppleDesktop 43 | Network Trash Folder 44 | Temporary Items 45 | .apdisk 46 | 47 | ### Swift ### 48 | # Xcode 49 | # 50 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 51 | 52 | ## Build generated 53 | build/ 54 | DerivedData/ 55 | 56 | ## Various settings 57 | *.pbxuser 58 | !default.pbxuser 59 | *.mode1v3 60 | !default.mode1v3 61 | *.mode2v3 62 | !default.mode2v3 63 | *.perspectivev3 64 | !default.perspectivev3 65 | xcuserdata/ 66 | 67 | ## Other 68 | *.moved-aside 69 | *.xccheckout 70 | *.xcscmblueprint 71 | 72 | ## Obj-C/Swift specific 73 | *.hmap 74 | *.ipa 75 | *.dSYM.zip 76 | *.dSYM 77 | 78 | ## Playgrounds 79 | timeline.xctimeline 80 | playground.xcworkspace 81 | 82 | # Swift Package Manager 83 | # 84 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 85 | # Packages/ 86 | # Package.pins 87 | .build/ 88 | 89 | # CocoaPods - Refactored to standalone file 90 | 91 | # Carthage - Refactored to standalone file 92 | 93 | # fastlane 94 | # 95 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 96 | # screenshots whenever they are needed. 97 | # For more information about the recommended setup visit: 98 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 99 | 100 | fastlane/report.xml 101 | fastlane/Preview.html 102 | fastlane/screenshots 103 | fastlane/test_output 104 | 105 | ### SwiftPackageManager ### 106 | Packages 107 | xcuserdata 108 | *.xcodeproj 109 | ### Xcode ### 110 | # Xcode 111 | # 112 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 113 | 114 | ## Build generated 115 | 116 | ## Various settings 117 | 118 | ## Other 119 | 120 | ### Xcode Patch ### 121 | *.xcodeproj/* 122 | !*.xcodeproj/project.pbxproj 123 | !*.xcodeproj/xcshareddata/ 124 | !*.xcworkspace/contents.xcworkspacedata 125 | /*.gcno 126 | 127 | 128 | # End of https://www.gitignore.io/api/xcode,macos,swift,carthage,cocoapods,swiftpackagemanager -------------------------------------------------------------------------------- /MarkRight/MarkdownParser/ContainerItems.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContainerItems.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import FP 11 | import ParserCombinator 12 | 13 | 14 | /********************************************* 15 | ********** Container Items Parser *********** 16 | ********************************************/ 17 | 18 | /// blockQuoteMarker = ">", [" "]; 19 | let blockQuoteMarker = string(">") <* string(" ").optional 20 | // blockQuote = blockQuteMarker, inlineLine, {blockQuteMarker, inlineLine}; (*2. Laziness is ignored for now*) 21 | let blockQuote = ContainerNode.blockQuote <^> (blockQuoteMarker *> inlineLine).many1 22 | 23 | let taskListUncheckMarker = { _ in curry(ContainerNode.taskListItem)(false) } <^> string("- [ ] ") 24 | let taskListCheckedMarker = { _ in curry(ContainerNode.taskListItem)(true) } <^> string("- [x] ") 25 | let taskListMarker = taskListUncheckMarker <|> taskListCheckedMarker 26 | 27 | 28 | /// bulletListMarker = "-"; (*plus and star ignored for now*) 29 | 30 | let bulletListMarker = character { "+-*".contains($0) }.difference(taskListMarker) 31 | func depthBulletListMarker(depth: Int) -> MDParser { 32 | 33 | let indentation = space.repeat(4 * depth - 4) 34 | return indentation *> bulletListMarker 35 | } 36 | 37 | /// orderedListMarker = digit, "." | ")"; 38 | let digits = character { CharacterSet.decimalDigits.contains($0) }.many1 39 | let orderedListMarker = digits <* string(".") 40 | func depthOrderedListMarker(depth: Int) -> MDParser<[Character]> { 41 | 42 | let indentation = listItemIndentation.repeat(depth - 1) 43 | return indentation *> orderedListMarker 44 | } 45 | 46 | func depthTaskListItem(depth: Int) -> MDParser { 47 | let indentation = listItemIndentation.repeat(depth - 1) 48 | return (indentation *> taskListMarker) <*> listItemParagraph(depth: depth) 49 | } 50 | 51 | func depthBulletListItem(depth: Int) -> MDParser { 52 | 53 | let indentation = listItemIndentation.repeat(depth - 1) 54 | return indentation *> bulletListMarker *> space *> listItemParagraph(depth: depth) 55 | } 56 | 57 | /// orderedListItem = orderedListMarker, 2 * space, listItemLeafBlock; 58 | func depthOrderedListItem(depth: Int) -> MDParser { 59 | 60 | let indentation = listItemIndentation.repeat(depth - 1) 61 | return indentation *> orderedListMarker *> space *> listItemParagraph(depth: depth) 62 | } 63 | 64 | /// orderedList = orderedListItem, [blankLine], {orderedListItem, [blankLine]}; 65 | func depthOrderedList(depth: Int) -> MDParser { 66 | 67 | return ContainerNode.orderedList <^> (depthOrderedListItem(depth: depth) <* blankLine.optional).many1 68 | } 69 | 70 | /// bulletList = bulletListItem, [blankLine], {bulletListItem, [blankLine]}; 71 | func depthBulletList(depth: Int) -> MDParser { 72 | 73 | return ContainerNode.bulletList <^> (depthBulletListItem(depth: depth) <* blankLine.optional).many1 74 | } 75 | 76 | func depthTaskList(depth: Int) -> MDParser { 77 | 78 | return ContainerNode.taskList <^> (depthTaskListItem(depth: depth) <* blankLine.optional).many1 79 | } 80 | 81 | //containerBlock = blockQuote; 82 | let containerBlock = MarkdownNode.container <^> (blockQuote <|> depthOrderedList(depth: 1) <|> depthBulletList(depth: 1) <|> depthTaskList(depth: 1)) 83 | -------------------------------------------------------------------------------- /MarkRight/Extension/BlockNode+HTML.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BlockNode+HTML.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | extension TableDataAlignment: HTMLConversionProtocol { 12 | 13 | var htmlText: String { 14 | 15 | switch self { 16 | case .center: 17 | 18 | return """ 19 | align="center" 20 | """ 21 | case .left: 22 | 23 | return """ 24 | align="left" 25 | """ 26 | case .right: 27 | 28 | return """ 29 | align="right" 30 | """ 31 | } 32 | } 33 | } 34 | 35 | private func headerHTMLString(text: String, level: Int) -> String { 36 | 37 | let id = String(text.filter { !NSCharacterSet.whitespaces.contains($0) && $0 != "\"" }) 38 | return """ 39 | \(text) 40 | """ 41 | } 42 | 43 | extension BlockNode: HTMLConversionProtocol { 44 | 45 | var htmlText: String { 46 | switch self { 47 | case .h1(let h): 48 | return headerHTMLString(text: h.htmlEscape(), level: 1) 49 | case .h2(let h): 50 | return headerHTMLString(text: h.htmlEscape(), level: 2) 51 | case .h3(let h): 52 | return headerHTMLString(text: h.htmlEscape(), level: 3) 53 | case .h4(let h): 54 | return headerHTMLString(text: h.htmlEscape(), level: 4) 55 | case .h5(let h): 56 | return headerHTMLString(text: h.htmlEscape(), level: 5) 57 | case .h6(let h): 58 | return headerHTMLString(text: h.htmlEscape(), level: 6) 59 | case let .fencedCodeBlock(info, lines): 60 | let code = (lines ?? []).map{ $0.htmlEscape() }.joined(separator: "\n") 61 | return """ 62 |
    \(code)
    63 | """ 64 | case .thematicBreak: 65 | return """ 66 |
    67 | """ 68 | case .blankLines(_): 69 | return """ 70 | """ 71 | case let .paragraph(lines): 72 | return """ 73 |

    74 | \(lines.htmlText) 75 |

    76 | """ 77 | case let .indentedChunk(strings): 78 | return """ 79 | \(strings.map { $0.htmlEscape() }.joined()) 80 | """ 81 | case let .indentedCodeBlock(chunks): 82 | return """ 83 | \(chunks.htmlText) 84 | """ 85 | case let .tableHeading(align, inlines): 86 | 87 | return """ 88 | \(inlines.htmlText) 89 | """ 90 | case let .tableData(align, inlines): 91 | return """ 92 | \(inlines.htmlText) 93 | """ 94 | case let .tableRow(items): 95 | return """ 96 | 97 | \(items.htmlText) 98 | 99 | """ 100 | case let .table(thr, tdr): 101 | return """ 102 | 103 | 104 | \(thr.htmlText) 105 | 106 | 107 | \(tdr.htmlText) 108 | 109 |
    110 | """ 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /MarkRight/MarkdownParser/GenericStringTerms.swift: -------------------------------------------------------------------------------- 1 | // 2 | // GenericStringTerms.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/11. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import FP 11 | import ParserCombinator 12 | 13 | /********************************************* 14 | ********** Generic String Terms *********** 15 | ********************************************/ 16 | 17 | public typealias MDParser = Parser 18 | 19 | func not(_ parser: MDParser) -> MDParser { 20 | 21 | return MDParser { 22 | input in 23 | var chs = [Character]() 24 | var remainder = input 25 | while let first = remainder.first, case .fail = parser.parse(remainder) { 26 | chs.append(first) 27 | remainder = remainder.dropFirst() 28 | } 29 | return .done(remainder, Substring(chs)) 30 | } 31 | } 32 | 33 | func stringExcept(_ chs: [Character]) -> MDParser { 34 | 35 | return { String($0) } <^> character { !chs.contains($0) }.many1 36 | } 37 | 38 | /// 换行符 39 | 40 | /// newline = U+000A; 41 | let newLine = character { $0 == "\n" } 42 | 43 | /// 回车 44 | /// carriageReturn = U+000D; 45 | let carriageReturn = character { $0 == "\r" } 46 | 47 | /// 行尾 48 | /// lineEnding = newline | carriageReturn; 49 | let lineEnding = newLine <|> carriageReturn 50 | 51 | /// 空格 52 | /// space = U+0020; 53 | let space = character { $0 == " " } 54 | 55 | /// TAB:水平制表符 56 | /// tab = U+0009; 57 | let tab = character { $0 == "\t" } 58 | 59 | /// 空白行 60 | /// {(space | tab)}, lineEnding; 61 | let blankLine = (space <|> tab).many.followed(by: lineEnding) 62 | 63 | /// 垂直制表 64 | /// lineTabulation = U+000B; 65 | let lineTabulation = character { $0 == "\u{000B}" } 66 | 67 | /// 换页符 68 | /// formFeed = U+000C; 69 | let formFeed = character { $0 == "\u{000C}" } 70 | 71 | /// 空白字符 72 | /// whitespaceCharacter = newline | carriageReturn | space | tab | lineTabulation | formFeed; 73 | let whiteSpaceCharacter = newLine <|> carriageReturn <|> space <|> tab <|> lineTabulation <|> formFeed 74 | 75 | /// 空白区域 76 | /// whitespace = whitespaceCharacter, {whitespaceCharacter}; 77 | let whiteSpace = { String($0) } <^> whiteSpaceCharacter.many1 78 | 79 | /// (*any code point in the Unicode Zs class*) | tab | carriageReturn | newline | formFeed; 80 | let unicodeWhitespaceCharacter = character { CharacterSet.whitespaces.contains($0) } 81 | 82 | /// unicodeWhitespace = unicodeWhitespaceCharacter, {unicodeWhitespaceCharacter}; 83 | let unicodeWhitespace = { String($0)} <^> unicodeWhitespaceCharacter.many1 84 | 85 | /// nonWhitespaceCharacter = (*any character that is not a whitespaceCharacter*); 86 | let nonWhitespaceCharacter = character { !CharacterSet.whitespacesAndNewlines.contains($0) } 87 | 88 | 89 | /// asciiPunctuationCharacter = "!" | '"' | "#" | "$" | "%" | "&" | "'" | "(" | ")" | "*" | "+" | "," | "-" | "." | "/" | ":" | ";" | "<" | "=" | ">" | "?" | "@" | "[" | "\\" | "]" | "^" | "_" | "`" | "{" | "|" | "}" | "~"; 90 | let asciiPunctuationCharacter = character { 91 | "!|#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".contains($0) 92 | } 93 | 94 | 95 | /// punctuationCharacter = asciiPunctuationCharacter | (*anything in the Unicode Classes Pc, Pd, Pe, Pf, Pi, Po, Ps*) 96 | let punctuationCharacter = asciiPunctuationCharacter <|> character { 97 | 98 | NSCharacterSet.punctuationCharacters.contains($0) 99 | } 100 | 101 | /// characterWithoutLinebreak = (*Unicode code point except newline (U+000A) and carriage return (U+000D)*); 102 | let characterWithoutLinebreak = character { $0 != "\n" && $0 != "\r" } 103 | 104 | /// nonBlankLine = nonWhitespaceCharacter, {characterWithoutLinebreak}, lineEnding; 105 | private func nonBlankLineJoiner(ch: Character, s: [Character]?, e: Character) -> String { 106 | 107 | return String([ch] + (s ?? []) + [e]) 108 | } 109 | 110 | let nonBlankLine = curry(nonBlankLineJoiner) <^> nonWhitespaceCharacter <*> characterWithoutLinebreak.many <*> lineEnding 111 | 112 | let line = { String($0) } <^> character { $0 != "\n" && $0 != "\r" }.many <* lineEnding 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /MarkRight/HTMLEntities/Utilities.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright IBM Corporation 2016, 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | extension Dictionary { 18 | /// Union of two dictionaries 19 | /// Note: The in the argument will override 20 | /// the current dictionary's if the keys match 21 | func updating(_ dict: [Key: Value]) -> [Key: Value] { 22 | var newDict = self 23 | 24 | for (key, value) in dict { 25 | newDict[key] = value 26 | } 27 | 28 | return newDict 29 | } 30 | } 31 | 32 | extension Dictionary where Value: Hashable { 33 | /// Invert a dictionary: -> 34 | /// Note: Does not check for uniqueness among values 35 | func inverting(_ pick: (Key, Key) -> Key = { existingValue, newValue in 36 | return newValue 37 | }) -> [Value: Key] { 38 | var inverseDict: [Value: Key] = [:] 39 | 40 | for (key, value) in self { 41 | if let existing = inverseDict[value] { 42 | inverseDict[value] = pick(existing, key) 43 | } 44 | else { 45 | inverseDict[value] = key 46 | } 47 | } 48 | 49 | return inverseDict 50 | } 51 | } 52 | 53 | extension UInt32 { 54 | var isAlphaNumeric: Bool { 55 | // unicode values of [0-9], [A-Z], and [a-z] 56 | return self.isNumeral || 0x41...0x5A ~= self || 0x61...0x7A ~= self 57 | } 58 | 59 | var isAmpersand: Bool { 60 | // unicode value of & 61 | return self == 0x26 62 | } 63 | 64 | var isASCII: Bool { 65 | // Less than 0x80 66 | return self < 0x80 67 | } 68 | 69 | /// https://www.w3.org/International/questions/qa-escapes#use 70 | var isAttributeSyntax: Bool { 71 | // unicode values of [", '] 72 | return self == 0x22 || self == 0x27 73 | } 74 | 75 | var isDisallowedReference: Bool { 76 | // unicode values of [0x1-0x8], [0xD-0x1F], [0x7F-0x9F], [0xFDD0-0xFDEF], 77 | // 0xB, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 78 | // 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 79 | // 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 80 | // 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 81 | // 0x10FFFE, and 0x10FFFF 82 | return disallowedNumericReferences.contains(self) 83 | } 84 | 85 | var isHash: Bool { 86 | // unicode value of # 87 | return self == 0x23 88 | } 89 | 90 | var isHexNumeral: Bool { 91 | // unicode values of [0-9], [A-F], and [a-f] 92 | return isNumeral || 0x41...0x46 ~= self || 0x61...0x66 ~= self 93 | } 94 | 95 | var isNumeral: Bool { 96 | // unicode values of [0-9] 97 | return 0x30...0x39 ~= self 98 | } 99 | 100 | /// https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 101 | var isReplacementCharacterEquivalent: Bool { 102 | // UInt32 values of [0xD800-0xDFFF], (0x10FFFF-∞] 103 | return 0xD800...0xDFFF ~= self || 0x10FFFF < self 104 | } 105 | 106 | var isSafeASCII: Bool { 107 | return self.isASCII && !self.isAttributeSyntax && !self.isTagSyntax 108 | } 109 | 110 | var isSemicolon: Bool { 111 | // unicode value of ; 112 | return self == 0x3B 113 | } 114 | 115 | /// https://www.w3.org/International/questions/qa-escapes#use 116 | var isTagSyntax: Bool { 117 | // unicode values of [&, < , >] 118 | return self.isAmpersand || self == 0x3C || self == 0x3E 119 | } 120 | 121 | var isX: Bool { 122 | // unicode values of X and x 123 | return self == 0x58 || self == 0x78 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /MarkRight/ViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/12. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Cocoa 10 | import WebKit 11 | import FP 12 | 13 | private let theme: String = { 14 | 15 | let path = Bundle.main.path(forResource: "theme", ofType: "css")! 16 | return try! String(contentsOfFile: path) 17 | }() 18 | 19 | private let hjs: String = { 20 | let path = Bundle.main.path(forResource: "highlight", ofType: "js")! 21 | return try! String(contentsOfFile: path) 22 | }() 23 | 24 | private func previewHTMLGen(theme: String, scale: CGFloat, content: String) -> String { 25 | return """ 26 | 27 | 28 | 29 | 30 | 33 | 36 | 48 | 49 | 50 | \(content) 51 | 52 | 53 | 54 | 55 | """ 56 | } 57 | 58 | class ViewController: NSViewController, NSTextStorageDelegate, WKNavigationDelegate, NSTextViewDelegate { 59 | 60 | var textView: NSTextView { 61 | 62 | return scrollView.documentView as! NSTextView 63 | } 64 | 65 | var offsetRatio: CGFloat { 66 | 67 | let height = scrollView.documentView!.frame.size.height 68 | let viewHeight = scrollView.frame.size.height 69 | var outH = height - viewHeight 70 | 71 | if outH < 0 { 72 | outH = 0 73 | } 74 | return scrollView.contentView.bounds.origin.y / outH 75 | } 76 | 77 | var testText: String { 78 | 79 | let path = Bundle.main.path(forResource: "Test", ofType: "md")! 80 | return try! String(contentsOfFile: path) 81 | } 82 | 83 | @IBOutlet weak var webView: WKWebView! 84 | @IBOutlet weak var scrollView: NSScrollView! 85 | 86 | 87 | override func viewDidLoad() { 88 | super.viewDidLoad() 89 | 90 | view.wantsLayer = true 91 | view.layer?.backgroundColor = NSColor(white: 0.8, alpha: 1).cgColor 92 | configTextView() 93 | configScrollView() 94 | webView.navigationDelegate = self 95 | 96 | let text = testText 97 | textView.string = text 98 | if let html = MarkdownParser.toHTML(text).map(curry(previewHTMLGen)(theme)(offsetRatio)) { 99 | self.webView.loadHTMLString(html, baseURL: URL(string: "markright://markdown")) 100 | } 101 | } 102 | 103 | func configScrollView() { 104 | 105 | scrollView.contentView.postsBoundsChangedNotifications = true 106 | NotificationCenter.default.addObserver(self, selector: #selector(self.autoScrollWebView), name: NSView.boundsDidChangeNotification, object: nil) 107 | } 108 | 109 | @objc func autoScrollWebView() { 110 | 111 | webView.evaluateJavaScript("window.oct_scroll(\(offsetRatio))", completionHandler: nil) 112 | } 113 | 114 | func configTextView() { 115 | 116 | textView.isEditable = true 117 | textView.backgroundColor = .white 118 | textView.font = NSFont.systemFont(ofSize: 16) 119 | textView.textColor = NSColor(white: 0.2, alpha: 1) 120 | textView.isAutomaticQuoteSubstitutionEnabled = false 121 | textView.isAutomaticDashSubstitutionEnabled = false 122 | textView.enabledTextCheckingTypes = 0 123 | textView.textStorage?.delegate = self 124 | textView.delegate = self 125 | } 126 | 127 | // MARK: NSTextStorageDelegate 128 | 129 | func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) { 130 | 131 | let text = textView.string 132 | let ratio = self.offsetRatio 133 | 134 | DispatchQueue.global(qos: .default).async { 135 | if let html = MarkdownParser.toHTML(text).map(curry(previewHTMLGen)(theme)(ratio)) { 136 | DispatchQueue.main.async { 137 | self.webView.loadHTMLString(html, baseURL: URL(string: "markright://markdown")) 138 | } 139 | } else { 140 | print("failed") 141 | } 142 | } 143 | } 144 | 145 | // MARK: WKNavigationDelegate 146 | 147 | func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { 148 | 149 | if navigationAction.request.url?.scheme == "markright" { 150 | decisionHandler(.allow) 151 | return 152 | } 153 | 154 | if let url = navigationAction.request.url { 155 | NSWorkspace.shared.open(url) 156 | } 157 | decisionHandler(.cancel) 158 | } 159 | 160 | // MARK: NSTextViewDelegate 161 | func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { 162 | 163 | if commandSelector == #selector(textView.insertTab(_:)) { 164 | 165 | textView.insertText(" ", replacementRange: textView.selectedRange()) 166 | return true 167 | } 168 | return false 169 | } 170 | } 171 | 172 | -------------------------------------------------------------------------------- /MarkRight/MarkdownParser/LeafBlock.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LeafBlock.swift 3 | // MarkRight 4 | // 5 | // Created by Octree on 2018/4/11. 6 | // Copyright © 2018年 Octree. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import FP 11 | import ParserCombinator 12 | 13 | /********************************************* 14 | ********** Leaf Block Parser *********** 15 | ********************************************/ 16 | 17 | /// thematicBreak = (3 * "-"), {-}, {space}, lineEnding; 18 | private let hyphen = character { $0 == "-" } 19 | let thematicBreak = { _ in return BlockNode.thematicBreak } <^> hyphen.repeat(3).followed(by: string("-").many).followed(by: space.many).followed(by: lineEnding) 20 | 21 | 22 | ///(*Inline Parsing ommitted, for now the Headings can only be simple Text*) 23 | 24 | 25 | /// atxHeading1 = "#", space, textualContent, atxClosingSequence; 26 | let atxHeading1 = BlockNode.h1 <^> (string("#") *> space *> textualContent <* space.many <* lineEnding) 27 | 28 | /// atxHeading2 = "##", space, textualContent, atxClosingSequence; 29 | let atxHeading2 = BlockNode.h2 <^> (string("##") *> space *> textualContent <* space.many <* lineEnding) 30 | 31 | /// atxHeading3 = "###", space, textualContent, atxClosingSequence; 32 | let atxHeading3 = BlockNode.h3 <^> (string("###") *> space *> textualContent <* space.many <* lineEnding) 33 | 34 | /// atxHeading4 = "####", space, textualContent, atxClosingSequence; 35 | let atxHeading4 = BlockNode.h4 <^> (string("####") *> space *> textualContent <* space.many <* lineEnding) 36 | 37 | /// atxHeading5 = "#####", space, textualContent, atxClosingSequence; 38 | let atxHeading5 = BlockNode.h5 <^> (string("#####") *> space *> textualContent <* space.many <* lineEnding) 39 | 40 | /// atxHeading6 = "######", space, textualContent, atxClosingSequence; 41 | let atxHeading6 = BlockNode.h6 <^> (string("######") *> space *> textualContent <* space.many <* lineEnding) 42 | 43 | /// atxHeading = atxHeading1 | atxHeading2 | atxHeading3 | atxHeading4 | atxHeading5 | atxHeading6; 44 | let atxHeading = atxHeading1 <|> atxHeading2 <|> atxHeading3 <|> atxHeading4 <|> atxHeading5 <|> atxHeading6 45 | 46 | /// blankLines = blankLine, {blankLine}; 47 | let blankLines = { BlockNode.blankLines($0.count) } <^> blankLine.many1 48 | 49 | /// indentedChunk = (4 * space, {space}, nonBlankLine), {(4 * space, {space}, nonBlankLine)}; 50 | let indentedChunk = BlockNode.indentedChunk <^> (space.repeat(4) *> space.many *> nonBlankLine).many1 51 | 52 | /// indentedCodeBlock = blankLine, (indentedChunk, blankLine), {(indentedChunk, blankLine)}; 53 | let indentedCodeBlock = BlockNode.indentedCodeBlock <^> (blankLine *> (indentedChunk <* blankLine).many1) 54 | 55 | /// fencedCodeBlock = ("```", [infoString], lineEnding, 56 | /// {line}, 57 | /// "```", lineEnding); 58 | let fencedCodeBlock = curry(BlockNode.fencedCodeBlock) <^> (string("```") *> textualContent.optional <* lineEnding) <*> 59 | line.difference(string("```")).many <* string("```") <* lineEnding 60 | 61 | 62 | /************************************ MARKDOWN TABLE ******************************************/ 63 | 64 | private let tableSep = character { $0 == "|" } 65 | 66 | 67 | private let tableData = space.many *> (not(tableSep <|> lineEnding) >>- { 68 | substring in 69 | return MDParser<[InlineNode]> { 70 | 71 | guard case let .done(_, nodes) = inlineWithoutLineBreak.many.parse(substring) else { 72 | return .fail(ParserError.notMatch) 73 | } 74 | return .done($0, nodes) 75 | } 76 | }) <* space.many 77 | 78 | private let colon = character { $0 == ":" } 79 | private typealias TableDataNodeGen = (TableDataAlignment) -> ([InlineNode]) -> BlockNode 80 | 81 | private func alignmentApply(_ any: Any, align: TableDataAlignment) -> (TableDataNodeGen) -> ([InlineNode]) -> BlockNode { 82 | 83 | return { 84 | f in 85 | return f(align) 86 | } 87 | } 88 | 89 | private let centerAlignmentData = { alignmentApply($0, align: .center ) } <^> (space.many *> colon *> hyphen.many1 *> colon *> space.many *> tableSep.lookAhead) 90 | 91 | private let leftAlignmentData = { alignmentApply($0, align: .left ) } <^> (space.many *> colon.optional *> hyphen.many1 *> space.many *> tableSep.lookAhead) 92 | 93 | private let rightAlignmentData = { alignmentApply($0, align: .right ) } <^> (space.many *> hyphen.many1 *> colon *> space.many *> tableSep.lookAhead) 94 | 95 | private let tableRow = tableSep *> (curry({ x, y in [x] + y}) <^> (tableData <* tableSep) <*> (tableData <* tableSep).many1) <* space.many <* lineBreak 96 | 97 | private func specificAmountTableRow(_ n: Int) -> MDParser<[[InlineNode]]> { 98 | 99 | return tableSep *> (tableData <* tableSep).repeat(n) <* space.many <* lineBreak 100 | } 101 | 102 | private func specificAmountDelimiterRow(_ n: Int) -> Parser ([InlineNode]) -> BlockNode]> { 103 | 104 | let delimiterItem = leftAlignmentData <|> centerAlignmentData <|> rightAlignmentData 105 | return tableSep *> (delimiterItem <* tableSep).repeat(n) <* space.many <* lineBreak 106 | } 107 | 108 | private func tableRowApply(f: TableDataNodeGen,fs: [(TableDataNodeGen) -> ([InlineNode]) -> BlockNode],row: [[InlineNode]]) -> BlockNode { 109 | let count = fs.count 110 | let datas = (0 ..< count).map { fs[$0](f)(row[$0]) } 111 | return BlockNode.tableRow(datas) 112 | } 113 | 114 | private func tableRowsApply(f: TableDataNodeGen,fs: [(TableDataNodeGen) -> ([InlineNode]) -> BlockNode],rows: [[[InlineNode]]]) -> [BlockNode] { 115 | 116 | return rows.map { tableRowApply(f: f, fs: fs, row: $0) } 117 | } 118 | 119 | private func tableGen(headingRow: [[InlineNode]], fs: [(TableDataNodeGen) -> ([InlineNode]) -> BlockNode],rows: [[[InlineNode]]]) -> BlockNode { 120 | 121 | let headingRow = tableRowApply(f: curry(BlockNode.tableHeading), fs: fs, row: headingRow) 122 | return BlockNode.table(headingRow, tableRowsApply(f: curry(BlockNode.tableData), fs: fs, rows: rows)) 123 | } 124 | 125 | private let table = tableRow >>- { 126 | row in 127 | 128 | return curry(tableGen)(row) <^> specificAmountDelimiterRow(row.count) <*> specificAmountTableRow(row.count).many1 129 | } 130 | 131 | /************************************ MARKDOWN TABLE ******************************************/ 132 | 133 | 134 | /// paragraph = inlineLine, {inlineLine}; 135 | private let specialLeaf = table <|> thematicBreak <|> atxHeading <|> indentedCodeBlock <|> fencedCodeBlock <|> blankLines 136 | let paragraph = BlockNode.paragraph <^> inlineLine.difference(specialLeaf).difference(containerBlock).many1 137 | 138 | // leafBlock = thematicBreak | atxHeading | indentedCodeBlock | fencedCodeBlock | linkReferenceDefinition | paragraph | blankLines; 139 | 140 | let leafBlock = MarkdownNode.leaf <^> ( specialLeaf <|> paragraph ) 141 | 142 | -------------------------------------------------------------------------------- /MarkRight/Resource/theme-light.css: -------------------------------------------------------------------------------- 1 | html, body, * { 2 | /* font-size: 14px;*/ 3 | margin: 0; 4 | padding: 0; 5 | font-smoothing: antialiased; 6 | } 7 | 8 | *, *:before, *:after { 9 | box-sizing: border-box; 10 | } 11 | 12 | html, body { 13 | letter-spacing: 0.2px; 14 | word-wrap: break-word; 15 | line-height: 1.6; 16 | color: #333; 17 | font-family:"Helvetica Neue",Helvetica,Arial,sans-serif; 18 | -webkit-font-smoothing: antialiased 19 | } 20 | 21 | .markdown { 22 | position: relative; 23 | max-width: 800px; 24 | margin: 0 auto; 25 | padding: 1em 1em 3em 1em; 26 | } 27 | 28 | .markdown img { 29 | max-width: 100%; 30 | } 31 | 32 | .markdown h1 { 33 | font-weight: 700; 34 | font-size: 2em; 35 | margin-top: 0!important 36 | } 37 | 38 | .markdown h2 { 39 | font-size: 1.75em; 40 | font-weight: 700; 41 | } 42 | 43 | .markdown h3 { 44 | font-size: 1.5em; 45 | } 46 | 47 | .markdown h4 { 48 | font-size: 1.25em; 49 | } 50 | 51 | .markdown h5 { 52 | font-size: 1em; 53 | } 54 | 55 | .markdown h6 { 56 | font-size: 1em; 57 | color: #777; 58 | } 59 | 60 | .markdown h1, .markdown h2, .markdown h3, .markdown h4, .markdown h5 { 61 | color: #333; 62 | page-break-after: avoid; 63 | margin-top: 1.275em; 64 | margin-bottom: .85em; 65 | orphans: 3; 66 | widows: 3; 67 | } 68 | 69 | .markdown p { 70 | orphans: 3; 71 | widows: 3; 72 | } 73 | 74 | .markdown hr { 75 | display: block; 76 | height: 4px; 77 | border:none; 78 | margin: 1.7em 0; 79 | padding: 0; 80 | background-color: #e7e7e7; 81 | } 82 | 83 | .markdown pre, .markdown ul, .markdown ol, .markdown blockquote, .markdown p, .markdown table { 84 | margin-bottom: .85em; 85 | } 86 | 87 | .markdown ul, .markdown ol { 88 | padding-left: 2em; 89 | } 90 | 91 | .markdown li { 92 | margin-bottom: 4px; 93 | } 94 | 95 | .markdown .task-list-item { 96 | list-style-type: none; 97 | display: block; 98 | position: relative; 99 | } 100 | 101 | /* The container */ 102 | /* Hide the browser's default checkbox */ 103 | .markdown .task-list-item input { 104 | position: absolute; 105 | opacity: 0; 106 | cursor: pointer; 107 | } 108 | 109 | /* Create a custom checkbox */ 110 | .markdown .task-list-item .checkmark { 111 | position: absolute; 112 | top: 5px; 113 | left: -1.6em; 114 | height: 16px; 115 | width: 16px; 116 | background-color: #eee; 117 | } 118 | 119 | /* When the checkbox is checked, add a blue background */ 120 | .markdown .task-list-item input:checked ~ .checkmark { 121 | border-radius: 3px; 122 | } 123 | 124 | .markdown .task-list-item input ~ .checkmark { 125 | border-radius: 3px; 126 | } 127 | 128 | /* Create the checkmark/indicator (hidden when not checked) */ 129 | .markdown .task-list-item .checkmark:after { 130 | content: ""; 131 | position: absolute; 132 | display: none; 133 | } 134 | 135 | /* Show the checkmark when checked */ 136 | .markdown .task-list-item input:checked ~ .checkmark:after { 137 | display: block; 138 | } 139 | 140 | /* Style the checkmark/indicator */ 141 | .markdown .task-list-item .checkmark:after { 142 | left: 6px; 143 | top: 2px; 144 | width: 5px; 145 | height: 10px; 146 | border: solid #ccc; 147 | border-width: 0 2px 2px 0; 148 | -webkit-transform: rotate(45deg); 149 | -ms-transform: rotate(45deg); 150 | transform: rotate(45deg); 151 | } 152 | 153 | .markdown code, .markdown pre { 154 | font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace !important; 155 | font-size:1em 156 | } 157 | 158 | .markdown pre { 159 | background-color: #f7f7f7; 160 | padding: 10px 18px; 161 | border-radius: 4px; 162 | color: #9dbed8; 163 | } 164 | 165 | .markdown code { 166 | background-color: #f7f7f7; 167 | padding: .2em; 168 | border-radius: 2px; 169 | /* color: #9dbed8;*/ 170 | font-size: .85em; 171 | } 172 | 173 | .markdown code:before, .markdown code:after { 174 | letter-spacing: -.2em; 175 | content: "\00a0"; 176 | } 177 | 178 | .markdown strong { 179 | font-weight: bold; 180 | } 181 | 182 | .markdown em { 183 | font-weight: normal; 184 | font-style:italic; 185 | } 186 | 187 | .markdown a { 188 | color: #4183c4; 189 | text-decoration:none; 190 | text-decoration-color: #3eb1d0; 191 | } 192 | 193 | .markdown a:hover { 194 | text-decoration: underline; 195 | } 196 | 197 | .markdown blockquote { 198 | position: relative; 199 | display: block; 200 | border-left: solid 4px #e5e5e5; 201 | padding: 2px 15px; 202 | color: #858585; 203 | } 204 | 205 | .markdown table { 206 | display: table; 207 | width: 100%; 208 | border-collapse: collapse; 209 | border-spacing: 0; 210 | overflow: auto; 211 | line-height: 1.5; 212 | word-wrap: break-word; 213 | background-color: #fff; 214 | border: 1px solid #ddd; 215 | } 216 | 217 | .markdown thead { 218 | display: table-header-group; 219 | vertical-align: middle; 220 | border-color: inherit; 221 | } 222 | 223 | .markdown tbody { 224 | display: table-row-group; 225 | vertical-align: middle; 226 | border-color: inherit; 227 | } 228 | 229 | .markdown th { 230 | font-weight: bold; 231 | padding: 6px 12px; 232 | border: 1px solid #ddd; 233 | } 234 | 235 | .markdown td { 236 | padding: 6px 12px; 237 | border: 1px solid #ddd; 238 | } 239 | 240 | .markdown tr { 241 | background-color: #ffffff; 242 | border-top: 1px solid #ccc 243 | color: #b6c2d2; 244 | } 245 | 246 | .markdown tr:nth-child(2n) { 247 | background-color: #f8f8f8; 248 | } 249 | 250 | /* Tomorrow Night Blue Theme */ 251 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 252 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 253 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 254 | 255 | /* Tomorrow Comment */ 256 | .hljs-comment, 257 | .hljs-quote { 258 | color: #8e908c; 259 | } 260 | 261 | /* Tomorrow Red */ 262 | .hljs-variable, 263 | .hljs-template-variable, 264 | .hljs-tag, 265 | .hljs-name, 266 | .hljs-selector-id, 267 | .hljs-selector-class, 268 | .hljs-regexp, 269 | .hljs-deletion { 270 | color: #c82829; 271 | } 272 | 273 | /* Tomorrow Orange */ 274 | .hljs-number, 275 | .hljs-built_in, 276 | .hljs-builtin-name, 277 | .hljs-literal, 278 | .hljs-type, 279 | .hljs-params, 280 | .hljs-meta, 281 | .hljs-link { 282 | color: #f5871f; 283 | } 284 | 285 | /* Tomorrow Yellow */ 286 | .hljs-attribute { 287 | color: #eab700; 288 | } 289 | 290 | /* Tomorrow Green */ 291 | .hljs-string, 292 | .hljs-symbol, 293 | .hljs-bullet, 294 | .hljs-addition { 295 | color: #718c00; 296 | } 297 | 298 | /* Tomorrow Blue */ 299 | .hljs-title, 300 | .hljs-section { 301 | color: #3e999f; 302 | } 303 | 304 | /* Tomorrow Purple */ 305 | .hljs-keyword, 306 | .hljs-selector-tag { 307 | color: #8959a8; 308 | } 309 | 310 | .hljs { 311 | display: block; 312 | overflow-x: auto; 313 | background-color: #f7f7f7 !important; 314 | color: #4d4d4c; 315 | padding: 0.5em; 316 | } 317 | 318 | .hljs-emphasis { 319 | font-style: italic; 320 | } 321 | 322 | .hljs-strong { 323 | font-weight: bold; 324 | } 325 | -------------------------------------------------------------------------------- /MarkRight/Resource/theme.css: -------------------------------------------------------------------------------- 1 | 2 | html, body, * { 3 | font-size: 14px; 4 | margin: 0; 5 | padding: 0; 6 | font-smoothing: antialiased; 7 | } 8 | 9 | *, *:before, *:after { 10 | box-sizing: border-box; 11 | } 12 | 13 | html, body { 14 | background-color: #1c1f2b; 15 | letter-spacing: 0.2px; 16 | word-wrap: break-word; 17 | line-height: 1.6; 18 | color: #bdcadb; 19 | font-family:"Helvetica Neue",Helvetica,Arial,sans-serif; 20 | -webkit-font-smoothing: antialiased 21 | } 22 | 23 | .markdown { 24 | position: relative; 25 | max-width: 800px; 26 | margin: 0 auto; 27 | padding: 24px 20px 50px 20px;; 28 | background-color: #1c1f2b; 29 | } 30 | 31 | .markdown img { 32 | max-width: 100%; 33 | } 34 | 35 | .markdown h1 { 36 | font-weight: 700; 37 | font-size: 2em; 38 | margin-top: 0!important 39 | } 40 | 41 | .markdown h2 { 42 | font-size: 1.75em; 43 | font-weight: 700; 44 | } 45 | 46 | .markdown h3 { 47 | font-size: 1.5em; 48 | } 49 | 50 | .markdown h4 { 51 | font-size: 1.25em; 52 | } 53 | 54 | .markdown h5 { 55 | font-size: 1em; 56 | } 57 | 58 | .markdown h6 { 59 | font-size: 1em; 60 | color: #777; 61 | } 62 | 63 | .markdown h1, .markdown h2, .markdown h3, .markdown h4, .markdown h5 { 64 | color: #fffffa; 65 | page-break-after: avoid; 66 | margin-top: 1.275em; 67 | margin-bottom: .85em; 68 | orphans: 3; 69 | widows: 3; 70 | } 71 | 72 | .markdown p { 73 | orphans: 3; 74 | widows: 3; 75 | } 76 | 77 | .markdown hr { 78 | display: block; 79 | height: 4px; 80 | border:none; 81 | margin: 1.7em 0; 82 | padding: 0; 83 | background-color: #373b4e; 84 | } 85 | 86 | .markdown pre, .markdown ul, .markdown ol, .markdown blockquote, .markdown p, .markdown table { 87 | 88 | margin-bottom: .85em; 89 | } 90 | 91 | .markdown ul, .markdown ol { 92 | padding-left: 2em; 93 | } 94 | 95 | .markdown li { 96 | margin-bottom: 4px; 97 | } 98 | 99 | .markdown .task-list-item { 100 | list-style-type: none; 101 | display: block; 102 | position: relative; 103 | } 104 | 105 | /* The container */ 106 | /* Hide the browser's default checkbox */ 107 | .markdown .task-list-item input { 108 | position: absolute; 109 | opacity: 0; 110 | cursor: pointer; 111 | } 112 | 113 | /* Create a custom checkbox */ 114 | .markdown .task-list-item .checkmark { 115 | position: absolute; 116 | top: 5px; 117 | left: -1.6em; 118 | height: 16px; 119 | width: 16px; 120 | background-color: #2d3143; 121 | } 122 | 123 | /* When the checkbox is checked, add a blue background */ 124 | .markdown .task-list-item input:checked ~ .checkmark { 125 | border-radius: 3px; 126 | } 127 | 128 | .markdown .task-list-item input ~ .checkmark { 129 | border-radius: 3px; 130 | } 131 | 132 | /* Create the checkmark/indicator (hidden when not checked) */ 133 | .markdown .task-list-item .checkmark:after { 134 | content: ""; 135 | position: absolute; 136 | display: none; 137 | } 138 | 139 | /* Show the checkmark when checked */ 140 | .markdown .task-list-item input:checked ~ .checkmark:after { 141 | display: block; 142 | } 143 | 144 | /* Style the checkmark/indicator */ 145 | .markdown .task-list-item .checkmark:after { 146 | left: 6px; 147 | top: 2px; 148 | width: 5px; 149 | height: 10px; 150 | border: solid #9dbed8; 151 | border-width: 0 2px 2px 0; 152 | -webkit-transform: rotate(45deg); 153 | -ms-transform: rotate(45deg); 154 | transform: rotate(45deg); 155 | } 156 | 157 | .markdown code, .markdown pre { 158 | font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace !important; 159 | font-size:1em 160 | } 161 | 162 | .markdown pre { 163 | background-color: #2d3143; 164 | padding: 10px 18px; 165 | border-radius: 4px; 166 | color: #9dbed8; 167 | } 168 | 169 | .markdown code { 170 | background-color: #2d3143; 171 | padding: .2em; 172 | border-radius: 2px; 173 | color: #9dbed8; 174 | font-size: .85em; 175 | } 176 | 177 | .markdown code:before, .markdown code:after { 178 | letter-spacing: -.2em; 179 | content: "\00a0"; 180 | } 181 | 182 | .markdown strong { 183 | font-weight: bold; 184 | } 185 | 186 | .markdown em { 187 | font-weight: normal; 188 | font-style:italic; 189 | } 190 | 191 | .markdown a { 192 | color: #3eb1d0; 193 | text-decoration:none; 194 | text-decoration-color: #3eb1d0; 195 | } 196 | 197 | .markdown a:hover { 198 | text-decoration: underline; 199 | } 200 | 201 | .markdown blockquote { 202 | position: relative; 203 | display: block; 204 | border-left: solid 4px #373b4e; 205 | padding: 2px 15px; 206 | color: #858585; 207 | } 208 | 209 | .markdown table { 210 | display: table; 211 | width: 100%; 212 | border-collapse: collapse; 213 | border-spacing: 0; 214 | overflow: auto; 215 | line-height: 1.5; 216 | word-wrap: break-word; 217 | background-color: #2E3143; 218 | border: 1px solid #3b3f54; 219 | } 220 | 221 | .markdown thead { 222 | display: table-header-group; 223 | vertical-align: middle; 224 | border-color: inherit; 225 | } 226 | 227 | .markdown tbody { 228 | display: table-row-group; 229 | vertical-align: middle; 230 | border-color: inherit; 231 | } 232 | 233 | .markdown th { 234 | font-weight: bold; 235 | padding: 6px 12px; 236 | border: 1px solid #3b3f54; 237 | } 238 | 239 | .markdown td { 240 | padding: 6px 12px; 241 | border: 1px solid #3b3f54; 242 | } 243 | 244 | .markdown tr { 245 | background-color: #2d3143; 246 | color: #b6c2d2; 247 | } 248 | 249 | .markdown tr:nth-child(2n) { 250 | 251 | background-color: #35394b; 252 | } 253 | 254 | /* Tomorrow Night Blue Theme */ 255 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 256 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 257 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 258 | 259 | /* Tomorrow Comment */ 260 | .hljs-comment, 261 | .hljs-quote { 262 | color: #969896; 263 | } 264 | 265 | /* Tomorrow Red */ 266 | .hljs-variable, 267 | .hljs-template-variable, 268 | .hljs-tag, 269 | .hljs-name, 270 | .hljs-selector-id, 271 | .hljs-selector-class, 272 | .hljs-regexp, 273 | .hljs-deletion { 274 | color: #d54e53; 275 | } 276 | 277 | /* Tomorrow Orange */ 278 | .hljs-number, 279 | .hljs-built_in, 280 | .hljs-builtin-name, 281 | .hljs-literal, 282 | .hljs-type, 283 | .hljs-params, 284 | .hljs-meta, 285 | .hljs-link { 286 | color: #e78c45; 287 | } 288 | 289 | /* Tomorrow Yellow */ 290 | .hljs-attribute { 291 | color: #e7c547; 292 | } 293 | 294 | /* Tomorrow Green */ 295 | .hljs-string, 296 | .hljs-symbol, 297 | .hljs-bullet, 298 | .hljs-addition { 299 | color: #b9ca4a; 300 | } 301 | 302 | /* Tomorrow Blue */ 303 | .hljs-title, 304 | .hljs-section { 305 | color: #7aa6da; 306 | } 307 | 308 | /* Tomorrow Purple */ 309 | .hljs-keyword, 310 | .hljs-selector-tag { 311 | color: #c397d8; 312 | } 313 | 314 | .hljs { 315 | display: block; 316 | overflow-x: auto; 317 | background-color: #2d3143 !important; 318 | color: #9dbed8; 319 | padding: 0.5em; 320 | } 321 | 322 | .hljs-emphasis { 323 | font-style: italic; 324 | } 325 | 326 | .hljs-strong { 327 | font-weight: bold; 328 | } 329 | -------------------------------------------------------------------------------- /MarkRight/HTMLEntities/String+HTMLEntities.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright IBM Corporation 2016, 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /// This String extension provides utility functions to convert strings to their 18 | /// HTML escaped equivalents and vice versa. 19 | public extension String { 20 | /// Global HTML escape options 21 | struct HTMLEscapeOptions { 22 | /// Specifies if all ASCII characters should be skipped when escaping text 23 | public static var allowUnsafeSymbols = false 24 | 25 | /// Specifies if decimal escapes should be used instead of hexadecimal escapes 26 | public static var decimal = false 27 | 28 | /// Specifies if all characters should be escaped, even if some are safe characters 29 | public static var encodeEverything = false 30 | 31 | /// Specifies if named character references should be used whenever possible 32 | public static var useNamedReferences = false 33 | } 34 | 35 | // Private enum used by the parser state machine 36 | private enum EntityParseState { 37 | case Dec 38 | case Hex 39 | case Invalid 40 | case Named 41 | case Number 42 | case Unknown 43 | } 44 | 45 | /// Return string as HTML escaped by replacing non-ASCII and unsafe characters 46 | /// with their numeric character escapes, or if such exists, their HTML named 47 | /// character reference equivalents. For example, this function turns 48 | /// 49 | /// `""` 50 | /// 51 | /// into 52 | /// 53 | /// `"<script>alert("abc")</script>"` 54 | /// 55 | /// You can view/change default option values globally via `String.HTMLEscapeOptions`. 56 | /// 57 | /// - Parameter allowUnsafeSymbols: Specifies if all ASCII characters should be skipped 58 | /// when escaping text. *Optional* 59 | /// - Parameter decimal: Specifies if decimal escapes should be used instead of 60 | /// hexadecimal escapes. *Optional* 61 | /// - Parameter encodeEverything: Specifies if all characters should be escaped, even if 62 | /// some are safe characters. *Optional* 63 | /// - Parameter useNamedReferences: Specifies if named character references 64 | /// should be used whenever possible. *Optional* 65 | func htmlEscape(allowUnsafeSymbols: Bool = HTMLEscapeOptions.allowUnsafeSymbols, 66 | decimal: Bool = HTMLEscapeOptions.decimal, 67 | encodeEverything: Bool = HTMLEscapeOptions.encodeEverything, 68 | useNamedReferences: Bool = HTMLEscapeOptions.useNamedReferences) 69 | -> String { 70 | // result buffer 71 | var str: String = "" 72 | 73 | #if swift(>=3.2) 74 | let characters = self 75 | #else 76 | let characters = self.characters 77 | #endif 78 | 79 | for c in characters { 80 | let unicodes = String(c).unicodeScalars 81 | 82 | if !encodeEverything, 83 | unicodes.count == 1, 84 | let unicode = unicodes.first?.value, 85 | unicode.isASCII && allowUnsafeSymbols || unicode.isSafeASCII { 86 | // character consists of only one unicode, 87 | // and is a safe ASCII character, 88 | // or allowUnsafeSymbols is true 89 | str += String(c) 90 | } 91 | else if useNamedReferences, 92 | let entity = namedCharactersEncodeMap[c] { 93 | // character has a named character reference equivalent 94 | str += "&" + entity 95 | } 96 | else { 97 | // all other cases: 98 | // deconstruct character into unicodes, 99 | // then escape each unicode individually 100 | for scalar in unicodes { 101 | let unicode = scalar.value 102 | 103 | if !encodeEverything && unicode.isSafeASCII { 104 | str += String(scalar) 105 | } 106 | else { 107 | let codeStr = decimal ? String(unicode, radix: 10) : 108 | "x" + String(unicode, radix: 16, uppercase: true) 109 | 110 | str += "&#" + codeStr + ";" 111 | } 112 | } 113 | } 114 | } 115 | 116 | return str 117 | } 118 | 119 | /// Return string as HTML unescaped by replacing HTML character references with their 120 | /// unicode character equivalents. For example, this function turns 121 | /// 122 | /// `"<script>alert("abc")</script>"` 123 | /// 124 | /// into 125 | /// 126 | /// `""` 127 | /// 128 | /// - Parameter strict: Specifies if escapes MUST always end with `;`. 129 | /// - Throws: (Only if `strict == true`) The first `ParseError` encountered during parsing. 130 | func htmlUnescape(strict: Bool) throws -> String { 131 | // result buffer 132 | var str = "" 133 | 134 | // entity buffers 135 | var entityPrefix = "" 136 | var entity = "" 137 | 138 | // current parse state 139 | var state = EntityParseState.Invalid 140 | 141 | for u in self.unicodeScalars { 142 | let unicodeAsString = String(u) 143 | let unicode = u.value 144 | 145 | // nondeterminstic finite automaton for parsing entity 146 | switch state { 147 | case .Invalid: 148 | if unicode.isAmpersand { 149 | // start of a possible character reference 150 | state = .Unknown 151 | entityPrefix = unicodeAsString 152 | } 153 | else { 154 | // move unicode to result buffer 155 | str += unicodeAsString 156 | } 157 | case .Unknown: 158 | // previously parsed & 159 | // need to determine type of character reference 160 | if unicode.isAmpersand { 161 | // parsed & again 162 | // move previous & to result buffer 163 | str += unicodeAsString 164 | } 165 | else if unicode.isHash { 166 | // numeric character reference 167 | state = .Number 168 | entityPrefix += unicodeAsString 169 | } 170 | else if unicode.isAlphaNumeric { 171 | // named character reference 172 | state = .Named 173 | 174 | // move current unicode to entity buffer 175 | entity += unicodeAsString 176 | } 177 | else { 178 | // false alarm, not a character reference 179 | // move back to invalid state 180 | state = .Invalid 181 | 182 | // move the consumed & and current unicode to result buffer 183 | str += entityPrefix + unicodeAsString 184 | 185 | // clear entityPrefix buffer 186 | entityPrefix = "" 187 | } 188 | case .Number: 189 | // previously parsed &# 190 | // need to determine dec or hex 191 | if unicode.isAmpersand { 192 | // parsed & again 193 | if strict { 194 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 195 | // "If no characters match the range, then don't consume any characters 196 | // (and unconsume the U+0023 NUMBER SIGN character and, if appropriate, 197 | // the X character). This is a parse error; nothing is returned." 198 | throw ParseError.MalformedNumericReference(entityPrefix + unicodeAsString) 199 | } 200 | 201 | // move the consume &# to result buffer 202 | str += entityPrefix 203 | 204 | // move to unknown state 205 | state = .Unknown 206 | entityPrefix = unicodeAsString 207 | } 208 | else if unicode.isX { 209 | // hexadecimal numeric character reference 210 | state = .Hex 211 | entityPrefix += unicodeAsString 212 | } 213 | else if unicode.isNumeral { 214 | // decimal numeric character reference 215 | state = .Dec 216 | entity += unicodeAsString 217 | } 218 | else { 219 | // false alarm, not a character reference 220 | if strict { 221 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 222 | // "If no characters match the range, then don't consume any characters 223 | // (and unconsume the U+0023 NUMBER SIGN character and, if appropriate, 224 | // the X character). This is a parse error; nothing is returned." 225 | throw ParseError.MalformedNumericReference(entityPrefix + unicodeAsString) 226 | } 227 | 228 | // move the consumed &# and current unicode to result buffer 229 | str += entityPrefix + unicodeAsString 230 | 231 | // move to invalid state 232 | state = .Invalid 233 | entityPrefix = "" 234 | entity = "" 235 | } 236 | case .Dec, .Hex: 237 | // previously parsed &#[0-9]+ or &#[xX][0-9A-Fa-f]* 238 | if state == .Dec && unicode.isNumeral || state == .Hex && unicode.isHexNumeral { 239 | // greedy matching 240 | // consume as many valid characters as possible before unescaping 241 | entity += unicodeAsString 242 | } 243 | else { 244 | // current character is not in matching range 245 | if strict { 246 | if entity == "" { 247 | // no characters matching range was parsed 248 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 249 | // "If no characters match the range, then don't consume any characters 250 | // (and unconsume the U+0023 NUMBER SIGN character and, if appropriate, 251 | // the X character). This is a parse error; nothing is returned." 252 | throw ParseError.MalformedNumericReference(entityPrefix + unicodeAsString) 253 | } 254 | 255 | if !unicode.isSemicolon { 256 | // entity did not end with ; 257 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 258 | // "[I]f the next character is a U+003B SEMICOLON, consume that too. 259 | // If it isn't, there is a parse error." 260 | throw ParseError.MissingSemicolon(entityPrefix + entity) 261 | } 262 | } 263 | 264 | let unescaped = try decode(entity: entity, entityPrefix: entityPrefix, strict: strict) 265 | 266 | // append unescaped numeric reference to result buffer 267 | str += unescaped 268 | 269 | if unicode.isAmpersand { 270 | // parsed & again 271 | // move to unknown state 272 | state = .Unknown 273 | entityPrefix = unicodeAsString 274 | entity = "" 275 | } 276 | else { 277 | if !unicode.isSemicolon { 278 | // move current unicode to result buffer 279 | str += unicodeAsString 280 | } 281 | 282 | // move back to invalid state 283 | state = .Invalid 284 | entityPrefix = "" 285 | entity = "" 286 | } 287 | } 288 | case .Named: 289 | // previously parsed &[0-9A-Za-z]+ 290 | if unicode.isAlphaNumeric { 291 | // keep consuming alphanumeric unicodes 292 | // only try to decode it when we encounter a nonalphanumeric unicode 293 | entity += unicodeAsString 294 | } 295 | else { 296 | if unicode.isSemicolon { 297 | entity += unicodeAsString 298 | } 299 | 300 | // try to decode parsed chunk of alphanumeric unicodes 301 | let unescaped = try decode(entity: entity, entityPrefix: entityPrefix, strict: strict) 302 | 303 | str += unescaped 304 | 305 | if unicode.isAmpersand { 306 | // parsed & again 307 | // move to unknown state 308 | state = .Unknown 309 | entityPrefix = unicodeAsString 310 | entity = "" 311 | 312 | break 313 | } 314 | else if !unicode.isSemicolon { 315 | // move current unicode to result buffer 316 | str += unicodeAsString 317 | } 318 | 319 | // move back to invalid state 320 | state = .Invalid 321 | entityPrefix = "" 322 | entity = "" 323 | } 324 | } 325 | } 326 | 327 | // one more round of finite automaton to catch the edge case where the original string 328 | // ends with a character reference that isn't terminated by ; 329 | switch state { 330 | case .Dec, .Hex: 331 | // parsed a partial numeric character reference 332 | if strict { 333 | if entity == "" { 334 | // no characters matching range was parsed 335 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 336 | // "If no characters match the range, then don't consume any characters 337 | // (and unconsume the U+0023 NUMBER SIGN character and, if appropriate, 338 | // the X character). This is a parse error; nothing is returned." 339 | throw ParseError.MalformedNumericReference(entityPrefix) 340 | } 341 | 342 | // by this point in code, entity is not empty and did not end with ; 343 | // if it did, the numeric character reference would've been unescaped inside the loop 344 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 345 | // "[I]f the next character is a U+003B SEMICOLON, consume that too. 346 | // If it isn't, there is a parse error." 347 | throw ParseError.MissingSemicolon(entityPrefix + entity) 348 | } 349 | 350 | fallthrough 351 | case .Named: 352 | // parsed a partial character reference 353 | // unescape what we have left 354 | str += try decode(entity: entity, entityPrefix: entityPrefix, strict: strict) 355 | default: 356 | // all other states 357 | // dump partial buffers into result string 358 | str += entityPrefix + entity 359 | } 360 | 361 | return str 362 | } 363 | 364 | /// Return string as HTML unescaped by replacing HTML character references with their 365 | /// unicode character equivalents. For example, this function turns 366 | /// 367 | /// `"<script>alert("abc")</script>"` 368 | /// 369 | /// into 370 | /// 371 | /// `""` 372 | /// 373 | /// Equivalent to `htmlUnescape(strict: false)`, but does NOT throw parse error. 374 | func htmlUnescape() -> String { 375 | // non-strict mode should never throw error 376 | return try! self.htmlUnescape(strict: false) 377 | } 378 | } 379 | 380 | // Utility function to decode a single entity 381 | fileprivate func decode(entity: String, entityPrefix: String, strict: Bool) throws -> String { 382 | switch entityPrefix { 383 | case "&#", "&#x", "&#X": 384 | // numeric character reference 385 | let radix = entityPrefix == "&#" ? 10 : 16 386 | 387 | if strict && entity == "" { 388 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 389 | // "If no characters match the range, then don't consume any characters 390 | // (and unconsume the U+0023 NUMBER SIGN character and, if appropriate, 391 | // the X character). This is a parse error; nothing is returned." 392 | throw ParseError.MalformedNumericReference(entityPrefix) 393 | } 394 | else if var code = UInt32(entity, radix: radix) { 395 | if code.isReplacementCharacterEquivalent { 396 | code = replacementCharacterAsUInt32 397 | 398 | if strict { 399 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 400 | // "[I]f the number is in the range 0xD800 to 0xDFFF or is greater 401 | // than 0x10FFFF, then this is a parse error." 402 | throw ParseError.OutsideValidUnicodeRange(entityPrefix + entity) 403 | } 404 | } 405 | else if let c = deprecatedNumericDecodeMap[code] { 406 | code = c 407 | 408 | if strict { 409 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 410 | // "If that number is one of the numbers in the first column of the 411 | // following table, then this is a parse error." 412 | throw ParseError.DeprecatedNumericReference(entityPrefix + entity) 413 | } 414 | } 415 | else if strict && code.isDisallowedReference { 416 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 417 | // "[I]f the number is in the range 0x0001 to 0x0008, 0x000D to 0x001F, 0x007F 418 | // to 0x009F, 0xFDD0 to 0xFDEF, or is one of 0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 419 | // 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 420 | // 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 421 | // 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 422 | // 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, or 0x10FFFF, then 423 | // this is a parse error." 424 | throw ParseError.DisallowedNumericReference(entityPrefix + entity) 425 | } 426 | 427 | return String(UnicodeScalar(code)!) 428 | } 429 | else { 430 | // Assume entity is nonempty and only contains valid characters for the given type 431 | // of numeric character reference. Given this assumption, at this point in the code 432 | // the numeric character reference must be greater than `UInt32.max`, i.e., it is 433 | // not representable by UInt32 (and it is, by transitivity, greater than 0x10FFFF); 434 | // therefore, the numeric character reference should be replaced by U+FFFD 435 | if strict { 436 | // https://www.w3.org/TR/html5/syntax.html#tokenizing-character-references 437 | // "[I]f the number is in the range 0xD800 to 0xDFFF or is greater 438 | // than 0x10FFFF, then this is a parse error." 439 | throw ParseError.OutsideValidUnicodeRange(entityPrefix + entity) 440 | } 441 | 442 | return String(UnicodeScalar(replacementCharacterAsUInt32)!) 443 | } 444 | case "&": 445 | // named character reference 446 | if entity == "" { 447 | return entityPrefix 448 | } 449 | 450 | if entity.hasSuffix(";") { 451 | // Step 1: check all other named characters first 452 | // Assume special case is rare, always check regular case first to minimize 453 | // search time cost amortization 454 | if let c = namedCharactersDecodeMap[entity] { 455 | return String(c) 456 | } 457 | 458 | // Step 2: check special named characters if entity didn't match any regular 459 | // named character references 460 | if let s = specialNamedCharactersDecodeMap[entity] { 461 | return s 462 | } 463 | } 464 | 465 | for length in legacyNamedCharactersLengthRange { 466 | #if swift(>=3.2) 467 | let count = entity.count 468 | #else 469 | let count = entity.characters.count 470 | #endif 471 | 472 | guard length <= count else { 473 | break 474 | } 475 | 476 | let upperIndex = entity.index(entity.startIndex, offsetBy: length) 477 | 478 | #if swift(>=3.2) 479 | let reference = String(entity[..]+>|\t|)+|(?:\n)))/gm,r={case_insensitive:"cI",lexemes:"l",contains:"c",keywords:"k",subLanguage:"sL",className:"cN",begin:"b",beginKeywords:"bK",end:"e",endsWithParent:"eW",illegal:"i",excludeBegin:"eB",excludeEnd:"eE",returnBegin:"rB",returnEnd:"rE",relevance:"r",variants:"v",IDENT_RE:"IR",UNDERSCORE_IDENT_RE:"UIR",NUMBER_RE:"NR",C_NUMBER_RE:"CNR",BINARY_NUMBER_RE:"BNR",RE_STARTERS_RE:"RSR",BACKSLASH_ESCAPE:"BE",APOS_STRING_MODE:"ASM",QUOTE_STRING_MODE:"QSM",PHRASAL_WORDS_MODE:"PWM",C_LINE_COMMENT_MODE:"CLCM",C_BLOCK_COMMENT_MODE:"CBCM",HASH_COMMENT_MODE:"HCM",NUMBER_MODE:"NM",C_NUMBER_MODE:"CNM",BINARY_NUMBER_MODE:"BNM",CSS_NUMBER_MODE:"CSSNM",REGEXP_MODE:"RM",TITLE_MODE:"TM",UNDERSCORE_TITLE_MODE:"UTM",COMMENT:"C",beginRe:"bR",endRe:"eR",illegalRe:"iR",lexemesRe:"lR",terminators:"t",terminator_end:"tE"},b="",h={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};function _(e){return e.replace(/&/g,"&").replace(//g,">")}function E(e){return e.nodeName.toLowerCase()}function v(e,n){var t=e&&e.exec(n);return t&&0===t.index}function l(e){return n.test(e)}function g(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function R(e){var a=[];return function e(n,t){for(var r=n.firstChild;r;r=r.nextSibling)3===r.nodeType?t+=r.nodeValue.length:1===r.nodeType&&(a.push({event:"start",offset:t,node:r}),t=e(r,t),E(r).match(/br|hr|img|input/)||a.push({event:"stop",offset:t,node:r}));return t}(e,0),a}function i(e){if(r&&!e.langApiRestored){for(var n in e.langApiRestored=!0,r)e[n]&&(e[r[n]]=e[n]);(e.c||[]).concat(e.v||[]).forEach(i)}}function m(o){function s(e){return e&&e.source||e}function c(e,n){return new RegExp(s(e),"m"+(o.cI?"i":"")+(n?"g":""))}!function n(t,e){if(!t.compiled){if(t.compiled=!0,t.k=t.k||t.bK,t.k){function r(t,e){o.cI&&(e=e.toLowerCase()),e.split(" ").forEach(function(e){var n=e.split("|");a[n[0]]=[t,n[1]?Number(n[1]):1]})}var a={};"string"==typeof t.k?r("keyword",t.k):u(t.k).forEach(function(e){r(e,t.k[e])}),t.k=a}t.lR=c(t.l||/\w+/,!0),e&&(t.bK&&(t.b="\\b("+t.bK.split(" ").join("|")+")\\b"),t.b||(t.b=/\B|\b/),t.bR=c(t.b),t.endSameAsBegin&&(t.e=t.b),t.e||t.eW||(t.e=/\B|\b/),t.e&&(t.eR=c(t.e)),t.tE=s(t.e)||"",t.eW&&e.tE&&(t.tE+=(t.e?"|":"")+e.tE)),t.i&&(t.iR=c(t.i)),null==t.r&&(t.r=1),t.c||(t.c=[]),t.c=Array.prototype.concat.apply([],t.c.map(function(e){return function(n){return n.v&&!n.cached_variants&&(n.cached_variants=n.v.map(function(e){return g(n,{v:null},e)})),n.cached_variants||n.eW&&[g(n)]||[n]}("self"===e?t:e)})),t.c.forEach(function(e){n(e,t)}),t.starts&&n(t.starts,e);var i=t.c.map(function(e){return e.bK?"\\.?(?:"+e.b+")\\.?":e.b}).concat([t.tE,t.i]).map(s).filter(Boolean);t.t=i.length?c(function(e,n){for(var t=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./,r=0,a="",i=0;i')+n+(t?"":b):n}function o(){E+=null!=l.sL?function(){var e="string"==typeof l.sL;if(e&&!N[l.sL])return _(g);var n=e?C(l.sL,g,!0,f[l.sL]):O(g,l.sL.length?l.sL:void 0);return 0")+'"');return g+=n,n.length||1}var s=B(e);if(!s)throw new Error('Unknown language: "'+e+'"');m(s);var a,l=t||s,f={},E="";for(a=l;a!==s;a=a.parent)a.cN&&(E=c(a.cN,"",!0)+E);var g="",R=0;try{for(var d,p,M=0;l.t.lastIndex=M,d=l.t.exec(n);)p=r(n.substring(M,d.index),d[0]),M=d.index+p;for(r(n.substr(M)),a=l;a.parent;a=a.parent)a.cN&&(E+=b);return{r:R,value:E,language:e,top:l}}catch(e){if(e.message&&-1!==e.message.indexOf("Illegal"))return{r:0,value:_(n)};throw e}}function O(t,e){e=e||h.languages||u(N);var r={r:0,value:_(t)},a=r;return e.filter(B).filter(M).forEach(function(e){var n=C(e,t,!1);n.language=e,n.r>a.r&&(a=n),n.r>r.r&&(a=r,r=n)}),a.language&&(r.second_best=a),r}function d(e){return h.tabReplace||h.useBR?e.replace(t,function(e,n){return h.useBR&&"\n"===e?"
    ":h.tabReplace?n.replace(/\t/g,h.tabReplace):""}):e}function o(e){var n,t,r,a,i,o=function(e){var n,t,r,a,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=s.exec(i))return B(t[1])?t[1]:"no-highlight";for(n=0,r=(i=i.split(/\s+/)).length;n/g,"\n"):n=e,i=n.textContent,r=o?C(o,i,!0):O(i),(t=R(n)).length&&((a=document.createElementNS("http://www.w3.org/1999/xhtml","div")).innerHTML=r.value,r.value=function(e,n,t){var r=0,a="",i=[];function o(){return e.length&&n.length?e[0].offset!==n[0].offset?e[0].offset"}function u(e){a+=""}function s(e){("start"===e.event?c:u)(e.node)}for(;e.length||n.length;){var l=o();if(a+=_(t.substring(r,l[0].offset)),r=l[0].offset,l===e){for(i.reverse().forEach(u);s(l.splice(0,1)[0]),(l=o())===e&&l.length&&l[0].offset===r;);i.reverse().forEach(c)}else"start"===l[0].event?i.push(l[0].node):i.pop(),s(l.splice(0,1)[0])}return a+_(t.substr(r))}(t,R(a),i)),r.value=d(r.value),e.innerHTML=r.value,e.className=function(e,n,t){var r=n?c[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}(e.className,o,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function p(){if(!p.called){p.called=!0;var e=document.querySelectorAll("pre code");f.forEach.call(e,o)}}function B(e){return e=(e||"").toLowerCase(),N[e]||N[c[e]]}function M(e){var n=B(e);return n&&!n.disableAutodetect}return a.highlight=C,a.highlightAuto=O,a.fixMarkup=d,a.highlightBlock=o,a.configure=function(e){h=g(h,e)},a.initHighlighting=p,a.initHighlightingOnLoad=function(){addEventListener("DOMContentLoaded",p,!1),addEventListener("load",p,!1)},a.registerLanguage=function(n,e){var t=N[n]=e(a);i(t),t.aliases&&t.aliases.forEach(function(e){c[e]=n})},a.listLanguages=function(){return u(N)},a.getLanguage=B,a.autoDetection=M,a.inherit=g,a.IR=a.IDENT_RE="[a-zA-Z]\\w*",a.UIR=a.UNDERSCORE_IDENT_RE="[a-zA-Z_]\\w*",a.NR=a.NUMBER_RE="\\b\\d+(\\.\\d+)?",a.CNR=a.C_NUMBER_RE="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",a.BNR=a.BINARY_NUMBER_RE="\\b(0b[01]+)",a.RSR=a.RE_STARTERS_RE="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",a.BE=a.BACKSLASH_ESCAPE={b:"\\\\[\\s\\S]",r:0},a.ASM=a.APOS_STRING_MODE={cN:"string",b:"'",e:"'",i:"\\n",c:[a.BE]},a.QSM=a.QUOTE_STRING_MODE={cN:"string",b:'"',e:'"',i:"\\n",c:[a.BE]},a.PWM=a.PHRASAL_WORDS_MODE={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},a.C=a.COMMENT=function(e,n,t){var r=a.inherit({cN:"comment",b:e,e:n,c:[]},t||{});return r.c.push(a.PWM),r.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),r},a.CLCM=a.C_LINE_COMMENT_MODE=a.C("//","$"),a.CBCM=a.C_BLOCK_COMMENT_MODE=a.C("/\\*","\\*/"),a.HCM=a.HASH_COMMENT_MODE=a.C("#","$"),a.NM=a.NUMBER_MODE={cN:"number",b:a.NR,r:0},a.CNM=a.C_NUMBER_MODE={cN:"number",b:a.CNR,r:0},a.BNM=a.BINARY_NUMBER_MODE={cN:"number",b:a.BNR,r:0},a.CSSNM=a.CSS_NUMBER_MODE={cN:"number",b:a.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},a.RM=a.REGEXP_MODE={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[a.BE,{b:/\[/,e:/\]/,r:0,c:[a.BE]}]},a.TM=a.TITLE_MODE={cN:"title",b:a.IR,r:0},a.UTM=a.UNDERSCORE_TITLE_MODE={cN:"title",b:a.UIR,r:0},a.METHOD_GUARD={b:"\\.\\s*"+a.UIR,r:0},a});hljs.registerLanguage("rust",function(e){var t="([ui](8|16|32|64|128|size)|f(32|64))?",r="drop i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 str char bool Box Option Result String Vec Copy Send Sized Sync Drop Fn FnMut FnOnce ToOwned Clone Debug PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator Extend IntoIterator DoubleEndedIterator ExactSizeIterator SliceConcatExt ToString assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! debug_assert! debug_assert_eq! env! panic! file! format! format_args! include_bin! include_str! line! local_data_key! module_path! option_env! print! println! select! stringify! try! unimplemented! unreachable! vec! write! writeln! macro_rules! assert_ne! debug_assert_ne!";return{aliases:["rs"],k:{keyword:"alignof as be box break const continue crate do else enum extern false fn for if impl in let loop match mod mut offsetof once priv proc pub pure ref return self Self sizeof static struct super trait true type typeof unsafe unsized use virtual while where yield move default",literal:"true false Some None Ok Err",built_in:r},l:e.IR+"!?",i:""}]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("php",function(e){var c={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},i={cN:"meta",b:/<\?(php)?|\?>/},t={cN:"string",c:[e.BE,i],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},a={v:[e.BNM,e.CNM]};return{aliases:["php","php3","php4","php5","php6","php7"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[i]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},i,{cN:"keyword",b:/\$this\b/},c,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",c,e.CBCM,t,a]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},t,a]}});hljs.registerLanguage("python",function(e){var r={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10",built_in:"Ellipsis NotImplemented",literal:"False None True"},b={cN:"meta",b:/^(>>>|\.\.\.) /},c={cN:"subst",b:/\{/,e:/\}/,k:r,i:/#/},a={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[e.BE,b],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[e.BE,b],r:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[e.BE,b,c]},{b:/(fr|rf|f)"""/,e:/"""/,c:[e.BE,b,c]},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[e.BE,c]},{b:/(fr|rf|f)"/,e:/"/,c:[e.BE,c]},e.ASM,e.QSM]},i={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},l={cN:"params",b:/\(/,e:/\)/,c:["self",b,i,a]};return c.c=[a,i,b],{aliases:["py","gyp","ipython"],k:r,i:/(<\/|->|\?)|=>/,c:[b,i,a,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,l,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("properties",function(r){var t="[ \\t\\f]*",e="("+t+"[:=]"+t+"|[ \\t\\f]+)",s="([^\\\\\\W:= \\t\\f\\n]|\\\\.)+",n="([^\\\\:= \\t\\f\\n]|\\\\.)+",a={e:e,r:0,starts:{cN:"string",e:/$/,r:0,c:[{b:"\\\\\\n"}]}};return{cI:!0,i:/\S/,c:[r.C("^\\s*[!#]","$"),{b:s+e,rB:!0,c:[{cN:"attr",b:s,endsParent:!0,r:0}],starts:a},{b:n+e,rB:!0,r:0,c:[{cN:"meta",b:n,endsParent:!0,r:0}],starts:a},{cN:"attr",r:0,b:n+t+"$"}]}});hljs.registerLanguage("nginx",function(e){var r={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},b={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,r],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[r]},{cN:"regexp",c:[e.BE,r],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},r]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:b}],r:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("objectivec",function(e){var t=/[a-zA-Z@][a-zA-Z0-9_]*/,_="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:{keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},l:t,i:""}]}]},{cN:"class",b:"("+_.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:_,l:t,c:[e.UTM]},{b:"\\."+e.UIR,r:0}]}});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,{cN:"string",b:/'/,e:/'/},t]}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("ruby",function(e){var b="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:r},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:b}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:b}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d;var l=[{b:/^\s*=>/,starts:{e:"$",c:i.c=d}},{cN:"meta",b:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+>|(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>)",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:s.concat(l).concat(d)}});hljs.registerLanguage("swift",function(e){var i={keyword:"#available #colorLiteral #column #else #elseif #endif #file #fileLiteral #function #if #imageLiteral #line #selector #sourceLocation _ __COLUMN__ __FILE__ __FUNCTION__ __LINE__ Any as as! as? associatedtype associativity break case catch class continue convenience default defer deinit didSet do dynamic dynamicType else enum extension fallthrough false fileprivate final for func get guard if import in indirect infix init inout internal is lazy left let mutating nil none nonmutating open operator optional override postfix precedence prefix private protocol Protocol public repeat required rethrows return right self Self set static struct subscript super switch throw throws true try try! try? Type typealias unowned var weak where while willSet",literal:"true false nil",built_in:"abs advance alignof alignofValue anyGenerator assert assertionFailure bridgeFromObjectiveC bridgeFromObjectiveCUnconditional bridgeToObjectiveC bridgeToObjectiveCUnconditional c contains count countElements countLeadingZeros debugPrint debugPrintln distance dropFirst dropLast dump encodeBitsAsWords enumerate equal fatalError filter find getBridgedObjectiveCType getVaList indices insertionSort isBridgedToObjectiveC isBridgedVerbatimToObjectiveC isUniquelyReferenced isUniquelyReferencedNonObjC join lazy lexicographicalCompare map max maxElement min minElement numericCast overlaps partition posix precondition preconditionFailure print println quickSort readLine reduce reflect reinterpretCast reverse roundUpToAlignment sizeof sizeofValue sort split startsWith stride strideof strideofValue swap toString transcode underestimateCount unsafeAddressOf unsafeBitCast unsafeDowncast unsafeUnwrap unsafeReflect withExtendedLifetime withObjectAtPlusZero withUnsafePointer withUnsafePointerToObject withUnsafeMutablePointer withUnsafeMutablePointers withUnsafePointer withUnsafePointers withVaList zip"},t=e.C("/\\*","\\*/",{c:["self"]}),n={cN:"subst",b:/\\\(/,e:"\\)",k:i,c:[]},r={cN:"string",c:[e.BE,n],v:[{b:/"""/,e:/"""/},{b:/"/,e:/"/}]},a={cN:"number",b:"\\b([\\d_]+(\\.[\\deE_]+)?|0x[a-fA-F0-9_]+(\\.[a-fA-F0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b",r:0};return n.c=[a],{k:i,c:[r,e.CLCM,t,{cN:"type",b:"\\b[A-Z][\\wÀ-ʸ']*[!?]"},{cN:"type",b:"\\b[A-Z][\\wÀ-ʸ']*",r:0},a,{cN:"function",bK:"func",e:"{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{b://},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:i,c:["self",a,r,e.CBCM,{b:":"}],i:/["']/}],i:/\[|%/},{cN:"class",bK:"struct protocol class extension enum",k:i,e:"\\{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/})]},{cN:"meta",b:"(@discardableResult|@warn_unused_result|@exported|@lazy|@noescape|@NSCopying|@NSManaged|@objc|@objcMembers|@convention|@required|@noreturn|@IBAction|@IBDesignable|@IBInspectable|@IBOutlet|@infix|@prefix|@postfix|@autoclosure|@testable|@available|@nonobjc|@NSApplicationMain|@UIApplicationMain)"},{bK:"import",e:/$/,c:[e.CLCM,t]}]}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},i=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+n},{sL:"javascript",eB:!0,eE:!0,v:[{b:"```",e:"```"},{b:"`",e:"`"}]}];r.c=i;var s=e.inherit(e.TM,{b:n}),t="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(i)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:i.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+t,e:"[-=]>",rB:!0,c:[s,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:t,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[s]},s]},{b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("haskell",function(e){var i={v:[e.C("--","$"),e.C("{-","-}",{c:["self"]})]},a={cN:"meta",b:"{-#",e:"#-}"},l={cN:"meta",b:"^#",e:"$"},c={cN:"type",b:"\\b[A-Z][\\w']*",r:0},n={b:"\\(",e:"\\)",i:'"',c:[a,l,{cN:"type",b:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TM,{b:"[_a-z][\\w']*"}),i]};return{aliases:["hs"],k:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",c:[{bK:"module",e:"where",k:"module where",c:[n,i],i:"\\W\\.|;"},{b:"\\bimport\\b",e:"$",k:"import qualified as hiding",c:[n,i],i:"\\W\\.|;"},{cN:"class",b:"^(\\s*)?(class|instance)\\b",e:"where",k:"class family instance where",c:[c,n,i]},{cN:"class",b:"\\b(data|(new)?type)\\b",e:"$",k:"data family type newtype deriving",c:[a,c,n,{b:"{",e:"}",c:n.c},i]},{bK:"default",e:"$",c:[c,n,i]},{bK:"infix infixl infixr",e:"$",c:[e.CNM,i]},{b:"\\bforeign\\b",e:"$",k:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",c:[c,e.QSM,i]},{cN:"meta",b:"#!\\/usr\\/bin\\/env runhaskell",e:"$"},a,l,e.QSM,e.CNM,c,e.inherit(e.TM,{b:"^[_a-z][\\w']*"}),i,{b:"->|<-"}]}});hljs.registerLanguage("css",function(e){var c={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:"[a-zA-Z-][a-zA-Z0-9_-]*",r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,c]}]}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment values with",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias all allocate allow alter always analyze ancillary and anti any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound bucket buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain explode export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour hours http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lateral lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minutes minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second seconds section securefile security seed segment select self semi sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tablesample tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace window with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null unknown",built_in:"array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text time timestamp tinyint varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t,e.HCM]},e.CBCM,t,e.HCM]}});hljs.registerLanguage("apache",function(e){var r={cN:"number",b:"[\\$%]\\d+"};return{aliases:["apacheconf"],cI:!0,c:[e.HCM,{cN:"section",b:""},{cN:"attribute",b:/\w+/,r:0,k:{nomarkup:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,r:0,k:{literal:"on off all"},c:[{cN:"meta",b:"\\s\\[",e:"\\]$"},{cN:"variable",b:"[\\$%]\\{",e:"\\}",c:["self",r]},r,e.QSM]}}],i:/\S/}});hljs.registerLanguage("ini",function(e){var b={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_\.-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_\.-]+/},{b:/=/,eW:!0,r:0,c:[e.C(";","$"),e.HCM,{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},b,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}});hljs.registerLanguage("xml",function(s){var e={eW:!0,i:/`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("\x3c!--","--\x3e",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"meta",b:/<\?xml/,e:/\?>/,r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0},{b:'b"',e:'"',skip:!0},{b:"b'",e:"'",skip:!0},s.inherit(s.ASM,{i:null,cN:null,c:null,skip:!0}),s.inherit(s.QSM,{i:null,cN:null,c:null,skip:!0})]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[e],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[e],starts:{e:"<\/script>",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},e]}]}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^\\s*([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}|\t)",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}});hljs.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}});hljs.registerLanguage("perl",function(e){var t="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when",r={cN:"subst",b:"[$@]\\{",e:"\\}",k:t},s={b:"->{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,r:0}]},i=[e.BE,r,n],o=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),s,{cN:"string",c:i,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,r:5,c:[e.TM]},{b:"-\\w\\b",r:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=o,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:s.c=o}});hljs.registerLanguage("cs",function(e){var i={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},r={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},t={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},a=e.inherit(t,{i:/\n/}),c={cN:"subst",b:"{",e:"}",k:i},n=e.inherit(c,{i:/\n/}),s={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,n]},b={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},c]},l=e.inherit(b,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},n]});c.c=[b,s,t,e.ASM,e.QSM,r,e.CBCM],n.c=[l,s,a,e.ASM,e.QSM,r,e.inherit(e.CBCM,{i:/\n/})];var o={v:[b,s,t,e.ASM,e.QSM]},d=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp","c#"],k:i,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:"\x3c!--|--\x3e"},{b:""}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},o,r,{bK:"class interface",e:/[{;=]/,i:/[^\s:,]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",r:0},{cN:"function",b:"("+d+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/\s*[{;=]/,eE:!0,k:i,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:i,r:0,c:[o,r,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("javascript",function(e){var r="[A-Za-z$_][0-9A-Za-z$_]*",a={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},t={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:a,c:[]},c={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,c,t,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:a,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,c,e.CLCM,e.CBCM,t,{b:/[{,]\s*/,r:0,c:[{b:r+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:r,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+r+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:r},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:a,c:s}]}]},{cN:"",b:/\s/,e:/\s*/,skip:!0},{b://,sL:"xml",c:[{b:/<[A-Za-z0-9\\._:-]+\s*\/>/,skip:!0},{b:/<[A-Za-z0-9\\._:-]+/,e:/(\/[A-Za-z0-9\\._:-]+|[A-Za-z0-9\\._:-]+\/)>/,skip:!0,c:[{b:/<[A-Za-z0-9\\._:-]+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:r}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor get set",e:/\{/,eE:!0}],i:/#(?!!)/}});hljs.registerLanguage("java",function(e){var a="false synchronized int abstract float private char boolean var static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",t={cN:"number",b:"\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",r:0};return{aliases:["jsp"],k:a,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"([À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(<[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(\\s*,\\s*[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*)*>)?\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:a,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:a,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},t,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("cpp",function(t){var e={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U|L)?"',e:'"',i:"\\n",c:[t.BE]},{b:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\((?:.|\n)*?\)\1"/},{b:"'\\\\?.",e:"'",i:"."}]},s={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},i={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},t.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:/<[^\n>]*>/,e:/$/,i:"\\n"},t.CLCM,t.CBCM]},a=t.IR+"\\s*\\(",c={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},n=[e,t.CLCM,t.CBCM,s,r];return{aliases:["c","cc","h","c++","h++","hpp","hh","hxx","cxx"],k:c,i:"",k:c,c:["self",e]},{b:t.IR+"::",k:c},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:c,c:n.concat([{b:/\(/,e:/\)/,k:c,c:n.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+t.IR+"[\\*&\\s]+)+"+a,rB:!0,e:/[{;=]/,eE:!0,k:c,i:/[^\w\s\*&]/,c:[{b:a,rB:!0,c:[t.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:c,r:0,c:[t.CLCM,t.CBCM,r,s,e,{b:/\(/,e:/\)/,k:c,r:0,c:["self",t.CLCM,t.CBCM,r,s,e]}]},t.CLCM,t.CBCM,i]},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b://,c:["self"]},t.TM]}]),exports:{preprocessor:i,strings:r,k:c}}});hljs.registerLanguage("makefile",function(e){var i={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@% > >= ` abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string=? string>? string? substring symbol->string symbol? tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?"}},d={v:[{b:"\\(",e:"\\)"},{b:"\\[",e:"\\]"}],c:[{b:/lambda/,eW:!0,rB:!0,c:[p,{b:/\(/,e:/\)/,endsParent:!0,c:[l]}]},p,o]};return o.c=[a,i,n,l,s,u,d].concat(c),{i:/\S/,c:[{cN:"meta",b:"^#!",e:"$"},i,n,s,u,d].concat(c)}}); --------------------------------------------------------------------------------