1 /*
2  * Copyright (C) 1999-2009  Lorenzo Bettini, http://www.lorenzobettini.it
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  *
18  */
19 
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23 
24 #include "chartranslator.h"
25 #include <sstream>
26 
27 using namespace std;
28 
29 namespace srchilite {
30 
CharTranslator(PreFormatterPtr f)31 CharTranslator::CharTranslator(PreFormatterPtr f) :
32     PreFormatter(f), counter(0), reg_exp(0), bol(true) {
33 }
34 
~CharTranslator()35 CharTranslator::~CharTranslator() {
36     if (reg_exp)
37         delete reg_exp;
38 }
39 
set_translation(const std::string & to_translate,const std::string & translate_into)40 void CharTranslator::set_translation(const std::string &to_translate,
41         const std::string &translate_into) {
42     // here we only buffer the translation regular expression
43     ostringstream exp;
44     exp << (translation_exp.size() ? "|" : "") << "(" << to_translate << ")";
45 
46     translation_exp += exp.str();
47 
48     ostringstream format;
49     // the translation format corresponding to "to_translate"
50     format << "(?" << ++counter << translate_into << ")";
51 
52     translation_format += format.str();
53 }
54 
doPreformat(const string & text)55 const string CharTranslator::doPreformat(const string &text) {
56     if (!translation_exp.size()) {
57         return text;
58     }
59 
60     // we finally build the actual regular expression
61     if (!reg_exp)
62         reg_exp = new boost::regex(translation_exp);
63 
64     boost::match_flag_type flags = boost::match_default | boost::format_all;
65     if (!bol)
66         flags |= boost::match_not_bol;
67     // if we're not at the beginning of the line, then we must not match the
68     // beginning of the string as the beginning of a line
69 
70     std::ostringstream preformat_text(std::ios::out | std::ios::binary);
71     std::ostream_iterator<char, char> oi(preformat_text);
72     boost::regex_replace(oi, text.begin(), text.end(), *reg_exp,
73             translation_format, flags);
74 
75     // keep track of the fact that we begin a new line
76     if (text.find('\n') != string::npos)
77         bol = true;
78     else
79         bol = false;
80 
81     return preformat_text.str();
82 }
83 
84 }
85