Merge pull request #2599 from unxed/iterm_fix
[far2l.git] / utils / src / Escaping.cpp
blob4c69db24b91d36c1de2b96e8de004dca15a54c8d
1 #include "utils.h"
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <string.h>
6 static struct EscapesLikeInC
8 char raw;
9 char encoded;
10 } s_escapes_like_in_c[] = {
11 { '\a', 'a'},
12 { '\b', 'b'},
13 { '\e', 'e'},
14 { '\f', 'f'},
15 { '\n', 'n'},
16 { '\r', 'r'},
17 { '\t', 't'},
18 { '\v', 'v'},
19 { '\\', '\\'},
20 { '\'', '\''},
21 { '\"', '\"'},
22 { '?', '?'}
25 std::string EscapeLikeInC(std::string str)
27 for (size_t i = str.size(); i;) {
28 --i;
29 for (const auto &esc : s_escapes_like_in_c) if (str[i] == esc.raw) {
30 char seq[] = {'\\', esc.encoded};
31 str.replace(i, 1, seq, 2);
32 break;
35 return str;
39 template <class STRING_T>
40 static STRING_T EscapeQuotesT(STRING_T str)
42 for(size_t p = str.find('\"'); p!=std::string::npos; p = str.find('\"', p)) {
43 str.insert(p, 1, '\\');
44 p+= 2;
46 return str;
49 std::string EscapeQuotes(const std::string &str) {return EscapeQuotesT(str); }
50 std::wstring EscapeQuotes(const std::wstring &str) {return EscapeQuotesT(str); }
52 template <class CHAR_T>
53 static std::basic_string<CHAR_T> EscapeCmdStrT(std::basic_string<CHAR_T> str, const CHAR_T *escaped_chars)
55 for(size_t p = str.find_first_of(escaped_chars);
56 p != std::basic_string<CHAR_T>::npos;
57 p = str.find_first_of(escaped_chars, p)) {
59 str.insert(p, 1, '\\');
60 p+= 2;
62 return str;
65 std::string EscapeCmdStr(const std::string &str, const char *escaped_chars) {return EscapeCmdStrT<char>(str, escaped_chars); }
66 std::wstring EscapeCmdStr(const std::wstring &str, const wchar_t *escaped_chars) {return EscapeCmdStrT<wchar_t>(str, escaped_chars); }
68 std::string EscapeEscapes(std::string str)
70 for (size_t p = 0; (p + 1) < str.size(); ) {
71 if (str[p] == '\\' && (str[p + 1] == '\"' || str[p + 1] == '\\' || str[ p + 1] == '\t'|| str[ p + 1] == '`'|| str[ p + 1] == '$') ) {
72 str.insert(p, 2, '\\');
73 p+= 4;
74 } else
75 ++p;
77 return str;
80 template <class STRING_T>
81 static void QuoteCmdArgT(STRING_T &str)
83 STRING_T tmp(1, '\"');
84 tmp+= EscapeCmdStr(str);
85 tmp+= '\"';
86 str.swap(tmp);
89 void QuoteCmdArg(std::string &str) { QuoteCmdArgT(str); }
90 void QuoteCmdArg(std::wstring &str) { QuoteCmdArgT(str); }
92 void QuoteCmdArgIfNeed(std::string &str)
94 if (str.find_first_of(" \\\"\'\r\n\t&|;,()`$#<>") != std::string::npos) {
95 QuoteCmdArg(str);
99 void QuoteCmdArgIfNeed(std::wstring &str)
101 if (str.find_first_of(L" \\\"\'\r\n\t&|;,()`$#<>") != std::wstring::npos) {
102 QuoteCmdArg(str);