]> git.lyx.org Git - lyx.git/blob - src/support/docstream.cpp
Extend the otexstream class to also report about paragraph breaks.
[lyx.git] / src / support / docstream.cpp
1 /**
2  * \file docstream.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Georg Baum
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "support/docstream.h"
14 #include "support/lstrings.h"
15 #include "support/unicode.h"
16
17 #include <algorithm>
18 #include <cerrno>
19 #include <cstdio>
20 #include <cstring>
21 #include <iconv.h>
22 #include <locale>
23
24 using namespace std;
25
26 using lyx::ucs4_codeset;
27 using lyx::support::contains;
28 using lyx::support::split;
29
30
31 #if defined(_MSC_VER) && (_MSC_VER >= 1600)
32 std::locale::id numpunct<lyx::char_type>::id;
33 #endif
34
35
36 namespace {
37
38 // We use C IO throughout this file, because the facets might be used with
39 // lyxerr in the future.
40
41
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>
45 {
46         typedef codecvt<lyx::char_type, char, mbstate_t> base;
47 public:
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,
52                         size_t refs = 0)
53                 : base(refs), encoding_(encoding)
54         {
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));
60                                 fflush(stderr);
61                                 throw lyx::iconv_codecvt_facet_exception();
62                         }
63                 } else
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));
70                                 fflush(stderr);
71                                 throw lyx::iconv_codecvt_facet_exception();
72                         }
73                 } else
74                         out_cd_ = (iconv_t)(-1);
75         }
76 protected:
77         virtual ~iconv_codecvt_facet()
78         {
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));
83                                 fflush(stderr);
84                         }
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));
89                                 fflush(stderr);
90                         }
91         }
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
96         {
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
106                 // the conversion.
107                 intern_type * from_new = 0;
108                 intern_type const * from_old = from;
109                 size_t extra = 0;
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));
114                         from_new[len] = 0;
115                         from_end = from_new + len + 1;
116                         from = from_new;
117                         extra = 1;
118                 }
119 #endif
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);
124 #endif
125                 from_next = from;
126                 to_next = to;
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.
133                 if (from_new) {
134                         --to_next;
135                         --from_next;
136                         from_next = from_old + (from_next - from);
137                         from = from_old;
138                         delete[] from_new;
139                 }
140 #endif
141                 if (retval == base::error) {
142                         fprintf(stderr,
143                                 "Error %d returned from iconv when converting from %s to %s: %s\n",
144                                 errno, ucs4_codeset, encoding_.c_str(),
145                                 strerror(errno));
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);
150                         }
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);
157                         }
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);
165                         }
166                         fputc('\n', stderr);
167                         fflush(stderr);
168                 }
169                 return retval;
170         }
171         virtual result do_unshift(state_type &, extern_type * to,
172                         extern_type *, extern_type *& to_next) const
173         {
174                 // utf8 does not use shifting
175                 to_next = to;
176                 return base::noconv;
177         }
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
183         {
184                 size_t inbytesleft = (from_end - from) * sizeof(extern_type);
185                 size_t outbytesleft = (to_end - to) * sizeof(intern_type);
186                 from_next = from;
187                 to_next = to;
188                 result const retval = do_iconv(in_cd_, &from_next, &inbytesleft,
189                                 reinterpret_cast<char **>(&to_next),
190                                 &outbytesleft);
191                 if (retval == base::error) {
192                         fprintf(stderr,
193                                 "Error %d returned from iconv when converting from %s to %s: %s\n",
194                                 errno, encoding_.c_str(), ucs4_codeset,
195                                 strerror(errno));
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);
203                         }
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);
212                         }
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);
217                         }
218                         fputc('\n', stderr);
219                         fflush(stderr);
220                 }
221                 return retval;
222         }
223         virtual int do_encoding() const throw()
224         {
225                 return 0;
226         }
227         virtual bool do_always_noconv() const throw()
228         {
229                 return false;
230         }
231         virtual int do_length(state_type & /*state*/, extern_type const * from,
232                         extern_type const * end, size_t max) const
233         {
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.
240 #if 0
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);
246                 delete[] to;
247                 return to_next - to;
248 #else
249                 size_t const length = end - from;
250                 return min(length, max);
251 #endif
252         }
253         virtual int do_max_length() const throw()
254         {
255                 return lyx::max_encoded_bytes(encoding_);
256         }
257 private:
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
262         {
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)) {
267                         switch(errno) {
268                         case 0: 
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
273                                 // for details
274                                 // http://thread.gmane.org/gmane.editors.lyx.devel/117636
275                                 break;
276                         case EINVAL:
277                         case E2BIG:
278                                 return base::partial;
279                         case EILSEQ:
280                         default:
281                                 return base::error;
282                         }
283                 }
284                 if (*to == to_start)
285                         return base::noconv;
286                 return base::ok;
287         }
288         iconv_t in_cd_;
289         iconv_t out_cd_;
290         /// The narrow encoding
291         string encoding_;
292 };
293
294 } // namespace anon
295
296
297 namespace lyx {
298
299 template<class Ios>
300 void setEncoding(Ios & ios, string const & encoding, ios_base::openmode mode)
301 {
302         // We must imbue the stream before openening the file
303         locale global;
304         locale locale(global, new iconv_codecvt_facet(encoding, mode));
305         ios.imbue(locale);
306 }
307
308
309 const char * iconv_codecvt_facet_exception::what() const throw()
310 {
311         return "iconv problem in iconv_codecvt_facet initialization";
312 }
313
314
315 ifdocstream::ifdocstream() : base()
316 {
317         setEncoding(*this, "UTF-8", in);
318 }
319
320
321 ifdocstream::ifdocstream(const char* s, ios_base::openmode mode,
322                          string const & encoding)
323         : base()
324 {
325         setEncoding(*this, encoding, in);
326         open(s, mode);
327 }
328
329
330 ofdocstream::ofdocstream(): base()
331 {
332         setEncoding(*this, "UTF-8", out);
333 }
334
335
336 ofdocstream::ofdocstream(const char* s, ios_base::openmode mode,
337                          string const & encoding)
338         : base()
339 {
340         setEncoding(*this, encoding, out);
341         open(s, mode);
342 }
343
344
345 void ofdocstream::reset(string const & encoding)
346 {
347         setEncoding(*this, encoding, out);
348 }
349
350
351
352 SetEnc setEncoding(string const & encoding)
353 {
354         return SetEnc(encoding);
355 }
356
357
358 odocstream & operator<<(odocstream & os, SetEnc e)
359 {
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.
365                 os.flush();
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?
372                 os.imbue(locale);
373         }
374         return os;
375 }
376
377
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)
381 {
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.
387                 //is.flush();
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?
394                 is.imbue(locale);
395         }
396         return is;
397 }
398
399
400 #if ! defined(USE_WCHAR_T)
401 odocstream & operator<<(odocstream & os, char c)
402 {
403         os.put(c);
404         return os;
405 }
406 #endif
407
408
409 void otexstream::put(char_type const & c)
410 {
411         if (protectspace_) {
412                 if (!canbreakline_ && c == ' ')
413                         os_ << "{}";
414                 protectspace_ = false;
415         }
416         os_.put(c);
417         lastChar(c);
418         if (c == '\n')
419                 texrow_.newline();
420 }
421
422
423 BreakLine breakln;
424 SafeBreakLine safebreakln;
425
426
427 otexstream & operator<<(otexstream & ots, BreakLine)
428 {
429         if (ots.canBreakLine()) {
430                 ots.os().put('\n');
431                 ots.lastChar('\n');
432                 ots.texrow().newline();
433         }
434         ots.protectSpace(false);
435         return ots;
436 }
437
438
439 otexstream & operator<<(otexstream & ots, SafeBreakLine)
440 {
441         if (ots.canBreakLine()) {
442                 ots.os() << "%\n";
443                 ots.lastChar('\n');
444                 ots.texrow().newline();
445         }
446         ots.protectSpace(false);
447         return ots;
448 }
449
450
451 otexstream & operator<<(otexstream & ots, odocstream_manip pf)
452 {
453         ots.os() << pf;
454         if (pf == static_cast<odocstream_manip>(endl)) {
455                 ots.lastChar('\n');
456                 ots.texrow().newline();
457         }
458         return ots;
459 }
460
461
462 otexstream & operator<<(otexstream & ots, docstring const & s)
463 {
464         size_t const len = s.length();
465
466         // Check whether there's something to output
467         if (len == 0)
468                 return ots;
469
470         if (ots.protectSpace()) {
471                 if (!ots.canBreakLine() && s[0] == ' ')
472                         ots.os() << "{}";
473                 ots.protectSpace(false);
474         }
475
476         if (contains(s, 0xF0000)) {
477                 // Some encoding changes for the underlying stream are embedded
478                 // in the docstring. The encoding names to be used are enclosed
479                 // between the code points 0xF0000 and 0xF0001, the first two
480                 // characters of plane 15, which is a Private Use Area whose
481                 // codepoints don't have any associated glyph.
482                 docstring s1;
483                 docstring s2 = split(s, s1, 0xF0000);
484                 while (true) {
485                         if (!s1.empty())
486                                 ots.os() << s1;
487                         if (s2.empty())
488                                 break;
489                         docstring enc;
490                         docstring const s3 = split(s2, enc, 0xF0001);
491                         if (!contains(s2, 0xF0001))
492                                 s2 = split(enc, s1, 0xF0000);
493                         else {
494                                 ots.os() << setEncoding(to_ascii(enc));
495                                 s2 = split(s3, s1, 0xF0000);
496                         }
497                 }
498         } else
499                 ots.os() << s;
500
501         if (len > 1)
502                 ots.canBreakLine(s[len - 2] != '\n');
503         ots.lastChar(s[len - 1]);
504         ots.texrow().newlines(count(s.begin(), s.end(), '\n'));
505         return ots;
506 }
507
508
509 otexstream & operator<<(otexstream & ots, string const & s)
510 {
511         ots << from_utf8(s);
512         return ots;
513 }
514
515
516 otexstream & operator<<(otexstream & ots, char const * s)
517 {
518         ots << from_utf8(s);
519         return ots;
520 }
521
522
523 otexstream & operator<<(otexstream & ots, char c)
524 {
525         if (ots.protectSpace()) {
526                 if (!ots.canBreakLine() && c == ' ')
527                         ots.os() << "{}";
528                 ots.protectSpace(false);
529         }
530         ots.os() << c;
531         ots.lastChar(c);
532         if (c == '\n')
533                 ots.texrow().newline();
534         return ots;
535 }
536
537
538 template <typename Type>
539 otexstream & operator<<(otexstream & ots, Type value)
540 {
541         ots.os() << value;
542         ots.lastChar(0);
543         ots.protectSpace(false);
544         return ots;
545 }
546
547 template otexstream & operator<< <SetEnc>(otexstream & os, SetEnc);
548 template otexstream & operator<< <double>(otexstream &, double);
549 template otexstream & operator<< <int>(otexstream &, int);
550 template otexstream & operator<< <unsigned int>(otexstream &, unsigned int);
551 template otexstream & operator<< <unsigned long>(otexstream &, unsigned long);
552
553 }
554
555 #if ! defined(USE_WCHAR_T) && defined(__GNUC__)
556 // We get undefined references to these virtual methods. This looks like
557 // a bug in gcc. The implementation here does not do anything useful, since
558 // it is overriden in iconv_codecvt_facet.
559 namespace std {
560
561 template<> codecvt<lyx::char_type, char, mbstate_t>::result
562 codecvt<lyx::char_type, char, mbstate_t>::do_out(
563         mbstate_t &, const lyx::char_type *, const lyx::char_type *,
564         const lyx::char_type *&, char *, char *, char *&) const
565 {
566         return error;
567 }
568
569
570 template<> codecvt<lyx::char_type, char, mbstate_t>::result
571 codecvt<lyx::char_type, char, mbstate_t>::do_unshift(
572         mbstate_t &, char *, char *, char *&) const
573 {
574         return error;
575 }
576
577
578 template<> codecvt<lyx::char_type, char, mbstate_t>::result
579 codecvt<lyx::char_type, char, mbstate_t>::do_in(
580         mbstate_t &, const char *, const char *, const char *&,
581         lyx::char_type *, lyx::char_type *, lyx::char_type *&) const
582 {
583         return error;
584 }
585
586
587 template<>
588 int codecvt<lyx::char_type, char, mbstate_t>::do_encoding() const throw()
589 {
590         return 0;
591 }
592
593
594 template<>
595 bool codecvt<lyx::char_type, char, mbstate_t>::do_always_noconv() const throw()
596 {
597         return true;
598 }
599
600 #if __GNUC__ == 3 && __GNUC_MINOR__ < 4
601
602 template<>
603 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
604         mbstate_t const &, const char *, const char *, size_t) const
605 {
606         return 1;
607 }
608
609 #else
610
611 template<>
612 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
613         mbstate_t &, const char *, const char *, size_t) const
614 {
615         return 1;
616 }
617
618 #endif
619
620 template<>
621 int codecvt<lyx::char_type, char, mbstate_t>::do_max_length() const throw()
622 {
623         return 4;
624 }
625
626 } // namespace std
627 #endif