]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
Implementation of the conclusion of the "LyX/Mac 1.6 -- Window issues" thread:
[lyx.git] / src / Paragraph.cpp
1 /**
2  * \file Paragraph.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Dekel Tsur
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "Paragraph.h"
21
22 #include "LayoutFile.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "Changes.h"
26 #include "Counters.h"
27 #include "Encoding.h"
28 #include "InsetList.h"
29 #include "Language.h"
30 #include "LaTeXFeatures.h"
31 #include "Layout.h"
32 #include "Length.h"
33 #include "Font.h"
34 #include "FontList.h"
35 #include "LyXRC.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
40 #include "sgml.h"
41 #include "TextClass.h"
42 #include "TexRow.h"
43 #include "Text.h"
44 #include "VSpace.h"
45 #include "WordList.h"
46
47 #include "frontends/alert.h"
48
49 #include "insets/InsetBibitem.h"
50 #include "insets/InsetLabel.h"
51 // needed only for inTableCell()
52 #include "insets/InsetText.h"
53
54 #include "support/convert.h"
55 #include "support/debug.h"
56 #include "support/gettext.h"
57 #include "support/lstrings.h"
58 #include "support/Messages.h"
59 #include "support/textutils.h"
60
61 #include <sstream>
62 #include <vector>
63
64 using namespace std;
65 using namespace lyx::support;
66
67 namespace lyx {
68
69 namespace {
70 /// Inset identifier (above 0x10ffff, for ucs-4)
71 char_type const META_INSET = 0x200001;
72 };
73
74 /////////////////////////////////////////////////////////////////////
75 //
76 // Paragraph::Private
77 //
78 /////////////////////////////////////////////////////////////////////
79
80 class Paragraph::Private
81 {
82 public:
83         ///
84         Private(Paragraph * owner, Layout const & layout);
85         /// "Copy constructor"
86         Private(Private const &, Paragraph * owner);
87
88         ///
89         void insertChar(pos_type pos, char_type c, Change const & change);
90
91         /// Output the surrogate pair formed by \p c and \p next to \p os.
92         /// \return the number of characters written.
93         int latexSurrogatePair(odocstream & os, char_type c, char_type next,
94                                Encoding const &);
95
96         /// Output a space in appropriate formatting (or a surrogate pair
97         /// if the next character is a combining character).
98         /// \return whether a surrogate pair was output.
99         bool simpleTeXBlanks(OutputParams const &,
100                              odocstream &, TexRow & texrow,
101                              pos_type i,
102                              unsigned int & column,
103                              Font const & font,
104                              Layout const & style);
105
106         /// Output consecutive unicode chars, belonging to the same script as
107         /// specified by the latex macro \p ltx, to \p os starting from \p i.
108         /// \return the number of characters written.
109         int writeScriptChars(odocstream & os, docstring const & ltx,
110                            Change &, Encoding const &, pos_type & i);
111
112         /// This could go to ParagraphParameters if we want to.
113         int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
114                               bool) const;
115
116         /// This could go to ParagraphParameters if we want to.
117         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
118                             bool) const;
119
120         ///
121         void latexInset(BufferParams const &,
122                                    odocstream &,
123                                    TexRow & texrow, OutputParams &,
124                                    Font & running_font,
125                                    Font & basefont,
126                                    Font const & outerfont,
127                                    bool & open_font,
128                                    Change & running_change,
129                                    Layout const & style,
130                                    pos_type & i,
131                                    unsigned int & column);
132
133         ///
134         void latexSpecialChar(
135                                    odocstream & os,
136                                    OutputParams & runparams,
137                                    Font & running_font,
138                                    Change & running_change,
139                                    Layout const & style,
140                                    pos_type & i,
141                                    unsigned int & column);
142
143         ///
144         bool latexSpecialT1(
145                 char_type const c,
146                 odocstream & os,
147                 pos_type & i,
148                 unsigned int & column);
149         ///
150         bool latexSpecialTypewriter(
151                 char_type const c,
152                 odocstream & os,
153                 pos_type & i,
154                 unsigned int & column);
155         ///
156         bool latexSpecialPhrase(
157                 odocstream & os,
158                 pos_type & i,
159                 unsigned int & column,
160                 OutputParams & runparams);
161
162         ///
163         void validate(LaTeXFeatures & features,
164                       Layout const & layout) const;
165
166         /// Checks if the paragraph contains only text and no inset or font change.
167         bool onlyText(Buffer const & buf, Font const & outerfont,
168                       pos_type initial) const;
169
170         /// match a string against a particular point in the paragraph
171         bool isTextAt(string const & str, pos_type pos) const;
172         
173         /// Which Paragraph owns us?
174         Paragraph * owner_;
175
176         /// In which Inset?
177         Inset * inset_owner_;
178
179         ///
180         FontList fontlist_;
181
182         ///
183         unsigned int id_;
184         ///
185         static unsigned int paragraph_id;
186         ///
187         ParagraphParameters params_;
188
189         /// for recording and looking up changes
190         Changes changes_;
191
192         ///
193         InsetList insetlist_;
194
195         /// end of label
196         pos_type begin_of_body_;
197
198         typedef docstring TextContainer;
199         ///
200         TextContainer text_;
201         
202         typedef std::set<docstring> Words;
203         ///
204         Words words_;
205         ///
206         Layout const * layout_;
207 };
208
209
210 // Initialization of the counter for the paragraph id's,
211 unsigned int Paragraph::Private::paragraph_id = 0;
212
213 namespace {
214
215 struct special_phrase {
216         string phrase;
217         docstring macro;
218         bool builtin;
219 };
220
221 special_phrase const special_phrases[] = {
222         { "LyX", from_ascii("\\LyX{}"), false },
223         { "TeX", from_ascii("\\TeX{}"), true },
224         { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
225         { "LaTeX", from_ascii("\\LaTeX{}"), true },
226 };
227
228 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
229
230 } // namespace anon
231
232
233 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
234         : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
235 {
236         id_ = paragraph_id++;
237         text_.reserve(100);
238 }
239
240
241 Paragraph::Private::Private(Private const & p, Paragraph * owner)
242         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_), 
243           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
244           begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
245           layout_(p.layout_)
246 {
247         id_ = paragraph_id++;
248 }
249
250
251 bool Paragraph::isChanged(pos_type start, pos_type end) const
252 {
253         BOOST_ASSERT(start >= 0 && start <= size());
254         BOOST_ASSERT(end > start && end <= size() + 1);
255
256         return d->changes_.isChanged(start, end);
257 }
258
259
260 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
261 {
262         // keep the logic here in sync with the logic of eraseChars()
263         if (!trackChanges)
264                 return true;
265
266         Change const change = d->changes_.lookup(size());
267         return change.type == Change::INSERTED && change.author == 0;
268 }
269
270
271 void Paragraph::setChange(Change const & change)
272 {
273         // beware of the imaginary end-of-par character!
274         d->changes_.set(change, 0, size() + 1);
275
276         /*
277          * Propagate the change recursively - but not in case of DELETED!
278          *
279          * Imagine that your co-author makes changes in an existing inset. He
280          * sends your document to you and you come to the conclusion that the
281          * inset should go completely. If you erase it, LyX must not delete all
282          * text within the inset. Otherwise, the change tracked insertions of
283          * your co-author get lost and there is no way to restore them later.
284          *
285          * Conclusion: An inset's content should remain untouched if you delete it
286          */
287
288         if (change.type != Change::DELETED) {
289                 for (pos_type pos = 0; pos < size(); ++pos) {
290                         if (Inset * inset = getInset(pos))
291                                 inset->setChange(change);
292                 }
293         }
294 }
295
296
297 void Paragraph::setChange(pos_type pos, Change const & change)
298 {
299         BOOST_ASSERT(pos >= 0 && pos <= size());
300         d->changes_.set(change, pos);
301
302         // see comment in setChange(Change const &) above
303         if (change.type != Change::DELETED && pos < size())
304                         if (Inset * inset = getInset(pos))
305                                 inset->setChange(change);
306 }
307
308
309 Change const & Paragraph::lookupChange(pos_type pos) const
310 {
311         BOOST_ASSERT(pos >= 0 && pos <= size());
312         return d->changes_.lookup(pos);
313 }
314
315
316 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
317                 pos_type end)
318 {
319         BOOST_ASSERT(start >= 0 && start <= size());
320         BOOST_ASSERT(end > start && end <= size() + 1);
321
322         for (pos_type pos = start; pos < end; ++pos) {
323                 switch (lookupChange(pos).type) {
324                         case Change::UNCHANGED:
325                                 // accept changes in nested inset
326                                 if (Inset * inset = getInset(pos))
327                                         inset->acceptChanges(bparams);
328                                 break;
329
330                         case Change::INSERTED:
331                                 d->changes_.set(Change(Change::UNCHANGED), pos);
332                                 // also accept changes in nested inset
333                                 if (Inset * inset = getInset(pos))
334                                         inset->acceptChanges(bparams);
335                                 break;
336
337                         case Change::DELETED:
338                                 // Suppress access to non-existent
339                                 // "end-of-paragraph char"
340                                 if (pos < size()) {
341                                         eraseChar(pos, false);
342                                         --end;
343                                         --pos;
344                                 }
345                                 break;
346                 }
347
348         }
349 }
350
351
352 void Paragraph::rejectChanges(BufferParams const & bparams,
353                 pos_type start, pos_type end)
354 {
355         BOOST_ASSERT(start >= 0 && start <= size());
356         BOOST_ASSERT(end > start && end <= size() + 1);
357
358         for (pos_type pos = start; pos < end; ++pos) {
359                 switch (lookupChange(pos).type) {
360                         case Change::UNCHANGED:
361                                 // reject changes in nested inset
362                                 if (Inset * inset = getInset(pos))
363                                                 inset->rejectChanges(bparams);
364                                 break;
365
366                         case Change::INSERTED:
367                                 // Suppress access to non-existent
368                                 // "end-of-paragraph char"
369                                 if (pos < size()) {
370                                         eraseChar(pos, false);
371                                         --end;
372                                         --pos;
373                                 }
374                                 break;
375
376                         case Change::DELETED:
377                                 d->changes_.set(Change(Change::UNCHANGED), pos);
378
379                                 // Do NOT reject changes within a deleted inset!
380                                 // There may be insertions of a co-author inside of it!
381
382                                 break;
383                 }
384         }
385 }
386
387
388 void Paragraph::Private::insertChar(pos_type pos, char_type c,
389                 Change const & change)
390 {
391         BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
392
393         // track change
394         changes_.insert(change, pos);
395
396         // This is actually very common when parsing buffers (and
397         // maybe inserting ascii text)
398         if (pos == pos_type(text_.size())) {
399                 // when appending characters, no need to update tables
400                 text_.push_back(c);
401                 return;
402         }
403
404         text_.insert(text_.begin() + pos, c);
405
406         // Update the font table.
407         fontlist_.increasePosAfterPos(pos);
408
409         // Update the insets
410         insetlist_.increasePosAfterPos(pos);
411 }
412
413
414 void Paragraph::insertInset(pos_type pos, Inset * inset,
415                                    Change const & change)
416 {
417         BOOST_ASSERT(inset);
418         BOOST_ASSERT(pos >= 0 && pos <= size());
419
420         d->insertChar(pos, META_INSET, change);
421         BOOST_ASSERT(d->text_[pos] == META_INSET);
422
423         // Add a new entry in the insetlist_.
424         d->insetlist_.insert(inset, pos);
425 }
426
427
428 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
429 {
430         BOOST_ASSERT(pos >= 0 && pos <= size());
431
432         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
433
434         if (trackChanges) {
435                 Change change = d->changes_.lookup(pos);
436
437                 // set the character to DELETED if
438                 //  a) it was previously unchanged or
439                 //  b) it was inserted by a co-author
440
441                 if (change.type == Change::UNCHANGED ||
442                     (change.type == Change::INSERTED && change.author != 0)) {
443                         setChange(pos, Change(Change::DELETED));
444                         return false;
445                 }
446
447                 if (change.type == Change::DELETED)
448                         return false;
449         }
450
451         // Don't physically access the imaginary end-of-paragraph character.
452         // eraseChar() can only mark it as DELETED. A physical deletion of
453         // end-of-par must be handled externally.
454         if (pos == size()) {
455                 return false;
456         }
457
458         // track change
459         d->changes_.erase(pos);
460
461         // if it is an inset, delete the inset entry
462         if (d->text_[pos] == META_INSET)
463                 d->insetlist_.erase(pos);
464
465         d->text_.erase(d->text_.begin() + pos);
466
467         // Update the fontlist_
468         d->fontlist_.erase(pos);
469
470         // Update the insetlist_
471         d->insetlist_.decreasePosAfterPos(pos);
472
473         return true;
474 }
475
476
477 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
478 {
479         BOOST_ASSERT(start >= 0 && start <= size());
480         BOOST_ASSERT(end >= start && end <= size() + 1);
481
482         pos_type i = start;
483         for (pos_type count = end - start; count; --count) {
484                 if (!eraseChar(i, trackChanges))
485                         ++i;
486         }
487         return end - i;
488 }
489
490
491 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
492                 char_type next, Encoding const & encoding)
493 {
494         // Writing next here may circumvent a possible font change between
495         // c and next. Since next is only output if it forms a surrogate pair
496         // with c we can ignore this:
497         // A font change inside a surrogate pair does not make sense and is
498         // hopefully impossible to input.
499         // FIXME: change tracking
500         // Is this correct WRT change tracking?
501         docstring const latex1 = encoding.latexChar(next);
502         docstring const latex2 = encoding.latexChar(c);
503         os << latex1 << '{' << latex2 << '}';
504         return latex1.length() + latex2.length() + 2;
505 }
506
507
508 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
509                                        odocstream & os, TexRow & texrow,
510                                        pos_type i,
511                                        unsigned int & column,
512                                        Font const & font,
513                                        Layout const & style)
514 {
515         if (style.pass_thru || runparams.verbatim)
516                 return false;
517
518         if (i + 1 < int(text_.size())) {
519                 char_type next = text_[i + 1];
520                 if (Encodings::isCombiningChar(next)) {
521                         Encoding const & encoding = *(runparams.encoding);
522                         // This space has an accent, so we must always output it.
523                         column += latexSurrogatePair(os, ' ', next, encoding) - 1;
524                         return true;
525                 }
526         }
527
528         if (lyxrc.plaintext_linelen > 0
529             && column > lyxrc.plaintext_linelen
530             && i
531             && text_[i - 1] != ' '
532             && (i + 1 < int(text_.size()))
533             // same in FreeSpacing mode
534             && !owner_->isFreeSpacing()
535             // In typewriter mode, we want to avoid
536             // ! . ? : at the end of a line
537             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
538                  && (text_[i - 1] == '.'
539                      || text_[i - 1] == '?'
540                      || text_[i - 1] == ':'
541                      || text_[i - 1] == '!'))) {
542                 os << '\n';
543                 texrow.newline();
544                 texrow.start(owner_->id(), i + 1);
545                 column = 0;
546         } else if (style.free_spacing) {
547                 os << '~';
548         } else {
549                 os << ' ';
550         }
551         return false;
552 }
553
554
555 int Paragraph::Private::writeScriptChars(odocstream & os,
556                                          docstring const & ltx,
557                                          Change & runningChange,
558                                          Encoding const & encoding,
559                                          pos_type & i)
560 {
561         // FIXME: modifying i here is not very nice...
562
563         // We only arrive here when a proper language for character text_[i] has
564         // not been specified (i.e., it could not be translated in the current
565         // latex encoding) and it belongs to a known script.
566         // Parameter ltx contains the latex translation of text_[i] as specified in
567         // the unicodesymbols file and is something like "\textXXX{<spec>}".
568         // The latex macro name "textXXX" specifies the script to which text_[i]
569         // belongs and we use it in order to check whether characters from the
570         // same script immediately follow, such that we can collect them in a
571         // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
572         // for the first char but only "<spec>" for all subsequent chars.
573         docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
574         docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
575         string script = to_ascii(ltx.substr(1, brace1 - 1));
576         int length = ltx.substr(0, brace2).length();
577         os << ltx.substr(0, brace2);
578         int size = text_.size();
579         while (i + 1 < size) {
580                 char_type const next = text_[i + 1];
581                 // Stop here if next character belongs to another script
582                 // or there is a change in change tracking status.
583                 if (!Encodings::isKnownScriptChar(next, script) ||
584                     runningChange != owner_->lookupChange(i + 1))
585                         break;
586                 Font prev_font;
587                 bool found = false;
588                 FontList::const_iterator cit = fontlist_.begin();
589                 FontList::const_iterator end = fontlist_.end();
590                 for (; cit != end; ++cit) {
591                         if (cit->pos() >= i && !found) {
592                                 prev_font = cit->font();
593                                 found = true;
594                         }
595                         if (cit->pos() >= i + 1)
596                                 break;
597                 }
598                 // Stop here if there is a font attribute or encoding change.
599                 if (found && cit != end && prev_font != cit->font())
600                         break;
601                 docstring const latex = encoding.latexChar(next);
602                 docstring::size_type const b1 =
603                                         latex.find_first_of(from_ascii("{"));
604                 docstring::size_type const b2 =
605                                         latex.find_last_of(from_ascii("}"));
606                 int const len = b2 - b1 - 1;
607                 os << latex.substr(b1 + 1, len);
608                 length += len;
609                 ++i;
610         }
611         os << '}';
612         ++length;
613         return length;
614 }
615
616
617 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
618 {
619         pos_type const len = str.length();
620
621         // is the paragraph large enough?
622         if (pos + len > int(text_.size()))
623                 return false;
624
625         // does the wanted text start at point?
626         for (string::size_type i = 0; i < str.length(); ++i) {
627                 // Caution: direct comparison of characters works only
628                 // because str is pure ASCII.
629                 if (str[i] != text_[pos + i])
630                         return false;
631         }
632
633         return fontlist_.hasChangeInRange(pos, len);
634 }
635
636
637 void Paragraph::Private::latexInset(
638                                              BufferParams const & bparams,
639                                              odocstream & os,
640                                              TexRow & texrow,
641                                              OutputParams & runparams,
642                                              Font & running_font,
643                                              Font & basefont,
644                                              Font const & outerfont,
645                                              bool & open_font,
646                                              Change & running_change,
647                                              Layout const & style,
648                                              pos_type & i,
649                                              unsigned int & column)
650 {
651         Inset * inset = owner_->getInset(i);
652         BOOST_ASSERT(inset);
653
654         if (style.pass_thru) {
655                 inset->plaintext(os, runparams);
656                 return;
657         }
658
659         // FIXME: move this to InsetNewline::latex
660         if (inset->lyxCode() == NEWLINE_CODE) {
661                 // newlines are handled differently here than
662                 // the default in simpleTeXSpecialChars().
663                 if (!style.newline_allowed) {
664                         os << '\n';
665                 } else {
666                         if (open_font) {
667                                 column += running_font.latexWriteEndChanges(
668                                         os, bparams, runparams,
669                                         basefont, basefont);
670                                 open_font = false;
671                         }
672
673                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
674                                 os << '~';
675
676                         basefont = owner_->getLayoutFont(bparams, outerfont);
677                         running_font = basefont;
678
679                         if (runparams.moving_arg)
680                                 os << "\\protect ";
681
682                 }
683                 texrow.newline();
684                 texrow.start(owner_->id(), i + 1);
685                 column = 0;
686         }
687
688         if (owner_->lookupChange(i).type == Change::DELETED) {
689                 if( ++runparams.inDeletedInset == 1)
690                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
691         }
692
693         if (inset->canTrackChanges()) {
694                 column += Changes::latexMarkChange(os, bparams, running_change,
695                         Change(Change::UNCHANGED));
696                 running_change = Change(Change::UNCHANGED);
697         }
698
699         bool close = false;
700         odocstream::pos_type const len = os.tellp();
701
702         if (inset->forceLTR() 
703             && running_font.isRightToLeft()
704                 // ERT is an exception, it should be output with no decorations at all
705                 && inset->lyxCode() != ERT_CODE) {
706                 if (running_font.language()->lang() == "farsi")
707                         os << "\\beginL{}";
708                 else
709                         os << "\\L{";
710                 close = true;
711         }
712
713         // FIXME: Bug: we can have an empty font change here!
714         // if there has just been a font change, we are going to close it
715         // right now, which means stupid latex code like \textsf{}. AFAIK,
716         // this does not harm dvi output. A minor bug, thus (JMarc)
717
718         // Some insets cannot be inside a font change command.
719         // However, even such insets *can* be placed in \L or \R
720         // or their equivalents (for RTL language switches), so we don't
721         // close the language in those cases.
722         // ArabTeX, though, cannot handle this special behavior, it seems.
723         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
724                 || running_font.language()->lang() == "arabic_arabtex";
725         if (open_font && inset->noFontChange()) {
726                 bool closeLanguage = arabtex
727                         || basefont.isRightToLeft() == running_font.isRightToLeft();
728                 unsigned int count = running_font.latexWriteEndChanges(os,
729                         bparams, runparams, basefont, basefont, closeLanguage);
730                 column += count;
731                 // if any font properties were closed, update the running_font, 
732                 // making sure, however, to leave the language as it was
733                 if (count > 0) {
734                         // FIXME: probably a better way to keep track of the old 
735                         // language, than copying the entire font?
736                         Font const copy_font(running_font);
737                         basefont = owner_->getLayoutFont(bparams, outerfont);
738                         running_font = basefont;
739                         if (!closeLanguage)
740                                 running_font.setLanguage(copy_font.language());
741                         // leave font open if language is still open
742                         open_font = (running_font.language() == basefont.language());
743                         if (closeLanguage)
744                                 runparams.local_font = &basefont;
745                 }
746         }
747
748         int tmp = inset->latex(os, runparams);
749
750         if (close) {
751         if (running_font.language()->lang() == "farsi")
752                         os << "\\endL{}";
753                 else
754                         os << '}';
755         }
756
757         if (tmp) {
758                 for (int j = 0; j < tmp; ++j)
759                         texrow.newline();
760
761                 texrow.start(owner_->id(), i + 1);
762                 column = 0;
763         } else {
764                 column += os.tellp() - len;
765         }
766
767         if (owner_->lookupChange(i).type == Change::DELETED)
768                 --runparams.inDeletedInset;
769 }
770
771
772 void Paragraph::Private::latexSpecialChar(
773                                              odocstream & os,
774                                              OutputParams & runparams,
775                                              Font & running_font,
776                                              Change & running_change,
777                                              Layout const & style,
778                                              pos_type & i,
779                                              unsigned int & column)
780 {
781         char_type const c = text_[i];
782
783         if (style.pass_thru) {
784                 if (c != '\0')
785                         // FIXME UNICODE: This can fail if c cannot
786                         // be encoded in the current encoding.
787                         os.put(c);
788                 return;
789         }
790
791         if (runparams.verbatim) {
792                 os.put(c);
793                 return;
794         }
795
796         if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
797                 return;
798
799         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
800                 && latexSpecialTypewriter(c, os, i, column))
801                 return;
802
803         // Otherwise, we use what LaTeX provides us.
804         switch (c) {
805         case '\\':
806                 os << "\\textbackslash{}";
807                 column += 15;
808                 break;
809         case '<':
810                 os << "\\textless{}";
811                 column += 10;
812                 break;
813         case '>':
814                 os << "\\textgreater{}";
815                 column += 13;
816                 break;
817         case '|':
818                 os << "\\textbar{}";
819                 column += 9;
820                 break;
821         case '-':
822                 os << '-';
823                 break;
824         case '\"':
825                 os << "\\char`\\\"{}";
826                 column += 9;
827                 break;
828
829         case '$': case '&':
830         case '%': case '#': case '{':
831         case '}': case '_':
832                 os << '\\';
833                 os.put(c);
834                 column += 1;
835                 break;
836
837         case '~':
838                 os << "\\textasciitilde{}";
839                 column += 16;
840                 break;
841
842         case '^':
843                 os << "\\textasciicircum{}";
844                 column += 17;
845                 break;
846
847         case '*': case '[':
848                 // avoid being mistaken for optional arguments
849                 os << '{';
850                 os.put(c);
851                 os << '}';
852                 column += 2;
853                 break;
854
855         case ' ':
856                 // Blanks are printed before font switching.
857                 // Sure? I am not! (try nice-latex)
858                 // I am sure it's correct. LyX might be smarter
859                 // in the future, but for now, nothing wrong is
860                 // written. (Asger)
861                 break;
862
863         default:
864
865                 // LyX, LaTeX etc.
866                 if (latexSpecialPhrase(os, i, column, runparams))
867                         return;
868
869                 if (c == '\0')
870                         return;
871
872                 Encoding const & encoding = *(runparams.encoding);
873                 if (i + 1 < int(text_.size())) {
874                         char_type next = text_[i + 1];
875                         if (Encodings::isCombiningChar(next)) {
876                                 column += latexSurrogatePair(os, c, next, encoding) - 1;
877                                 ++i;
878                                 break;
879                         }
880                 }
881                 string script;
882                 docstring const latex = encoding.latexChar(c);
883                 if (Encodings::isKnownScriptChar(c, script)
884                     && prefixIs(latex, from_ascii("\\" + script)))
885                         column += writeScriptChars(os, latex,
886                                         running_change, encoding, i) - 1;
887                 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
888                         // Prevent eating of a following
889                         // space or command corruption by
890                         // following characters
891                         column += latex.length() + 1;
892                         os << latex << "{}";
893                 } else {
894                         column += latex.length() - 1;
895                         os << latex;
896                 }
897                 break;
898         }
899 }
900
901
902 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
903         pos_type & i, unsigned int & column)
904 {
905         switch (c) {
906         case '>':
907         case '<':
908                 os.put(c);
909                 // In T1 encoding, these characters exist
910                 // but we should avoid ligatures
911                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
912                         return true;
913                 os << "\\,{}";
914                 column += 3;
915                 // Alternative code:
916                 //os << "\\textcompwordmark{}";
917                 //column += 19;
918                 return true;
919         case '|':
920                 os.put(c);
921                 return true;
922         default:
923                 return false;
924         }
925 }
926
927
928 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
929         pos_type & i, unsigned int & column)
930 {
931         switch (c) {
932         case '-':
933                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
934                         // "--" in Typewriter mode -> "-{}-"
935                         os << "-{}";
936                         column += 2;
937                 } else
938                         os << '-';
939                 return true;
940
941         // I assume this is hack treating typewriter as verbatim
942         // FIXME UNICODE: This can fail if c cannot be encoded
943         // in the current encoding.
944
945         case '\0':
946                 return true;
947
948         // Those characters are not directly supported.
949         case '\\':
950         case '\"':
951         case '$': case '&':
952         case '%': case '#': case '{':
953         case '}': case '_':
954         case '~':
955         case '^':
956         case '*': case '[':
957         case ' ':
958                 return false;
959
960         default:
961                 // With Typewriter font, these characters exist.
962                 os.put(c);
963                 return true;
964         }
965 }
966
967
968 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
969         unsigned int & column, OutputParams & runparams)
970 {
971         // FIXME: if we have "LaTeX" with a font
972         // change in the middle (before the 'T', then
973         // the "TeX" part is still special cased.
974         // Really we should only operate this on
975         // "words" for some definition of word
976
977         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
978                 if (!isTextAt(special_phrases[pnr].phrase, i))
979                         continue;
980                 if (runparams.moving_arg)
981                         os << "\\protect";
982                 os << special_phrases[pnr].macro;
983                 i += special_phrases[pnr].phrase.length() - 1;
984                 column += special_phrases[pnr].macro.length() - 1;
985                 return true;
986         }
987         return false;
988 }
989
990
991 void Paragraph::Private::validate(LaTeXFeatures & features,
992                                 Layout const & layout) const
993 {
994         // check the params.
995         if (!params_.spacing().isDefault())
996                 features.require("setspace");
997
998         // then the layouts
999         features.useLayout(layout.name());
1000
1001         // then the fonts
1002         fontlist_.validate(features);
1003
1004         // then the indentation
1005         if (!params_.leftIndent().zero())
1006                 features.require("ParagraphLeftIndent");
1007
1008         // then the insets
1009         InsetList::const_iterator icit = insetlist_.begin();
1010         InsetList::const_iterator iend = insetlist_.end();
1011         for (; icit != iend; ++icit) {
1012                 if (icit->inset) {
1013                         icit->inset->validate(features);
1014                         if (layout.needprotect &&
1015                             icit->inset->lyxCode() == FOOT_CODE)
1016                                 features.require("NeedLyXFootnoteCode");
1017                 }
1018         }
1019
1020         // then the contents
1021         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1022                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1023                         if (!special_phrases[pnr].builtin
1024                             && isTextAt(special_phrases[pnr].phrase, i)) {
1025                                 features.require(special_phrases[pnr].phrase);
1026                                 break;
1027                         }
1028                 }
1029                 Encodings::validate(text_[i], features);
1030         }
1031 }
1032
1033 /////////////////////////////////////////////////////////////////////
1034 //
1035 // Paragraph
1036 //
1037 /////////////////////////////////////////////////////////////////////
1038
1039 namespace {
1040         Layout const emptyParagraphLayout;
1041 }
1042
1043 Paragraph::Paragraph() 
1044         : d(new Paragraph::Private(this, emptyParagraphLayout))
1045 {
1046         itemdepth = 0;
1047         d->params_.clear();
1048 }
1049
1050
1051 Paragraph::Paragraph(Paragraph const & par)
1052         : itemdepth(par.itemdepth),
1053         d(new Paragraph::Private(*par.d, this))
1054 {
1055         registerWords();
1056 }
1057
1058
1059 Paragraph & Paragraph::operator=(Paragraph const & par)
1060 {
1061         // needed as we will destroy the private part before copying it
1062         if (&par != this) {
1063                 itemdepth = par.itemdepth;
1064
1065                 deregisterWords();
1066                 delete d;
1067                 d = new Private(*par.d, this);
1068                 registerWords();
1069         }
1070         return *this;
1071 }
1072
1073
1074 Paragraph::~Paragraph()
1075 {
1076         deregisterWords();
1077         delete d;
1078 }
1079
1080
1081 void Paragraph::write(ostream & os, BufferParams const & bparams,
1082         depth_type & dth) const
1083 {
1084         // The beginning or end of a deeper (i.e. nested) area?
1085         if (dth != d->params_.depth()) {
1086                 if (d->params_.depth() > dth) {
1087                         while (d->params_.depth() > dth) {
1088                                 os << "\n\\begin_deeper";
1089                                 ++dth;
1090                         }
1091                 } else {
1092                         while (d->params_.depth() < dth) {
1093                                 os << "\n\\end_deeper";
1094                                 --dth;
1095                         }
1096                 }
1097         }
1098
1099         // First write the layout
1100         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1101
1102         d->params_.write(os);
1103
1104         Font font1(inherit_font, bparams.language);
1105
1106         Change running_change = Change(Change::UNCHANGED);
1107
1108         int column = 0;
1109         for (pos_type i = 0; i <= size(); ++i) {
1110
1111                 Change change = lookupChange(i);
1112                 Changes::lyxMarkChange(os, column, running_change, change);
1113                 running_change = change;
1114
1115                 if (i == size())
1116                         break;
1117
1118                 // Write font changes
1119                 Font font2 = getFontSettings(bparams, i);
1120                 if (font2 != font1) {
1121                         font2.lyxWriteChanges(font1, os);
1122                         column = 0;
1123                         font1 = font2;
1124                 }
1125
1126                 char_type const c = d->text_[i];
1127                 switch (c) {
1128                 case META_INSET:
1129                         if (Inset const * inset = getInset(i)) {
1130                                 if (inset->directWrite()) {
1131                                         // international char, let it write
1132                                         // code directly so it's shorter in
1133                                         // the file
1134                                         inset->write(os);
1135                                 } else {
1136                                         if (i)
1137                                                 os << '\n';
1138                                         os << "\\begin_inset ";
1139                                         inset->write(os);
1140                                         os << "\n\\end_inset\n\n";
1141                                         column = 0;
1142                                 }
1143                         }
1144                         break;
1145                 case '\\':
1146                         os << "\n\\backslash\n";
1147                         column = 0;
1148                         break;
1149                 case '.':
1150                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1151                                 os << ".\n";
1152                                 column = 0;
1153                         } else
1154                                 os << '.';
1155                         break;
1156                 default:
1157                         if ((column > 70 && c == ' ')
1158                             || column > 79) {
1159                                 os << '\n';
1160                                 column = 0;
1161                         }
1162                         // this check is to amend a bug. LyX sometimes
1163                         // inserts '\0' this could cause problems.
1164                         if (c != '\0')
1165                                 os << to_utf8(docstring(1, c));
1166                         else
1167                                 lyxerr << "ERROR (Paragraph::writeFile):"
1168                                         " NULL char in structure." << endl;
1169                         ++column;
1170                         break;
1171                 }
1172         }
1173
1174         os << "\n\\end_layout\n";
1175 }
1176
1177
1178 void Paragraph::validate(LaTeXFeatures & features) const
1179 {
1180         d->validate(features, *d->layout_);
1181 }
1182
1183
1184 void Paragraph::insert(pos_type start, docstring const & str,
1185                        Font const & font, Change const & change)
1186 {
1187         for (size_t i = 0, n = str.size(); i != n ; ++i)
1188                 insertChar(start + i, str[i], font, change);
1189 }
1190
1191
1192 void Paragraph::appendChar(char_type c, Font const & font,
1193                 Change const & change)
1194 {
1195         // track change
1196         d->changes_.insert(change, d->text_.size());
1197         // when appending characters, no need to update tables
1198         d->text_.push_back(c);
1199         setFont(d->text_.size() - 1, font);
1200 }
1201
1202
1203 void Paragraph::appendString(docstring const & s, Font const & font,
1204                 Change const & change)
1205 {
1206         pos_type end = s.size();
1207         size_t oldsize = d->text_.size();
1208         size_t newsize = oldsize + end;
1209         size_t capacity = d->text_.capacity();
1210         if (newsize >= capacity)
1211                 d->text_.reserve(max(capacity + 100, newsize));
1212
1213         // when appending characters, no need to update tables
1214         d->text_.append(s);
1215
1216         // FIXME: Optimize this!
1217         for (pos_type i = 0; i != end; ++i) {
1218                 // track change
1219                 d->changes_.insert(change, i);
1220         }
1221         d->fontlist_.set(oldsize, font);
1222         d->fontlist_.set(newsize - 1, font);
1223 }
1224
1225
1226 void Paragraph::insertChar(pos_type pos, char_type c,
1227                            bool trackChanges)
1228 {
1229         d->insertChar(pos, c, Change(trackChanges ?
1230                            Change::INSERTED : Change::UNCHANGED));
1231 }
1232
1233
1234 void Paragraph::insertChar(pos_type pos, char_type c,
1235                            Font const & font, bool trackChanges)
1236 {
1237         d->insertChar(pos, c, Change(trackChanges ?
1238                            Change::INSERTED : Change::UNCHANGED));
1239         setFont(pos, font);
1240 }
1241
1242
1243 void Paragraph::insertChar(pos_type pos, char_type c,
1244                            Font const & font, Change const & change)
1245 {
1246         d->insertChar(pos, c, change);
1247         setFont(pos, font);
1248 }
1249
1250
1251 void Paragraph::insertInset(pos_type pos, Inset * inset,
1252                             Font const & font, Change const & change)
1253 {
1254         insertInset(pos, inset, change);
1255         // Set the font/language of the inset...
1256         setFont(pos, font);
1257 }
1258
1259
1260 bool Paragraph::insetAllowed(InsetCode code)
1261 {
1262         return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1263 }
1264
1265
1266 void Paragraph::resetFonts(Font const & font)
1267 {
1268         d->fontlist_.clear();
1269         d->fontlist_.set(0, font);
1270         d->fontlist_.set(d->text_.size() - 1, font);
1271 }
1272
1273 // Gets uninstantiated font setting at position.
1274 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1275                                          pos_type pos) const
1276 {
1277         if (pos > size()) {
1278                 lyxerr << " pos: " << pos << " size: " << size() << endl;
1279                 BOOST_ASSERT(pos <= size());
1280         }
1281
1282         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1283         if (cit != d->fontlist_.end())
1284                 return cit->font();
1285
1286         if (pos == size() && !empty())
1287                 return getFontSettings(bparams, pos - 1);
1288
1289         return Font(inherit_font, getParLanguage(bparams));
1290 }
1291
1292
1293 FontSpan Paragraph::fontSpan(pos_type pos) const
1294 {
1295         BOOST_ASSERT(pos <= size());
1296         pos_type start = 0;
1297
1298         FontList::const_iterator cit = d->fontlist_.begin();
1299         FontList::const_iterator end = d->fontlist_.end();
1300         for (; cit != end; ++cit) {
1301                 if (cit->pos() >= pos) {
1302                         if (pos >= beginOfBody())
1303                                 return FontSpan(max(start, beginOfBody()),
1304                                                 cit->pos());
1305                         else
1306                                 return FontSpan(start,
1307                                                 min(beginOfBody() - 1,
1308                                                          cit->pos()));
1309                 }
1310                 start = cit->pos() + 1;
1311         }
1312
1313         // This should not happen, but if so, we take no chances.
1314         //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1315         //      << endl;
1316         return FontSpan(pos, pos);
1317 }
1318
1319
1320 // Gets uninstantiated font setting at position 0
1321 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1322 {
1323         if (!empty() && !d->fontlist_.empty())
1324                 return d->fontlist_.begin()->font();
1325
1326         return Font(inherit_font, bparams.language);
1327 }
1328
1329
1330 // Gets the fully instantiated font at a given position in a paragraph
1331 // This is basically the same function as Text::GetFont() in text2.cpp.
1332 // The difference is that this one is used for generating the LaTeX file,
1333 // and thus cosmetic "improvements" are disallowed: This has to deliver
1334 // the true picture of the buffer. (Asger)
1335 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1336                                  Font const & outerfont) const
1337 {
1338         BOOST_ASSERT(pos >= 0);
1339
1340         Font font = getFontSettings(bparams, pos);
1341
1342         pos_type const body_pos = beginOfBody();
1343         if (pos < body_pos)
1344                 font.fontInfo().realize(d->layout_->labelfont);
1345         else
1346                 font.fontInfo().realize(d->layout_->font);
1347
1348         font.fontInfo().realize(outerfont.fontInfo());
1349         font.fontInfo().realize(bparams.getFont().fontInfo());
1350
1351         return font;
1352 }
1353
1354
1355 Font const Paragraph::getLabelFont
1356         (BufferParams const & bparams, Font const & outerfont) const
1357 {
1358         FontInfo tmpfont = d->layout_->labelfont;
1359         tmpfont.realize(outerfont.fontInfo());
1360         tmpfont.realize(bparams.getFont().fontInfo());
1361         return Font(tmpfont, getParLanguage(bparams));
1362 }
1363
1364
1365 Font const Paragraph::getLayoutFont
1366         (BufferParams const & bparams, Font const & outerfont) const
1367 {
1368         FontInfo tmpfont = d->layout_->font;
1369         tmpfont.realize(outerfont.fontInfo());
1370         tmpfont.realize(bparams.getFont().fontInfo());
1371         return Font(tmpfont, getParLanguage(bparams));
1372 }
1373
1374
1375 /// Returns the height of the highest font in range
1376 FontSize Paragraph::highestFontInRange
1377         (pos_type startpos, pos_type endpos, FontSize def_size) const
1378 {
1379         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1380 }
1381
1382
1383 char_type
1384 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1385 {
1386         char_type c = d->text_[pos];
1387         if (!lyxrc.rtl_support)
1388                 return c;
1389
1390         char_type uc = c;
1391         switch (c) {
1392         case '(':
1393                 uc = ')';
1394                 break;
1395         case ')':
1396                 uc = '(';
1397                 break;
1398         case '[':
1399                 uc = ']';
1400                 break;
1401         case ']':
1402                 uc = '[';
1403                 break;
1404         case '{':
1405                 uc = '}';
1406                 break;
1407         case '}':
1408                 uc = '{';
1409                 break;
1410         case '<':
1411                 uc = '>';
1412                 break;
1413         case '>':
1414                 uc = '<';
1415                 break;
1416         }
1417         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1418                 return uc;
1419         else
1420                 return c;
1421 }
1422
1423
1424 void Paragraph::setFont(pos_type pos, Font const & font)
1425 {
1426         BOOST_ASSERT(pos <= size());
1427
1428         // First, reduce font against layout/label font
1429         // Update: The setCharFont() routine in text2.cpp already
1430         // reduces font, so we don't need to do that here. (Asger)
1431         
1432         d->fontlist_.set(pos, font);
1433 }
1434
1435
1436 void Paragraph::makeSameLayout(Paragraph const & par)
1437 {
1438         d->layout_ = par.d->layout_;
1439         d->params_ = par.d->params_;
1440 }
1441
1442
1443 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1444 {
1445         if (isFreeSpacing())
1446                 return false;
1447
1448         int pos = 0;
1449         int count = 0;
1450
1451         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1452                 if (eraseChar(pos, trackChanges))
1453                         ++count;
1454                 else
1455                         ++pos;
1456         }
1457
1458         return count > 0 || pos > 0;
1459 }
1460
1461
1462 bool Paragraph::hasSameLayout(Paragraph const & par) const
1463 {
1464         return par.d->layout_ == d->layout_
1465                 && d->params_.sameLayout(par.d->params_);
1466 }
1467
1468
1469 depth_type Paragraph::getDepth() const
1470 {
1471         return d->params_.depth();
1472 }
1473
1474
1475 depth_type Paragraph::getMaxDepthAfter() const
1476 {
1477         if (d->layout_->isEnvironment())
1478                 return d->params_.depth() + 1;
1479         else
1480                 return d->params_.depth();
1481 }
1482
1483
1484 char Paragraph::getAlign() const
1485 {
1486         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1487                 return d->layout_->align;
1488         else
1489                 return d->params_.align();
1490 }
1491
1492
1493 docstring const & Paragraph::labelString() const
1494 {
1495         return d->params_.labelString();
1496 }
1497
1498
1499 // the next two functions are for the manual labels
1500 docstring const Paragraph::getLabelWidthString() const
1501 {
1502         if (d->layout_->margintype == MARGIN_MANUAL)
1503                 return d->params_.labelWidthString();
1504         else
1505                 return _("Senseless with this layout!");
1506 }
1507
1508
1509 void Paragraph::setLabelWidthString(docstring const & s)
1510 {
1511         d->params_.labelWidthString(s);
1512 }
1513
1514
1515 docstring const Paragraph::translateIfPossible(docstring const & s,
1516                 BufferParams const & bparams) const
1517 {
1518         if (!isAscii(s) || s.empty()) {
1519                 // This must be a user defined layout. We cannot translate
1520                 // this, since gettext accepts only ascii keys.
1521                 return s;
1522         }
1523         // Probably standard layout, try to translate
1524         Messages & m = getMessages(getParLanguage(bparams)->code());
1525         return m.get(to_ascii(s));
1526 }
1527
1528
1529 docstring Paragraph::expandLabel(Layout const & layout,
1530                 BufferParams const & bparams, bool process_appendix) const
1531 {
1532         DocumentClass const & tclass = bparams.documentClass();
1533
1534         docstring fmt;
1535         if (process_appendix && d->params_.appendix())
1536                 fmt = translateIfPossible(layout.labelstring_appendix(),
1537                         bparams);
1538         else
1539                 fmt = translateIfPossible(layout.labelstring(), bparams);
1540
1541         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1542             && !layout.counter.empty())
1543                 fmt = "\\the" + layout.counter;
1544
1545         // handle 'inherited level parts' in 'fmt',
1546         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1547         size_t const i = fmt.find('@', 0);
1548         if (i != docstring::npos) {
1549                 size_t const j = fmt.find('@', i + 1);
1550                 if (j != docstring::npos) {
1551                         docstring parent(fmt, i + 1, j - i - 1);
1552                         docstring label = from_ascii("??");
1553                         if (tclass.hasLayout(parent))
1554                                 docstring label = expandLabel(tclass[parent], bparams,
1555                                                       process_appendix);
1556                         fmt = docstring(fmt, 0, i) + label 
1557                                 + docstring(fmt, j + 1, docstring::npos);
1558                 }
1559         }
1560
1561         return tclass.counters().counterLabel(fmt);
1562 }
1563
1564
1565 void Paragraph::applyLayout(Layout const & new_layout)
1566 {
1567         d->layout_ = &new_layout;
1568         LyXAlignment const oldAlign = d->params_.align();
1569         
1570         if (!(oldAlign & d->layout_->alignpossible)) {
1571                 frontend::Alert::warning(_("Alignment not permitted"), 
1572                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1573                 d->params_.align(LYX_ALIGN_LAYOUT);
1574         }
1575 }
1576
1577
1578 pos_type Paragraph::beginOfBody() const
1579 {
1580         return d->begin_of_body_;
1581 }
1582
1583
1584 void Paragraph::setBeginOfBody()
1585 {
1586         if (d->layout_->labeltype != LABEL_MANUAL) {
1587                 d->begin_of_body_ = 0;
1588                 return;
1589         }
1590
1591         // Unroll the first two cycles of the loop
1592         // and remember the previous character to
1593         // remove unnecessary getChar() calls
1594         pos_type i = 0;
1595         pos_type end = size();
1596         if (i < end && !isNewline(i)) {
1597                 ++i;
1598                 char_type previous_char = 0;
1599                 char_type temp = 0;
1600                 if (i < end) {
1601                         previous_char = d->text_[i];
1602                         if (!isNewline(i)) {
1603                                 ++i;
1604                                 while (i < end && previous_char != ' ') {
1605                                         temp = d->text_[i];
1606                                         if (isNewline(i))
1607                                                 break;
1608                                         ++i;
1609                                         previous_char = temp;
1610                                 }
1611                         }
1612                 }
1613         }
1614
1615         d->begin_of_body_ = i;
1616 }
1617
1618
1619 namespace {
1620         // This is a hack based upon one in InsetText::neverIndent().
1621         // When we have a real InsetTableCell, then we won't need this
1622         // method, because InsetTableCell will return the right values.
1623         // The #include "insets/InsetText.h" can also be removed then.
1624         bool inTableCell(Inset const * inset)
1625         {
1626                 InsetText const * txt = inset->asInsetText();
1627                 if (!txt)
1628                         return false;
1629                 return txt->isTableCell();
1630         }
1631 }
1632
1633
1634 bool Paragraph::forceEmptyLayout() const
1635 {
1636         Inset * inset = inInset();
1637         return inset && 
1638                 (inTableCell(inset) || inInset()->forceEmptyLayout());
1639 }
1640
1641
1642 bool Paragraph::allowParagraphCustomization() const
1643 {
1644         return inInset() && inInset()->allowParagraphCustomization(0);
1645 }
1646
1647
1648 bool Paragraph::useEmptyLayout() const
1649 {
1650         Inset * inset = inInset();
1651         return inset && 
1652                 (inTableCell(inset) || inInset()->useEmptyLayout());
1653 }
1654
1655
1656 namespace {
1657
1658 // paragraphs inside floats need different alignment tags to avoid
1659 // unwanted space
1660
1661 bool noTrivlistCentering(InsetCode code)
1662 {
1663         return code == FLOAT_CODE || code == WRAP_CODE;
1664 }
1665
1666
1667 string correction(string const & orig)
1668 {
1669         if (orig == "flushleft")
1670                 return "raggedright";
1671         if (orig == "flushright")
1672                 return "raggedleft";
1673         if (orig == "center")
1674                 return "centering";
1675         return orig;
1676 }
1677
1678
1679 string const corrected_env(string const & suffix, string const & env,
1680         InsetCode code)
1681 {
1682         string output = suffix + "{";
1683         if (noTrivlistCentering(code))
1684                 output += correction(env);
1685         else
1686                 output += env;
1687         output += "}";
1688         if (suffix == "\\begin")
1689                 output += "\n";
1690         return output;
1691 }
1692
1693
1694 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1695 {
1696         if (!contains(str, "\n"))
1697                 column += str.size();
1698         else {
1699                 string tmp;
1700                 texrow.newline();
1701                 column = rsplit(str, tmp, '\n').size();
1702         }
1703 }
1704
1705 } // namespace anon
1706
1707
1708 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1709                                  odocstream & os, TexRow & texrow,
1710                                  bool moving_arg) const
1711 {
1712         int column = 0;
1713
1714         if (params_.noindent()) {
1715                 os << "\\noindent ";
1716                 column += 10;
1717         }
1718         
1719         LyXAlignment const curAlign = params_.align();
1720
1721         if (curAlign == layout_->align)
1722                 return column;
1723
1724         switch (curAlign) {
1725         case LYX_ALIGN_NONE:
1726         case LYX_ALIGN_BLOCK:
1727         case LYX_ALIGN_LAYOUT:
1728         case LYX_ALIGN_SPECIAL:
1729                 break;
1730         case LYX_ALIGN_LEFT:
1731         case LYX_ALIGN_RIGHT:
1732         case LYX_ALIGN_CENTER:
1733                 if (moving_arg) {
1734                         os << "\\protect";
1735                         column += 8;
1736                 }
1737                 break;
1738         }
1739
1740         switch (curAlign) {
1741         case LYX_ALIGN_NONE:
1742         case LYX_ALIGN_BLOCK:
1743         case LYX_ALIGN_LAYOUT:
1744         case LYX_ALIGN_SPECIAL:
1745                 break;
1746         case LYX_ALIGN_LEFT: {
1747                 string output;
1748                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1749                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1750                 else
1751                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1752                 os << from_ascii(output);
1753                 adjust_row_column(output, texrow, column);
1754                 break;
1755         } case LYX_ALIGN_RIGHT: {
1756                 string output;
1757                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1758                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1759                 else
1760                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1761                 os << from_ascii(output);
1762                 adjust_row_column(output, texrow, column);
1763                 break;
1764         } case LYX_ALIGN_CENTER: {
1765                 string output;
1766                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1767                 os << from_ascii(output);
1768                 adjust_row_column(output, texrow, column);
1769                 break;
1770         }
1771         }
1772
1773         return column;
1774 }
1775
1776
1777 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1778                                odocstream & os, TexRow & texrow,
1779                                bool moving_arg) const
1780 {
1781         int column = 0;
1782
1783         switch (params_.align()) {
1784         case LYX_ALIGN_NONE:
1785         case LYX_ALIGN_BLOCK:
1786         case LYX_ALIGN_LAYOUT:
1787         case LYX_ALIGN_SPECIAL:
1788                 break;
1789         case LYX_ALIGN_LEFT:
1790         case LYX_ALIGN_RIGHT:
1791         case LYX_ALIGN_CENTER:
1792                 if (moving_arg) {
1793                         os << "\\protect";
1794                         column = 8;
1795                 }
1796                 break;
1797         }
1798
1799         switch (params_.align()) {
1800         case LYX_ALIGN_NONE:
1801         case LYX_ALIGN_BLOCK:
1802         case LYX_ALIGN_LAYOUT:
1803         case LYX_ALIGN_SPECIAL:
1804                 break;
1805         case LYX_ALIGN_LEFT: {
1806                 string output;
1807                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1808                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1809                 else
1810                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1811                 os << from_ascii(output);
1812                 adjust_row_column(output, texrow, column);
1813                 break;
1814         } case LYX_ALIGN_RIGHT: {
1815                 string output;
1816                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1817                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1818                 else
1819                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1820                 os << from_ascii(output);
1821                 adjust_row_column(output, texrow, column);
1822                 break;
1823         } case LYX_ALIGN_CENTER: {
1824                 string output;
1825                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1826                 os << from_ascii(output);
1827                 adjust_row_column(output, texrow, column);
1828                 break;
1829         }
1830         }
1831
1832         return column;
1833 }
1834
1835
1836 // This one spits out the text of the paragraph
1837 bool Paragraph::latex(BufferParams const & bparams,
1838                                 Font const & outerfont,
1839                                 odocstream & os, TexRow & texrow,
1840                                 OutputParams const & runparams) const
1841 {
1842         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1843
1844         bool return_value = false;
1845
1846         bool asdefault = forceEmptyLayout();
1847
1848         Layout const & style = asdefault ?
1849                 bparams.documentClass().emptyLayout() :
1850                 *d->layout_;
1851
1852         // Current base font for all inherited font changes, without any
1853         // change caused by an individual character, except for the language:
1854         // It is set to the language of the first character.
1855         // As long as we are in the label, this font is the base font of the
1856         // label. Before the first body character it is set to the base font
1857         // of the body.
1858         Font basefont;
1859
1860         // Maybe we have to create a optional argument.
1861         pos_type body_pos = beginOfBody();
1862         unsigned int column = 0;
1863
1864         if (body_pos > 0) {
1865                 // the optional argument is kept in curly brackets in
1866                 // case it contains a ']'
1867                 os << "[{";
1868                 column += 2;
1869                 basefont = getLabelFont(bparams, outerfont);
1870         } else {
1871                 basefont = getLayoutFont(bparams, outerfont);
1872         }
1873
1874         // Which font is currently active?
1875         Font running_font(basefont);
1876         // Do we have an open font change?
1877         bool open_font = false;
1878
1879         Change runningChange = Change(Change::UNCHANGED);
1880
1881         texrow.start(id(), 0);
1882
1883         // if the paragraph is empty, the loop will not be entered at all
1884         if (empty()) {
1885                 if (style.isCommand()) {
1886                         os << '{';
1887                         ++column;
1888                 }
1889                 if (!asdefault)
1890                         column += d->startTeXParParams(bparams, os, texrow,
1891                                                     runparams.moving_arg);
1892         }
1893
1894         for (pos_type i = 0; i < size(); ++i) {
1895                 // First char in paragraph or after label?
1896                 if (i == body_pos) {
1897                         if (body_pos > 0) {
1898                                 if (open_font) {
1899                                         column += running_font.latexWriteEndChanges(
1900                                                 os, bparams, runparams,
1901                                                 basefont, basefont);
1902                                         open_font = false;
1903                                 }
1904                                 basefont = getLayoutFont(bparams, outerfont);
1905                                 running_font = basefont;
1906
1907                                 column += Changes::latexMarkChange(os, bparams,
1908                                                 runningChange, Change(Change::UNCHANGED));
1909                                 runningChange = Change(Change::UNCHANGED);
1910
1911                                 os << "}] ";
1912                                 column +=3;
1913                         }
1914                         if (style.isCommand()) {
1915                                 os << '{';
1916                                 ++column;
1917                         }
1918
1919                         if (!asdefault)
1920                                 column += d->startTeXParParams(bparams, os,
1921                                                             texrow,
1922                                                             runparams.moving_arg);
1923                 }
1924
1925                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1926                                                                  : lookupChange(i);
1927
1928                 if (bparams.outputChanges && runningChange != change) {
1929                         if (open_font) {
1930                                 column += running_font.latexWriteEndChanges(
1931                                                 os, bparams, runparams, basefont, basefont);
1932                                 open_font = false;
1933                         }
1934                         basefont = getLayoutFont(bparams, outerfont);
1935                         running_font = basefont;
1936
1937                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1938                         runningChange = change;
1939                 }
1940
1941                 // do not output text which is marked deleted
1942                 // if change tracking output is disabled
1943                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1944                         continue;
1945                 }
1946
1947                 ++column;
1948
1949                 // Fully instantiated font
1950                 Font const font = getFont(bparams, i, outerfont);
1951
1952                 Font const last_font = running_font;
1953
1954                 // Do we need to close the previous font?
1955                 if (open_font &&
1956                     (font != running_font ||
1957                      font.language() != running_font.language()))
1958                 {
1959                         column += running_font.latexWriteEndChanges(
1960                                         os, bparams, runparams, basefont,
1961                                         (i == body_pos-1) ? basefont : font);
1962                         running_font = basefont;
1963                         open_font = false;
1964                 }
1965
1966                 // close babel's font environment before opening CJK.
1967                 if (!running_font.language()->babel().empty() &&
1968                     font.language()->encoding()->package() == Encoding::CJK) {
1969                                 string end_tag = subst(lyxrc.language_command_end,
1970                                                         "$$lang",
1971                                                         running_font.language()->babel());
1972                                 os << from_ascii(end_tag);
1973                                 column += end_tag.length();
1974                 }
1975
1976                 // Switch file encoding if necessary (and allowed)
1977                 if (!runparams.verbatim && 
1978                     runparams.encoding->package() == Encoding::none &&
1979                     font.language()->encoding()->package() == Encoding::none) {
1980                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1981                                         runparams, *(font.language()->encoding()));
1982                         if (enc_switch.first) {
1983                                 column += enc_switch.second;
1984                                 runparams.encoding = font.language()->encoding();
1985                         }
1986                 }
1987
1988                 char_type const c = d->text_[i];
1989
1990                 // Do we need to change font?
1991                 if ((font != running_font ||
1992                      font.language() != running_font.language()) &&
1993                         i != body_pos - 1)
1994                 {
1995                         odocstringstream ods;
1996                         column += font.latexWriteStartChanges(ods, bparams,
1997                                                               runparams, basefont,
1998                                                               last_font);
1999                         running_font = font;
2000                         open_font = true;
2001                         docstring fontchange = ods.str();
2002                         // check if the fontchange ends with a trailing blank
2003                         // (like "\small " (see bug 3382)
2004                         if (suffixIs(fontchange, ' ') && c == ' ')
2005                                 os << fontchange.substr(0, fontchange.size() - 1) 
2006                                    << from_ascii("{}");
2007                         else
2008                                 os << fontchange;
2009                 }
2010
2011                 if (c == ' ') {
2012                         // FIXME: integrate this case in latexSpecialChar
2013                         // Do not print the separation of the optional argument
2014                         // if style.pass_thru is false. This works because
2015                         // latexSpecialChar ignores spaces if
2016                         // style.pass_thru is false.
2017                         if (i != body_pos - 1) {
2018                                 if (d->simpleTeXBlanks(
2019                                                 runparams, os, texrow,
2020                                                 i, column, font, style)) {
2021                                         // A surrogate pair was output. We
2022                                         // must not call latexSpecialChar
2023                                         // in this iteration, since it would output
2024                                         // the combining character again.
2025                                         ++i;
2026                                         continue;
2027                                 }
2028                         }
2029                 }
2030
2031                 OutputParams rp = runparams;
2032                 rp.free_spacing = style.free_spacing;
2033                 rp.local_font = &font;
2034                 rp.intitle = style.intitle;
2035
2036                 // Two major modes:  LaTeX or plain
2037                 // Handle here those cases common to both modes
2038                 // and then split to handle the two modes separately.
2039                 if (c == META_INSET)
2040                         d->latexInset(bparams, os,
2041                                         texrow, rp, running_font,
2042                                         basefont, outerfont, open_font,
2043                                         runningChange, style, i, column);
2044                 else {
2045                         try {
2046                                 d->latexSpecialChar(os, rp, running_font, runningChange,
2047                                         style, i, column);
2048                         } catch (EncodingException & e) {
2049                                 if (runparams.dryrun) {
2050                                         os << "<" << _("LyX Warning: ")
2051                                            << _("uncodable character") << " '";
2052                                         os.put(c);
2053                                         os << "'>";
2054                                 } else {
2055                                         // add location information and throw again.
2056                                         e.par_id = id();
2057                                         e.pos = i;
2058                                         throw(e);
2059                                 }
2060                         }
2061                 }
2062
2063                 // Set the encoding to that returned from simpleTeXSpecialChars (see
2064                 // comment for encoding member in OutputParams.h)
2065                 runparams.encoding = rp.encoding;
2066         }
2067
2068         // If we have an open font definition, we have to close it
2069         if (open_font) {
2070 #ifdef FIXED_LANGUAGE_END_DETECTION
2071                 if (next_) {
2072                         running_font
2073                                 .latexWriteEndChanges(os, bparams, runparams,
2074                                         basefont,
2075                                         next_->getFont(bparams, 0, outerfont));
2076                 } else {
2077                         running_font.latexWriteEndChanges(os, bparams,
2078                                         runparams, basefont, basefont);
2079                 }
2080 #else
2081 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2082 //FIXME: there as we start another \selectlanguage with the next paragraph if
2083 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2084                 running_font.latexWriteEndChanges(os, bparams, runparams,
2085                                 basefont, basefont);
2086 #endif
2087         }
2088
2089         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2090
2091         // Needed if there is an optional argument but no contents.
2092         if (body_pos > 0 && body_pos == size()) {
2093                 os << "}]~";
2094                 return_value = false;
2095         }
2096
2097         if (!asdefault) {
2098                 column += d->endTeXParParams(bparams, os, texrow,
2099                                           runparams.moving_arg);
2100         }
2101
2102         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2103         return return_value;
2104 }
2105
2106
2107 bool Paragraph::emptyTag() const
2108 {
2109         for (pos_type i = 0; i < size(); ++i) {
2110                 if (Inset const * inset = getInset(i)) {
2111                         InsetCode lyx_code = inset->lyxCode();
2112                         if (lyx_code != TOC_CODE &&
2113                             lyx_code != INCLUDE_CODE &&
2114                             lyx_code != GRAPHICS_CODE &&
2115                             lyx_code != ERT_CODE &&
2116                             lyx_code != LISTINGS_CODE &&
2117                             lyx_code != FLOAT_CODE &&
2118                             lyx_code != TABULAR_CODE) {
2119                                 return false;
2120                         }
2121                 } else {
2122                         char_type c = d->text_[i];
2123                         if (c != ' ' && c != '\t')
2124                                 return false;
2125                 }
2126         }
2127         return true;
2128 }
2129
2130
2131 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2132         const
2133 {
2134         for (pos_type i = 0; i < size(); ++i) {
2135                 if (Inset const * inset = getInset(i)) {
2136                         InsetCode lyx_code = inset->lyxCode();
2137                         if (lyx_code == LABEL_CODE) {
2138                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2139                                 docstring const & id = il->getParam("name");
2140                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2141                         }
2142                 }
2143         }
2144         return string();
2145 }
2146
2147
2148 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2149         const
2150 {
2151         pos_type i;
2152         for (i = 0; i < size(); ++i) {
2153                 if (Inset const * inset = getInset(i)) {
2154                         inset->docbook(os, runparams);
2155                 } else {
2156                         char_type c = d->text_[i];
2157                         if (c == ' ')
2158                                 break;
2159                         os << sgml::escapeChar(c);
2160                 }
2161         }
2162         return i;
2163 }
2164
2165
2166 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2167 {
2168         Font font_old;
2169         pos_type size = text_.size();
2170         for (pos_type i = initial; i < size; ++i) {
2171                 Font font = owner_->getFont(buf.params(), i, outerfont);
2172                 if (text_[i] == META_INSET)
2173                         return false;
2174                 if (i != initial && font != font_old)
2175                         return false;
2176                 font_old = font;
2177         }
2178
2179         return true;
2180 }
2181
2182
2183 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2184                                     odocstream & os,
2185                                     OutputParams const & runparams,
2186                                     Font const & outerfont,
2187                                     pos_type initial) const
2188 {
2189         bool emph_flag = false;
2190
2191         Layout const & style = *d->layout_;
2192         FontInfo font_old =
2193                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2194
2195         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2196                 os << "]]>";
2197
2198         // parsing main loop
2199         for (pos_type i = initial; i < size(); ++i) {
2200                 Font font = getFont(buf.params(), i, outerfont);
2201
2202                 // handle <emphasis> tag
2203                 if (font_old.emph() != font.fontInfo().emph()) {
2204                         if (font.fontInfo().emph() == FONT_ON) {
2205                                 os << "<emphasis>";
2206                                 emph_flag = true;
2207                         } else if (i != initial) {
2208                                 os << "</emphasis>";
2209                                 emph_flag = false;
2210                         }
2211                 }
2212
2213                 if (Inset const * inset = getInset(i)) {
2214                         inset->docbook(os, runparams);
2215                 } else {
2216                         char_type c = d->text_[i];
2217
2218                         if (style.pass_thru)
2219                                 os.put(c);
2220                         else
2221                                 os << sgml::escapeChar(c);
2222                 }
2223                 font_old = font.fontInfo();
2224         }
2225
2226         if (emph_flag) {
2227                 os << "</emphasis>";
2228         }
2229
2230         if (style.free_spacing)
2231                 os << '\n';
2232         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2233                 os << "<![CDATA[";
2234 }
2235
2236
2237 bool Paragraph::isHfill(pos_type pos) const
2238 {
2239         Inset const * inset = getInset(pos);
2240         return inset && inset->lyxCode() == HFILL_CODE;
2241 }
2242
2243
2244 bool Paragraph::isNewline(pos_type pos) const
2245 {
2246         Inset const * inset = getInset(pos);
2247         return inset && inset->lyxCode() == NEWLINE_CODE;
2248 }
2249
2250
2251 bool Paragraph::isLineSeparator(pos_type pos) const
2252 {
2253         char_type const c = d->text_[pos];
2254         if (isLineSeparatorChar(c))
2255                 return true;
2256         Inset const * inset = getInset(pos);
2257         return inset && inset->isLineSeparator();
2258 }
2259
2260
2261 /// Used by the spellchecker
2262 bool Paragraph::isLetter(pos_type pos) const
2263 {
2264         if (Inset const * inset = getInset(pos))
2265                 return inset->isLetter();
2266         char_type const c = d->text_[pos];
2267         return isLetterChar(c) || isDigit(c);
2268 }
2269
2270
2271 Language const *
2272 Paragraph::getParLanguage(BufferParams const & bparams) const
2273 {
2274         if (!empty())
2275                 return getFirstFontSettings(bparams).language();
2276         // FIXME: we should check the prev par as well (Lgb)
2277         return bparams.language;
2278 }
2279
2280
2281 bool Paragraph::isRTL(BufferParams const & bparams) const
2282 {
2283         return lyxrc.rtl_support
2284                 && getParLanguage(bparams)->rightToLeft()
2285                 && ownerCode() != ERT_CODE
2286                 && ownerCode() != LISTINGS_CODE;
2287 }
2288
2289
2290 void Paragraph::changeLanguage(BufferParams const & bparams,
2291                                Language const * from, Language const * to)
2292 {
2293         // change language including dummy font change at the end
2294         for (pos_type i = 0; i <= size(); ++i) {
2295                 Font font = getFontSettings(bparams, i);
2296                 if (font.language() == from) {
2297                         font.setLanguage(to);
2298                         setFont(i, font);
2299                 }
2300         }
2301 }
2302
2303
2304 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2305 {
2306         Language const * doc_language = bparams.language;
2307         FontList::const_iterator cit = d->fontlist_.begin();
2308         FontList::const_iterator end = d->fontlist_.end();
2309
2310         for (; cit != end; ++cit)
2311                 if (cit->font().language() != ignore_language &&
2312                     cit->font().language() != latex_language &&
2313                     cit->font().language() != doc_language)
2314                         return true;
2315         return false;
2316 }
2317
2318
2319 docstring Paragraph::asString(bool label) const
2320 {
2321         return asString(0, size(), label);
2322 }
2323
2324
2325 docstring Paragraph::asString(pos_type beg, pos_type end, bool label) const
2326 {
2327
2328         odocstringstream os;
2329
2330         if (beg == 0 && label && !d->params_.labelString().empty())
2331                 os << d->params_.labelString() << ' ';
2332
2333         for (pos_type i = beg; i < end; ++i) {
2334                 char_type const c = d->text_[i];
2335                 if (isPrintable(c))
2336                         os.put(c);
2337                 else if (c == META_INSET)
2338                         getInset(i)->textString(os);
2339         }
2340
2341         return os.str();
2342 }
2343
2344
2345 void Paragraph::setInsetOwner(Inset * inset)
2346 {
2347         d->inset_owner_ = inset;
2348 }
2349
2350
2351 int Paragraph::id() const
2352 {
2353         return d->id_;
2354 }
2355
2356
2357 Layout const & Paragraph::layout() const
2358 {
2359         return *d->layout_;
2360 }
2361
2362
2363 void Paragraph::setLayout(Layout const & layout)
2364 {
2365         d->layout_ = &layout;
2366 }
2367
2368
2369 void Paragraph::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2370 {
2371         if (useEmptyLayout())
2372                 setLayout(tclass.emptyLayout());
2373         else
2374                 setLayout(tclass.defaultLayout());
2375 }
2376
2377
2378 Inset * Paragraph::inInset() const
2379 {
2380         return d->inset_owner_;
2381 }
2382
2383
2384 InsetCode Paragraph::ownerCode() const
2385 {
2386         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2387 }
2388
2389
2390 ParagraphParameters & Paragraph::params()
2391 {
2392         return d->params_;
2393 }
2394
2395
2396 ParagraphParameters const & Paragraph::params() const
2397 {
2398         return d->params_;
2399 }
2400
2401
2402 bool Paragraph::isFreeSpacing() const
2403 {
2404         if (d->layout_->free_spacing)
2405                 return true;
2406         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2407 }
2408
2409
2410 bool Paragraph::allowEmpty() const
2411 {
2412         if (d->layout_->keepempty)
2413                 return true;
2414         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2415 }
2416
2417
2418 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2419 {
2420         if (!Encodings::is_arabic(c))
2421                 return c;
2422
2423         char_type prev_char = ' ';
2424         char_type next_char = ' ';
2425
2426         for (pos_type i = pos - 1; i >= 0; --i) {
2427                 char_type const par_char = d->text_[i];
2428                 if (!Encodings::isComposeChar_arabic(par_char)) {
2429                         prev_char = par_char;
2430                         break;
2431                 }
2432         }
2433
2434         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2435                 char_type const par_char = d->text_[i];
2436                 if (!Encodings::isComposeChar_arabic(par_char)) {
2437                         next_char = par_char;
2438                         break;
2439                 }
2440         }
2441
2442         if (Encodings::is_arabic(next_char)) {
2443                 if (Encodings::is_arabic(prev_char) &&
2444                         !Encodings::is_arabic_special(prev_char))
2445                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2446                 else
2447                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2448         } else {
2449                 if (Encodings::is_arabic(prev_char) &&
2450                         !Encodings::is_arabic_special(prev_char))
2451                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2452                 else
2453                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2454         }
2455 }
2456
2457
2458 int Paragraph::checkBiblio(Buffer const & buffer)
2459 {
2460         // FIXME From JS:
2461         // This is getting more and more a mess. ...We really should clean
2462         // up this bibitem issue for 1.6. See also bug 2743.
2463
2464         // Add bibitem insets if necessary
2465         if (d->layout_->labeltype != LABEL_BIBLIO)
2466                 return 0;
2467
2468         bool hasbibitem = !d->insetlist_.empty()
2469                 // Insist on it being in pos 0
2470                 && d->text_[0] == META_INSET
2471                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2472
2473         bool track_changes = buffer.params().trackChanges;
2474
2475         docstring oldkey;
2476         docstring oldlabel;
2477
2478         // remove a bibitem in pos != 0
2479         // restore it later in pos 0 if necessary
2480         // (e.g. if a user inserts contents _before_ the item)
2481         // we're assuming there's only one of these, which there
2482         // should be.
2483         int erasedInsetPosition = -1;
2484         InsetList::iterator it = d->insetlist_.begin();
2485         InsetList::iterator end = d->insetlist_.end();
2486         for (; it != end; ++it)
2487                 if (it->inset->lyxCode() == BIBITEM_CODE
2488                     && it->pos > 0) {
2489                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2490                         oldkey = olditem->getParam("key");
2491                         oldlabel = olditem->getParam("label");
2492                         erasedInsetPosition = it->pos;
2493                         eraseChar(erasedInsetPosition, track_changes);
2494                         break;
2495         }
2496
2497         // There was an InsetBibitem at the beginning, and we didn't
2498         // have to erase one.
2499         if (hasbibitem && erasedInsetPosition < 0)
2500                         return 0;
2501
2502         // There was an InsetBibitem at the beginning and we did have to
2503         // erase one. So we give its properties to the beginning inset.
2504         if (hasbibitem) {
2505                 InsetBibitem * inset =
2506                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2507                 if (!oldkey.empty())
2508                         inset->setParam("key", oldkey);
2509                 inset->setParam("label", oldlabel);
2510                 return -erasedInsetPosition;
2511         }
2512
2513         // There was no inset at the beginning, so we need to create one with
2514         // the key and label of the one we erased.
2515         InsetBibitem * inset = new InsetBibitem(InsetCommandParams(BIBITEM_CODE));
2516         inset->setBuffer(const_cast<Buffer &>(buffer));
2517         // restore values of previously deleted item in this par.
2518         if (!oldkey.empty())
2519                 inset->setParam("key", oldkey);
2520         inset->setParam("label", oldlabel);
2521         insertInset(0, static_cast<Inset *>(inset),
2522                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2523
2524         return 1;
2525 }
2526
2527
2528 void Paragraph::checkAuthors(AuthorList const & authorList)
2529 {
2530         d->changes_.checkAuthors(authorList);
2531 }
2532
2533
2534 bool Paragraph::isUnchanged(pos_type pos) const
2535 {
2536         return lookupChange(pos).type == Change::UNCHANGED;
2537 }
2538
2539
2540 bool Paragraph::isInserted(pos_type pos) const
2541 {
2542         return lookupChange(pos).type == Change::INSERTED;
2543 }
2544
2545
2546 bool Paragraph::isDeleted(pos_type pos) const
2547 {
2548         return lookupChange(pos).type == Change::DELETED;
2549 }
2550
2551
2552 InsetList const & Paragraph::insetList() const
2553 {
2554         return d->insetlist_;
2555 }
2556
2557
2558 Inset * Paragraph::releaseInset(pos_type pos)
2559 {
2560         Inset * inset = d->insetlist_.release(pos);
2561         /// does not honour change tracking!
2562         eraseChar(pos, false);
2563         return inset;
2564 }
2565
2566
2567 Inset * Paragraph::getInset(pos_type pos)
2568 {
2569         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2570                  ? d->insetlist_.get(pos) : 0;
2571 }
2572
2573
2574 Inset const * Paragraph::getInset(pos_type pos) const
2575 {
2576         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2577                  ? d->insetlist_.get(pos) : 0;
2578 }
2579
2580
2581 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2582                 pos_type & right, TextCase action)
2583 {
2584         // process sequences of modified characters; in change
2585         // tracking mode, this approach results in much better
2586         // usability than changing case on a char-by-char basis
2587         docstring changes;
2588
2589         bool const trackChanges = bparams.trackChanges;
2590
2591         bool capitalize = true;
2592
2593         for (; pos < right; ++pos) {
2594                 char_type oldChar = d->text_[pos];
2595                 char_type newChar = oldChar;
2596
2597                 // ignore insets and don't play with deleted text!
2598                 if (oldChar != META_INSET && !isDeleted(pos)) {
2599                         switch (action) {
2600                                 case text_lowercase:
2601                                         newChar = lowercase(oldChar);
2602                                         break;
2603                                 case text_capitalization:
2604                                         if (capitalize) {
2605                                                 newChar = uppercase(oldChar);
2606                                                 capitalize = false;
2607                                         }
2608                                         break;
2609                                 case text_uppercase:
2610                                         newChar = uppercase(oldChar);
2611                                         break;
2612                         }
2613                 }
2614
2615                 if (!isLetter(pos) || isDeleted(pos)) {
2616                         // permit capitalization again
2617                         capitalize = true;
2618                 }
2619
2620                 if (oldChar != newChar)
2621                         changes += newChar;
2622
2623                 if (oldChar == newChar || pos == right - 1) {
2624                         if (oldChar != newChar) {
2625                                 // step behind the changing area
2626                                 pos++;
2627                         }
2628                         int erasePos = pos - changes.size();
2629                         for (size_t i = 0; i < changes.size(); i++) {
2630                                 insertChar(pos, changes[i],
2631                                         getFontSettings(bparams,
2632                                         erasePos),
2633                                         trackChanges);
2634                                 if (!eraseChar(erasePos, trackChanges)) {
2635                                         ++erasePos;
2636                                         ++pos; // advance
2637                                         ++right; // expand selection
2638                                 }
2639                         }
2640                         changes.clear();
2641                 }
2642         }
2643 }
2644
2645
2646 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2647                 pos_type pos, bool del) const
2648 {
2649         int const strsize = str.length();
2650         int i = 0;
2651         pos_type const parsize = d->text_.size();
2652         for (i = 0; pos + i < parsize; ++i) {
2653                 if (i >= strsize)
2654                         break;
2655                 if (cs && str[i] != d->text_[pos + i])
2656                         break;
2657                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2658                         break;
2659                 if (!del && isDeleted(pos + i))
2660                         break;
2661         }
2662
2663         if (i != strsize)
2664                 return false;
2665
2666         // if necessary, check whether string matches word
2667         if (mw) {
2668                 if (pos > 0 && isLetter(pos - 1))
2669                         return false;
2670                 if (pos + strsize < parsize
2671                         && isLetter(pos + strsize))
2672                         return false;
2673         }
2674
2675         return true;
2676 }
2677
2678
2679 char_type Paragraph::getChar(pos_type pos) const
2680 {
2681         return d->text_[pos];
2682 }
2683
2684
2685 pos_type Paragraph::size() const
2686 {
2687         return d->text_.size();
2688 }
2689
2690
2691 bool Paragraph::empty() const
2692 {
2693         return d->text_.empty();
2694 }
2695
2696
2697 bool Paragraph::isInset(pos_type pos) const
2698 {
2699         return d->text_[pos] == META_INSET;
2700 }
2701
2702
2703 bool Paragraph::isSeparator(pos_type pos) const
2704 {
2705         //FIXME: Are we sure this can be the only separator?
2706         return d->text_[pos] == ' ';
2707 }
2708
2709
2710 void Paragraph::deregisterWords()
2711 {
2712         Private::Words::const_iterator it;
2713         WordList & wl = theWordList();
2714         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2715                 wl.remove(*it);
2716         d->words_.clear();
2717 }
2718
2719
2720 void Paragraph::collectWords(CursorSlice const & sl)
2721 {
2722         // find new words
2723         bool inword = false;
2724
2725         //lyxerr << "Words: ";
2726         pos_type n = size();
2727         for (pos_type pos = 0; pos != n; ++pos) {
2728                 if (isDeleted(pos))
2729                         continue;
2730
2731                 if (!isLetter(pos)) {
2732                         inword = false;
2733                         continue;
2734                 }
2735
2736                 if (inword)
2737                         continue;
2738
2739                 inword = true;
2740                 CursorSlice from = sl;
2741                 CursorSlice to = sl;
2742                 from.pos() = pos;
2743                 to.pos() = pos;
2744                 from.text()->getWord(from, to, WHOLE_WORD);
2745                 if (to.pos() - from.pos() < 6)
2746                         continue;
2747                 docstring word = asString(from.pos(), to.pos(), false);
2748                 d->words_.insert(word);
2749                 //lyxerr << word << " ";
2750         }
2751         //lyxerr << std::endl;
2752 }
2753
2754
2755 void Paragraph::registerWords()
2756 {
2757         Private::Words::const_iterator it;
2758         WordList & wl = theWordList();
2759         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2760                 wl.insert(*it);
2761 }
2762
2763
2764 void Paragraph::updateWords(CursorSlice const & sl)
2765 {
2766         BOOST_ASSERT(&sl.paragraph() == this);
2767         deregisterWords();
2768         collectWords(sl);
2769         registerWords();
2770 }
2771
2772 } // namespace lyx