Coder Social home page Coder Social logo

highlight's Introduction

Highlight

Go Report Card GoDoc MIT License

This is a package for syntax highlighting a large number of different languages. To see the list of languages currently supported, see the syntax_files directory.

Highlight allows you to pass in a string and get back all the information you need to syntax highlight that string well.

This project is still a work in progress and more features and documentation will be coming later.

Installation

go get github.com/zyedidia/highlight

Usage

Here is how to use this package to highlight a string. We will also be using github.com/fatih/color to actually colorize the output to the console.

package main

import (
    "fmt"
    "io/ioutil"
    "strings"

    "github.com/fatih/color"
    "github.com/zyedidia/highlight"
)

func main() {
    // Here is the go code we will highlight
    inputString := `package main

import "fmt"

// A hello world program
func main() {
    fmt.Println("Hello world")
}`

    // Load the go syntax file
    // Make sure that the syntax_files directory is in the current directory
    syntaxFile, _ := ioutil.ReadFile("highlight/syntax_files/go.yaml")

    // Parse it into a `*highlight.Def`
    syntaxDef, err := highlight.ParseDef(syntaxFile)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Make a new highlighter from the definition
    h := highlight.NewHighlighter(syntaxDef)
    // Highlight the string
    // Matches is an array of maps which point to groups
    // matches[lineNum][colNum] will give you the change in group at that line and column number
    // Note that there is only a group at a line and column number if the syntax highlighting changed at that position
    matches := h.HighlightString(inputString)

    // We split the string into a bunch of lines
    // Now we will print the string
    lines := strings.Split(inputString, "\n")
    for lineN, l := range lines {
        for colN, c := range l {
            // Check if the group changed at the current position
            if group, ok := matches[lineN][colN]; ok {
                // Check the group name and set the color accordingly (the colors chosen are arbitrary)
                if group == highlight.Groups["statement"] {
                    color.Set(color.FgGreen)
                } else if group == highlight.Groups["preproc"] {
                    color.Set(color.FgHiRed)
                } else if group == highlight.Groups["special"] {
                    color.Set(color.FgBlue)
                } else if group == highlight.Groups["constant.string"] {
                    color.Set(color.FgCyan)
                } else if group == highlight.Groups["constant.specialChar"] {
                    color.Set(color.FgHiMagenta)
                } else if group == highlight.Groups["type"] {
                    color.Set(color.FgYellow)
                } else if group == highlight.Groups["constant.number"] {
                    color.Set(color.FgCyan)
                } else if group == highlight.Groups["comment"] {
                    color.Set(color.FgHiGreen)
                } else {
                    color.Unset()
                }
            }
            // Print the character
            fmt.Print(string(c))
        }
        // This is at a newline, but highlighting might have been turned off at the very end of the line so we should check that.
        if group, ok := matches[lineN][len(l)]; ok {
            if group == highlight.Groups["default"] || group == highlight.Groups[""] {
                color.Unset()
            }
        }

        fmt.Print("\n")
    }
}

If you would like to automatically detect the filetype of a file based on the filename, and have the appropriate definition returned, you can use the DetectFiletype function:

// Name of the file
filename := ...
// The first line of the file (needed to check the filetype by header: e.g. `#!/bin/bash` means shell)
firstLine := ...

// Parse all the syntax files in an array with type []*highlight.Def
var defs []*highlight.Def
...

def := highlight.DetectFiletype(defs, filename, firstLine)
fmt.Println("Filetype is", def.FileType)

For a full example, see the syncat example which acts like cat but will syntax highlight the output (if highlight recognizes the filetype).

highlight's People

Contributors

eclipseo avatar zyedidia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

highlight's Issues

Escaped ^ and $ don't get handled correctly in findIndex and findAllIndex

if strings.Contains(regexStr, "^") {

does not check if there is a backslash before the character. This causes various issues in micro-editor's syntax highlighting (for example zyedidia/micro#2397, I have noticed similar problems in other languages too).

I thought about fixing it by simply checking if the previous character is a backslash, and although that would be an improvement it would still not be exactly correct because that backslash itself could be escaped by another backslash and so on. I'm not comfortable enough with Go-lang to go for a more proper fix myself.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.