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