forked from goldendict/goldendict
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhtmlescape.cc
120 lines (94 loc) · 2.04 KB
/
htmlescape.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/* This file is (c) 2008-2012 Konstantin Isakov <[email protected]>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#include "htmlescape.hh"
namespace Html {
string escape( string const & str )
{
string result( str );
for( size_t x = result.size(); x--; )
switch ( result[ x ] )
{
case '&':
result.erase( x, 1 );
result.insert( x, "&" );
break;
case '<':
result.erase( x, 1 );
result.insert( x, "<" );
break;
case '>':
result.erase( x, 1 );
result.insert( x, ">" );
break;
case '"':
result.erase( x, 1 );
result.insert( x, """ );
break;
default:
break;
}
return result;
}
string preformat( string const & str )
{
string escaped = escape( str ), result;
result.reserve( escaped.size() );
bool leading = true;
for( char const * nextChar = escaped.c_str(); *nextChar; ++nextChar )
{
if ( leading )
{
if ( *nextChar == ' ' )
{
result += " ";
continue;
}
else
if ( *nextChar == '\t' )
{
result += " ";
continue;
}
}
if ( *nextChar == '\n' )
{
result += "<br/>";
leading = true;
continue;
}
if ( *nextChar == '\r' )
continue; // Just skip all \r
result.push_back( *nextChar );
leading = false;
}
return result;
}
string escapeForJavaScript( string const & str )
{
string result( str );
for( size_t x = result.size(); x--; )
switch ( result[ x ] )
{
case '\\':
case '"':
case '\'':
result.insert( x, 1, '\\' );
break;
case '\n':
result.erase( x, 1 );
result.insert( x, "\\n" );
break;
case '\r':
result.erase( x, 1 );
result.insert( x, "\\r" );
break;
case '\t':
result.erase( x, 1 );
result.insert( x, "\\t" );
break;
default:
break;
}
return result;
}
}