2022-08-13 19:32:34 +01:00
// Copyright 2022 The Gitea Authors. All rights reserved.
2022-11-27 13:20:29 -05:00
// SPDX-License-Identifier: MIT
2022-01-07 01:18:52 +00:00
package charset
import (
2023-12-17 22:38:54 +08:00
"html/template"
2022-01-07 01:18:52 +00:00
"io"
"strings"
2023-12-17 22:38:54 +08:00
"code.gitea.io/gitea/modules/setting"
2022-08-13 19:32:34 +01:00
"code.gitea.io/gitea/modules/translation"
2022-01-07 01:18:52 +00:00
)
2026-04-06 13:07:33 +02:00
type EscapeOptions struct {
Allowed map [ rune ] bool
}
func AllowRuneNBSP ( ) map [ rune ] bool {
return map [ rune ] bool { 0xa0 : true }
}
func EscapeOptionsForView ( ) EscapeOptions {
return EscapeOptions {
// it's safe to see NBSP in the view, but maybe not in the diff
Allowed : AllowRuneNBSP ( ) ,
}
}
2022-01-07 01:18:52 +00:00
2025-12-14 18:40:55 +08:00
// EscapeControlHTML escapes the Unicode control sequences in a provided html document
2026-04-06 13:07:33 +02:00
func EscapeControlHTML ( html template . HTML , locale translation . Locale , opts ... EscapeOptions ) ( escaped * EscapeStatus , output template . HTML ) {
2025-12-14 18:40:55 +08:00
if ! setting . UI . AmbiguousUnicodeDetection {
return & EscapeStatus { } , html
}
2022-01-07 01:18:52 +00:00
sb := & strings . Builder { }
2026-04-06 13:07:33 +02:00
escaped , _ = EscapeControlReader ( strings . NewReader ( string ( html ) ) , sb , locale , opts ... ) // err has been handled in EscapeControlReader
2023-12-17 22:38:54 +08:00
return escaped , template . HTML ( sb . String ( ) )
2022-01-07 01:18:52 +00:00
}
2025-12-14 18:40:55 +08:00
// EscapeControlReader escapes the Unicode control sequences in a provided reader of HTML content and writer in a locale and returns the findings as an EscapeStatus
2026-04-06 13:07:33 +02:00
func EscapeControlReader ( reader io . Reader , writer io . Writer , locale translation . Locale , opts ... EscapeOptions ) ( * EscapeStatus , error ) {
return escapeStream ( locale , reader , writer , opts ... )
2022-01-07 01:18:52 +00:00
}