3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "support/docstream.h"
14 #include "support/lstrings.h"
15 #include "support/unicode.h"
26 using lyx::ucs4_codeset;
27 using lyx::support::contains;
28 using lyx::support::split;
31 #if defined(_MSC_VER) && (_MSC_VER >= 1600)
32 std::locale::id numpunct<lyx::char_type>::id;
38 // We use C IO throughout this file, because the facets might be used with
39 // lyxerr in the future.
42 /// codecvt facet for conversion of UCS4 (internal representation) to UTF8
43 /// (external representation) or vice versa
44 class iconv_codecvt_facet : public codecvt<lyx::char_type, char, mbstate_t>
46 typedef codecvt<lyx::char_type, char, mbstate_t> base;
48 /// Constructor. You have to specify with \p inout whether you want
49 /// to use this facet only for input, only for output or for both.
50 explicit iconv_codecvt_facet(string const & encoding = "UTF-8",
51 ios_base::openmode inout = ios_base::in | ios_base::out,
53 : base(refs), encoding_(encoding)
55 if (inout & ios_base::in) {
56 in_cd_ = iconv_open(ucs4_codeset, encoding.c_str());
57 if (in_cd_ == (iconv_t)(-1)) {
58 fprintf(stderr, "Error %d returned from iconv_open(in_cd_): %s\n",
59 errno, strerror(errno));
61 throw lyx::iconv_codecvt_facet_exception();
64 in_cd_ = (iconv_t)(-1);
65 if (inout & ios_base::out) {
66 out_cd_ = iconv_open(encoding.c_str(), ucs4_codeset);
67 if (out_cd_ == (iconv_t)(-1)) {
68 fprintf(stderr, "Error %d returned from iconv_open(out_cd_): %s\n",
69 errno, strerror(errno));
71 throw lyx::iconv_codecvt_facet_exception();
74 out_cd_ = (iconv_t)(-1);
77 virtual ~iconv_codecvt_facet()
79 if (in_cd_ != (iconv_t)(-1))
80 if (iconv_close(in_cd_) == -1) {
81 fprintf(stderr, "Error %d returned from iconv_close(in_cd_): %s\n",
82 errno, strerror(errno));
85 if (out_cd_ != (iconv_t)(-1))
86 if (iconv_close(out_cd_) == -1) {
87 fprintf(stderr, "Error %d returned from iconv_close(out_cd_): %s\n",
88 errno, strerror(errno));
92 virtual result do_out(state_type &, intern_type const * from,
93 intern_type const * from_end, intern_type const *& from_next,
94 extern_type * to, extern_type * to_end,
95 extern_type *& to_next) const
97 #define WORKAROUND_ICONV_BUG 1
98 #if WORKAROUND_ICONV_BUG
99 // Due to a bug in some iconv versions, when the last char
100 // in the buffer is a wide char and the output encoding is
101 // ISO-2022-JP and we are going to switch to another encoding,
102 // the appropriate escape sequence for changing the character
103 // set is not output (see bugs 5216, 5280, and also 5489).
104 // As a workaround, we append a nul char in order to force
105 // a switch to ASCII, and then remove it from output after
107 intern_type * from_new = 0;
108 intern_type const * from_old = from;
110 if (*(from_end - 1) >= 0x80 && encoding_ == "ISO-2022-JP") {
111 size_t len = from_end - from;
112 from_new = new intern_type[len + 1];
113 memcpy(from_new, from, len * sizeof(intern_type));
115 from_end = from_new + len + 1;
120 size_t inbytesleft = (from_end - from) * sizeof(intern_type);
121 size_t outbytesleft = (to_end - to) * sizeof(extern_type);
122 #if WORKAROUND_ICONV_BUG
123 outbytesleft += extra * sizeof(extern_type);
127 result const retval = do_iconv(out_cd_,
128 reinterpret_cast<char const **>(&from_next),
129 &inbytesleft, &to_next, &outbytesleft);
130 #if WORKAROUND_ICONV_BUG
131 // Remove from output the nul char that we inserted at the end
132 // of the input buffer in order to circumvent an iconv bug.
136 from_next = from_old + (from_next - from);
141 if (retval == base::error) {
143 "Error %d returned from iconv when converting from %s to %s: %s\n",
144 errno, ucs4_codeset, encoding_.c_str(),
146 fputs("Converted input:", stderr);
147 for (intern_type const * i = from; i < from_next; ++i) {
148 unsigned int const c = *i;
149 fprintf(stderr, " 0x%04x", c);
151 unsigned int const c = *from_next;
152 fprintf(stderr, "\nStopped at: 0x%04x\n", c);
153 fputs("Unconverted input:", stderr);
154 for (intern_type const * i = from_next + 1; i < from_end; ++i) {
155 unsigned int const c = *i;
156 fprintf(stderr, " 0x%04x", c);
158 fputs("\nConverted output:", stderr);
159 for (extern_type const * i = to; i < to_next; ++i) {
160 // extern_type may be signed, avoid output of
161 // something like 0xffffffc2
162 unsigned int const c =
163 *reinterpret_cast<unsigned char const *>(i);
164 fprintf(stderr, " 0x%02x", c);
171 virtual result do_unshift(state_type &, extern_type * to,
172 extern_type *, extern_type *& to_next) const
174 // utf8 does not use shifting
178 virtual result do_in(state_type &,
179 extern_type const * from, extern_type const * from_end,
180 extern_type const *& from_next,
181 intern_type * to, intern_type * to_end,
182 intern_type *& to_next) const
184 size_t inbytesleft = (from_end - from) * sizeof(extern_type);
185 size_t outbytesleft = (to_end - to) * sizeof(intern_type);
188 result const retval = do_iconv(in_cd_, &from_next, &inbytesleft,
189 reinterpret_cast<char **>(&to_next),
191 if (retval == base::error) {
193 "Error %d returned from iconv when converting from %s to %s: %s\n",
194 errno, encoding_.c_str(), ucs4_codeset,
196 fputs("Converted input:", stderr);
197 for (extern_type const * i = from; i < from_next; ++i) {
198 // extern_type may be signed, avoid output of
199 // something like 0xffffffc2
200 unsigned int const c =
201 *reinterpret_cast<unsigned char const *>(i);
202 fprintf(stderr, " 0x%02x", c);
204 unsigned int const c =
205 *reinterpret_cast<unsigned char const *>(from_next);
206 fprintf(stderr, "\nStopped at: 0x%02x\n", c);
207 fputs("Unconverted input:", stderr);
208 for (extern_type const * i = from_next + 1; i < from_end; ++i) {
209 unsigned int const c =
210 *reinterpret_cast<unsigned char const *>(i);
211 fprintf(stderr, " 0x%02x", c);
213 fputs("\nConverted output:", stderr);
214 for (intern_type const * i = to; i < to_next; ++i) {
215 unsigned int const c = *i;
216 fprintf(stderr, " 0x%02x", c);
223 virtual int do_encoding() const throw()
227 virtual bool do_always_noconv() const throw()
231 virtual int do_length(state_type & /*state*/, extern_type const * from,
232 extern_type const * end, size_t max) const
234 // The docs are a bit unclear about this method.
235 // It seems that we should calculate the actual length of the
236 // converted sequence, but that would not make sense, since
237 // once could just do the conversion directly.
238 // Therefore we just return the number of unconverted
239 // characters, since that is the best guess we can do.
241 intern_type * to = new intern_type[max];
242 intern_type * to_end = to + max;
243 intern_type * to_next = to;
244 extern_type const * from_next = from;
245 do_in(state, from, end, from_next, to, to_end, to_next);
249 size_t const length = end - from;
250 return min(length, max);
253 virtual int do_max_length() const throw()
255 return lyx::max_encoded_bytes(encoding_);
258 /// Do the actual conversion. The interface is equivalent to that of
259 /// iconv() (but const correct).
260 inline base::result do_iconv(iconv_t cd, char const ** from,
261 size_t * inbytesleft, char ** to, size_t * outbytesleft) const
263 char const * const to_start = *to;
264 size_t converted = iconv(cd, const_cast<char ICONV_CONST **>(from),
265 inbytesleft, to, outbytesleft);
266 if (converted == (size_t)(-1)) {
269 // As strange as it may seem, this
270 // does happen on windows when parsing
271 // comments with accented chars in
272 // tex2lyx. See the following thread
274 // http://thread.gmane.org/gmane.editors.lyx.devel/117636
278 return base::partial;
290 /// The narrow encoding
300 void setEncoding(Ios & ios, string const & encoding, ios_base::openmode mode)
302 // We must imbue the stream before openening the file
304 locale locale(global, new iconv_codecvt_facet(encoding, mode));
309 const char * iconv_codecvt_facet_exception::what() const throw()
311 return "iconv problem in iconv_codecvt_facet initialization";
315 ifdocstream::ifdocstream() : base()
317 setEncoding(*this, "UTF-8", in);
321 ifdocstream::ifdocstream(const char* s, ios_base::openmode mode,
322 string const & encoding)
325 setEncoding(*this, encoding, in);
330 ofdocstream::ofdocstream(): base()
332 setEncoding(*this, "UTF-8", out);
336 ofdocstream::ofdocstream(const char* s, ios_base::openmode mode,
337 string const & encoding)
340 setEncoding(*this, encoding, out);
345 void ofdocstream::reset(string const & encoding)
347 setEncoding(*this, encoding, out);
352 SetEnc setEncoding(string const & encoding)
354 return SetEnc(encoding);
358 odocstream & operator<<(odocstream & os, SetEnc e)
360 if (has_facet<iconv_codecvt_facet>(os.rdbuf()->getloc())) {
361 // This stream must be a file stream, since we never imbue
362 // any other stream with a locale having a iconv_codecvt_facet.
363 // Flush the stream so that all pending output is written
364 // with the old encoding.
366 locale locale(os.rdbuf()->getloc(),
367 new iconv_codecvt_facet(e.encoding, ios_base::out));
368 // FIXME Does changing the codecvt facet of an open file
369 // stream always work? It does with gcc 4.1, but I have read
370 // somewhere that it does not with MSVC.
371 // What does the standard say?
378 //CHECKME: I just copied the code above, and have no idea whether it
379 //is correct... (JMarc)
380 idocstream & operator<<(idocstream & is, SetEnc e)
382 if (has_facet<iconv_codecvt_facet>(is.rdbuf()->getloc())) {
383 // This stream must be a file stream, since we never imbue
384 // any other stream with a locale having a iconv_codecvt_facet.
385 // Flush the stream so that all pending output is written
386 // with the old encoding.
388 locale locale(is.rdbuf()->getloc(),
389 new iconv_codecvt_facet(e.encoding, ios_base::in));
390 // FIXME Does changing the codecvt facet of an open file
391 // stream always work? It does with gcc 4.1, but I have read
392 // somewhere that it does not with MSVC.
393 // What does the standard say?
400 #if ! defined(USE_WCHAR_T)
401 odocstream & operator<<(odocstream & os, char c)
409 void otexstream::put(char_type const & c)
412 if (!canbreakline_ && c == ' ')
414 protectspace_ = false;
420 canbreakline_ = false;
422 canbreakline_ = true;
427 SafeBreakLine safebreakln;
430 otexstream & operator<<(otexstream & ots, BreakLine)
432 if (ots.canBreakLine()) {
435 ots.canBreakLine(false);
436 ots.texrow().newline();
438 ots.protectSpace(false);
443 otexstream & operator<<(otexstream & ots, SafeBreakLine)
445 if (ots.canBreakLine()) {
448 ots.canBreakLine(false);
449 ots.texrow().newline();
451 ots.protectSpace(false);
456 otexstream & operator<<(otexstream & ots, odocstream_manip pf)
459 if (pf == static_cast<odocstream_manip>(endl)) {
461 ots.texrow().newline();
467 otexstream & operator<<(otexstream & ots, docstring const & s)
469 size_t const len = s.length();
471 // Check whether there's something to output
475 if (ots.protectSpace()) {
476 if (!ots.canBreakLine() && s[0] == ' ')
478 ots.protectSpace(false);
481 if (contains(s, 0xF0000)) {
482 // Some encoding changes for the underlying stream are embedded
483 // in the docstring. The encoding names to be used are enclosed
484 // between the code points 0xF0000 and 0xF0001, the first two
485 // characters of plane 15, which is a Private Use Area whose
486 // codepoints don't have any associated glyph.
488 docstring s2 = split(s, s1, 0xF0000);
495 docstring const s3 = split(s2, enc, 0xF0001);
496 if (!contains(s2, 0xF0001))
497 s2 = split(enc, s1, 0xF0000);
499 ots.os() << setEncoding(to_ascii(enc));
500 s2 = split(s3, s1, 0xF0000);
506 ots.lastChar(s[len - 1]);
507 ots.texrow().newlines(count(s.begin(), s.end(), '\n'));
508 ots.canBreakLine(s[len - 1] != '\n');
513 otexstream & operator<<(otexstream & ots, string const & s)
520 otexstream & operator<<(otexstream & ots, char const * s)
527 otexstream & operator<<(otexstream & ots, char c)
529 if (ots.protectSpace()) {
530 if (!ots.canBreakLine() && c == ' ')
532 ots.protectSpace(false);
537 ots.texrow().newline();
538 ots.canBreakLine(c != '\n');
543 template <typename Type>
544 otexstream & operator<<(otexstream & ots, Type value)
548 ots.canBreakLine(true);
549 ots.protectSpace(false);
553 template otexstream & operator<< <SetEnc>(otexstream & os, SetEnc);
554 template otexstream & operator<< <double>(otexstream &, double);
555 template otexstream & operator<< <int>(otexstream &, int);
556 template otexstream & operator<< <unsigned int>(otexstream &, unsigned int);
557 template otexstream & operator<< <unsigned long>(otexstream &, unsigned long);
561 #if ! defined(USE_WCHAR_T) && defined(__GNUC__)
562 // We get undefined references to these virtual methods. This looks like
563 // a bug in gcc. The implementation here does not do anything useful, since
564 // it is overriden in iconv_codecvt_facet.
567 template<> codecvt<lyx::char_type, char, mbstate_t>::result
568 codecvt<lyx::char_type, char, mbstate_t>::do_out(
569 mbstate_t &, const lyx::char_type *, const lyx::char_type *,
570 const lyx::char_type *&, char *, char *, char *&) const
576 template<> codecvt<lyx::char_type, char, mbstate_t>::result
577 codecvt<lyx::char_type, char, mbstate_t>::do_unshift(
578 mbstate_t &, char *, char *, char *&) const
584 template<> codecvt<lyx::char_type, char, mbstate_t>::result
585 codecvt<lyx::char_type, char, mbstate_t>::do_in(
586 mbstate_t &, const char *, const char *, const char *&,
587 lyx::char_type *, lyx::char_type *, lyx::char_type *&) const
594 int codecvt<lyx::char_type, char, mbstate_t>::do_encoding() const throw()
601 bool codecvt<lyx::char_type, char, mbstate_t>::do_always_noconv() const throw()
606 #if __GNUC__ == 3 && __GNUC_MINOR__ < 4
609 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
610 mbstate_t const &, const char *, const char *, size_t) const
618 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
619 mbstate_t &, const char *, const char *, size_t) const
627 int codecvt<lyx::char_type, char, mbstate_t>::do_max_length() const throw()