package shleximport ()// posixQuoteWord quotes a word for tcsh, the only remaining consumer.// Uses double-quote wrapping with escape sequences for $, `, " and \.// Newlines are emitted as backslash-newline, which tcsh preserves inside// double quotes (unlike bash, which drops it). Tab and CR are emitted// literally inside double quotes// since they are safe there and not backslash-escaped by the shell.// Safe words (no special chars) are returned as-is.func posixQuoteWord( string) string {if == "" {return`""` }if !strings.ContainsAny(, `"' `+"`$\n\r\t\\") {return }varstrings.Builder .WriteByte('"') .WriteString(posixStringEscape()) .WriteByte('"')return .String()}// posixStringEscape escapes the content of a tcsh double-quoted string// (the characters $, ` and ") without supplying the quotes. Newlines are// emitted as backslash-newline, which tcsh preserves inside double// quotes. bash, zsh and oil instead treat it as a line// continuation and drop the newline; use bashStringEscape for those.func posixStringEscape( string) string {varstrings.Builderfor , := range {switch {case'"': .WriteString(`\"`)case'\\': .WriteString(`\\`)case'$': .WriteString(`\$`)case'`': .WriteString("\\`")case'\n': .WriteString(`\` + "\n")default: .WriteRune() } }return .String()}// bashStringEscape escapes the content of a bash/zsh/oil double-quoted// string (the characters $, `, ", and \) without supplying the quotes.// Newlines are emitted as a quote-close/reopen sequence "'\n'" because// bash treats backslash-newline inside double quotes as a line// continuation and drops it; this requires the caller to wrap the result// in double quotes.func bashStringEscape( string) string {varstrings.Builderfor , := range {switch {case'"': .WriteString(`\"`)case'\\': .WriteString(`\\`)case'$': .WriteString(`\$`)case'`': .WriteString("\\`")case'\n': .WriteString(`"'`) .WriteRune('\n') .WriteString(`'"`)default: .WriteRune() } }return .String()}// bashQuoteWord quotes a word for bash/zsh/oil using bashStringEscape.func bashQuoteWord( string) string {returnquoteWrapped(, bashStringEscape)}// quoteWrapped wraps the output of the given escaper in double quotes,// leaving safe words as-is.func quoteWrapped( string, func(string) string) string {if == "" {return`""` }if !strings.ContainsAny(, `"' `+"`$\n\r\t\\") {return }return`"` + () + `"`}// fishQuoteWord quotes a word for fish.// Fish double quotes escape only ", $, \, and newline.// Backtick is a regular character in fish (not command substitution).func fishQuoteWord( string) string {if == "" {return`""` }if !strings.ContainsAny(, `"' `+"$\n\r\t\\") {return }varstrings.Builder .WriteByte('"') .WriteString(fishStringEscape()) .WriteByte('"')return .String()}// fishStringEscape escapes the content of a fish double-quoted string// (the characters ", $, and \) without supplying the quotes.// Backtick is a regular character in fish (not command substitution).// A raw newline is emitted verbatim: fish treats backslash-newline inside// double quotes as a line continuation and drops it.func fishStringEscape( string) string {varstrings.Builderfor , := range {switch {case'"': .WriteString(`\"`)case'\\': .WriteString(`\\`)case'$': .WriteString(`\$`)default: .WriteRune() } }return .String()}// hilbishQuoteWord quotes a word for hilbish.// Matches hilbish's own completion insertion style (complete.go// escapeFilename via charEscapeMap): metacharacters are backslash-escaped// in barewords rather than the word being quoted. Backslash and semicolon// are escaped too even though hilbish's charEscapeMap omits them — without// them a joined line would not round-trip (a raw \ is dropped by the sh// parser, a raw ; splits the command). Tab and carriage return are escaped// for the same reason: unlike POSIX double-quote wrapping they would// otherwise split the bareword.func hilbishQuoteWord( string) string {if == "" {return`""` }if !strings.ContainsAny(, "\"'` ()[]$&*><|\\;\t\r\n") {return }varstrings.Builderfor , := range {switch {case'"', '\'', '`', ' ', '(', ')', '[', ']', '$', '&', '*', '>', '<', '|', '\\', ';': .WriteByte('\\') .WriteRune()case'\n': .WriteString("\\\n")case'\t', '\r': .WriteByte('\\') .WriteRune()default: .WriteRune() } }return .String()}// elvishQuoteWord quotes a word for elvish.// Elvish barewords allow: letters, digits, -_:~./\@%+! and non-ASCII printable.// Single quotes: two consecutive single-quote chars produce one literal quote.// Empty string uses single-quoted empty (matching elvish Quote).func elvishQuoteWord( string) string {if == "" {return`''` }ifisElvishBareword() {return }varstrings.Builder .WriteByte('\'') .WriteString(elvishStringEscape()) .WriteByte('\'')return .String()}// elvishStringEscape escapes the content of an elvish single-quoted string// (two consecutive single-quote characters produce one literal quote)// without supplying the quotes.func elvishStringEscape( string) string {varstrings.Builderfor , := range {if == '\'' { .WriteString("''") } else { .WriteRune() } }return .String()}// isElvishBareword reports whether s is a valid elvish bareword (strict context).// Matches elvish's allowedInBareword with strictExpr context: = and , are// not allowed, and <>*^ are not allowed (those are CmdExpr-only).func isElvishBareword( string) bool {if [0] == '~' {returnfalse }for , := range {if !isElvishBarewordRune() {returnfalse } }returntrue}// isElvishBarewordRune reports whether r is allowed in an elvish bareword// in strict expression context.func isElvishBarewordRune( rune) bool {returnisElvishVariableNameRune() || == '.' || == '/' || == '\\' || == '@' || == '%' || == '+' || == '!'}// isElvishVariableNameRune reports whether r is allowed in an elvish// variable name (also the base for bareword characters).func isElvishVariableNameRune( rune) bool {return >= 0x80 && unicode.IsPrint() ||'0' <= && <= '9' ||'a' <= && <= 'z' ||'A' <= && <= 'Z' || == '-' || == '_' || == ':' || == '~'}// nushellQuoteWord quotes a word for nushell.// Uses double-quote wrapping with C-style escapes for \ and ".func nushellQuoteWord( string) string {if == "" {return`""` }if !strings.ContainsAny(, " {}()[]<>$&\"'|;#`\n\r\t\\") {return }varstrings.Builder .WriteByte('"')for , := range {switch {case'"': .WriteString(`\"`)case'\\': .WriteString(`\\`)default: .WriteRune() } } .WriteByte('"')return .String()}// nushellStringEscape escapes the content of a nushell double-quoted// string (the characters \ and "), with control characters written// using nushell's own escape sequences, without supplying the quotes.// Unlike tcsh, nushell treats $ and ` as literal inside double quotes,// so they are left as-is; because unrecognized escapes are parse errors// in nushell, only sequences from the nushell escape set are emitted.func nushellStringEscape( string) string {varstrings.Builderfor , := range {switch {case'\\': .WriteString(`\\`)case'"': .WriteString(`\"`)case'\n': .WriteString(`\n`)case'\r': .WriteString(`\r`)case'\t': .WriteString(`\t`)default: .WriteRune() } }return .String()}// powershellQuoteWord quotes a word for PowerShell.// Uses single-quote wrapping (verbatim, ” for literal ').func powershellQuoteWord( string) string {if == "" {return`''` }if !strings.ContainsAny(, " '\"`$&|;<>(){}\n\r\t") {return }varstrings.Builder .WriteByte('\'') .WriteString(powershellStringEscape()) .WriteByte('\'')return .String()}// powershellStringEscape escapes the content of a PowerShell single-quoted// string (a doubled quote produces one literal quote) without supplying// the quotes.func powershellStringEscape( string) string {varstrings.Builderfor , := range {if == '\'' { .WriteString("''") } else { .WriteRune() } }return .String()}// xonshQuoteWord quotes a word for xonsh.// Uses Python single-quote wrapping with \ escapes.func xonshQuoteWord( string) string {if == "" {return`""` }if !strings.ContainsAny(, "'\" \t\r\n\\") {return }varstrings.Builder .WriteByte('\'') .WriteString(xonshStringEscape()) .WriteByte('\'')return .String()}// xonshStringEscape escapes the content of a xonsh (Python)// single-quoted string with backslash escapes for quote, backslash and// newline (a raw newline is a syntax error in a Python string literal,// and a raw carriage return is normalized to a newline by the tokenizer// while reading the source) without supplying the quotes. Note that the// shlex lexer does not unescape \n (Value differs from the actual xonsh// value).func xonshStringEscape( string) string {varstrings.Builderfor , := range {switch {case'\'': .WriteString(`\'`)case'\\': .WriteString(`\\`)case'\n': .WriteString(`\n`)case'\r': .WriteString(`\r`)default: .WriteRune() } }return .String()}// cmdQuoteWord quotes a word for cmd.exe.// Uses double-quote wrapping for spaces. Since cmd.exe has no escape// mechanism inside double quotes (^ is literal inside quotes), a literal// " is handled by closing the quote, escaping the " with ^, and reopening:// "hello"^"world" — this produces the literal text hello"world.func cmdQuoteWord( string) string {if == "" {return`""` }if !strings.ContainsAny(, " \"&|<>()^,\t\n\r") {return }varstrings.Builder .WriteByte('"')for , := range {if == '"' { .WriteString(`"^"`) } else { .WriteRune() } } .WriteByte('"')return .String()}// quoteInserter is an optional interface for formats whose insertion// quoting differs from the POSIX-style default (PowerShell escapes with// the backtick, cmd doubles the quote and treats ^ literally inside// double quotes).type quoteInserter interface { QuoteInsertion(state LexerState, value string) string}// QuoteInsertion implements quoteInserter for PowerShell. Inside double// quotes the escape character is the backtick, not the backslash; other// states use the default rules.func (powershellFormat) ( LexerState, string) string {if == QUOTING_ESCAPING_STATE {varstrings.Builder .WriteByte('"')for , := range {switch {case'"': .WriteString("`\"")case'`': .WriteString("``")case'$': .WriteString("`$")default: .WriteRune() } } .WriteByte('"')return .String() }returnquoteInsertionDefault(powershellFormat{}, , )}// QuoteInsertion implements quoteInserter for cmd. The escape character// is literal inside double quotes, so the quote itself is doubled; other// states use the default rules.func (cmdFormat) ( LexerState, string) string {if == QUOTING_ESCAPING_STATE {return`"` + strings.ReplaceAll(, `"`, `""`) + `"` }returnquoteInsertionDefault(cmdFormat{}, , )}func quoteInsertion( formatImpl, LexerState, string) string {if , := .(quoteInserter); {return .QuoteInsertion(, ) }returnquoteInsertionDefault(, , )}// quoteInsertionDefault quotes value for insertion at a cursor in the// given lexer state using the format's quoting primitives: quoting// states are closed with the format's own escape rules, and barewords// are quoted as a complete word (the QuoteWord rules).func quoteInsertionDefault( formatImpl, LexerState, string) string {if , := .(stopParsingToken); && == STOP_PARSING_STATE {return// raw mode: nothing is quoted }switch {caseQUOTING_STATE: // inside single quotes: close themswitch {case .NonEscapingQuoteBackslashEscapes():return`'` + strings.ReplaceAll(, `'`, `\'`) + `'`case .NonEscapingQuoteEscapes():return`'` + strings.ReplaceAll(, `'`, `''`) + `'`default:return`'` + strings.ReplaceAll(, `'`, `'"'"'`) + `'` }caseQUOTING_ESCAPING_STATE: // inside double quotes: close themif .EscapeNotInEscapingQuote() {// the escape character is literal inside double quotes // (cmd): the quote itself is doubled insteadreturn`"` + strings.ReplaceAll(, `"`, `""`) + `"` }return`"` + escapeDoubleQuote(, ) + `"`caseQUOTING_TRIPLE_STATE: // inside '''...''': close themreturn`'''` + strings.ReplaceAll(, `'`, `\'`) + `'''`caseQUOTING_TRIPLE_ESCAPING_STATE: // inside """...""": close them := strings.ReplaceAll(, `\`, `\\`)return`"""` + strings.ReplaceAll(, `"`, `\"`) + `"""`default: // bareword: quote as a complete wordreturn .QuoteWord() }}// escapeDoubleQuote escapes value for the inside of a double-quoted// string: the quote itself, the escape character, and the format's// documented escape set (e.g. `$` in bash and fish).func escapeDoubleQuote( formatImpl, string) string { := .EscapingQuoteEscapeChars()varstrings.Builderfor , := range {switch {case == '"', == '\\', != nil && []: .WriteByte('\\') .WriteRune()default: .WriteRune() } }return .String()}// luaQuoteWord quotes a word for Lua (as used by cmd-clink snippets).// Lua identifiers stay bare; anything else is wrapped in double quotes// with backslash escapes for backslash and quote.func luaQuoteWord( string) string {if == "" {return`""` }ifisLuaBareword() {return }varstrings.Builder .WriteByte('"')for , := range {switch {case'"': .WriteString(`\"`)case'\\': .WriteString(`\\`)case'\n': .WriteString(`\n`)default: .WriteRune() } } .WriteByte('"')return .String()}// isLuaBareword reports whether s is a valid Lua identifier// ([A-Za-z_][A-Za-z0-9_]*), which is the only bareword word form.func isLuaBareword( string) bool {for , := range { := == '_' || ( >= 'a' && <= 'z') || ( >= 'A' && <= 'Z') || ( > 0 && >= '0' && <= '9')if ! {returnfalse } }returntrue}// luaStringEscape escapes the content of a Lua string (without supplying// the quotes) with backslash escapes for quote, backslash, and newline.func luaStringEscape( string) string {returnluaEscapeInterior(, '\'')}// bareWordRe is the shared conservative bareword list for the formats: a// word may consist of alphanumeric characters and the static characters// . _ - + as non-leading characters. Quotes, escapes, expansions// (` $ { ~ ( ), wordbreaks (: @ = ; | &) and history actives (!) are all// rejected, including the ones that act above a shell's lexer, so a word// passing this list stands as a single inert token in unquoted position,// for every currently supported format. Identifier validity is not// implied: dot- and dash-containing and digit-leading words are command// names, not identifiers. Formats may override with a sharper list via// IsBareWord, e.g. the Lua format which validates the whole identifier rule.var bareWordRe = regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9._+-]*$`)
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.