highlight

package module
Version: v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2022 License: AGPL-3.0 Imports: 2 Imported by: 1

README

Go report Go Reference Release License

highlight is a golang library for highlighting code syntax of different programming and markup languages inside HTML documents.

Install

Supported Go versions:

  • 1.11
  • 1.17
  • 1.18

Add to go.mod file:

require github.com/lcomrade/highlight v1

How it works?

The <span> tag is used to highlight syntax when converting to HTML. This tag does not do anything on its own, but you can assign different properties to it in CSS. Including color and font.

All extraneous HTML tags will be protected.

Before highlighting:

User-agent: * # comment
Disallow: /faq

# comment 1
# comment 2

Allow: /
Crawl-delay: 10
Sitemap: https://example.org/sitemap.xml
Host: https://mirror.example.org

After highlighting:

<span class='code-keyword'>User-agent:</span> * <span class='code-c'># comment</span>
<span class='code-keyword'>Disallow:</span> /faq

<span class='code-comment'># comment 1</span>
<span class='code-comment'># comment 2</span>

<span class='code-keyword'>Allow:</span> /
<span class='code-keyword'>Crawl-delay:</span> 10
<span class='code-keyword'>Sitemap:</span> https://example.org/sitemap.xml
<span class='code-keyword'>Host:</span> https://mirror.example.org

Supported languages

  • C
  • Dockerfile
  • Golang
  • go.mod
  • INI
  • Java
  • JSON
  • Python
  • robots.txt
  • SQL

Code example

package main

import (
	"fmt"
	"github.com/lcomrade/highlight"
)

func main() {
	// Code written in the C language
	myCode := `
#include <stdio.h>

// Comment

int main() {
	printf("Hello, world!");

	return 0;
}
`

	// Highlight
	fmt.Println(highlight.C(myCode))
}

Read more in the documentation

CSS classes

Example of a CSS file:

.code-operator, .code-keyword, .code-build-in-func, .code-key {
	color: Firebrick;
}

.code-var-type, .code-build-in-var {
	color: RoyalBlue;
}

.code-brackets {
	color: ForestGreen;
}

.code-comment {
	color: DimGray;
}

Documentation

Documentation

Index

Constants

View Source
const (
	StyleKeyword     = "code-keyword"
	StyleOperator    = "code-operator"
	StyleVarType     = "code-var-type"
	StyleBuildInVar  = "code-build-in-var"
	StyleBuildInFunc = "code-build-in-func"
	StyleComment     = "code-comment"
	StyleBrackets    = "code-brackets"
	StyleKey         = "code-key"
	StyleValue       = "code-value"
)

These constants describe the name of the class that will be assigned to the HTML tag '<span>'.

Examples:

<span style='code-keyword'>User-Agent:</span>
<span style='code-comment'># My comment</span>

Variables

This section is empty.

Functions

func ByName

func ByName(code string, language string) (string, error)

ByName helps to highlight code based on the language name. This can be useful for Markdown and some other cases. The name of the language is not case sensitive.

| Function name | Language name   |
|---------------|-----------------|
| C             | c               |
| Dockerfile    | dockerfile      |
| Golang        | go, golang      |
| GoMod         | go.mod          |
| INI config    | ini             |
| Java          | java            |
| JSON          | json            |
| Python        | python, python3 |
| RobotsTxt     | robots.txt      |
| SQL           | sql             |

func C

func C(code string) string

C processes C source code (*.c files).

Supported preprocessor directives (const StyleKeyword):

#define
#elif
#else
#endif
#error
#if
#ifdef
#ifndef
#import
#include
#line
#pragma
#undef
#using

Supported keywords (const StyleKeyword):

auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
inline
int
long
register
restrict
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
_Alignas
_Alignof
_Atomic
_Bool
_Complex
_Decimal128
_Decimal32
_Decimal64
_Generic
_Imaginary
_Noreturn
_Static_assert
_Thread_local

Supported operators (const StyleOperator):

->
==
!=
<=>
<<=
=>>
<<
>>
<=
<
>=
>
=
^
&&
&
||
?:
%=
&=
^=
|=
++
--
+
-
!
~
*
/
%

Also supported:

Single-line comments (//)
Multi-line comments (/* */)
Single-line brackets (", ')
Numbers (100, 1.2, 1.25)

func Dockerfile

func Dockerfile(code string) string

Dockerfile processes Docker builder files. Read more: https://docs.docker.com/engine/reference/builder/

Supported commands (const StyleKeyword):

FROM
RUN
CMD
LABEL
MAINTAINER
EXPOSE
ENV
ADD
COPY
ENTRYPOINT
VOLUME
USER
WORKDIR
ARG
ONBUILD
STOPSIGNAL
HEALTHCHECK
SHELL

Comments (#) are also supported.

func GoMod added in v1.0.2

func GoMod(code string) string

GoMod processes go.mod files. Read more: https://go.dev/ref/mod#go-mod-file-module

Supported keywords (const StyleKeyword):

module
go
require
exclude
replace
retract

Supported operators (const StyleOperator):

=>

Single-line comments (//) and numbers (100, 1.2, 1.25) are also supported.

func Golang

func Golang(code string) string

Golang processes go source code (*.go files). Read more: https://go.dev/ref/spec

Supported keywords (const StyleKeyword):

break
case
chan
const
continue
default
defer
else
fallthrough
for
func
go
goto
if
import
interface
map
package
range
return
select
struct
switch
type
var

Supported values (const StyleValue):

true
false
nil
All numbers (100, 1.3, 2.25)

Supported operators (const StyleOperator):

!
!=
%
&
&&
&^
*
+
-
/
<
<-
<<
<=
==
>
>=
>>
^
|
||
=
:=

Supported variable types (const StyleVarType):

bool
uint
uint8
uint16
uint32
uint64
uintptr
int
int8
int16
int32
int64
float32
float64
complex64
complex128
byte
rune
string

Supported built-in functions (const StyleBuildInFunc):

append
cap
close
complex
copy
delete
imag
len
make
new
panic
print
println
real
recover

Also supported:

Single-line comments (//)
Multi-line comments (/* */)
Single-line brackets (", ')
Multi-line brackets (` `)

func INI added in v1.0.4

func INI(code string) string

INI processes .INI configuration files. Read more: https://en.wikipedia.org/wiki/INI_file

Supported:

Sections ([....])
Single-line comments (# and ;)

func JSON added in v1.0.4

func JSON(code string) string

JSON processes JSON config files (*.json files). Read more: https://en.wikipedia.org/wiki/JSON

Supported values (const StyleValue):

true
false
null
All numbers (100, 1.3, 2.25)

Also supported:

Single-line comments (//)
Multi-line comments (/* */)
Single-line brackets (", ')

func Java added in v1.0.4

func Java(code string) string

Java processes Java source code (*.java files). Read more: https://en.wikipedia.org/wiki/Java_(programming_language)

Supported keywords (const StyleKeyword):

abstract
assert
break
case
catch
class
const
continue
default
do
else
enum
extends
final
finally
for
goto
if
implements
import
instanceof
interface
native
new
package
private
protected
public
return
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while

Supported values (const StyleValue):

true
false
null
All numbers (100, 1.3, 2.25)

Supported operators (const StyleOperator):

!
!=
%
%=
&&
&=
*/
*=
+
++
+=
-
--
-=
/=
<
<<=
<=
=
==
>
>=
>>=
^=
|=
||

Supported variable types (const StyleVarType):

boolean
byte
char
double
float
int
long
short
String

Also supported:

Single-line comments (//)
Multi-line comments (/* */)
Single-line brackets (", ')
Multi-line brackets (""" """)

func Python

func Python(code string) string

Python processes python source code (*.py files). Read more: https://docs.python.org/3/reference/index.html

Supported keywords (const StyleKeyword):

and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

Supported values (const StyleValue):

True
False
None
All numbers (100, 1.3, 2.25)

Supported operators (const StyleOperator):

+
-
*
**
/
//
%
@
<<
>>
&
|
^
~
:=
<
>
<=
>=
==
!=

Supported import-related module attributes (const StyleBuildInVar):

__name__
__loader__
__package__
__spec__
__path__
__file__
__cached__

Supported built-in functions (const StyleBuildInFunc):

abs()
aiter()
all()
any()
anext()
ascii()
bin()
bool()
breakpoint()
bytearray()
bytes()
callable()
chr()
classmethod()
compile()
complex()
delattr()
dict()
dir()
divmod()
enumerate()
eval()
exec()
filter()
float()
format()
frozenset()
getattr()
globals()
hasattr()
hash()
help()
hex()
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals()
map()
max()
memoryview()
min()
next()
object()
oct()
open()
ord()
pow()
print()
property()
range()
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
vars()
zip()
__import__()

Also supported:

Single-line comments (#)
Multi-line comments (''' ''')
Single-line brackets (", ')
Multi-line brackets (""" """)

func RobotsTxt

func RobotsTxt(code string) string

RobotsTxt processes robots.txt files (Robots exclusion standard). Read more: https://en.wikipedia.org/wiki/Robots_exclusion_standard

Supports standard directives (const StyleKeyword):

User-agent
Disallow

And nonstandard extensions (const StyleKeyword):

Allow
Crawl-delay
Sitemap
Host

Comments (#) are also supported.

func SQL added in v1.0.2

func SQL(code string) string

SQL processes Structured Query Language. Read more: https://en.wikipedia.org/wiki/SQL

Supported keywords (const StyleKeyword):

ALTER
AND
AS
BEGIN
COMMIT
CONNECT BY
CREATE
DELETE
DENY
DROP
FROM
GRANT
GROUP BY
HAVING
IN
INSERT
INTO
JOIN
OR
ORDER BY
RELEASE
REVOKE
ROLLBACK
ROLLBACK TO
SAVEPOINT
SELECT
SET
TRANSACTION
UPDATE
VALUES
WHERE
WORK

Brackets (", ') and numbers (100, 1.2, 1.25) are also supported.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL