]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
18b73346b99ec300d158ba9af4b940d90d97a503
[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 bool Paragraph::forceEmptyLayout() const
1620 {
1621         Inset const * const inset = inInset();
1622         if (!inset)
1623                 return true;
1624         // FIXME At present, this is wrong for table cells
1625         return inset->forceEmptyLayout();
1626 }
1627
1628
1629 bool Paragraph::allowParagraphCustomization() const
1630 {
1631         Inset const * const inset = inInset();
1632         if (!inset)
1633                 return true;
1634         // FIXME At present, this is wrong for table cells
1635         return inset->allowParagraphCustomization();
1636 }
1637
1638
1639 namespace {
1640         // FIXME
1641         // This is a hack based upon one in InsetText::neverIndent().
1642         // When we have a real InsetTableCell, then we won't need this
1643         // method, because InsetTableCell will return the right values,
1644         // viz: InsetTableCell::useEmptyLayout() should return true, and
1645         // InsetTableCell::forceEmptyLayout() should still return true
1646         // unless the width has been set.
1647         //
1648         // The #include "insets/InsetText.h" can also be removed then.
1649         bool inTableCell(Inset const * inset)
1650         {
1651                 InsetText const * txt = inset->asInsetText();
1652                 if (!txt)
1653                         return false;
1654                 return txt->isTableCell();
1655         }
1656 }
1657
1658
1659 bool Paragraph::useEmptyLayout() const
1660 {
1661         Inset const * const inset = inInset();
1662         return inset && 
1663                 (inTableCell(inset) || inset->useEmptyLayout());
1664 }
1665
1666
1667 namespace {
1668
1669 // paragraphs inside floats need different alignment tags to avoid
1670 // unwanted space
1671
1672 bool noTrivlistCentering(InsetCode code)
1673 {
1674         return code == FLOAT_CODE || code == WRAP_CODE;
1675 }
1676
1677
1678 string correction(string const & orig)
1679 {
1680         if (orig == "flushleft")
1681                 return "raggedright";
1682         if (orig == "flushright")
1683                 return "raggedleft";
1684         if (orig == "center")
1685                 return "centering";
1686         return orig;
1687 }
1688
1689
1690 string const corrected_env(string const & suffix, string const & env,
1691         InsetCode code)
1692 {
1693         string output = suffix + "{";
1694         if (noTrivlistCentering(code))
1695                 output += correction(env);
1696         else
1697                 output += env;
1698         output += "}";
1699         if (suffix == "\\begin")
1700                 output += "\n";
1701         return output;
1702 }
1703
1704
1705 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1706 {
1707         if (!contains(str, "\n"))
1708                 column += str.size();
1709         else {
1710                 string tmp;
1711                 texrow.newline();
1712                 column = rsplit(str, tmp, '\n').size();
1713         }
1714 }
1715
1716 } // namespace anon
1717
1718
1719 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1720                                  odocstream & os, TexRow & texrow,
1721                                  bool moving_arg) const
1722 {
1723         int column = 0;
1724
1725         if (params_.noindent()) {
1726                 os << "\\noindent ";
1727                 column += 10;
1728         }
1729         
1730         LyXAlignment const curAlign = params_.align();
1731
1732         if (curAlign == layout_->align)
1733                 return column;
1734
1735         switch (curAlign) {
1736         case LYX_ALIGN_NONE:
1737         case LYX_ALIGN_BLOCK:
1738         case LYX_ALIGN_LAYOUT:
1739         case LYX_ALIGN_SPECIAL:
1740                 break;
1741         case LYX_ALIGN_LEFT:
1742         case LYX_ALIGN_RIGHT:
1743         case LYX_ALIGN_CENTER:
1744                 if (moving_arg) {
1745                         os << "\\protect";
1746                         column += 8;
1747                 }
1748                 break;
1749         }
1750
1751         switch (curAlign) {
1752         case LYX_ALIGN_NONE:
1753         case LYX_ALIGN_BLOCK:
1754         case LYX_ALIGN_LAYOUT:
1755         case LYX_ALIGN_SPECIAL:
1756                 break;
1757         case LYX_ALIGN_LEFT: {
1758                 string output;
1759                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1760                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1761                 else
1762                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1763                 os << from_ascii(output);
1764                 adjust_row_column(output, texrow, column);
1765                 break;
1766         } case LYX_ALIGN_RIGHT: {
1767                 string output;
1768                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1769                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1770                 else
1771                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1772                 os << from_ascii(output);
1773                 adjust_row_column(output, texrow, column);
1774                 break;
1775         } case LYX_ALIGN_CENTER: {
1776                 string output;
1777                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1778                 os << from_ascii(output);
1779                 adjust_row_column(output, texrow, column);
1780                 break;
1781         }
1782         }
1783
1784         return column;
1785 }
1786
1787
1788 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1789                                odocstream & os, TexRow & texrow,
1790                                bool moving_arg) const
1791 {
1792         int column = 0;
1793
1794         switch (params_.align()) {
1795         case LYX_ALIGN_NONE:
1796         case LYX_ALIGN_BLOCK:
1797         case LYX_ALIGN_LAYOUT:
1798         case LYX_ALIGN_SPECIAL:
1799                 break;
1800         case LYX_ALIGN_LEFT:
1801         case LYX_ALIGN_RIGHT:
1802         case LYX_ALIGN_CENTER:
1803                 if (moving_arg) {
1804                         os << "\\protect";
1805                         column = 8;
1806                 }
1807                 break;
1808         }
1809
1810         switch (params_.align()) {
1811         case LYX_ALIGN_NONE:
1812         case LYX_ALIGN_BLOCK:
1813         case LYX_ALIGN_LAYOUT:
1814         case LYX_ALIGN_SPECIAL:
1815                 break;
1816         case LYX_ALIGN_LEFT: {
1817                 string output;
1818                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1819                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1820                 else
1821                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1822                 os << from_ascii(output);
1823                 adjust_row_column(output, texrow, column);
1824                 break;
1825         } case LYX_ALIGN_RIGHT: {
1826                 string output;
1827                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1828                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1829                 else
1830                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1831                 os << from_ascii(output);
1832                 adjust_row_column(output, texrow, column);
1833                 break;
1834         } case LYX_ALIGN_CENTER: {
1835                 string output;
1836                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1837                 os << from_ascii(output);
1838                 adjust_row_column(output, texrow, column);
1839                 break;
1840         }
1841         }
1842
1843         return column;
1844 }
1845
1846
1847 // This one spits out the text of the paragraph
1848 bool Paragraph::latex(BufferParams const & bparams,
1849                                 Font const & outerfont,
1850                                 odocstream & os, TexRow & texrow,
1851                                 OutputParams const & runparams) const
1852 {
1853         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1854
1855         bool return_value = false;
1856
1857         bool asdefault = forceEmptyLayout();
1858
1859         Layout const & style = asdefault ?
1860                 bparams.documentClass().emptyLayout() :
1861                 *d->layout_;
1862
1863         // Current base font for all inherited font changes, without any
1864         // change caused by an individual character, except for the language:
1865         // It is set to the language of the first character.
1866         // As long as we are in the label, this font is the base font of the
1867         // label. Before the first body character it is set to the base font
1868         // of the body.
1869         Font basefont;
1870
1871         // Maybe we have to create a optional argument.
1872         pos_type body_pos = beginOfBody();
1873         unsigned int column = 0;
1874
1875         if (body_pos > 0) {
1876                 // the optional argument is kept in curly brackets in
1877                 // case it contains a ']'
1878                 os << "[{";
1879                 column += 2;
1880                 basefont = getLabelFont(bparams, outerfont);
1881         } else {
1882                 basefont = getLayoutFont(bparams, outerfont);
1883         }
1884
1885         // Which font is currently active?
1886         Font running_font(basefont);
1887         // Do we have an open font change?
1888         bool open_font = false;
1889
1890         Change runningChange = Change(Change::UNCHANGED);
1891
1892         texrow.start(id(), 0);
1893
1894         // if the paragraph is empty, the loop will not be entered at all
1895         if (empty()) {
1896                 if (style.isCommand()) {
1897                         os << '{';
1898                         ++column;
1899                 }
1900                 if (!asdefault)
1901                         column += d->startTeXParParams(bparams, os, texrow,
1902                                                     runparams.moving_arg);
1903         }
1904
1905         for (pos_type i = 0; i < size(); ++i) {
1906                 // First char in paragraph or after label?
1907                 if (i == body_pos) {
1908                         if (body_pos > 0) {
1909                                 if (open_font) {
1910                                         column += running_font.latexWriteEndChanges(
1911                                                 os, bparams, runparams,
1912                                                 basefont, basefont);
1913                                         open_font = false;
1914                                 }
1915                                 basefont = getLayoutFont(bparams, outerfont);
1916                                 running_font = basefont;
1917
1918                                 column += Changes::latexMarkChange(os, bparams,
1919                                                 runningChange, Change(Change::UNCHANGED));
1920                                 runningChange = Change(Change::UNCHANGED);
1921
1922                                 os << "}] ";
1923                                 column +=3;
1924                         }
1925                         if (style.isCommand()) {
1926                                 os << '{';
1927                                 ++column;
1928                         }
1929
1930                         if (!asdefault)
1931                                 column += d->startTeXParParams(bparams, os,
1932                                                             texrow,
1933                                                             runparams.moving_arg);
1934                 }
1935
1936                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1937                                                                  : lookupChange(i);
1938
1939                 if (bparams.outputChanges && runningChange != change) {
1940                         if (open_font) {
1941                                 column += running_font.latexWriteEndChanges(
1942                                                 os, bparams, runparams, basefont, basefont);
1943                                 open_font = false;
1944                         }
1945                         basefont = getLayoutFont(bparams, outerfont);
1946                         running_font = basefont;
1947
1948                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1949                         runningChange = change;
1950                 }
1951
1952                 // do not output text which is marked deleted
1953                 // if change tracking output is disabled
1954                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1955                         continue;
1956                 }
1957
1958                 ++column;
1959
1960                 // Fully instantiated font
1961                 Font const font = getFont(bparams, i, outerfont);
1962
1963                 Font const last_font = running_font;
1964
1965                 // Do we need to close the previous font?
1966                 if (open_font &&
1967                     (font != running_font ||
1968                      font.language() != running_font.language()))
1969                 {
1970                         column += running_font.latexWriteEndChanges(
1971                                         os, bparams, runparams, basefont,
1972                                         (i == body_pos-1) ? basefont : font);
1973                         running_font = basefont;
1974                         open_font = false;
1975                 }
1976
1977                 // close babel's font environment before opening CJK.
1978                 if (!running_font.language()->babel().empty() &&
1979                     font.language()->encoding()->package() == Encoding::CJK) {
1980                                 string end_tag = subst(lyxrc.language_command_end,
1981                                                         "$$lang",
1982                                                         running_font.language()->babel());
1983                                 os << from_ascii(end_tag);
1984                                 column += end_tag.length();
1985                 }
1986
1987                 // Switch file encoding if necessary (and allowed)
1988                 if (!runparams.verbatim && 
1989                     runparams.encoding->package() == Encoding::none &&
1990                     font.language()->encoding()->package() == Encoding::none) {
1991                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1992                                         runparams, *(font.language()->encoding()));
1993                         if (enc_switch.first) {
1994                                 column += enc_switch.second;
1995                                 runparams.encoding = font.language()->encoding();
1996                         }
1997                 }
1998
1999                 char_type const c = d->text_[i];
2000
2001                 // Do we need to change font?
2002                 if ((font != running_font ||
2003                      font.language() != running_font.language()) &&
2004                         i != body_pos - 1)
2005                 {
2006                         odocstringstream ods;
2007                         column += font.latexWriteStartChanges(ods, bparams,
2008                                                               runparams, basefont,
2009                                                               last_font);
2010                         running_font = font;
2011                         open_font = true;
2012                         docstring fontchange = ods.str();
2013                         // check if the fontchange ends with a trailing blank
2014                         // (like "\small " (see bug 3382)
2015                         if (suffixIs(fontchange, ' ') && c == ' ')
2016                                 os << fontchange.substr(0, fontchange.size() - 1) 
2017                                    << from_ascii("{}");
2018                         else
2019                                 os << fontchange;
2020                 }
2021
2022                 if (c == ' ') {
2023                         // FIXME: integrate this case in latexSpecialChar
2024                         // Do not print the separation of the optional argument
2025                         // if style.pass_thru is false. This works because
2026                         // latexSpecialChar ignores spaces if
2027                         // style.pass_thru is false.
2028                         if (i != body_pos - 1) {
2029                                 if (d->simpleTeXBlanks(
2030                                                 runparams, os, texrow,
2031                                                 i, column, font, style)) {
2032                                         // A surrogate pair was output. We
2033                                         // must not call latexSpecialChar
2034                                         // in this iteration, since it would output
2035                                         // the combining character again.
2036                                         ++i;
2037                                         continue;
2038                                 }
2039                         }
2040                 }
2041
2042                 OutputParams rp = runparams;
2043                 rp.free_spacing = style.free_spacing;
2044                 rp.local_font = &font;
2045                 rp.intitle = style.intitle;
2046
2047                 // Two major modes:  LaTeX or plain
2048                 // Handle here those cases common to both modes
2049                 // and then split to handle the two modes separately.
2050                 if (c == META_INSET)
2051                         d->latexInset(bparams, os,
2052                                         texrow, rp, running_font,
2053                                         basefont, outerfont, open_font,
2054                                         runningChange, style, i, column);
2055                 else {
2056                         try {
2057                                 d->latexSpecialChar(os, rp, running_font, runningChange,
2058                                         style, i, column);
2059                         } catch (EncodingException & e) {
2060                                 if (runparams.dryrun) {
2061                                         os << "<" << _("LyX Warning: ")
2062                                            << _("uncodable character") << " '";
2063                                         os.put(c);
2064                                         os << "'>";
2065                                 } else {
2066                                         // add location information and throw again.
2067                                         e.par_id = id();
2068                                         e.pos = i;
2069                                         throw(e);
2070                                 }
2071                         }
2072                 }
2073
2074                 // Set the encoding to that returned from simpleTeXSpecialChars (see
2075                 // comment for encoding member in OutputParams.h)
2076                 runparams.encoding = rp.encoding;
2077         }
2078
2079         // If we have an open font definition, we have to close it
2080         if (open_font) {
2081 #ifdef FIXED_LANGUAGE_END_DETECTION
2082                 if (next_) {
2083                         running_font
2084                                 .latexWriteEndChanges(os, bparams, runparams,
2085                                         basefont,
2086                                         next_->getFont(bparams, 0, outerfont));
2087                 } else {
2088                         running_font.latexWriteEndChanges(os, bparams,
2089                                         runparams, basefont, basefont);
2090                 }
2091 #else
2092 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2093 //FIXME: there as we start another \selectlanguage with the next paragraph if
2094 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2095                 running_font.latexWriteEndChanges(os, bparams, runparams,
2096                                 basefont, basefont);
2097 #endif
2098         }
2099
2100         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2101
2102         // Needed if there is an optional argument but no contents.
2103         if (body_pos > 0 && body_pos == size()) {
2104                 os << "}]~";
2105                 return_value = false;
2106         }
2107
2108         if (!asdefault) {
2109                 column += d->endTeXParParams(bparams, os, texrow,
2110                                           runparams.moving_arg);
2111         }
2112
2113         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2114         return return_value;
2115 }
2116
2117
2118 bool Paragraph::emptyTag() const
2119 {
2120         for (pos_type i = 0; i < size(); ++i) {
2121                 if (Inset const * inset = getInset(i)) {
2122                         InsetCode lyx_code = inset->lyxCode();
2123                         if (lyx_code != TOC_CODE &&
2124                             lyx_code != INCLUDE_CODE &&
2125                             lyx_code != GRAPHICS_CODE &&
2126                             lyx_code != ERT_CODE &&
2127                             lyx_code != LISTINGS_CODE &&
2128                             lyx_code != FLOAT_CODE &&
2129                             lyx_code != TABULAR_CODE) {
2130                                 return false;
2131                         }
2132                 } else {
2133                         char_type c = d->text_[i];
2134                         if (c != ' ' && c != '\t')
2135                                 return false;
2136                 }
2137         }
2138         return true;
2139 }
2140
2141
2142 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2143         const
2144 {
2145         for (pos_type i = 0; i < size(); ++i) {
2146                 if (Inset const * inset = getInset(i)) {
2147                         InsetCode lyx_code = inset->lyxCode();
2148                         if (lyx_code == LABEL_CODE) {
2149                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2150                                 docstring const & id = il->getParam("name");
2151                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2152                         }
2153                 }
2154         }
2155         return string();
2156 }
2157
2158
2159 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2160         const
2161 {
2162         pos_type i;
2163         for (i = 0; i < size(); ++i) {
2164                 if (Inset const * inset = getInset(i)) {
2165                         inset->docbook(os, runparams);
2166                 } else {
2167                         char_type c = d->text_[i];
2168                         if (c == ' ')
2169                                 break;
2170                         os << sgml::escapeChar(c);
2171                 }
2172         }
2173         return i;
2174 }
2175
2176
2177 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2178 {
2179         Font font_old;
2180         pos_type size = text_.size();
2181         for (pos_type i = initial; i < size; ++i) {
2182                 Font font = owner_->getFont(buf.params(), i, outerfont);
2183                 if (text_[i] == META_INSET)
2184                         return false;
2185                 if (i != initial && font != font_old)
2186                         return false;
2187                 font_old = font;
2188         }
2189
2190         return true;
2191 }
2192
2193
2194 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2195                                     odocstream & os,
2196                                     OutputParams const & runparams,
2197                                     Font const & outerfont,
2198                                     pos_type initial) const
2199 {
2200         bool emph_flag = false;
2201
2202         Layout const & style = *d->layout_;
2203         FontInfo font_old =
2204                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2205
2206         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2207                 os << "]]>";
2208
2209         // parsing main loop
2210         for (pos_type i = initial; i < size(); ++i) {
2211                 Font font = getFont(buf.params(), i, outerfont);
2212
2213                 // handle <emphasis> tag
2214                 if (font_old.emph() != font.fontInfo().emph()) {
2215                         if (font.fontInfo().emph() == FONT_ON) {
2216                                 os << "<emphasis>";
2217                                 emph_flag = true;
2218                         } else if (i != initial) {
2219                                 os << "</emphasis>";
2220                                 emph_flag = false;
2221                         }
2222                 }
2223
2224                 if (Inset const * inset = getInset(i)) {
2225                         inset->docbook(os, runparams);
2226                 } else {
2227                         char_type c = d->text_[i];
2228
2229                         if (style.pass_thru)
2230                                 os.put(c);
2231                         else
2232                                 os << sgml::escapeChar(c);
2233                 }
2234                 font_old = font.fontInfo();
2235         }
2236
2237         if (emph_flag) {
2238                 os << "</emphasis>";
2239         }
2240
2241         if (style.free_spacing)
2242                 os << '\n';
2243         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2244                 os << "<![CDATA[";
2245 }
2246
2247
2248 bool Paragraph::isHfill(pos_type pos) const
2249 {
2250         Inset const * inset = getInset(pos);
2251         return inset && (inset->lyxCode() == SPACE_CODE &&
2252                          inset->isStretchableSpace());
2253 }
2254
2255
2256 bool Paragraph::isNewline(pos_type pos) const
2257 {
2258         Inset const * inset = getInset(pos);
2259         return inset && inset->lyxCode() == NEWLINE_CODE;
2260 }
2261
2262
2263 bool Paragraph::isLineSeparator(pos_type pos) const
2264 {
2265         char_type const c = d->text_[pos];
2266         if (isLineSeparatorChar(c))
2267                 return true;
2268         Inset const * inset = getInset(pos);
2269         return inset && inset->isLineSeparator();
2270 }
2271
2272
2273 /// Used by the spellchecker
2274 bool Paragraph::isLetter(pos_type pos) const
2275 {
2276         if (Inset const * inset = getInset(pos))
2277                 return inset->isLetter();
2278         char_type const c = d->text_[pos];
2279         return isLetterChar(c) || isDigit(c);
2280 }
2281
2282
2283 Language const *
2284 Paragraph::getParLanguage(BufferParams const & bparams) const
2285 {
2286         if (!empty())
2287                 return getFirstFontSettings(bparams).language();
2288         // FIXME: we should check the prev par as well (Lgb)
2289         return bparams.language;
2290 }
2291
2292
2293 bool Paragraph::isRTL(BufferParams const & bparams) const
2294 {
2295         return lyxrc.rtl_support
2296                 && getParLanguage(bparams)->rightToLeft()
2297                 && ownerCode() != ERT_CODE
2298                 && ownerCode() != LISTINGS_CODE;
2299 }
2300
2301
2302 void Paragraph::changeLanguage(BufferParams const & bparams,
2303                                Language const * from, Language const * to)
2304 {
2305         // change language including dummy font change at the end
2306         for (pos_type i = 0; i <= size(); ++i) {
2307                 Font font = getFontSettings(bparams, i);
2308                 if (font.language() == from) {
2309                         font.setLanguage(to);
2310                         setFont(i, font);
2311                 }
2312         }
2313 }
2314
2315
2316 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2317 {
2318         Language const * doc_language = bparams.language;
2319         FontList::const_iterator cit = d->fontlist_.begin();
2320         FontList::const_iterator end = d->fontlist_.end();
2321
2322         for (; cit != end; ++cit)
2323                 if (cit->font().language() != ignore_language &&
2324                     cit->font().language() != latex_language &&
2325                     cit->font().language() != doc_language)
2326                         return true;
2327         return false;
2328 }
2329
2330
2331 docstring Paragraph::asString(bool label) const
2332 {
2333         return asString(0, size(), label);
2334 }
2335
2336
2337 docstring Paragraph::asString(pos_type beg, pos_type end, bool label) const
2338 {
2339
2340         odocstringstream os;
2341
2342         if (beg == 0 && label && !d->params_.labelString().empty())
2343                 os << d->params_.labelString() << ' ';
2344
2345         for (pos_type i = beg; i < end; ++i) {
2346                 char_type const c = d->text_[i];
2347                 if (isPrintable(c))
2348                         os.put(c);
2349                 else if (c == META_INSET)
2350                         getInset(i)->textString(os);
2351         }
2352
2353         return os.str();
2354 }
2355
2356
2357 void Paragraph::setInsetOwner(Inset * inset)
2358 {
2359         d->inset_owner_ = inset;
2360 }
2361
2362
2363 int Paragraph::id() const
2364 {
2365         return d->id_;
2366 }
2367
2368
2369 Layout const & Paragraph::layout() const
2370 {
2371         return *d->layout_;
2372 }
2373
2374
2375 void Paragraph::setLayout(Layout const & layout)
2376 {
2377         d->layout_ = &layout;
2378 }
2379
2380
2381 void Paragraph::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2382 {
2383         if (useEmptyLayout())
2384                 setLayout(tclass.emptyLayout());
2385         else
2386                 setLayout(tclass.defaultLayout());
2387 }
2388
2389
2390 Inset * Paragraph::inInset() const
2391 {
2392         return d->inset_owner_;
2393 }
2394
2395
2396 InsetCode Paragraph::ownerCode() const
2397 {
2398         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2399 }
2400
2401
2402 ParagraphParameters & Paragraph::params()
2403 {
2404         return d->params_;
2405 }
2406
2407
2408 ParagraphParameters const & Paragraph::params() const
2409 {
2410         return d->params_;
2411 }
2412
2413
2414 bool Paragraph::isFreeSpacing() const
2415 {
2416         if (d->layout_->free_spacing)
2417                 return true;
2418         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2419 }
2420
2421
2422 bool Paragraph::allowEmpty() const
2423 {
2424         if (d->layout_->keepempty)
2425                 return true;
2426         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2427 }
2428
2429
2430 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2431 {
2432         if (!Encodings::is_arabic(c))
2433                 return c;
2434
2435         char_type prev_char = ' ';
2436         char_type next_char = ' ';
2437
2438         for (pos_type i = pos - 1; i >= 0; --i) {
2439                 char_type const par_char = d->text_[i];
2440                 if (!Encodings::isComposeChar_arabic(par_char)) {
2441                         prev_char = par_char;
2442                         break;
2443                 }
2444         }
2445
2446         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2447                 char_type const par_char = d->text_[i];
2448                 if (!Encodings::isComposeChar_arabic(par_char)) {
2449                         next_char = par_char;
2450                         break;
2451                 }
2452         }
2453
2454         if (Encodings::is_arabic(next_char)) {
2455                 if (Encodings::is_arabic(prev_char) &&
2456                         !Encodings::is_arabic_special(prev_char))
2457                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2458                 else
2459                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2460         } else {
2461                 if (Encodings::is_arabic(prev_char) &&
2462                         !Encodings::is_arabic_special(prev_char))
2463                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2464                 else
2465                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2466         }
2467 }
2468
2469
2470 int Paragraph::checkBiblio(Buffer const & buffer)
2471 {
2472         // FIXME From JS:
2473         // This is getting more and more a mess. ...We really should clean
2474         // up this bibitem issue for 1.6. See also bug 2743.
2475
2476         // Add bibitem insets if necessary
2477         if (d->layout_->labeltype != LABEL_BIBLIO)
2478                 return 0;
2479
2480         bool hasbibitem = !d->insetlist_.empty()
2481                 // Insist on it being in pos 0
2482                 && d->text_[0] == META_INSET
2483                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2484
2485         bool track_changes = buffer.params().trackChanges;
2486
2487         docstring oldkey;
2488         docstring oldlabel;
2489
2490         // remove a bibitem in pos != 0
2491         // restore it later in pos 0 if necessary
2492         // (e.g. if a user inserts contents _before_ the item)
2493         // we're assuming there's only one of these, which there
2494         // should be.
2495         int erasedInsetPosition = -1;
2496         InsetList::iterator it = d->insetlist_.begin();
2497         InsetList::iterator end = d->insetlist_.end();
2498         for (; it != end; ++it)
2499                 if (it->inset->lyxCode() == BIBITEM_CODE
2500                     && it->pos > 0) {
2501                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2502                         oldkey = olditem->getParam("key");
2503                         oldlabel = olditem->getParam("label");
2504                         erasedInsetPosition = it->pos;
2505                         eraseChar(erasedInsetPosition, track_changes);
2506                         break;
2507         }
2508
2509         // There was an InsetBibitem at the beginning, and we didn't
2510         // have to erase one.
2511         if (hasbibitem && erasedInsetPosition < 0)
2512                         return 0;
2513
2514         // There was an InsetBibitem at the beginning and we did have to
2515         // erase one. So we give its properties to the beginning inset.
2516         if (hasbibitem) {
2517                 InsetBibitem * inset =
2518                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2519                 if (!oldkey.empty())
2520                         inset->setParam("key", oldkey);
2521                 inset->setParam("label", oldlabel);
2522                 return -erasedInsetPosition;
2523         }
2524
2525         // There was no inset at the beginning, so we need to create one with
2526         // the key and label of the one we erased.
2527         InsetBibitem * inset = new InsetBibitem(InsetCommandParams(BIBITEM_CODE));
2528         inset->setBuffer(const_cast<Buffer &>(buffer));
2529         // restore values of previously deleted item in this par.
2530         if (!oldkey.empty())
2531                 inset->setParam("key", oldkey);
2532         inset->setParam("label", oldlabel);
2533         insertInset(0, static_cast<Inset *>(inset),
2534                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2535
2536         return 1;
2537 }
2538
2539
2540 void Paragraph::checkAuthors(AuthorList const & authorList)
2541 {
2542         d->changes_.checkAuthors(authorList);
2543 }
2544
2545
2546 bool Paragraph::isUnchanged(pos_type pos) const
2547 {
2548         return lookupChange(pos).type == Change::UNCHANGED;
2549 }
2550
2551
2552 bool Paragraph::isInserted(pos_type pos) const
2553 {
2554         return lookupChange(pos).type == Change::INSERTED;
2555 }
2556
2557
2558 bool Paragraph::isDeleted(pos_type pos) const
2559 {
2560         return lookupChange(pos).type == Change::DELETED;
2561 }
2562
2563
2564 InsetList const & Paragraph::insetList() const
2565 {
2566         return d->insetlist_;
2567 }
2568
2569
2570 Inset * Paragraph::releaseInset(pos_type pos)
2571 {
2572         Inset * inset = d->insetlist_.release(pos);
2573         /// does not honour change tracking!
2574         eraseChar(pos, false);
2575         return inset;
2576 }
2577
2578
2579 Inset * Paragraph::getInset(pos_type pos)
2580 {
2581         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2582                  ? d->insetlist_.get(pos) : 0;
2583 }
2584
2585
2586 Inset const * Paragraph::getInset(pos_type pos) const
2587 {
2588         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2589                  ? d->insetlist_.get(pos) : 0;
2590 }
2591
2592
2593 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2594                 pos_type & right, TextCase action)
2595 {
2596         // process sequences of modified characters; in change
2597         // tracking mode, this approach results in much better
2598         // usability than changing case on a char-by-char basis
2599         docstring changes;
2600
2601         bool const trackChanges = bparams.trackChanges;
2602
2603         bool capitalize = true;
2604
2605         for (; pos < right; ++pos) {
2606                 char_type oldChar = d->text_[pos];
2607                 char_type newChar = oldChar;
2608
2609                 // ignore insets and don't play with deleted text!
2610                 if (oldChar != META_INSET && !isDeleted(pos)) {
2611                         switch (action) {
2612                                 case text_lowercase:
2613                                         newChar = lowercase(oldChar);
2614                                         break;
2615                                 case text_capitalization:
2616                                         if (capitalize) {
2617                                                 newChar = uppercase(oldChar);
2618                                                 capitalize = false;
2619                                         }
2620                                         break;
2621                                 case text_uppercase:
2622                                         newChar = uppercase(oldChar);
2623                                         break;
2624                         }
2625                 }
2626
2627                 if (!isLetter(pos) || isDeleted(pos)) {
2628                         // permit capitalization again
2629                         capitalize = true;
2630                 }
2631
2632                 if (oldChar != newChar)
2633                         changes += newChar;
2634
2635                 if (oldChar == newChar || pos == right - 1) {
2636                         if (oldChar != newChar) {
2637                                 // step behind the changing area
2638                                 pos++;
2639                         }
2640                         int erasePos = pos - changes.size();
2641                         for (size_t i = 0; i < changes.size(); i++) {
2642                                 insertChar(pos, changes[i],
2643                                         getFontSettings(bparams,
2644                                         erasePos),
2645                                         trackChanges);
2646                                 if (!eraseChar(erasePos, trackChanges)) {
2647                                         ++erasePos;
2648                                         ++pos; // advance
2649                                         ++right; // expand selection
2650                                 }
2651                         }
2652                         changes.clear();
2653                 }
2654         }
2655 }
2656
2657
2658 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2659                 pos_type pos, bool del) const
2660 {
2661         int const strsize = str.length();
2662         int i = 0;
2663         pos_type const parsize = d->text_.size();
2664         for (i = 0; pos + i < parsize; ++i) {
2665                 if (i >= strsize)
2666                         break;
2667                 if (cs && str[i] != d->text_[pos + i])
2668                         break;
2669                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2670                         break;
2671                 if (!del && isDeleted(pos + i))
2672                         break;
2673         }
2674
2675         if (i != strsize)
2676                 return false;
2677
2678         // if necessary, check whether string matches word
2679         if (mw) {
2680                 if (pos > 0 && isLetter(pos - 1))
2681                         return false;
2682                 if (pos + strsize < parsize
2683                         && isLetter(pos + strsize))
2684                         return false;
2685         }
2686
2687         return true;
2688 }
2689
2690
2691 char_type Paragraph::getChar(pos_type pos) const
2692 {
2693         return d->text_[pos];
2694 }
2695
2696
2697 pos_type Paragraph::size() const
2698 {
2699         return d->text_.size();
2700 }
2701
2702
2703 bool Paragraph::empty() const
2704 {
2705         return d->text_.empty();
2706 }
2707
2708
2709 bool Paragraph::isInset(pos_type pos) const
2710 {
2711         return d->text_[pos] == META_INSET;
2712 }
2713
2714
2715 bool Paragraph::isSeparator(pos_type pos) const
2716 {
2717         //FIXME: Are we sure this can be the only separator?
2718         return d->text_[pos] == ' ';
2719 }
2720
2721
2722 void Paragraph::deregisterWords()
2723 {
2724         Private::Words::const_iterator it;
2725         WordList & wl = theWordList();
2726         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2727                 wl.remove(*it);
2728         d->words_.clear();
2729 }
2730
2731
2732 void Paragraph::collectWords(CursorSlice const & sl)
2733 {
2734         // find new words
2735         bool inword = false;
2736
2737         //lyxerr << "Words: ";
2738         pos_type n = size();
2739         for (pos_type pos = 0; pos != n; ++pos) {
2740                 if (isDeleted(pos))
2741                         continue;
2742
2743                 if (!isLetter(pos)) {
2744                         inword = false;
2745                         continue;
2746                 }
2747
2748                 if (inword)
2749                         continue;
2750
2751                 inword = true;
2752                 CursorSlice from = sl;
2753                 CursorSlice to = sl;
2754                 from.pos() = pos;
2755                 to.pos() = pos;
2756                 from.text()->getWord(from, to, WHOLE_WORD);
2757                 if (to.pos() - from.pos() < 6)
2758                         continue;
2759                 docstring word = asString(from.pos(), to.pos(), false);
2760                 d->words_.insert(word);
2761                 //lyxerr << word << " ";
2762         }
2763         //lyxerr << std::endl;
2764 }
2765
2766
2767 void Paragraph::registerWords()
2768 {
2769         Private::Words::const_iterator it;
2770         WordList & wl = theWordList();
2771         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2772                 wl.insert(*it);
2773 }
2774
2775
2776 void Paragraph::updateWords(CursorSlice const & sl)
2777 {
2778         BOOST_ASSERT(&sl.paragraph() == this);
2779         deregisterWords();
2780         collectWords(sl);
2781         registerWords();
2782 }
2783
2784 } // namespace lyx